This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author skrisman
Recipients michael.foord, skrisman
Date 2013-09-14.09:36:44
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1379151405.44.0.0889223840628.issue19016@psf.upfronthosting.co.za>
In-reply-to
Content
import mock
from collections import namedtuple

Foo = namedtuple('Foo', bar)
mock_foo = mock.create_autospec(Foo)

if mock_foo:
    print('the namedtuple is truthy')
else:
    print('the namedtuple is not truthy')


The expected behavior is that it should print "the namedtuple is truthy." Instead it prints "the namedtuple is not truthy." Almost all namedtuples are truthy, the exception being the nearly useless namedtuple with 0 fields. The problem stems from the fact that tuples have a __len__ defined which is what is used derive truthiness. MagicMocks define __len__ to be zero by default. Workarounds to the problem are very difficult because you cannot simply define __len__ to be a nonzero number and have the mock work correctly. 


In general MagicMock has defaults that encourage the mocks to be very truthy all around:

__bool__ -- True
__int__ -- 1
__complex__ -- 1j
__float__ -- 1.0
__index__ -- 1

So it was interesting to me to find out that __len__ was defined to be 0. The fix that I am proposing is to make 1 the new default for __len__. I believe this is a more useful default in general because an instance of a class with a __len__ attribute will likely be truthy far more often then not.


There are of course backwards compatibility issues to consider here, however I don't think many people are assuming this behavior. Certainly nobody in the python code base.
History
Date User Action Args
2013-09-14 09:36:45skrismansetrecipients: + skrisman, michael.foord
2013-09-14 09:36:45skrismansetmessageid: <1379151405.44.0.0889223840628.issue19016@psf.upfronthosting.co.za>
2013-09-14 09:36:45skrismanlinkissue19016 messages
2013-09-14 09:36:44skrismancreate