这是一个非常有趣的问题。正如BrenBarn所指出的,unittest框架不支持做你想做的事情,但在我看来,没有什么特别的原因可以让它适应。setUp/tearDown对是其他没有生成器的语言的遗留问题。在
下面的代码定义了一个新的“ContextTest”类,该类将setUp和tearDown方法合并到一个生成器中,该生成器同时生成和销毁测试的上下文。您可以将您的with语句以及任何其他样板放入context()方法中。在#!/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()