Return Value (Part 1)
00:00 One of the main reasons of using mock objects is to control the behavior of your code during tests. And one way to do this is to control the return value of a function, whether it’s one of your own or one of your dependencies.
Let’s look at an example of how we can control the return value of a function. Create a new file. I called mine
calendar.py. And we’re going to import
from datetime import datetime.
It’s not really relevant or important in this course about mocks to learn about the
datetime package, which is a whole other video course in itself, but we’re going to use one or two of these methods to help us explore this idea of changing the return value of a function.
Create a method called
is_weekday(), and this is just going to basically tell us if today is a weekday or not. Let’s say
today = datetime.today() and for exploratory purposes, let’s just go ahead and print
And we’ll call our function
is_weekday() down here. Let’s head down into the terminal and run this program
calendar.py and we’ll see that this returns today’s date, which is December 1st, 2019.
And we’ll create another variable called
day_of_the_week and this is going to be
.weekday() method will return an integer from
0 is going to be Monday, and then
6 will be Sunday.
And let’s just verify that. We’ll print
run the program again, and today is
6, which is Sunday, and yeah—it is actually Sunday where I am right now. So the purpose of this method is to return
True if today is a weekday and
False if it’s a weekend today.
So essentially, we want the day of the week to be between
day_of_the_week is greater than or equal to
0, so Monday. And we want it to be less than Saturday, which is
I’m going to clean up here and delete these two lines—the comment and the print statement. And then let’s go ahead and print this return value of
It is Sunday today, so I expect this to be
False. I’m going to clear the screen and run the
calendar.py and it’s
False. Yours might return
True depending on what day of the week you’re writing this program. Cool.
Let’s write a test for
is_weekday(), so instead of printing it I’m just going to say
assert is_weekday(). Save that and run
calendar.py again, and we get an
is_weekday() is returning
False because today is Sunday. Again, your results may be different. When you’re writing tests, you want the results to be predictable.
03:16 Whether it’s a weekend or a weekday, we want our results to be the same every time we run our tests. And that’s really important, especially when you’re using something like continuous integration and continuous delivery—you don’t want your test to fail just because today is Sunday. In the next video, we’ll look at how we can use mocks to set the return value of this function.
Become a Member to join the conversation.
Felipe on Jan. 19, 2022
Great video, thanks.
December 1st, 2019: Weeks before the great pandemic of 2020.