python单元测试入门_最佳 Python 单元测试框架(1):unittest

classTestStringMethods(unittest.TestCase):

deftest_upper(self):self.assertEqual('foo'.upper, 'FOO')

deftest_isupper(self):self.assertTrue('FOO'.isupper)self.assertFalse('Foo'.isupper)

deftest_split(self):s = 'hello world'self.assertEqual(s.split, ['hello', 'world'])# check that s.split fails when the separator is not a stringwithself.assertRaises(TypeError):s.split(2)

if__name__ == '__main__':unittest.main

上述示例中,通过继承 unittest.TestCase[4] 来创建一个测试用例。在这个类中,定义以 test 开头的方法,测试框架将把它作为独立的测试去执行。

每个用例都采用 unittest 内置的断言方法来判断被测对象的行为是否符合预期,比如:

在 test_upper 测试中,使用 assertEqual[5] 检查是否是预期值

在 test_isupper 测试中,使用 assertTrue[6] 或 assertFalse[7] 验证是否符合条件

在 test_split 测试中,使用 assertRaises[8] 验证是否抛出一个特定异常

可能有人会好奇,为什么不使用内置断言语句 assert,而要额外提供这么多断言方法并使用呢?原因是通过使用 unittest 提供的断言方法,测试框架在运行结束后,能够聚合所有的测试结果并产生信息丰富的测试报告。而直接使用 assert 虽然也可以达到验证被测对象是否符合预期的目的,但在用例出错时,报错信息不够丰富。

三、用例发现和执行

unittest 支持用例自动(递归)发现:

默认发现当前目录下所有符合 test*.py 测试用例

使用 python -m unittest 或 python -m unittest discover

通过 -s 参数指定要自动发现的目录, -p 参数指定用例文件的名称模式

python -m unittest discover -s project_directory -p "test_*.py"

通过位置参数指定自动发现的目录和用例文件的名称模式

python -m unittest discover project_directory "test_*.py"

unittest 支持执行指定用例:

指定测试模块

python -m unittest test_module1 test_module2

指定测试类

python -m unittest test_module.TestClass

指定测试方法

python -m unittest test_module.TestClass.test_method

指定测试文件路径(仅 Python 3)

python -m unittest tests/test_something.py四、测试夹具(Fixtures)

测试夹具也就是测试前置(setUp)和清理(tearDown)方法。

测试前置方法 setUp[9] 用来做一些准备工作,比如建立数据库连接。它会在用例执行前被测试框架自动调用。

测试清理方法 tearDown[10] 用来做一些清理工作,比如断开数据库连接。它会在用例执行完成(包括失败的情况)后被测试框架自动调用。

测试前置和清理方法可以有不同的执行级别。

4.1 生效级别:测试方法

如果我们希望每个测试方法之前前后分别执行测试前置和清理方法,那么需要在测试类中定义好 setUp[11] 和 tearDown[12]:

classMyTestCase(unittest.TestCase):defsetUp(self):passdeftearDown(self):pass

4.2 生效级别:测试类

如果我们希望单个测试类中只执行一次前置方法,再执行该测试类中的所有测试,最后执行一次清理方法,那么需要在测试类中定义好 setUpClass[13] 和 tearDownClass[14]:

classMyTestCase(unittest.TestCase):defsetUpClass(self):passdeftearDownClass(self):pass

4.3 生效级别:测试模块

如果我们希望单个测试模块中只执行一次前置方法,再执行该模块中所有测试类的所有测试,最后执行一次清理方法,那么需要在测试模块中定义好 setUpModule[15] 和 tearDownModule[16]:

defsetUpModule:passdeftearDownModule:pass

五、跳过测试和预计失败

unittest 支持直接跳过或按条件跳过测试,也支持预计测试失败:

通过 skip[17] 装饰器或 SkipTest[18] 直接跳过测试

通过 skipIf[19] 或 skipUnless[20] 按条件跳过或不跳过测试

通过 expectedFailure[21] 预计测试失败

classMyTestCase(unittest.TestCase):@unittest.skip("直接跳过")deftest_nothing(self):self.fail("shouldn't happen")

@unittest.skipIf(mylib.__version__ < (1, 3),"满足条件跳过")deftest_format(self):# Tests that work for only a certain version of the library.pass

@unittest.skipUnless(sys.platform.startswith("win"), "满足条件不跳过")deftest_windows_support(self):# windows specific testing codepass

deftest_maybe_skipped(self):ifnotexternal_resource_available:self.skipTest("跳过")# test code that depends on the external resourcepass

@unittest.expectedFailuredeftest_fail(self):self.assertEqual(1, 0, "这个目前是失败的")

六、子测试

有时候,你可能想编写这样的测试:在一个测试方法中传入不同的参数来测试同一段逻辑,但它将被视作一个测试,但是如果使用了子测试[22],就能被视作 N(即为参数的个数)个测试。下面是一个示例:

classNumbersTest(unittest.TestCase):deftest_even(self):"""Test that numbers between 0 and 5 are all even."""fori inrange(0, 6):withself.subTest(i=i):self.assertEqual(i % 2, 0)

示例中使用了 with self.subTest(i=i) 的方式定义子测试,这种情况下,即使单个子测试执行失败,也不会影响后续子测试的执行。这样,我们就能看到输出中有三个子测试不通过:

======================================================================FAIL: test_even (__main__.NumbersTest) (i=1)----------------------------------------------------------------------Traceback (most recent call last):File "subtests.py", line 32, intest_evenself.assertEqual(i % 2, 0)Asserti: 1 != 0======================================================================FAIL: test_even (__main__.NumbersTest) (i=3)----------------------------------------------------------------------Traceback (most recent call last):File "subtests.py", line 32, intest_evenself.assertEqual(i % 2, 0)Asserti: 1 != 0

======================================================================FAIL: test_even (__main__.NumbersTest) (i=5)----------------------------------------------------------------------Traceback (most recent call last):File "subtests.py", line 32, intest_evenself.assertEqual(i % 2, 0)Asserti: 1 != 0

七、测试结果输出

基于简单示例小节中提到的例子,来说明下 unittest 在运行完测试后的结果输出。

默认情况下的输出非常简单,展示运行了多少个用例,以及所花费的时间:

...----------------------------------------------------------------------Ran 3 tests in0.000sOK

通过指定 -v 参数,可以得到详细输出,除了默认输出的内容,还额外显示了用例名称:

test_isupper (__main__.TestStringMethods) ... oktest_split (__main__.TestStringMethods) ... oktest_upper (__main__.TestStringMethods) ... ok----------------------------------------------------------------------Ran 3 tests in0.001s

OK

假定 test_upper 测试失败,则在详细输出模式下,结果如下:

test_isupper (tests.test.TestStringMethods) ... oktest_split (tests.test.TestStringMethods) ... oktest_upper (tests.test.TestStringMethods) ... FAIL======================================================================FAIL: test_upper (tests.test.TestStringMethods)----------------------------------------------------------------------Traceback (most recent call last):File "/Uvsers/prodesire/projects/tests/test.py", line 6, intest_upperself.assertEqual('foo'.upper, 'FOO1')Asserti: 'FOO'!= 'FOO1'- FOO+ FOO1? +

----------------------------------------------------------------------Ran 3 tests in0.001s

FAILED (failures=1)

如果我们将 test_upper 测试方法中的 self.assertEqual 改为 assert,则测试结果输出中将会少了对排查错误很有帮助的上下文信息:

test_isupper (tests.test.TestStringMethods) ... oktest_split (tests.test.TestStringMethods) ... oktest_upper (tests.test.TestStringMethods) ... FAIL======================================================================FAIL: test_upper (tests.test.TestStringMethods)----------------------------------------------------------------------Traceback (most recent call last):File "/Users/prodesire/projects/tests/test.py", line 6, intest_upperassert 'foo'.upper == 'FOO1'Asserti

----------------------------------------------------------------------Ran 3 tests in0.001s

FAILED (failures=1)

如果想要生成 HTML 格式的报告,那么就需要额外借助第三方库(如 HtmlTestRunner[23])来操作。

在安装好第三方库后,你不能直接使用 python -m unittest 加上类似 --html report.html 的方式来生成 HTML 报告,而是需要自行编写少量代码来运行测试用例进而得到 HTML 报告。详情请查看 HtmlTestRunner 使用说明[24]。

八、小结

unittest[25] 作为 Python 标准库提供的单元测试框架,使用简单、功能强大,日常测试需求均能得到很好的满足。在不引入第三方库的情况下,是单元测试的不二之选。

在下篇文章中,我们将介绍第三方单元测试框架 nose 和 nose2,讲讲它对比于 unittest 有哪些改进,以至于让很多开发人员优先选择了它。

References [1] unittest:https://docs.python.org/3/library/unittest.html

[2] unittest:https://docs.python.org/3/library/unittest.html

[3] 官方文档:https://docs.python.org/3/library/unittest.html#basic-example [4] unittest.TestCase:https://docs.python.org/3/library/unittest.html#unittest.TestCase

[5] assertEqual:https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertEqual

[6] assertTrue:https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertTrue [7] assertFalse:https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertFalse

[8] assertRaises:https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertRaises

[9] setUp:https://docs.python.org/3/library/unittest.html#unittest.TestCase.setUp [10] tearDown:https://docs.python.org/3/library/unittest.html#unittest.TestCase.tearDown

[11] setUp:https://docs.python.org/3/library/unittest.html#unittest.TestCase.setUp [12] tearDown:https://docs.python.org/3/library/unittest.html#unittest.TestCase.tearDown

[13] setUpClass:https://docs.python.org/3/library/unittest.html#unittest.TestCase.setUpClass

[14] tearDownClass:https://docs.python.org/3/library/unittest.html#unittest.TestCase.tearDownClass [15] setUpModule:https://docs.python.org/3/library/unittest.html#setupmodule-and-teardownmodule

[16] tearDownModule:https://docs.python.org/3/library/unittest.html#setupmodule-and-teardownmodule [17] skip:https://docs.python.org/3/library/unittest.html#unittest.skip

[18] SkipTest:https://docs.python.org/3/library/unittest.html#unittest.SkipTest [19] skipIf:https://docs.python.org/3/library/unittest.html#unittest.skipIf

[20] skipUnless:https://docs.python.org/3/library/unittest.html#unittest.skipUnless [21] SkipTest:https://docs.python.org/3/library/unittest.html#unittest.SkipTest [22] skipIf:https://docs.python.org/3/library/unittest.html#unittest.skipIf

[23] HtmlTestRunner:https://github.com/oldani/HtmlTestRunner [24] HtmlTestRunner 使用说明:https://github.com/oldani/HtmlTestRunner#usage [25] unittest:https://docs.python.org/3/library/unittest.html 返回搜狐,查看更多

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值