crmpicco
crmpicco

Reputation: 17181

Persisting PyTest data parameters across multiple test cases

Is there a way from me to persist the "ref" parameters across multiple test cases inside the same Python script?

This setup "works", but it feels sub-optimal to have to copy/paste the same data for each test case.

@pytest.mark.parametrize('ref', [
    'crmpicco1872',
    'crmpicco2001',
    'crmpicco2008',
    'crmpicco2013',
    'crmpicco2021',
])
def test_data_directory_does_not_already_exist(ref):
    datadir = f"/var/lib/data/sites/{ref}"

    assert not os.path.exists(datadir)


@pytest.mark.parametrize('ref', [
    'crmpicco1872',
    'crmpicco2001',
    'crmpicco2008',
    'crmpicco2013',
    'crmpicco2021',
])
def test_data_directory_is_created(logger_fixture, config_parser_fixture, clean_context_fixture, ref):
    datadir = f"/var/lib/data/sites/{ref}"

    clean_context_fixture.data = "data0"
    clean_context_fixture.ref = ref

    create_data = CreateData(logger_fixture, config_parser_fixture)
    create_data.execute(clean_context_fixture)

    assert os.path.exists(datadir)
    shutil.rmtree(datadir)

Upvotes: 0

Views: 645

Answers (1)

MrBean Bremen
MrBean Bremen

Reputation: 16805

I see two possibilities: just extract the parameters into a function and use it in parametrize:

def my_params():
    return [
        'crmpicco1872',
        'crmpicco2001',
        'crmpicco2008',
        'crmpicco2013',
        'crmpicco2021'
    ]

@pytest.mark.parametrize('ref', my_params())
def test_data_directory_is_created(logger_fixture, config_parser_fixture, clean_context_fixture, ref):
    ...

Or set the parameters in the pytest_generate_tests, provided you always want to use the same parameters for the ref argument:

def pytest_generate_tests(metafunc):
    if 'ref' in metafunc.fixturenames:
        params = [
            'crmpicco1872',
            'crmpicco2001',
            'crmpicco2008',
            'crmpicco2013',
            'crmpicco2021'
        ]
        metafunc.parametrize('ref', params)

def test_data_directory_is_created(logger_fixture, config_parser_fixture, clean_context_fixture, ref):
   ...

Note that this is out of my head and may contain typos.

Upvotes: 2

Related Questions