1

Python's unittest.mock built-in library provides patch.object, which let's you:

patch the named member (attribute) on an object (target) with a mock object.

With regular patch, you can easily replace an entire object with a MagicMock.

Is it possible to one patch an entire object (and not just one attribute) using patch.object?

I am using Python 3.8.6.


Research

It seems this question was asked 4.5 years ago: How to mock use patch.object to patch the whole object in python

However, no one answered, and the OP also seems to have had bugs elsewhere in his system.


Motivation

Why not just use patch? Because it's just easier, when the object is already imported, to use patch.object on it directly, instead of having to think about what target to provide to a regular patch.

Intrastellar Explorer
  • 3,005
  • 9
  • 52
  • 119
  • Why not use `patch` for that? It allows you to replace an object with your own (a `MagicMock` is just the default). Maybe I didn't understand the question... – MrBean Bremen Dec 16 '20 at 17:31
  • Yes @MrBeanBremen I have added a motivation section to the answer. It may not be the most quantitative motivation, but I just find myself often wishing I could use `patch.object` on an entire object. Also, thank you for responding. – Intrastellar Explorer Dec 16 '20 at 17:38
  • So basically you want to [monkeypatch](https://stackoverflow.com/questions/3765222/monkey-patch-python-class) an object. In `pytest` there is the `monkeypatch` fixture to do this, I don't know a similar feature in `unittest`. You could always roll your own, of course, for example by writing a simple context manager that patches the object and restores it on exit. – MrBean Bremen Dec 16 '20 at 18:50

0 Answers0