patch() as Decorator
And let’s do a similar test where we will mock the
requests.get() to have a side effect of a
Timeout. In order to have access to that
Timeout exception, we’ll say
from requests.exceptions import Timeout.
Then we’ll come into our
TestCalendar class and create a function called
.test_get_holidays_timeout() and this will take
self. And we’ll write a function in here, but first let’s think about what we want to mock.
So, we want the effect of
requests.get() to be a
Timeout exception. But we haven’t mocked the
requests module. The
requests module is imported in
my_calendar, so we’ve imported
requests because we need it to make a
GET request to our
What we want to do is mock this method
requests.get() and have it raise a
Timeout exception as a side effect. Let’s go back into
tests.py and we’ll use the
patch() function as a decorator to patch
requests.get(). So above the test, we’ll decorate it with the
And the first argument here is the path to the module that we want to mock, and it’s represented as a string. The path first starts with the module—and that means our local module,
'my_calendar' and then the module object that we want to patch.
We want to patch the
requests module—again, which we have imported in
my_calendar. So we’re using
@patch() to patch this particular object—let’s call it an object, just to be clear. This
my_calendar is the module and we’re patching this
requests object in our test.
And now we can write our test that verifies that when we call
get_holidays(), it should raise a
Timeout exception. So
with self.assertRaises(Timeout): we’ll call
get_holidays(). And then to run our test, we’ll create our entry point of
if __name__ == '__main__': we’ll run
Become a Member to join the conversation.