Sean
Sean

Reputation: 13

pytest session scoped fixture that takes parameterized argument from pytest_generate_tests()

Good afternoon,

I have a fixture that loads in a large amount of data that will have been logged overnight. This is then used in various tests which analyse different aspects of the data.

Loading this data takes quite a while so i only want the fixture to run once and pass the same data to each test. I read the way to do this was marking the fixture scope to session the issue then is that because the fixture takes in a command line argument (location of the test data) passed through pytest_generate_tests() i get the following error: ScopeMismatch: You tried to access the 'function' scoped fixture 'path' with a 'session' scoped request object, involved factories

Here is a simplified recreation:

conftest.py

import pytest

def pytest_addoption(parser):
    parser.addoption("--path", action="store", required=True, help='Path to folder containing the data for the tests to inspect, e.g. ncom files.')


def pytest_generate_tests(metafunc):
    # This is called for every test. Only get/set command line arguments
    # if the argument is specified in the list of test "fixturenames".
    if "path" in metafunc.fixturenames:
        metafunc.parametrize("path", ['../temp/' + metafunc.config.getoption("--path")])

Test file

import pytest

@pytest.fixture(scope='session')
def supply_data(path):
    data = path
    return data

def test_one(supply_data):
    assert supply_data=='a path', 'Failed'

Can anybody please suggest how to make this work or a better way to achive what i am trying to do?

Many thanks

Sean

Upvotes: 1

Views: 2046

Answers (1)

MrBean Bremen
MrBean Bremen

Reputation: 16805

If I understand this correctly, your path does not change during a test session, so it would be sufficient to read it in the fixture from the command line parameters:

@pytest.fixture(scope='session')
def supply_data(request):
    path = '../temp/' + request.config.getoption("--path")
    data = read_data_from_path(path)
    yield data

Upvotes: 2

Related Questions