Another way you can do this is by using
create_autospec. So if we say
from unittest.mock import create_autospec, we can say
calendar = create_autospec() of
I misspelled it again. And then if we look at
calendar, it’s going to be a
NonCallableMagicMock. This is kind of outside the scope of this course, but essentially it’s a
Mock object, and its
spec is coming from the module
If we look at the
calendar, again, we’ll see
'requests'—all these things that are coming from the
And we can do the same thing,
and then try to misspell it, and we get an
AttributeError. And the cool thing about
autospec is that we can actually use that in our
patch() function, whether as a decorator or a context manager.
01:16 Let me show you what that looks like.
We can say
with patch(), and since we’re in the same directory as
my_calendar, you can just say
'__main__.my_calendar' and then pass in this
autospec parameter and set it to
So what that’s going to do is create a specification that is the interface of
my_calendar as the
Mock object, so we’ll have the same interface and avoid those typos and misspellings—those common errors that come up. And then we say
as calendar: and we can say
calendar.is_weekday(), so that should be fine.
Let’s try one that doesn’t exist, so
calendar.is_a_holiday_foo()—something that I know doesn’t exist. So when we execute this—well, ha, we haven’t imported
from unittest.mock import patch, and let’s go ahead and run that again.
You get an
AttributeError and it’s pointing at this particular line:
.is_a_holiday_foo(). So it worked for this one, didn’t work for this one, and that’s great because we’ve
autospec-ed it, so the interface for the
Mock is the same as the interface for the actual module.
Become a Member to join the conversation.