Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson


00:00 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 my_calendar.

00:23 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 my_calendar.

00:44 If we look at the dir() of calendar, again, we’ll see 'is_weekday', 'get_holidays', 'requests'all these things that are coming from the my_calendar module.

00:55 And we can do the same thing, calendar.is_weekday(),

01:02 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.

01:20 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 True.

01:41 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.

02:07 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 patch().

02:24 So from unittest.mock import patch, and let’s go ahead and run that again.

02:34 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.