Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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