Side Effects: Testing
00:00
Let’s get back to side effects. You could say that the side effect of get_holidays()
was that it raised a ConnectionError
exception. We didn’t return the .json()
, we didn’t return None
, but there was a side effect of an exception being raised.
00:19
So let’s use the .side_effect
attribute of the Mock
object to allow us to control this and test different side effects. So we’re going up to our imports.
00:29
Let’s also import requests.exceptions
—or rather, we’ll import them one at a time. From requests.exceptions
we’ll import this ConnectionError
.
00:45
And then instead of using the actual requests
module, we’ll say requests
is now a Mock
object. This will give us access to that .side_effect
attribute.
00:57
And then in our unit test down here, we’ll say requests.get.side_effect = ConnectionError
. We are explicitly making the .get()
method have a .side_effect
of ConnectionError
. Here’s the .get()
method again, and now since we’ve mocked requests
and we’re using it here, any call to using .get()
is going to have a side effect of raising a ConnectionError
.
01:33
So even if this URL was valid and there was a /holidays
endpoint that returned 200
, it would still return the .json()
, but it would also have the side effect of raising a ConnectionError
in this test. So then to actually test that, we can say with self.assertRaises(ConnectionError)
.
01:56
Wow. That’s a lot of popups. Okay. ConnectionError
.
02:04
So we’re saying with self.assertRaises(ConnectionError):
we want to call the get_holidays()
function.
02:15
If you’re unfamiliar with this construct, it’s just saying when we call get_holidays()
, we expect it to raise a ConnectionError
.
02:26
Let’s see what happens when we run this test. Down here in the entry point we’ll delete this line. And the way that we can invoke the unittest
module to run our tests is we can just say unittest.main()
.
02:42
And then it knows to look for these classes that inherit from unittest.TestCase
, and then run each function within the class. I’m going to clear the screen in the terminal and we’ll run python my_calendar
.
Become a Member to join the conversation.