What Is a Side Effect?
00:00
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.
00:21
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.
00:56
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 is_weekday()
function.
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.
01:18
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 .side_effect
.
01:29
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.