Skip to content

Provide a helper to copy args #37

@blueyed

Description

@blueyed

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().

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions