pytest-dev / pytest-dev/pytest

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

Open
#8,412 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

plugin: unittest topic: fixtures
Dominant language
Python
Stars
14.5k
Forks
3.4k
Avg merge
2d 9h
Merged PRs (30d)
35

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

No repository files or tests are named. Start by running the supplied reproduction with pytest 6.2.2 and trace fixture, setup_method, and setUp ordering for TestCase and non-TestCase classes. Done should explain the differing ordering and establish the intended behavior with coverage.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
testing-qa
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.