Side Effects: Another Test
Currently, this is kind of a useless test because, as we saw when we ran it without setting the
.side_effect, it raised the
ConnectionError automatically because I don’t have the holidays API running on my machine. But let’s set another side effect.
One of the other exceptions that come with this
requests module is a
Timeout meaning you make a request to a server, the server—there’s something wrong with it, or it’s just really slow. The response you get back might raise a
As we saw when we first made this
GET request, it returned a
ConnectionError, or rather it raised a
ConnectionError. It didn’t raise a
Timeout error, but we can actually test the
Timeout error by setting a
.side_effect in a test.
So let’s go ahead and copy this, we’ll copy this test here, and we’ll make a new one called
And then here we can set the
.side_effect to not a
ConnectionError, but a
Timeout. And we’ll say it raises a
when we call
get_holidays(). And we’ll go into the console and let’s run our tests once again.
And there we
Ran 2 tests and they both succeeded. So this shows that you can use the
.side_effect attribute to assign a side effect of a mocked function, like the
.get() method. Right now, like, you might not see the value of using
It almost feels like you’re cheating in a test. Like, why would you just test, you know, make the
Timeout and then it should just verify it—like, wouldn’t this always raise a
Timeout if you set the
.side_effect to a
Timeout? Well, yes it would.
But we’re going to continue exploring
.side_effect a little bit more and hopefully things will make more sense and you’ll see how you can use it to write better tests.
Become a Member to join the conversation.
vijay singh on April 28, 2023
It would really help to have the entire code set unless others are seeing all the lecture codes in the zip file