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))
为什么使用 testtools?
匹配器:比断言方法更好
当然,在任何严肃的项目中,你都想拥有特定于该项目及其解决特定问题的断言。testtools 允许你编写自己的“匹配器”,这些是可插入单元测试的自定义谓词,而不是强迫你定义自己的断言方法并维护自己的 TestCase 类的继承层次。
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 做了很多工作,让严肃的测试作者和测试 框架 作者能够随意处理他们的测试和扩展,同时保持与标准库的 unittest 兼容。
testtools 完全参数化了如何在测试中抛出的异常映射到 TestResult 方法,以及测试是如何实际执行的(是否希望无论 setUp 是否成功,都调用 tearDown?)
它还提供了一些简单但实用的工具,例如能够克隆测试,一个 MultiTestResult 对象,它允许多个结果对象从单个测试套件中获取结果,以及将旧 TestResult 对象引入我们新时代的适配器。
跨 Python 兼容性
testtools 以一种与 Python 3.7+ 和 PyPy3 兼容的方式,为您提供最新的单元测试技术。
如果您希望使用 Python 2.4 或 2.5 的 testtools,请使用 testtools 0.9.15。
如果您希望使用 Python 2.6 或 3.2 的 testtools,请使用 testtools 1.9.0。
如果您希望使用 Python 3.3 或 3.4 的 testtools,请使用 testtools 2.3.0。
如果您希望使用 Python 2.7 或 3.5 的 testtools,请使用 testtools 2.4.0。
项目详情
下载文件
下载适用于您平台的文件。如果您不确定该选择哪个,请了解更多关于安装包的信息。