Python mock multiple return values

浪尽此生 提交于 2019-11-27 11:16:08
Martijn Pieters

You can assign an iterable to side_effect, and the mock will return the next value in the sequence each time it is called:

>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'baz'

Quoting the Mock() documentation:

If side_effect is an iterable then each call to the mock will return the next value from the iterable.

As an aside, the test response is not 'y' or 'n' or 'yes' or 'no' will not work; you are asking if the expression (response is not 'y') is true, or 'y' is true (always the case, a non-empty string is always true), etc. The various expressions on either side of or operators are independent. See How do I test one variable against multiple values?

You should also not use is to test against a string. The CPython interpreter may reuse string objects under certain circumstances, but this is not behaviour you should count on.

As such, use:

response not in ('y', 'n', 'yes', 'no')

instead; this will use equality tests (==) to determine if response references a string with the same contents (value).

The same applies to response == 'y' or 'yes'; use response in ('y', 'yes') instead.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!