在PyTes中创建临时目录

2024-05-20 04:38:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我的Python项目导入pytest2.9.0很好,没有任何问题。

我想创建一个新的空目录,它只会持续测试会话的生命周期。我看到pytest提供了临时目录支持:

https://pytest.org/latest/tmpdir.html

You can use the tmpdir fixture which will provide a temporary directory unique to the test invocation, created in the base temporary directory.

tmpdir is a py.path.local object which offers os.path methods and more. Here is an example test usage:

pytest的源代码显示def tmpdir是一个全局/模块函数:https://pytest.org/latest/_modules/_pytest/tmpdir.html

但是我的测试文件失败了:

import pytest

# ...

def test_foo():
    p = pytest.tmpdir()

有错误:

AttributeError: 'module' object has no attribute 'tmpdir'

执行from pytest import tmpdir失败,原因是:

ImportError: cannot import name tmpdir


Tags: thepathhttpsorgtestimportwhichobject
1条回答
网友
1楼 · 发布于 2024-05-20 04:38:47

我对它进行了研究,也发现了这种行为的特殊性,并总结了我在下面学到的东西,供那些不太直观的人参考。

tmpdir是pytest中预定义的fixture,类似于这里如何定义setup

import pytest

class TestSetup:
    def __init__(self):
        self.x = 4

@pytest.fixture()
def setup():
    return TestSetup()

def test_something(setup)
    assert setup.x == 4

因此tmpdir是在pytest中定义的一个固定名称,如果您将其作为参数名,则该名称将传递给您的testfunction。

示例用法:

def test_something_else(tmpdir):
    #create a file "myfile" in "mydir" in temp folder
    f1 = tmpdir.mkdir("mydir").join("myfile")

    #create a file "myfile" in temp folder
    f2 = tmpdir.join("myfile")

    #write to file as normal 
    f1.write("text to myfile")

    assert f1.read() == "text to myfile"

这在使用pytest运行它时有效,例如在终端中运行py.test test_foo.py。以这种方式生成的文件具有读写权限,以后可以在系统临时文件夹中查看(对我来说,这是/tmp/pytest-of-myfolder/pytest-1/test_create_file0

更新:使用tmp_path,而不是tmpdirtmp_path是一个pathlib.Path/pathlib2.Pathtmpdir是一个py.path(实际上是LocalPath),它提供了与pathlib.Path非常相似的语法。见pytest issue

开发人员不再推荐使用py.path。

语法相同,例如:

def test_something_else(tmp_path):
    #create a file "myfile" in "mydir" in temp folder
    f1 = tmp_path.mkdir("mydir").join("myfile")

    #create a file "myfile" in temp folder
    f2 = tmp_path.join("myfile")

    #write to file as normal 
    f1.write("text to myfile")

    assert f1.read() == "text to myfile" 
网友
2楼 · 发布于 2024-05-20 04:38:47

您只需将tmpdir作为函数参数传递,因为它是py.test fixture。

def test_foo(tmpdir):
    # do things with tmpdir

相关问题 更多 >