简体   繁体   English

unittest.mock.patch 的(未记录的)return_value 参数如何工作?

[英]How does the (undocumented) return_value argument for unittest.mock.patch work?

I've seen examples of unittest.mock.patch() and unittest.mock.patch.object() directly using a return_value argument.我已经看到了unittest.mock.patch()unittest.mock.patch.object()直接使用return_value参数的例子。

Example:例子:

with patch.object(ProductionClass, 'method', return_value=None) as mock_method:
    thing = ProductionClass()
    thing.method(1, 2, 3)

However, this argument is not officially documented for unittest.mock.patch() nor unittest.mock.patch.object() .然而,这个论点没有正式记录在unittest.mock.patch()unittest.mock.patch.object() (It is however used in the examples of the official documentation). (然而它在官方文档的示例中使用)。

Is this supported or is it undefined behavior?这是支持还是未定义的行为? Is it supposed to be documented and isn't?它应该被记录在案吗,不是吗? Do these examples work by coincidence?这些例子是巧合吗? What does this argument do;这个论点有什么作用? does it do something unintuitive, or is it self-explanatory?它做了一些不直观的事情,还是不言自明?

From the documentation for mock.patch :来自mock.patch的文档:

patch() takes arbitrary keyword arguments. patch()接受任意关键字参数。 These will be passed to AsyncMock if the patched object is asynchronous, to MagicMock otherwise or to new_callable if specified.这些将被传递到AsyncMock如果修补的物体是异步的,以MagicMock否则或new_callable如果指定。

From the documentation of mock.patch.object :mock.patch.object的文档:

Like patch() , patch.object() takes arbitrary keyword arguments for configuring the mock object it creates.patch()一样, patch.object()任意关键字参数来配置它创建的模拟对象。

And from the documentation of mock.Mock , where it is actually used:mock.Mock的文档来看,它实际使用的地方:

return_value : The value returned when the mock is called. return_value :调用模拟时返回的值。 By default this is a new Mock (created on first access).默认情况下,这是一个新的 Mock(在第一次访问时创建)。 See the return_value attribute.请参阅return_value属性。

And for good measure, the documentation of the return_value attribute, which shows the usage with examples:为了更好地衡量, return_value属性的文档,其中显示了示例的用法:

Set this to configure the value returned by calling the mock:设置此项以配置通过调用模拟返回的值:

>>> mock = Mock()
>>> mock.return_value = 'fish'
>>> mock()
'fish'

The default return value is a mock object and you can configure it in the normal way:默认返回值是一个模拟对象,您可以按正常方式配置它:

>>> mock = Mock()
>>> mock.return_value.attribute = sentinel.Attribute
>>> mock.return_value()
<Mock name='mock()()' id='...'>
>>> mock.return_value.assert_called_with()

return_value can also be set in the constructor: return_value也可以在构造函数中设置:

>>> mock = Mock(return_value=3)
>>> mock.return_value
3
>>> mock()
3

So, as you can see, this is all well documented, though admittedly it may be overlooked at a first glance due to the arguments not present in the signature.因此,正如您所看到的,这一切都有据可查,尽管不可否认,由于签名中不存在参数,乍一看可能会忽略它。

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

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