Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a subscriptable Mock object?

Suppose, I have a code snippet as

foo = SomeClass()
bar = foo[1:999].execute()

To test this, I have tried something as

foo_mock = Mock()
foo_mock[1:999].execute()

Unfortunately, this raised an exception,

TypeError: 'Mock' object is not subscriptable

So, How can I create a subscriptable Mock object?

like image 634
JPG Avatar asked Oct 02 '20 18:10

JPG


Video Answer


1 Answers

Just use a MagicMock instead.

>>> from unittest.mock import Mock, MagicMock
>>> Mock()[1:999]
TypeError: 'Mock' object is not subscriptable
>>> MagicMock()[1:999]
<MagicMock name='mock.__getitem__()' id='140737078563504'>

It's so called "magic" because it supports __magic__ methods such as __getitem__.

like image 142
wim Avatar answered Sep 18 '22 12:09

wim