feature request: fail on improper use of mock.side_effect
upstartjohnvandivier opened this issue ยท 2 comments
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
Alternative Solutions
feature request also filed on ruff astral-sh/ruff#6199 and we have considered a custom internal linter (not ideal ofc)
Thanks for writing!
Note that this is a thin-wrapper for easier pytest integration -- this library does not implement Mock.side_effect
, this is implemented in the unittest.mock
standard library.
I believe this issue should be brought up upstream.
Closing for now, feel free to follow up! ๐
Thanks @nicoddemus
Python language proposal created at https://discuss.python.org/t/feat-unittest-mock-side-effect-fails-on-improper-usage/31003
Support is welcome