Configure Mocks (Part 1)
00:00
All right, we’re going to switch gears into talking about how you can configure your Mock
objects. I’m going to start an IPython session. And let’s do from unittest.mock
, import the Mock
class.
00:15
What we’ve done so far is something like mock = Mock()
and then mock.side_effect
is maybe a KeyError
exception. And we’ve kind of configured our Mock
attributes line by line, like .call_count = 0
and mock.return_value = True
.
00:40
And then we can use our Mock
object and see how it raises a KeyError
because we’ve set the .side_effect
. Rather than setting these attributes of the Mock
object line by line, we can set them when we first initiate the Mock
object by using the .__init__()
method that comes with this Mock
class.
01:02
I’ll clear the screen and show you what I mean. Instead of doing it line by line, we can just say mock = Mock()
and then within the parentheses, we can define our return_value
, our side_effect
, or whatever we want to do. Let’s say the side_effect
is an AttributeError
.
01:24
And then when we press Enter, we have these attributes set already on our Mock
object. So when we call mock()
, we see that it’s an AttributeError
now.
01:38
That’s one way you can configure your mocks—during the initialization of the Mock
object. Another way is by using a function called .configure_mock()
,
01:53
and this is useful for when you want to change an attribute of a Mock
object that already exists. So for example, when we call mock()
, it raises an AttributeError
—but what if we didn’t want that anymore, or what if we wanted to change that?
02:12
What we could do is say mock.configure_mock()
, and then here we can set the side_effect
again. Maybe we don’t want to have a side effect this time.
02:26
So we configured Mock
to have no side effect, and this time when we call mock()
the exception isn’t raised and it returns True
because we originally set the .return_value
02:39
to be True
, right? So you can configure your Mock
through the .__init__()
method or use this .configure_mock()
in the same way, setting the attributes within the parentheses.
02:52
But this is a little more dynamic—you can do it with existing Mock
objects. And just to verify that one more time, let’s change the .return_value
.
Become a Member to join the conversation.