pytest icon indicating copy to clipboard operation
pytest copied to clipboard

Document how to build dynamic session-scoped fixtures

Open sirosen opened this issue 3 years ago • 0 comments

My particular case was that I wanted a session-scoped fixture which was parametrized by some CLI arguments. This was much tougher than I expected it to be, and I think a doc example would help. I'm more than happy to write it up, but want to first make sure it's a welcome contribution.

The answer is a variant on the one provided many years ago here: https://github.com/pytest-dev/pytest/issues/2959#issuecomment-347458695

The only thing which needs a tweak is the self-arg. Combined with py3-only, and fleshed out with a CLI option, it becomes something like:

def pytest_addoption(parser):
    group = parser.getgroup("myopts")
    group.addoption(
        "--servers",
        help="comma-delimited servers to use",
        default="localhost",
        type=str,
    )

def pytest_configure(config):
    server_list = config.getoption("servers").strip().split(",")

    class DynamicFixturePlugin:
        @pytest.fixture(scope='session', params=server_list)
        def server_hostname(self, request):
            return request.param

    config.pluginmanager.register(DynamicFixturePlugin(), 'server-hostname-fixture')


@pytest.mark.parametrize(scope="session")
def server_connection(server_hostname):
    return connect_to_server(server_hostname)
  • Is this a good thing to document?
  • Did I understand the original example correctly?
  • Where should it go?

sirosen avatar Jul 19 '22 20:07 sirosen