py.test 在哪里以及如何寻找夹具?我在同一文件夹的 2 个文件中有相同的代码。当我删除 conftest.py 时,找不到正在运行test_conf.py的cmdopt(也在同一文件夹中。 为什么不搜索 sonoftest.py?
# content of test_sample.py
def test_answer(cmdopt):
if cmdopt == "type1":
print ("first")
elif cmdopt == "type2":
print ("second")
assert 0 # to see what was printed
conftest.py 内容
import pytest
def pytest_addoption(parser):
parser.addoption("--cmdopt", action="store", default="type1",
help="my option: type1 or type2")
@pytest.fixture
def cmdopt(request):
return request.config.getoption("--cmdopt")
sonoftest.py 内容
import pytest
def pytest_addoption(parser):
parser.addoption("--cmdopt", action="store", default="type1",
help="my option: type1 or type2")
@pytest.fixture
def cmdopt(request):
return request.config.getoption("--cmdopt")
文档说
http://pytest.org/latest/fixture.html#fixture-function
- pytest 由于前缀test_而查找test_ehlo。测试函数需要一个名为 smtp 的函数参数。匹配的夹具 通过查找名为 啪。
- 调用 smtp() 来创建实例。
- test_ehlo() 被调用并在测试函数的最后一行失败。
py.test 将导入conftest.py
和所有与python_files
模式匹配的 Python 文件,默认情况下test_*.py
。 如果您有测试夹具,则需要从conftest.py
或依赖于它的测试文件包含或导入它:
from sonoftest import pytest_addoption, cmdopt
这是顺序和 py.test 查找夹具(和测试)的位置(从这里获取):
py.test 在工具启动时按以下方式加载插件模块:
- 通过
通过加载所有内置插件
加载通过 SetupTools 入口点注册的所有插件。
通过预先扫描命令行中的
-p name
选项并在实际命令行解析之前加载指定的插件。通过加载命令行调用推断的所有
conftest.py
文件(测试文件及其所有父目录)。请注意, 默认情况下,子目录中的conftest.py
文件不会在 工具启动。通过在
conftest.py
文件中递归加载 pytest_plugins 变量指定的所有插件
我遇到了同样的问题,并花了很多时间来找出一个简单的解决方案,这个例子适用于与我有类似情况的其他人。
- conftest.py:
import pytest
pytest_plugins = [
"some_package.sonoftest"
]
def pytest_addoption(parser):
parser.addoption("--cmdopt", action="store", default="type1",
help="my option: type1 or type2")
@pytest.fixture
def cmdopt(request):
return request.config.getoption("--cmdopt")
- some_package/sonoftest.py:
import pytest
@pytest.fixture
def sono_cmdopt(request):
return request.config.getoption("--cmdopt")
- some_package/test_sample.py
def test_answer1(cmdopt):
if cmdopt == "type1":
print ("first")
elif cmdopt == "type2":
print ("second")
assert 0 # to see what was printed
def test_answer2(sono_cmdopt):
if sono_cmdopt == "type1":
print ("first")
elif sono_cmdopt == "type2":
print ("second")
assert 0 # to see what was printed
你可以在这里找到一个类似的例子:https://github.com/pytest-dev/pytest/issues/3039#issuecomment-464489204和其他在这里 https://stackoverflow.com/a/54736376/6655459
来自官方 pytest 文档的描述:https://docs.pytest.org/en/latest/reference.html?highlight=pytest_plugins#pytest-plugins
作为注释,各个目录在
some_package.test_sample"
需要有__init__.py
文件才能加载插件pytest