2020年8月13日 星期四

[ Python 常見問題 ] unittst - Mocking python function based on input arguments

 Source From Here

Question
We have been using Mock for python for a while. Now, we have a situation in which we want to mock a function:
  1. def foo(self, my_param):  
  2.     #do something here, assign something to my_result  
  3.     return my_result  
Normally, the way to mock this would be (assuming foo being part of an object):
  1. self.foo = MagicMock(return_value="mocked!")  
Even, if i call foo() a couple of times i can use:
  1. self.foo = MagicMock(side_effect=["mocked once""mocked twice!"])  
Now, I am facing a situation in which I want to return a fixed value when the input parameter has a particular value. So if let's say "my_param" is equal to "something" then I want to return "my_cool_mock"

This seems to be available on mockito for python:
  1. when(dummy).foo("something").thenReturn("my_cool_mock")  
I have been searching on how to achieve the same with Mock with no success? Any idea?

How-To
If side_effect is a function then whatever that function returns is what calls to the mock return. The side_effect function is called with the same arguments as the mock. This allows you to vary the return value of the call dynamically, based on the input. Consider below function my_side_effect:
  1. def my_side_effect(value):  
  2.     return value + 1  
Then we can use it to customized the mock function output:
>>> m = MagicMock(side_effect=my_side_effect)
>>> m(1)
2
>>> m(2)
3
>>> m.mock_calls
[call(1), call(2)]


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...