I'm using Python 3 with PyTest and have defined a number of fixture objects in conftest.py. The problem I'm having is that there are some fixture objects that will be needed by every test case. Requesting these fixture references in all test cases results in a lot of repeated boilerplate code.
Here's the fixture in conftest.py:
def fixtureA(request):
_fixture = FixtureA()
# initialize the fixture, do stuff with request
return _fixture
Here's the current test class, where I want to remove all fixtures from arguments for readability:
class TestSomeFeature(BaseTest):
def test_some_function(self, fixtureA, fixtureB, fixtureC):
fixtureA.doSomething()
# execute test case, do stuff with other fixtures
def test_some_other_function(self, fixtureA, fixtureB, fixtureC):
data = fixtureB.getData()
# execute test case
This approach works, but I'd like to find a way to use dependency injection (or similar) to automagically inject the fixtures in BaseTest attributes without having to specify them in every test case's argument list. I'm looking for something like this, but open to any other suggestions:
class BaseTest:
# This does not work, since pytest does not allow constructors in the test class
def __init__(fixtureA, fixtureB, fixtureC):
self.fixtureA = fixtureA
self.fixtureB = fixtureB
self.fixtureC = fixtureC
I want the test class to look like this, much cleaner!
class TestSomeFeature(BaseTest):
def test_some_function(self):
self.FixtureA.doSomething()
# execute test case
def test_some_other_function(self):
data = self.FixtureB.getData()
# execute test case