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
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")
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的夹具标记函数来发现匹配夹具功能。
- 调用smtp()来创建实例。
- 调用test_ehlo()并在测试函数的最后一行失败。
py.test将导入conftest.py
和所有匹配python_files
模式的Python文件,默认为test_*.py
。如果您有测试夹具,则需要从conftest.py
或依赖它的测试文件中包含或导入它:
from sonoftest import pytest_addoption, cmdopt
以下是py.test查找夹具(和测试)的顺序(取自here):
py.test以下列方式在工具启动时加载插件模块:
- 通过加载所有内置插件
- 通过加载通过setuptools入口点注册的所有插件。
- 通过预扫描
-p name
选项的命令行并在实际命令行解析之前加载指定的插件。- 通过加载命令行调用推断的所有
conftest.py
文件(测试文件及其所有父目录)。请注意,默认情况下,子目录中的conftest.py
文件未在工具启动时加载。- 通过递归加载
conftest.py
文件中pytest_plugins变量指定的所有插件
我遇到了同样的问题,并花了很多时间找出一个简单的解决方案,这个例子适用于其他与我有类似情况的人。
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")
import pytest
@pytest.fixture
def sono_cmdopt(request):
return request.config.getoption("--cmdopt")
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
加载插件