patch.object() as Context Manager
Now, what if you don’t want to mock an entire module, but you only want to mock a particular object within that module? Well, fortunately, we have a function called
patch.object() to do exactly that.
patch.object() can be used as a context manager or a decorator just as
patch() can. Let me show you what that looks like. So it’s basically the same thing here, except that this argument is no longer the path to the object that you want to mock—it needs to be the object itself.
So this needs to be
requests and we want to patch
requests.get(), and that is coming from
my_calendar.py. So again, just higher level, remember that we’re testing
and we can use it as the first argument here to
patch.object(). Then the second argument is the object that we want to patch. We’ve brought in this
requests module and we want to patch
'get', and this is a string. And then we can set the attributes, the
Mock object attributes that we are now familiar with, such as
02:30 And I’m getting a syntax kind of warning here saying that it’s not used, it’s an Unused variable. We actually don’t need to use it since we’re already, you know, we’re patching it, we’re not using this variable directly.
and the test succeeds. Let’s just try to break this just to make sure we’re actually doing something that’s working, so I’m just going to change this to
'getz'—just, I don’t think there’s an attribute in the
requests module—or an object, rather—called
Become a Member to join the conversation.