在PyTest中创建一个临时目录

Dai*_*Dai 7 python pytest

我的Python项目pytest没有任何问题导入2.9.0罚款.

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

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

您可以使用tmpdir fixture,它将提供在基本临时目录中创建的测试调用唯一的临时目录.

tmpdir是一个py.path.local对象,它提供了os.path方法等.以下是测试用法的示例:

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

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

import pytest

# ...

def test_foo():
    p = pytest.tmpdir()
Run Code Online (Sandbox Code Playgroud)

有错误:

AttributeError:'module'对象没有属性'tmpdir'

做错from pytest import tmpdir了:

ImportError:无法导入名称tmpdir

M.T*_*M.T 24

我调查了一下也发现了一种特殊的行为,我总结了下面我学到的东西,对于那些没有发现它如此直观的人.

它似乎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
Run Code Online (Sandbox Code Playgroud)

因此,如果您将其作为参数名称,则tmpdir定义的固定名称将pytest传递给您的测试函数.

用法示例:

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"
Run Code Online (Sandbox Code Playgroud)

当您使用pytest运行它时,这可以工作,例如py.test test_foo.py在终端中运行.以这种方式生成的文件具有读写访问权限,稍后可以在系统临时文件夹中查看(对我而言/tmp/pytest-of-myfolder/pytest-1/test_create_file0)

  • +1 指出 `tmpdir` / `tmp_path` 差异。我收到一些奇怪的错误,因为我认为 `tmpdir` 已经是一个 pathlib.Path (2认同)

Ily*_*yas 8

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

def test_foo(tmpdir):
    # do things with tmpdir
Run Code Online (Sandbox Code Playgroud)