Skip to content

Document how to build dynamic session-scoped fixtures #10156

@sirosen

Description

@sirosen

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:
#2959 (comment)

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    status: help wanteddevelopers would like help from experts on this topictopic: fixturesanything involving fixtures directly or indirectlytype: docsdocumentation improvement, missing or needing clarification

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions