Skip to content

Mock patching does not work after module is reloaded #104520

Closed as not planned
Closed as not planned
@edwardwang888

Description

@edwardwang888

Bug report

If a part of a module is patched via unittest.mock, reloading the module does not carry over the desired patching behavior. A new patch must be created on the reloaded module if patching is desired.

import importlib
from unittest import mock

import mymodule


with mock.patch('mymodule.value') as mock_value: 
    # Function is mocked correctly
    mock_value.return_value = 10
    print(mymodule.value_plus_one(1234))
    
    # Function is not mocked correctly after reloading
    importlib.reload(mymodule)
    print(mymodule.value_plus_one(1234))

    # Setting the return value again does not help
    mock_value.return_value = 10
    print(mymodule.value_plus_one(1234))

    # Mock object must be recreated for function to be mocked correctly
    with mock.patch('mymodule.value') as mock_value:
        mock_value.return_value = 20
        print(mymodule.value_plus_one(1234))

mymodule.py:

def value(val):
    return val


def value_plus_one(val):
    return value(val) + 1

Output:

11
1235
1235
21

Your environment

  • CPython versions tested on: Python 3.11.3 (main, Apr 19 2023, 18:51:09)
  • Operating system and architecture: [Clang 14.0.6 ] on darwin

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions