Skip to content

Instantly share code, notes, and snippets.

@anfernee
Created November 20, 2015 00:24
Show Gist options
  • Select an option

  • Save anfernee/36864570febca7749187 to your computer and use it in GitHub Desktop.

Select an option

Save anfernee/36864570febca7749187 to your computer and use it in GitHub Desktop.
class Defer(object):
""" Defer is the idea stolen from golang. Instead of calling a function
immediately, it defers running the function by saving it to a list. The
saved list of functions get executed when the surrounding function returns.
"""
def __init__(self):
self.funcs = []
def defer(self, func, args=()):
self.funcs.append((func, args))
def run(self):
for f in reversed(self.funcs):
f[0](*f[1])
import unittest
from hamcrest import * # noqa
from matchers import * # noqa
from mock import MagicMock
from common.defer import Defer
class TestDefer(unittest.TestCase):
def test_defer(self):
d = Defer()
f1 = MagicMock()
f2 = MagicMock()
f3 = MagicMock()
d.defer(f1, (1,2,3))
d.defer(f2, (1,))
d.defer(f3)
d.run()
f1.assert_called_once_with(1,2,3)
f2.assert_called_once_with(1,)
f3.assert_called_once_with()
def test_defer_order(self):
d = Defer()
order = []
def f1():
order.append("f1")
def f2():
order.append("f2")
d.defer(f1)
d.defer(f2)
d.run()
assert_that(order, equal_to(["f2", "f1"]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment