[英]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:总结一下:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.