我的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()
有错误:
AttributeError:' module'对象没有属性' tmpdir'
执行from pytest import tmpdir
失败并执行:
ImportError:无法导入名称tmpdir
答案 0 :(得分:18)
我调查了一下也发现了一种特殊的行为,我总结了下面我学到的东西,对于那些没有发现它如此直观的人来说。
似乎tmpdir
是pytest中预定义的夹具,类似于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
中定义的固定名称,如果将其作为参数名称传递给测试函数。
使用示例:
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
)
答案 1 :(得分:5)
你必须将tmpdir作为函数参数传递,因为它是py.test fixture。
def test_foo(tmpdir):
# do things with tmpdir