mock.patch applied at class level behaves incorrectly
Nobody has claimed this yet.
- 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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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