pytest-dev / pytest-dev/pytest-mock

Provide a helper to copy args

Open
#37 6 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

enhancement
Dominant language
Python
Stars
2k
Forks
173
Avg merge
1d 10h
Merged PRs (30d)
6

Description

mock will store references in call_args and call_args_list (see https://docs.python.org/3/library/unittest.mock-examples.html#coping-with-mutable-arguments).

I think that pytest-mock could provide a helper based on the example from the doc:

from copy import deepcopy
>>> class CopyingMock(MagicMock):
...     def __call__(self, *args, **kwargs):
...         args = deepcopy(args)
...         kwargs = deepcopy(kwargs)
...         return super(CopyingMock, self).__call__(*args, **kwargs)

The following works (by extending the pytest-mock mocker fixture).

@pytest.fixture
def mocker(mocker):
    from copy import deepcopy
    from mock import MagicMock

    class CopyingMock(MagicMock):
        def __call__(self, *args, **kwargs):
            args = deepcopy(args)
            kwargs = deepcopy(kwargs)
            return super(CopyingMock, self).__call__(*args, **kwargs)

    mocker.CopyingMock = CopyingMock
    return mocker
    patched = mocker.patch('foo.bar', new_callable=mocker.CopyingMock)

Not sure if that's helpful enough and/or if there could be a mocker_copy fixture instead, which would handle new_callable not only for patch().

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 issue discussion and the linked unittest.mock example, then inspect the existing mocker fixture and its patch() and new_callable entry points. Clarify whether the project should provide a CopyingMock helper, a separate fixture, or both, and define tests for the chosen public API and copied call arguments.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
testing
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.