Skip to content

Instantly share code, notes, and snippets.

@sarum90
Last active November 19, 2015 11:54
Show Gist options
  • Save sarum90/b8af8684f524b62987a6 to your computer and use it in GitHub Desktop.
Save sarum90/b8af8684f524b62987a6 to your computer and use it in GitHub Desktop.
from twisted.internet import reactor
from twisted.internet.task import Clock, deferLater
from twisted.internet.defer import succeed
def opaque_animal_noise_generator():
"""
Opaque piece of test infra that we can't touch (actually does networking or
something so really uses the real reactor).
"""
return deferLater(reactor, 0.5, lambda: u'meow')
def code_under_test(dependency, r):
d = opaque_animal_noise_generator()
def dependency_loop(noise):
a = dependency(noise)
def we_done(arg):
if arg == "not_yet":
return deferLater(r, 1000.0, dependency_loop, noise)
else:
return succeed(arg + ' for everyone!')
a.addCallback(we_done)
return a
d.addCallback(dependency_loop)
return d
def test():
r = Clock()
answers = iter(['not_yet', 'not_yet', 'Money'])
def test_func(_):
# Ew? Maybe? have to callLater since code under test needs
# us to return before it puts things on the Clock.
reactor.callLater(0.0, lambda: r.advance(1000.0))
return succeed(next(answers))
d = code_under_test(test_func, r)
def verify(o):
if o != 'Money for everyone!':
print "FAIL!"
d.addCallback(verify)
return d
d = test()
d.addCallback(lambda _: reactor.stop())
reactor.run()
@sarum90
Copy link
Author

sarum90 commented Nov 19, 2015

Solution #1 that both Richard and Tom come up with separately: don't have opaque dependencies in your testing infrastructure that use the real reactor.

@exarkun
Copy link

exarkun commented Nov 19, 2015

That's a very good solution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment