python / python/cpython

mock.patch applied at class level behaves incorrectly

Open
#93,582 6 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

stdlib type-bug
Dominant language
Python
Stars
77.2k
Forks
36k
PR merge metrics
PR metrics pending

Description

Bug report

When applying @mock.patch to classes where the test_ method is inherited, this applies the patch to the base class,, instead of to the specific class. In this case, the patch to the g method applies in MockedFTests and MockedFStraightGTests.

# a.py
import unittest
from unittest import mock

def f():
    return 41

def g():
    return 43

class BaseFTests(unittest.TestCase):
    def test_a(self):
        self._asserts(f())

    def _asserts(self, val):
        print(self, val)

@mock.patch('a.f', new=lambda: 2)
class MockedFTests(BaseFTests):
    def _asserts(self, val):
        print(self, val)
        self.assertEqual(val, 2)
        self.assertEqual(g(), 43)

@mock.patch('a.g', new=lambda: 3)
class MockedFMockedGTests(MockedFTests):
    def _asserts(self, val):
        print(self, val)
        self.assertEqual(val, g()-1)

class MockedFStraightGTests(MockedFTests):
    def _asserts(self, val):
        print(self, val)
        self.assertEqual(val, 2)
        self.assertEqual(g(), 43)

Expect all tests to pass.
Actual output: 2 tests fail with error AssertionError: 3 != 43

Your environment

  • CPython versions tested on: Python 3.10.4 on Windows

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

Start by reproducing the example in a small module using unittest.mock.patch, focusing on inherited test_ methods and the classes BaseFTests, MockedFTests, MockedFMockedGTests, and MockedFStraightGTests. Trace the class-level patch behavior in unittest.mock and add a regression test for the reported inheritance case. Done means the example's tests pass without applying the subclass patch to sibling classes.

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
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.