Skip to content

Instantly share code, notes, and snippets.

@itamarst
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itamarst/947474a4e00d358892fe to your computer and use it in GitHub Desktop.
Save itamarst/947474a4e00d358892fe to your computer and use it in GitHub Desktop.
Effect-inspired library idea aimed at unit testing Deferred-using code
# my_effect.py
"""
In normal code, side-effecty code is run as usual.
In tests one can (with a context manager, perhaps) disable side-effects and figure out
what the intention of the code is without actually triggering any side-effects.
"""
class IEffect(Interface):
def run():
"return a Deferred that will eventually fire"
IN_TEST_MODE = False
def result_of(effect):
if IN_TEST_MODE:
d = Deferred()
effect.deferred = d
d.__effect__ = effect
return d
else:
return effect.run()
def get_intended_effect(d):
"""For use with unit tests only."""
return d.__effect__
@contextmanager
def test_effects():
"""For use with unit tests only."""
global IN_TEST_MODE
IN_TEST_MODE = True
try:
yield
finally:
IN_TEST_MODE = False
def resolve_effect_to(effect, result):
"""For use with unit tests only."""
effect.deferred.callback(result)
# ============ Example usage: ========
from myeffect import result_of, get_intended_effect, resovle_effect_to
def mycode():
d = result_of(MyEffect(123))
d.addCallback(blah)
return d
def test_mycode():
with test_effects:
effect = get_intended_effect(mycode())
self.assertEqual(effect, MyEffect(123))
with test_effects:
d = mycode()
resolve_effect_to(d, 456)
self.assertEqual(self.successResultOf, blah(456))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment