I am trying to reuse some unit testing functionality. The only variable part is actually the set of test data. Therefore I encapsulate the testing logic in a class and inject the actual test data at object creation.
Unfortunately this does not seem to work with the @pytest.fixture decorator.
Some minimal code to reproduce.
This is the common definition of my test class in define_test.py:
#!/usr/bin/env python3
import pytest
class TestDemo:
def __init__(self, _data: list):
self.__testData = _data
@pytest.fixture(scope='module', params=self.__testData)
def fixture(self, request):
return request.param
def test(self, fixture):
foo = fixture
assert foo is not None
Intended usage would be something like this in use_test.py
#!/usr/bin/env python3
import define_test
data1 = [1, 2, 3, 4]
test1 = define_test.TestDemo(data1)
data2 = [4, 3, 2, 1]
test2 = define_test.TestDemo(data2)
Trying to run this code produces
define_test.py:9: in TestDemo
???
E NameError: name 'self' is not defined
I am pretty sure that the problem is, that one cannot simply apply the usual OO mechanisms to the pytest decorator. It seems as either the decorator is evaluated before even an instance of this class exists or it cannot handle instances at all.
So what would be the correct way of achieving the goal of reusable tests with variable data?