![](/img/trans.png)
[英]How can I provide a non-fixture pytest parameter via a custom decorator?
[英]How to read pytest cmd configs from a non-fixture function
conftest.py
def pytest_addoption(parser):
parser.addoption('--env', action='store', default='qa',
help='setup environment: development')
@pytest.fixture(scope="session", autouse=True)
def get_config(request):
environment = request.config.getoption("--env")
with open(environment, "r") as f:
config = json.load(f)
return config
库文件
class lib1():
def cal_message():
# get something from config, do something and return it, but how to get the config here
测试配置文件
import lib
def test_lib():
a = lib.lib1()
a.cal_message()
问题是如何从 lib.py 获取配置?
您可以向 pytest 添加自定义属性并以这种方式传递变量。
def pytest_addoption(parser):
parser.addoption('--env', action='store', default='qa',
help='setup environment: development')
@pytest.fixture(scope="session", autouse=True)
def get_config(request):
environment = request.config.getoption("--env")
pytest.custom_config = {"env":environment}
with open(environment, "r") as f:
config = json.load(f)
return config
并且,在 lib.py 中获取它:
import pytest
class lib1():
def cal_message():
env = pytest.custom_config["env"]
警告:这仅在从 pytest 测试会话的测试模块调用 lib.py 时才有效。 如果您尝试在独立脚本中使用它,它将不起作用。 例如python lib.py --env a
将不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.