How do I share fixtures between classes in pytest?

Viewed 280

I am trying to share class scope and method scope fixtures across different classes using pytest. Currently, I get a syntax error if I try to add a fixture from another class as shown below.

I am aware that one way to work around this is to not have the fixture enclosed by a class. However, enclosing the fixtures makes sense for what I am trying to do.

import pytest
class Test_example1(object):

    @classmethod
    @pytest.fixture(scope='class')
    def example1_fixture(self):
        print("example1_fixture setup")
        yield
        print("example1_fixture teardown")

    def test_1(self, example1_fixture):
        print("class example1::test_1")

# This works if I comment out the code causing errors
@pytest.fixture(scope='class')
def global_example_fixture():
    print("global_example_fixture setup")
    yield
    print("global_example_fixture teardown")

class Test_example2(object):

    @pytest.fixture(scope='class')
    def example2_fixture(self):
        print("example2_fixture setup")
        yield
        print("example2_fixture teardown")

    # Results in fixture not found error
    def test_1(self, example1_fixture):
        print("class example2::test_1")

    # Results in syntax error
    def test_2(self, Test_example1.example1_fixture, global_example_fixture):
        print("class example2::test_1")

    # This works...
    def test_2(self, example2_fixture, global_example_fixture):
        print("class example2::test_2")

I expect to be able to call the class level and method level fixtures across classes.

0 Answers
Related