X Tutup
The Wayback Machine - https://web.archive.org/web/20250602140434/https://github.com/python/cpython/issues/93582
Skip to content

mock.patch applied at class level behaves incorrectly  #93582

Open
@r3m0t

Description

@r3m0t

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibPython modules in the Lib dirtype-bugAn unexpected behavior, bug, or error

    Projects

    Status

    No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      X Tutup