python / python/cpython

new_callable arg to unittest.mock.patch seems not to support partial

Open
#137,145 3 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:

As in the title. The following code seems to disregard the partial and proceed to call the wrapped function right away (instead of calling the wrapping partial object).

from functools import partial
from unittest.mock import patch

def wrapped():
  """an exemplary response from `some.directory.module.my_function` function"""
    return [
        {
            "some_key": "some_value",
        }]

def test_some_func():
    with patch(
        "some.directory.module.my_function", new_callable=partial(wrapped)
    ):

    # calls `my_function` internally
    some.directory.module.another_function()

Running the above will produce: TypeError: 'list' object is not callable.
Acc. to the docs an object passed as new_callable argument should be called by patch to create a new dummy object replacing the target (some.directory.module.my_function). However it seems that instead of partial being called and returning a wrapped function, a wrapped function itself is called returning the list.

CPython versions tested on:

3.11

Operating systems tested on:

macOS

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 with the unittest.mock.patch entry point and its new_callable handling, using the partial(wrapped) reproducer in the report. Compare the observed call sequence with the documented contract, then add or update regression coverage so the target is replaced by the expected callable behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
testing
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.