Feat: unittest.Mock.side_effect fails on improper usage

What’s the problem this feature will solve?

Mock.side_effect is tricky to use properly. Problem cases include:

setting the value to an array of length less than two, in which case return_value is more readable and debuggable
setting the value to an array of length n where the value doesn’t change. This can be dangerous when the value is another mock or otherwise mutable byref
Having the test simply fail in these cases prevents other hard-to-trace errors from arising in the first place.

Describe the solution you’d like

two proposed options:

throw an error which includes an instructive message like "please ensure that a method under side_effect is called more than once, otherwise prefer return_value
whenever side_effect is set, automatically create an assertion that the method under side effect is not called only once
this behavior would only trigger when the side_effect has a non-None return value; ie it is exempt if it is actually creating a side effect like throwing an error instead of being used as a sort of dynamic return_value tool

Open to others, of course

Additional Context



Love it John. I do have some implementation suggestions:

Implementations could include:

Improved Documentation: The documentation of Mock.side_effect could be expanded to cover these cases, advising developers on best practices.

Warnings Instead of Errors: Instead of throwing an error when Mock.side_effect is misused, a warning could be emitted. This would alert developers of the potential issue without breaking existing test code.

Introduce a New Method/Attribute: A new method or attribute could be added to the Mock class which encapsulates the proposed behavior, leaving the original Mock.side_effect intact. This would maintain backward compatibility while offering the new functionality to those who want it.