What Is a Side Effect?
Okay, so you just learned how to use this
.return_value attribute from the
Mock object to set the return value of a function. But functions are sometimes really complex, and mocking the return value just isn’t enough to write a good test. Functions often have something called side effects.
A side effect of a function is something that happens—for example, printing to standard output, making a request to a web server, raising an exception—something beyond just the return value can be considered a side effect of a function. So if you have a function like this
is_weekday()—it takes no parameters and it just returns a Boolean—we might have something that says
print('i am in is_weekday'), and say we wanted to print that to the screen.
Or rather, we wanted to log that in some way to help us debug. This statement here would be considered a side effect of this
01:09 We’re not returning this log statement. We’re not returning a string, we’re still returning a Boolean, but we’re also doing something else while we’re in the function.
So this is a side effect. And if you looked closely at the
dir() representation of a
Mock object, you would have seen that there is an attribute called
In this video, we’re going to make a function and use that
.side_effect attribute to control these types of things that are different than the return—these so-called side effects.
Become a Member to join the conversation.