简体   繁体   English

Python将对象作为side_effect传递给ock.patch

[英]Python passing an object as side_effect to mock.patch

I'm in an argument with my lecturer -- he insists that an object can be passed to mock.patch as value of side_effect to mock out an original function in program, while still taking the arguments passed to that function -- in this particular case, storing them inside the object. 我和我的讲师争论不休-他坚持认为可以将对象作为side_effect的值传递给mock.patch,以模拟程序中的原始函数,同时仍然接受传递给该函数的论点-特别是情况下,将它们存储在对象中。

Basically: 基本上:

with mock.patch('function_to_be_mocked', side_effect=my_object) as m:
    function_to_be_mocked(arg1, arg2)

After these two lines of code, arg1 and arg2 will be stored as attributes in my_object. 在这两行代码之后,arg1和arg2将作为属性存储在my_object中。

However according to documentation for side_effect , the only objects that can be passed to side_effect are either Exceptions or iterables, and neither cares about the arguments passed to original function. 但是,根据side_effect的文档,唯一可以传递给side_effect的对象是Exception或Iterables,并且它们都不关心传递给原始函数的参数。

I tried to point out this error, but my lecturer said there's a way to get it around. 我试图指出这个错误,但是我的讲师说有一种解决方法。

Is there actually a way to do it, or just my lecturer refused to admit his mistake? 实际上有办法吗,还是只是我的讲师拒绝承认自己的错误?

I think he is right. 我认为他是对的。 We can assign callables to side_effect, and the callable will be called with the same arguments the function_to_be_mocked was called with arg1 , arg2 . 我们可以将callable分配给side_effect,并且可调用function_to_be_mocked将使用与arg1arg2调用function_to_be_mocked相同的参数来调用。

source and examples: https://docs.python.org/3.6/library/unittest.mock.html#unittest.mock.Mock.side_effect 来源和范例: https//docs.python.org/3.6/library/unittest.mock.html#unittest.mock.Mock.side_effect

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM