pytest如何以及在哪里找到固定装置

问题描述 投票:29回答:3

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

content of 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")

content of 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

  1. pytest因test_前缀而找到test_ehlo。测试函数需要一个名为smtp的函数参数。通过查找名为smtp的夹具标记函数来发现匹配夹具功能。
  2. 调用smtp()来创建实例。
  3. 调用test_ehlo()并在测试函数的最后一行失败。
python fixtures pytest
3个回答
31
投票

py.test将导入conftest.py和所有匹配python_files模式的Python文件,默认为test_*.py。如果您有测试夹具,则需要从conftest.py或依赖它的测试文件中包含或导入它:

from sonoftest import pytest_addoption, cmdopt

19
投票

以下是py.test查找夹具(和测试)的顺序(取自here):

py.test以下列方式在工具启动时加载插件模块:

  1. 通过加载所有内置插件
  2. 通过加载通过setuptools入口点注册的所有插件。
  3. 通过预扫描-p name选项的命令行并在实际命令行解析之前加载指定的插件。
  4. 通过加载命令行调用推断的所有conftest.py文件(测试文件及其所有父目录)。请注意,默认情况下,子目录中的conftest.py文件未在工具启动时加载。
  5. 通过递归加载conftest.py文件中pytest_plugins变量指定的所有插件

1
投票

我遇到了同样的问题,并花了很多时间找出一个简单的解决方案,这个例子适用于其他与我有类似情况的人。

  • conf test.朋友:
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加载插件

© www.soinside.com 2019 - 2024. All rights reserved.