Skip to content

Instantly share code, notes, and snippets.

@thomasst
Created March 16, 2016 23:06
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 thomasst/7e2375239ed66663179f to your computer and use it in GitHub Desktop.
Save thomasst/7e2375239ed66663179f to your computer and use it in GitHub Desktop.
Context for tests
# Inspired by http://stackoverflow.com/a/13875412
class ContextMixin(object):
def setup_context(self):
self._ctxs = []
for cls in reversed(self.__class__.mro()):
context_method = cls.__dict__.get('context')
if context_method:
ctx = context_method(self)
self._ctxs.append(ctx)
for ctx in self._ctxs:
try:
next(ctx)
except TypeError:
raise RuntimeError('{}.context() must yield'.format(cls.__name__))
def teardown_context(self):
for ctx in reversed(self._ctxs):
for _ in ctx:
raise RuntimeError('{}.context() must not yield more than once'.format(cls.__name__))
class A(ContextMixin):
def context(self):
print 'set up A'
yield
print 'tear down A'
class B(ContextMixin):
def context(self):
print 'set up B'
yield
print 'tear down B'
class C(object):
pass
class Test(C, B, A):
def context(self):
print 'set up test'
with open('/tmp/testfile', 'w') as f:
self.f = f
yield
print 'tear down test'
test = Test()
test.setup_context()
print 'run test here', test.f
test.teardown_context()
"""
Output:
set up A
set up B
set up test
run test here <open file '/tmp/testfile', mode 'w' at 0x1109d48a0>
tear down test
tear down B
tear down A
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment