Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Side Effects as an Iterable (Part 1)

00:00 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—

00:16 our get_holidays() API—it times out on the first time, and then it responds successfully on the second time.

00:25 The way we can do that is to say the .side_effect of request.get()remember, this is defined in our get_holidays() function—the .side_effect will first be a Timeout.

00:38 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.

01:03 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 Timeout exception.

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.

01:39 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.

01:50 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.

02:20 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.