简体   繁体   English

function 中的 side_effect 与装饰器中的 side_effect 之间的区别

[英]Difference between side_effect within function vs side_effect in decorator

What is the difference between passing side_effect in decorator vs setting within a function?在装饰器中传递 side_effect 与在 function 中设置有什么区别? When should I use one over the other?我什么时候应该使用其中一种?

   @patch(“my_class.Order.get_order”, side_effect=“mock_order”)
def test_order(self, mock_order):

This is the alternate way I'm using it这是我使用它的另一种方式

@patch(“my_class.Order.get_order”)
 def test_order(self, mock_order):
         mock_order.side_effect = self.mock_order

There is no difference apart from the time the side effect is set.除了设置副作用的时间外,没有任何区别。
In your example, where the side effect is set at the beginning of the test function, the two variants are interchangeable sematically, and it is a matter of taste which to use (I would say the decorator shows best that it is intented for the whole test, but there is also the consideration of readability if the decorator expression gets too long).在您的示例中,在测试 function 开始时设置了副作用,这两个变体在语义上是可互换的,使用哪个是一个品味问题(我会说装饰器最好地表明它是针对整个测试,但如果装饰器表达式太长,也会考虑可读性)。

In principle, there is a difference when the side effect is applied, as the decorator creates the patched object at load time, while assigning the side effect in the test assigns it only at runtime.原则上,应用副作用存在差异,因为装饰器在加载时创建修补的 object,而在测试中分配副作用仅在运行时分配。 Though as far as I can see, this does not impact the test functionality.尽管据我所知,这不会影响测试功能。

This is only true, if a globally known variable or function is used as side effect in the first method, as the class itself is not defined yet, and no class instance exist at load time.仅当在第一种方法中使用全局已知变量或 function 作为副作用时才如此,因为 class 本身尚未定义,并且在加载时不存在 class 实例。 If you want to use an attribute or method of the class itself, only the second variant will work at all.如果您想使用 class 本身的属性或方法,则根本只有第二个变体有效。 Any side effect that depends on the test class itself will not work.任何依赖于测试 class 本身的副作用都不起作用。

If you want to set the side effect only later in your test, or want to change it during the test, obviously only the second variant can be used.如果您只想在测试后期设置副作用,或者想在测试期间更改它,显然只能使用第二个变体。

To summarize:总结一下:

  • you can always use the second variant (setting the side effect at runtime)您始终可以使用第二个变体(在运行时设置副作用)
  • the second variant gives you the ability to change the side effect later (though that is seldom useful)第二个变体使您能够稍后更改副作用(尽管这很少有用)
  • you can use the decorator version if the side effect does not depend on the test class itself, or on any object only created at runtime如果副作用不依赖于测试 class 本身,或者仅在运行时创建的任何 object ,则可以使用装饰器版本
  • if you are able to use the decorator version, it is semantically equivalent to the second variant如果您能够使用装饰器版本,它在语义上等同于第二个变体

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

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