Created
August 7, 2012 02:36
-
-
Save daltonmatos/3280885 to your computer and use it in GitHub Desktop.
Hack to mock the python True object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import mock | |
class AlmostAlwaysTrue(object): | |
def __init__(self, total_iterations=1): | |
self.total_iterations = total_iterations | |
self.current_iteration = 0 | |
def __nonzero__(self): | |
if self.current_iteration < self.total_iterations: | |
self.current_iteration += 1 | |
return bool(1) | |
return bool(0) | |
with mock.patch('__builtin__.True', AlmostAlwaysTrue(4)): | |
while True: | |
print "Loop!" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
daltonmatos@jetta wsgid % python mocktrue.py | |
Loop! | |
Loop! | |
Loop! | |
Loop! | |
daltonmatos@jetta wsgid % |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks! Though I don't need to change the value of True, this snippet did show me how to work around Python 2.7
mock
's lack of ability to mock__bool__
: you instead mock__nonzero__
.