我的Python项目导入pytest
2.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
我对它进行了研究,也发现了这种行为的特殊性,并总结了我在下面学到的东西,供那些不太直观的人参考。
tmpdir
是pytest中预定义的fixture,类似于这里如何定义setup
:因此
tmpdir
是在pytest
中定义的一个固定名称,如果您将其作为参数名,则该名称将传递给您的testfunction。示例用法:
这在使用pytest运行它时有效,例如在终端中运行
py.test test_foo.py
。以这种方式生成的文件具有读写权限,以后可以在系统临时文件夹中查看(对我来说,这是/tmp/pytest-of-myfolder/pytest-1/test_create_file0
)更新:使用
tmp_path
,而不是tmpdir
。tmp_path
是一个pathlib.Path/pathlib2.Path。tmpdir
是一个py.path(实际上是LocalPath),它提供了与pathlib.Path非常相似的语法。见pytest issue。开发人员不再推荐使用py.path。
语法相同,例如:
您只需将tmpdir作为函数参数传递,因为它是py.test fixture。
相关问题 更多 >
编程相关推荐