如何从非夹具函数读取 pytest cmd 配置

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

lib.py

class lib1():
    def cal_message():
        # get something from config, do something and return it, but how to get the config here 

test_config.py

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 将不起作用。