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

Unlock This Lesson

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

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set your subtitle preferences in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please refer to our video player troubleshooting guide for assistance.

spec List

00:00 All right, so you’ve heard about some of the common problems that come up when you use mocking, such as typos, misspellings, and interface changes. Fortunately, there is something called spec in the mock module that we can use to prevent some of these common problems. When you’re configuring a Mock, you can pass a specification using the spec parameter.

00:25 Let me show you what I mean. We’re going to create a calendar,

00:31 and it’s going to be a Mock object, and we’ll use the spec parameter, and we pass this a string or a list of strings of objects that we claim are available within this calendar Mock object.

00:48 We had two functions in our calendar—one of them was called 'is_weekday' and the other one was 'get_holidays'. When we press Enter—oh, I haven’t imported Mock.

01:02 from unittest.mock import Mock.

01:08 Let’s try that again. So now we have this calendar Mock object and let’s look at the dir()

01:17 and we have the kind of built-in Mock object attributes and methods, but we also have 'get_holidays' and 'is_weekday'.

01:26 Let’s see what happens when we try to access one of those methods: calendar.is_weekday().

01:35 This returns a Mock object, which is good. That’s expected, that’s what we would want to happen. Let’s say that we want to try to access .is_weekday() but we have a typo and we accidentally put an extra y.

01:51 Now this raises an AttributeError, saying that the Mock object has no attribute 'is_weekdayy', with two y’s. This is catching a common problem of misspelling the names of attributes or methods or object interfaces. So as a reminder, if we just set calendar as a regular Mock object without a specso if we said calendar = Mock(), and we said calendar.is_weekday(), it would be a Mock object. Cool.

02:25 And if we did that again with the typo, it would return another Mock object because remember, Mock objects will create the attributes or the methods on the fly as you type them out.

02:37 But if we set the spec, use a spec parameter to define what attributes are available,

02:47 then when we try to access the mistyped one, we get an AttributeError. So this is super powerful. I highly recommend that you use spec to define what your module actually serves, actually has available.

Become a Member to join the conversation.