我的 Python 项目导入 pytest
2.9.0 没有任何问题。
我想创建一个新的空目录,该目录仅在测试 session 期间有效。我看到 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
最佳答案
更新:使用tmp_path
代替tmpdir
。 tmp_path
是 pathlib.Path/pathlib2.Path . tmpdir
是一个 py.path (实际上是 LocalPath ),它提供的语法与 pathlib.Path 非常相似。参见 pytest issue .
开发人员不再推荐使用 py.path。
语法类似,例如:
def test_something_else(tmp_path):
#create a file "myfile" in "mydir" in temp directory
f1 = tmp_path / "mydir/myfile"
f1.parent.mkdir() #create a directory "mydir" in temp folder (which is the parent directory of "myfile"
f1.touch() #create a file "myfile" in "mydir"
#write to file as normal
f1.write_text("text to myfile")
assert f1.read_text() == "text to myfile"
原文:我调查了它,也发现了这种行为很奇怪,我在下面总结了我学到的东西,以供那些不那么直观的人使用。
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
中定义的固定名称,如果您将其作为参数名称,它会传递给您的测试函数。
示例用法:
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
)
关于python - 在 PyTest 中创建一个临时目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36070031/