python / python/cpython

Mocked value at method level not overriding class-level mock in unittest

Open
#122,726 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Bug report

Bug description:
Description

I encountered an issue where mocking a value at the method level does not override the class-level mock in unit tests. Even though the method-level mock should take precedence, the value from the class-level mock is still being used.

Steps to Reproduce

Create a test class with a class-level mock using @mock.patch.
Add a method-level mock to one of the test methods to override the class-level mock.
Run the tests and observe that the class-level mock value is still used instead of the method-level mock.

Expected Behavior

The method-level mock should override the class-level mock, and the value set in the method-level mock should be used in the test.

Actual Behavior

The class-level mock value is used, and the method-level mock is ignored.

Sample code
import unittest
from unittest import mock

# Function to be mocked
def get_value():
    return "original"

# Class-level mock
@mock.patch('module.get_value', return_value='class-level')
class TestMock(unittest.TestCase):

    def test_class_level_mock(self, mock_get_value):
        # This should return 'class-level'
        result = get_value()
        self.assertEqual(result, 'class-level')

    @mock.patch('module.get_value', return_value='method-level')
    def test_method_level_mock(self, mock_get_value):
        # This should return 'method-level', but it returns 'class-level'
        result = get_value()
        self.assertEqual(result, 'method-level')

if __name__ == '__main__':
    unittest.main()

CPython versions tested on:

3.10

Operating systems tested on:

No response

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 sample with unittest.mock.patch applied at both class and method level, then inspect the unittest.mock patch decorators and their interaction with unittest.TestCase methods. Confirm whether the method-level return value is ignored, and add or update a focused regression test showing the expected method-level override.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
testing-qa
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.