@@ -838,56 +838,6 @@ and the `return_value` will use your subclass automatically. That means all
838838children of a `CopyingMock ` will also have the type `CopyingMock `.
839839
840840
841- Multiple calls with different effects
842- -------------------------------------
843-
844- Handling code that needs to behave differently on subsequent calls during the
845- test can be tricky. For example you may have a function that needs to raise
846- an exception the first time it is called but returns a response on the second
847- call (testing retry behaviour).
848-
849- One approach is to use a :attr: `side_effect ` function that replaces itself. The
850- first time it is called the `side_effect ` sets a new `side_effect ` that will
851- be used for the second call. It then raises an exception:
852-
853- >>> def side_effect (* args ):
854- ... def second_call (* args ):
855- ... return ' response'
856- ... mock.side_effect = second_call
857- ... raise Exception (' boom' )
858- ...
859- >>> mock = Mock(side_effect = side_effect)
860- >>> mock(' first' )
861- Traceback (most recent call last):
862- ...
863- Exception: boom
864- >>> mock(' second' )
865- 'response'
866- >>> mock.assert_called_with(' second' )
867-
868- Another perfectly valid way would be to pop return values from a list. If the
869- return value is an exception, raise it instead of returning it:
870-
871- >>> returns = [Exception (' boom' ), ' response' ]
872- >>> def side_effect (* args ):
873- ... result = returns.pop(0 )
874- ... if isinstance (result, Exception ):
875- ... raise result
876- ... return result
877- ...
878- >>> mock = Mock(side_effect = side_effect)
879- >>> mock(' first' )
880- Traceback (most recent call last):
881- ...
882- Exception: boom
883- >>> mock(' second' )
884- 'response'
885- >>> mock.assert_called_with(' second' )
886-
887- Which approach you prefer is a matter of taste. The first approach is actually
888- a line shorter but maybe the second approach is more readable.
889-
890-
891841Nesting Patches
892842---------------
893843
0 commit comments