What Is patch()?
So far throughout this course, we’ve been doing things like mocking entire modules within the same file as our tests. So for example, here’s
my_calendar and I cleaned it up a little bit.
I removed all the tests and just have the core functions
get_holidays(). We’ve been things like
requests is a
Mock object and setting the side effects of
00:30 this is okay for very simple use cases and experimenting, but usually you would want to patch objects in separate files. Having your tests in a separate file is good for organization, it’s a good practice to do that, and you want to separate your mock objects from your actual codebase, right?
So, this is our codebase. This is our
my_calendar module. We don’t really want to have
Mock objects in here—we want to have them in our tests file.
So what I’ve done is I created another file called
tests.py. It is located in the same directory as
my_calendar.py and that’s going to be important because we’re going to be doing some importing.
What we’ll learn about next is the
patch() method. The
patch() method is really useful for importing
Mock objects into your tests—importing functionality from your codebase into your tests.
Become a Member to join the conversation.