在结构项目中测试@pytest.fixture(scope="module")
时
├── main.py
├── pytest.ini
├── src
│ └── tasks
│ ├── __init__.py
│ └── conftest.py
└── tests
└── func
└── test_authors.py
pytest.ini
包含
[pytest]
xfail_strict=true
当测试文件包含 fixture 时 - tests/func/test_authors.py
,测试工作正常
import json, pytest
@pytest.fixture(scope='module')
def author_file_json(tmpdir_factory):
python_author_data = {
'Ned': {'City': 'Boston'},
'Brian': {'City': 'Portland'},
'Luciano': {'City': 'Sau Paulo'}
}
file = tmpdir_factory.mktemp('data').join('author_file.json')
print('file:{}'.format(str(file)))
with file.open('w') as f:
json.dump(python_author_data, f)
return file
def test_brian_in_portland(author_file_json):
with author_file_json.open() as f:
authors = json.load(f)
assert authors['Brian']['City'] == 'Portland'
- 如果我将固定装置
author_file_json
添加到conftest.py- 并运行
pytest --fixtures
- 它显示在跟踪中
- 但现在如果我运行
pytest测试/test_authors.py
- 我收到错误 -
未找到 E 固定装置“author_file_json”
- 我收到错误 -
- 并运行
我该如何解决这个问题?
最佳答案
将 conftest.py
文件放在与测试文件目录 (func
) 或测试用例文件的父目录之一处于同一级别的位置在您的项目工作区中(在您的情况下,tests
或项目的根目录
)。您当前将其放在同级目录 tasks
中,pytest 不会扫描该目录。
关于python - Pytest:测试文件中具有模块范围的固定装置可以工作,但在 conftest.py 中会引发错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51610771/