This is a very interesting question. As BrenBarn pointed out, the unittest framework doesn't support doing what you want, but it seems to me that there's no particular reason why you couldn't adapt it to fit. The setUp
/tearDown
pairing is a hangover from other languages that didn't have generators.
The code below defines a new 'ContextTest' class which amalgamates both setUp and tearDown methods into a single generator that both builds and destroys the context for the test. You can drop your with
statement into the context()
method along with any other boilerplate.
#!/usr/bin/python3.3
import unittest
class ContextTest(unittest.TestCase):
"""A unit test where setUp/tearDown are amalgamated into a
single generator"""
def context(self):
"""Put both setUp and tearDown code in this generator method
with a single `yield` between"""
yield
def setUp(self):
self.__context = self.context()
next(self.__context)
def tearDown(self):
for _ in self.__context:
raise RuntimeError("context method should only yield once")
from contextlib import closing
from urllib.request import urlopen
class MyTest(ContextTest):
def context(self):
with closing(urlopen('http://www.python.org')) as self.page:
yield
def testFoo(self):
self.assertIsNotNone(self.page)
if __name__=='__main__':
unittest.main()