How to let MagicMock behave like a dict?

前端 未结 2 1524
情话喂你
情话喂你 2021-02-18 17:36

mock(http://mock.readthedocs.org/en/latest/index.html) is a great tool in python for unit test. It can conveniently mock a method or class or dict.But I encountered a problem wh

相关标签:
2条回答
  • 2021-02-18 17:50

    Why mess around with __iter__? It seems to me that you want to mess with __contains__:

    >>> import mock
    >>> m = mock.MagicMock()
    >>> d = {'foo': 'bar'}
    >>> m.__getitem__.side_effect = d.__getitem__
    >>> m.__iter__.side_effect = d.__iter__
    >>> m['foo']
    'bar'
    >>> 'foo' in m
    False
    >>> m.__contains__.side_effect = d.__contains__
    >>> 'foo' in m
    True
    
    0 讨论(0)
  • 2021-02-18 18:02

    You can always just create some silly class to do the same thing.

    In [94]: class MockResponses(dict):
       ....:     def redundantErrorResponses(self):
       ....:         return {}
    
    0 讨论(0)
提交回复
热议问题