Pytest - Pass fixture into setup method

Viewed 18

I'm trying to pass fixture into setup method:

@pytest.fixture
def my_fixture():
    return 'value'


class TestSome:
    def setup(self, my_fixture):
        print(my_fixture)  # <bound method TestSome.test_some of <test_views.TestSome object at 0x7ffc80e9b730>>

    def test_method(self):
        assert True

But as you can see it's not working. To fix this I'm forced to do this way:

class TestSome:

    @pytest.fixture(autouse=True)
    def setup_smth_with_my_fixture(self, my_fixture):
        pass

    def test_some(self):
        assert False

Is there any way to pass fixture into setup method?

1 Answers

Rather than using classes with setup/teardown methods, you can put your setup/teardown logic into fixtures:

import pytest

expected_value = None


@pytest.fixture
def my_fixture():
  return 'value'

@pytest.fixture(autouse=True)
def setup(my_fixture):
  global expected_value
  expected_value = my_fixture


def test_some():
  assert expected_value == 'value'

That will often simplify the structure of your tests.

The fixtures documentation is a good read on this topic.

Related