Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pytest: Using fixtures in setup_method

Tags:

python

pytest

Following this pattern: https://docs.pytest.org/en/latest/xunit_setup.html

How do I use/inject fixture_foo into setup_method

class TestClassX:
    def setup_method(self, method):
        # I need `fixture_foo` here

    def teardown_method(self, method):
        # N/A

    def test_cool(self, fixture_foo):
        # Why can `fixture_foo` be injected here and not in `setup_method`?

like image 230
X_Trust Avatar asked Mar 08 '19 17:03

X_Trust


People also ask

Can I use fixture in Parametrize pytest?

You can use such a simple parametrized fixture for more complex fixtures by combining the param value with some kind of factory. You can also alias the call to parametrize: numbers = pytest.

How do I use pytest fixtures?

To access the fixture function, the tests have to mention the fixture name as input parameter. Pytest while the test is getting executed, will see the fixture name as input parameter. It then executes the fixture function and the returned value is stored to the input parameter, which can be used by the test.

Can pytest fixtures use other fixtures?

A fixture can use multiple other fixtures. Just like a test method can take multiple fixtures as arguments, a fixture can take multiple other fixtures as arguments and use them to create the fixture value that it returns.

Can you use pytest fixtures with Unittest?

pytest supports running Python unittest -based tests out of the box. It's meant for leveraging existing unittest -based test suites to use pytest as a test runner and also allow to incrementally adapt the test suite to take full advantage of pytest's features.


1 Answers

You'd have to switch to the pytest-style fixturing to access fixtures. An equivalent of the setup_method can be achieved as follows:

@pytest.fixture
def f():
    return 'ohai'


class Test:
    @pytest.fixture(autouse=True)
    def setup_method_fixture(self, request, f):
        self.f = f
        self.method_name = request.function.__name__

    def test(self):
        assert self.method_name == 'test'
        assert self.f == 'ohai'

This autouse fixture will get called once per test method inside the class

like image 140
Anthony Sottile Avatar answered Oct 23 '22 03:10

Anthony Sottile