16

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?

JPG
  • 82,442
  • 19
  • 127
  • 206

1 Answers1

33

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__.

wim
  • 338,267
  • 99
  • 616
  • 750
  • 1
    If you plan on altering the result of a subscriptable mock, note that you have to either change `MagicMock().__getitem__.return_value` or set a new variable equal to the result of the subscription `result = MagicMock()[1:999]`. – Chris Collett Jun 07 '21 at 17:38