Skip to content

@pytest.fixture(autouse=True) on methods on base classes run in a different order for TestCase and non-TestCase #8412

Open
@nedbat

Description

@nedbat

I have an existing test suite that was based on unittest.TestCase. I used @pytest.fixture(autouse=True) on some methods to provide common behavior. The ordering of the fixtures and the setup differed depending on whether the class inherits from TestCase.

This shows the behavior:

import unittest
import pytest


class EnvironmentAwareMixin(object):
    @pytest.fixture(autouse=True)
    def _monkeypatch(self, monkeypatch):
        self._envpatcher = monkeypatch

    def set_environ(self, name, value):
        self._envpatcher.setenv(name, value)


# This arrangement works: _monkeypatch does run
class MyPytestBase(
    EnvironmentAwareMixin,
    ):
    pass

class TestAnotherThing(MyPytestBase):
    def test_another_thing(self):
        self.set_environ("X", "1")
        assert 1 == 1


# This arrangement fails: setup_method runs before _monkeypatch
class TestSomething(MyPytestBase):
    def setup_method(self):
        self.set_environ("X", "1")

    def test_something(self):
        assert 1 == 1


# This arrangement works: _monkeypatch runs before setUp
class MyUnittestBase(
    EnvironmentAwareMixin,
    unittest.TestCase,
    ):
    pass

class TestSomethingElse(MyUnittestBase):
    def setUp(self):
        self.set_environ("X", "1")

    def test_something_else(self):
        assert 1 == 1

Pytest version 6.2.2

Metadata

Metadata

Assignees

No one assigned

    Labels

    plugin: unittestrelated to the unittest integration builtin plugintopic: fixturesanything involving fixtures directly or indirectly

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions