我想在 pytest 中设置一个可选参数,并在 test_ 方法之外访问它。
我有一个定义参数的conftest.py 文件:
def pytest_addoption(parser):
parser.addoption('--mode', action='store', default='STANDARD', help="STANDARD, DOCUMENTATION")
我想访问此“模式”外部测试/夹具。此参数用于设置在 setup_class 中初始化的代码的某些部分的行为:
class TestSomething:
def setup_class(cls):
cls.my_object = MyObject(mode)
----- 当前“工作”代码 -----
我有一个 arg_manager 文件:
class __Arg:
mode = ''
def test_init_args(mode):
__Arg.mode = mode
def get_mode():
return __Arg.mode
我的对象文件:
from arg_manager import *
class MyObject :
def __init__(self):
self.mode = get_mode()
在我的测试文件中
from myObject import *
class TestSomething:
def setup_class(cls):
cls.my_object = MyObject()
作为 pytest 的这项工作将通过开始导入在我的管理器中找到测试,但它很丑陋并且引发了很多 pylint / ruff / mypy 问题
对于 pytest,您可以使用
pytest_addoption()
注入 argparse 参数,并在测试中将其用作 @pytest.mark.parametrize()
装饰器:
在conftest.py中:
def pytest_addoption(parser):
parser.addoption("--webhost")
parser = argparse.ArgumentParser(description="description of your testsuite here")
parser.add_argument('--webhost', help='webhost to run tests on (default: %(default)s)', default=['test1'])
:
# --webhost must be a list, so --webhost=test1 is converted to ['test1']
if args.webhost and isinstance(args.webhost, str):
args.webhost = args.webhost.split(',')
在您的测试中,您可以将其用作参数 csv 列表:
@pytest.mark.parametrize("webhost", args.webhost)
def test01_service_up(self, webhost):
""" A particular test """
因此
pytest ./tests --webhost=test12,test1
将在两个虚拟主机上运行
这只适用于当前不存在的参数。