Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/wimglenn/copyingmock

A subclass of MagicMock that copies the arguments
https://github.com/wimglenn/copyingmock

Last synced: 3 days ago
JSON representation

A subclass of MagicMock that copies the arguments

Awesome Lists containing this project

README

        

Copying Mock
============

|pypi|_ |pyversions|_ |actions|_ |codecov|_ |womm|_

.. |pypi| image:: https://img.shields.io/pypi/v/copyingmock.svg
.. _pypi: https://pypi.org/project/copyingmock

.. |pyversions| image:: https://img.shields.io/pypi/pyversions/copyingmock.svg
.. _pyversions:

.. |actions| image:: https://github.com/wimglenn/copyingmock/actions/workflows/ci.yml/badge.svg
.. _actions: https://github.com/wimglenn/copyingmock/actions/workflows/ci.yml/

.. |codecov| image:: https://codecov.io/gh/wimglenn/copyingmock/branch/master/graph/badge.svg
.. _codecov: https://codecov.io/gh/wimglenn/copyingmock

.. |womm| image:: https://cdn.rawgit.com/nikku/works-on-my-machine/v0.2.0/badge.svg
.. _womm: https://github.com/nikku/works-on-my-machine

``MagicMock`` has problems when used on a function with mutable arguments. This is called out in the `documentation `_:

Another situation is rare, but can bite you, is when your mock is called with mutable arguments. ``call_args`` and ``call_args_list`` store references to the arguments. If the arguments are mutated by the code under test then you can no longer make assertions about what the values were when the mock was called.

They then go on to propose a workaround, using ``side_effect``, but it's not very likable. There is also an elegant recipe offered which copies arguments at call-time. It's simply a subclass of ``MagicMock`` which copies the arguments, instead of storing references. I'm not sure why the recipe wasn't included directly in ``mock``, so here it is as a third-party package.