Is there a way to somehow use pytest fixtures from conftest.py in a test class\'s setup? I need to initialize an object when the session starts and use it in so
I don't think you can do it directly. However, you can decorate the whole class with pytest.mark.usefixtures, if that helps:
@pytest.mark.usefixtures(['myfixture'])
class TestAAA(object):
...
IIRC, setup_method
will be called before any of the automatically applied fixtures.
You can also utilize autouse for class-level fixtures like so:
class TestAAA(object):
@pytest.fixture(autouse=True)
def init_aaa(self, myfixture):
...
I used this kind of a setup for a test class with pytest<=3.7.0 (it stopped working with pytest 3.7.1 release):
# conftest.py:
import pytest
# autouse=True does not work for fixtures that return value
# request param for fixture function is only required if the fixture uses it:
# e.g. for a teardown or parametrization. Otherwise don't use it.
@pytest.fixture(scope="session")
def myfixture():
return "myfixture"
# test_aaa.py
import pytest
class TestAAA(object):
@classmethod
@pytest.fixture(scope="class", autouse=True)
def setup(self, myfixture):
self.myfixture = myfixture
def test_function1(self):
# now you can use myfixture without passing it as param to each test function
assert self.myfixture == "myfixture"
For the example provided above, the object returned from the fixture can be set as an attribute of the test class. Any methods of this class will have access.
# test_fixture.py
import pytest
class TestAAA():
@pytest.fixture(scope="class", autouse=True)
def setup(self, myfixture):
TestAAA.myfixture = myfixture
def test_function1(self):
assert self.myfixture == "myfixture"
or if you inherit from unittest.Testcase
you can do the following
# test_fixture.py
import pytest
from unittest import TestCase
class TestAAA(TestCase):
@pytest.fixture(scope="class", autouse=True)
def setup(self, myfixture):
self.myfixture = myfixture
def test_function1(self):
self.assertEqual(self.myfixture, "myfixture")