python标准库单元测试框架的扩展
testtools的Python项目详细描述
testtools是python标准库单元测试的一组扩展 框架。这些扩展源于多年的经验 使用python进行单元测试,并且来自许多不同的来源。
有什么比从一个虚构的代码片段开始更好的方法呢?:
from testtools import TestCase from testtools.content import Content from testtools.content_type import UTF8_TEXT from testtools.matchers import Equals from myproject import SillySquareServer class TestSillySquareServer(TestCase): def setUp(self): super(TestSillySquareServer, self).setUp() self.server = self.useFixture(SillySquareServer()) self.addCleanup(self.attach_log_file) def attach_log_file(self): self.addDetail( 'log-file', Content(UTF8_TEXT, lambda: open(self.server.logfile, 'r').readlines())) def test_server_is_cool(self): self.assertThat(self.server.temperature, Equals("cool")) def test_square(self): self.assertThat(self.server.silly_square_of(7), Equals(49))
为什么使用测试工具?
更好的断言方法
unittest附带的标准断言方法不如 可能是的,但还不够。testtools添加 assertIn,assertIs,assertIsInstance及其底片。
匹配器:优于断言方法
当然,在任何严肃的项目中,你都希望能够有这样的断言 具体到那个项目和它正在解决的特定问题。 而不是强迫您定义自己的断言方法并维护 拥有TestCase类的继承层次结构,testtools允许您编写 您自己的“匹配器”,可以插入单元测试的自定义谓词:
def test_response_has_bold(self): # The response has bold text. response = self.server.getResponse() self.assertThat(response, HTMLContains(Tag('bold', 'b')))
更多调试信息,当您需要时
testtools使向测试结果中添加任意数据变得容易。如果你 想知道测试失败时日志文件中的内容,或加载的内容 测试开始时的计算机,或者打开了哪些文件,可以添加 带有TestCase.addDetail的信息,它将出现在测试中 如果测试失败。
扩展unittest,但保持兼容和可重用性
testtools会尽最大努力允许严肃的测试作者和测试人员 framework作者可以对他们的测试和 扩展,同时与标准库的unittest保持兼容。
testtools已经完全参数化了在测试中引发异常的方式。 映射到TestResult方法以及测试的实际执行方式(永远 不管setUp是否成功,都希望调用tearDown?
它还提供了许多简单但方便的实用程序,如克隆 test,一个MultiTestResult对象,它允许许多result对象获取 结果来自一个测试套件,适配器带来了遗留的TestResult对象 进入我们新的黄金时代。
跨python兼容性
testtools为您提供了最新的单元测试技术 将使用Python2.7、3.3、3.4、3.5和Pypy。
如果您希望在python 2.4或2.5中使用testtools,那么请使用testtools 0.9.15分。
如果您希望在python 2.6或3.2中使用testtools,那么请使用testtools 1.9.0条。