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
Let me show you what I mean. We’re going to create a
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
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
from unittest.mock import Mock.
Let’s try that again. So now we have this
Mock object and let’s look at the
and we have the kind of built-in
Mock object attributes and methods, but we also have
Let’s see what happens when we try to access one of those methods:
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
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
spec—so if we said
calendar = Mock(), and we said
calendar.is_weekday(), it would be a
Mock object. Cool.
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.
But if we set the
spec, use a
spec parameter to define what attributes are available,
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.