How to let MagicMock behave like a dict?

前端 未结 2 1525
情话喂你
情话喂你 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
    

提交回复
热议问题