Side Effects as an Iterable (Part 1)
Okay. So before moving away from side effects, let’s look at one more feature that I think is really cool. And that is using
.side_effect as an iterable.
00:10 Let’s say that when we make a request to our API—
get_holidays() API—it times out on the first time, and then it responds successfully on the second time.
The way we can do that is to say the
request.get()—remember, this is defined in our
.side_effect will first be a
We have this
Timeout exception imported. So we can set the
.side_effect as not just this callable, but a list, and the first side effect is a
Timeout and then the second one is a call to our
.log_request() function, which mocks a successful response.
And then in our test, we can say
with self.assertRaises(Timeout): we will call
get_holidays(). So again, this is saying that when we call
get_holidays(), we expect it to raise a
01:24 This is going to be the first side effect. And then after that, our second side effect is the call to our function, which returns a response successfully, so this test should pass.
And then we can verify that we’re actually calling
requests.get() twice. So, the first time is with the
Timeout, the second time is a successful response.
We can say
assert requests.get.—and remember, this is a
Mock object, so we have this attribute called
.call_count, and that should be
2. Let’s save that and we will open up a terminal. Whoops, I had a typo here—
requests. We’ll save that, open up a terminal, let’s clear the screen, and we’re going to run our test cases again.
Okay. So we have an error. That looks like
line 24, in get_holidays […]
'function' object has no attribute 'status_code'.
Become a Member to join the conversation.