patch() as Context Manager
Another form of
patch() is to use it as a context manager, so let me show you what that looks like. We can delete the decorator and we can delete the argument to our test function, and then use the context manager syntax—so
with and then
patch() and same thing we did as a decorator, so it’s the local module
and then the object that we want to patch, which is the
requests module. And then
as and let’s keep the same name, so
mocked_requests, and then bring this code inside of the context manager block.
And we’ve set the
.get() to be
Timeout. So, this should be good enough to run our tests. Let’s go ahead and try it out in the terminal. And it succeeds—there’s no syntax errors or anything like that.
This is just another form of the exact same functionality using
patch() to import
requests from a different file into our tests and have it scoped locally to whatever is inside that context manager block.
Become a Member to join the conversation.