简体   繁体   中英

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? 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).

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. 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. If you want to use an attribute or method of the class itself, only the second variant will work at all. Any side effect that depends on the test class itself will not work.

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
  • if you are able to use the decorator version, it is semantically equivalent to the second variant

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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