Why would mock be adding __nonzero__ method calls?
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzling Curiosities
--
Chapters
00:00 Why Would Mock Be Adding __nonzero__ Method Calls?
01:11 Accepted Answer Score 23
02:17 Thank you
--
Full question
https://stackoverflow.com/questions/1404...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #unittesting #mocking
#avk47
ACCEPTED ANSWER
Score 23
Short answer:
If your mocked function does not have an explicit return_value or side_effect that returns, you will see this as Python attempts to evaluate the truthiness of your mock. Ensure your mock has one.
Either initialise it with one:
item = MagicMock(return_value=True)
or add one in:
item.return_value = True
Explanation:
When you do if not x:, you are probably thinking if x is False.
Python doesn't actually do this - it does if bool(x) is False (this is Python's truthiness concept - that values evaluate to True or False), and bool(x) is actually a call to x.__nonzero__() (or x.__bool__() in 3.x).
This is to provide Python's nice if behaviour - when you do if []:, a lot of languages would treat any object as True, but Python is designed to make code readable, so it delegates and a list's __nonzero__() method will return False if it is empty. This allows for more code that reads more naturally, and explains why you will see these calls.