Difference between side_effect within function vs side_effect in decorator

Question:

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
Asked By: Punter Vicky

||

Answers:

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
Answered By: MrBean Bremen
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.