从 args 动态设置 pytest fixture 的范围

set pytest fixture's scope dynamically from args

一点背景知识:

我想动态配置fixture的作用域,请问如何实现?

是否可以配置像“--scope={scope}”这样的 pytest args 并将其提供给 fixture。?

伪代码片段:

@pytest.fixture(scope="function")
def test_helper(request):
    # Configure browser

    browser = # Saucelab browser
    yield browser
    browser.quit()

您可以为您的夹具创建一个选项来使用并告诉 pytest 使用 kwarg scope=callable

使其动态化

https://docs.pytest.org/en/6.2.x/fixture.html#dynamic-scope

def pytest_addoption(parser):
    parser.addoption('--precious', default=None, help='cli to set scope of fixture "precious"')

def myscope(fixture_name, config):
    scope = config.getoption(fixture_name) or 'function'
    return scope

ring_count = Counter()

@fixture(scope=myscope)
def one_ring(request):
    response = Object()
    yield response 
    ring_count[id(response)] += 1
    # do something here to assert about the id of precious
    if request.config.option.precious:
        assert len(ring_count) == 1

def test_lord(precious):
    """a test about dynamic scope."""

def test_owner(precious):
    """if --precious, then precious is the one ring that all tests get."""