pytest class scope parametrisation not working as expected

80 Views Asked by At

The idea is to re-create the 'connector' fixture for each 'port' parametrisation of the class. However, currently it only creates the fixture once for the whole test class and not on each param iteration. How would I make the fixtures scope only for each parametrisation of the class.

conftest.py -

@pytest.fixture(scope="class")
def connector():
    # RUN ON CREATE ...
    # connect to TCP
    
    yield tcp_client

    # RUN ON DESTROY ...
    # disconnect and destroy

test_device.py -

@pytest.mark.parametrize('ports', [0, 2], scope="class")
class TestDevice:

    device_info = load_device_info('device_model')['device']

    def test_power_on(self, switcher, ports):
            # switch power on for the port the device is on

    @pytest.mark.parametrize('inputs', device_info['inputs'])
    def test_init_inputs(self, inputs, connector, ports):
            # send some messages over TCP network and set the inputs for the device
            #     destroy and recreate the simple_tcp_client fixture after each iteration of the class parametrization when it reaches this function ...


    @pytest.mark.parametrize("samplerate", [samplerate for samplerate in SampleRate])
    def test_run_device_tests(self, samplerate, ports):
            # run tests on each device with different samplerates ...

I've also tried this in conftest but get the same issue:

@pytest.fixture(params=[0, 2], scope='class')
def ports(request):
    return request.param

The structure I want:

TestClass [port: '1', 2]
├─ power_on [port: 1]
├─ init_inputs [input: 1, 2], [new connector]
│  ├─ set inputs[1]
│  ├─ set inputs[2]
├─ run_test [samplerate [44100, 96000 ...]
│  ├─ run with [44100]
│  ├─ run with [96000]

TestClass [port: 1, '2']
├─ power_on [port: 2]
├─ init_inputs [input: 1, 2], [new connector]
│  ├─ set inputs[1]
│  ├─ set inputs[2]
├─ run_test [samplerate [44100, 96000 ...]
│  ├─ run with [44100]
│  ├─ run with [96000]

How it currently runs:

TestClass [port: '1', 2]
├─ power_on [port: 1]
├─ init_inputs [input: 1, 2], [new connector]
│  ├─ set inputs[1]
│  ├─ set inputs[2]
├─ run_test [samplerate [44100, 96000 ...]
│  ├─ run with [44100]
│  ├─ run with [96000]

TestClass [port: 1, '2']
├─ power_on [port: 2]
├─ init_inputs [input: 1, 2], [same connector]
│  ├─ set inputs[1]
│  ├─ set inputs[2]
├─ run_test [samplerate [44100, 96000 ...]
│  ├─ run with [44100]
│  ├─ run with [96000]

I'm new to pytest so maybe I'm not using fixtures and parametrization correctly?

1

There are 1 best solutions below

3
SystemSigma_ On

Have you tried not to use the class scope for your connector fixture?

@pytest.fixture
def connector():
    # RUN ON CREATE ...
    # connect to TCP
    
    yield tcp_client

    # RUN ON DESTROY ...
    # disconnect and destroy