Side Effects: Setting Up
I’m going to make a little more space in this file, just come down here, and we’ll write a new function. Let’s use the
requests module, so we’ll import
And with the theme of this calendar thing we have going on, we’ll define a function called
get_holidays() will take no parameters. And we’ll make a request, let’s say
r = requests.get().
And let’s make up a little server here, let’s say we’re running on
If you’re not familiar with the
requests module, it provides a library of functions to make HTTP requests and a lot more. But essentially, this
r is making a
GET request to this URL.
After it makes this
GET request, it’ll check the status code. So we’ll say if
r.status_code == 200—meaning a successful response—we’ll return that response as JSON, and anything else will just return
So we have this little
get_holidays() function that hits an API, and who knows what this API does, but we check the response code. If it’s successful, we’ll return a dictionary of its JSON. And say we want to now test this function.
Let’s use the built-in
unittest framework and we’ll go down and make a class called
TestGetHolidays, and this will inherit from
We will need to import
import unittest—and if you’re unfamiliar with the
unittest framework, you have to create a class and then you define functions within that class for each test case.
So this class will represent all of our unit tests for the
get_holidays() function—that’s why I named it get
TestGetHolidays. And for our first test, let’s define a function called
You have to give it
self. And this is where we start to play with the side effects, but before we do that, let’s just
pass here for a second and let’s see what happens when we actually call this
get_holidays() function as it is.
Become a Member to join the conversation.