[英]Make a python py.test unit test run independantly of the location where py.test in executed?
可以说我的代码看起来像这样
import pytest
import json
@pytest.fixture
def test_item():
test_item = json.load(open('./directory/sample_item_for_test.json','rb'))
return test_item
def test_fun(test_document):
assert type(test_item.description[0]) == unicode
我想通过Py.Test运行此测试
如果我从它所在的目录运行Py.test,那就很好。 但是,如果我从上述目录中运行它,则由于找不到“ sample_item_for_test.json”而失败。 无论我在哪里执行Py.test,有没有办法使此测试正确运行?
魔术属性__file__
是文件系统上python文件的路径。 因此,您可以将其与os
一起使用,以获取当前目录...
import pytest
import json
import os
_HERE = os.path.dirname(__file__)
_TEST_JSON_FILENAME = os.path.join(_HERE, 'directory', 'sample_item_for_test.json')
@pytest.fixture
def test_item():
with open(_TEST_JSON_FILENAME, 'rb') as file_input:
return json.load(file_input)
当我迁移到py.test时,我有大量的旧式测试习惯于在测试文件所在的目录中执行。 我没有跟踪每个测试失败,而是在每次测试开始之前将pytest钩子添加到conftest.py
到chdir的test目录中:
import os
import functools
def pytest_runtest_setup(item):
"""
Execute each test in the directory where the test file lives.
"""
starting_directory = os.getcwd()
test_directory = os.path.dirname(str(item.fspath))
os.chdir(test_directory)
teardown = functools.partial(os.chdir, starting_directory)
# There's probably a cleaner way than accessing a private member.
item.session._setupstate.addfinalizer(teardown, item)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.