From f027cef844bf1ccbd07e8efe02aab8427a8982f4 Mon Sep 17 00:00:00 2001 From: TheMasterOfMagic <18811569079@163.com> Date: Sat, 15 Dec 2018 15:50:13 +0800 Subject: [PATCH] =?UTF-8?q?=E5=9C=A8python=E9=80=9F=E6=9F=A5=E8=A1=A8?= =?UTF-8?q?=E4=B8=AD=E6=B7=BB=E5=8A=A0=E4=BA=86=E5=8D=95=E5=85=83=E6=B5=8B?= =?UTF-8?q?=E8=AF=95=E7=9A=84=E7=9B=B8=E5=85=B3=E9=83=A8=E5=88=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- languages/python.md | 54 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/languages/python.md b/languages/python.md index c7b5f05..ada4abc 100755 --- a/languages/python.md +++ b/languages/python.md @@ -26,6 +26,8 @@ Python 速查表中文版 [对列表、字典和元组的深入理解](#对列表和字典以及元组的深入理解) +[单元测试](#单元测试) + ## 惯例 - Python 对大小写敏感; @@ -543,3 +545,55 @@ for val in collection: [expr for val in collection for innerVal in val if condition] ``` +## 单元测试 + +Python自带`unittest`模块,可供我们编写单元测试。 + +```python +import unittest +``` + +我们可以编写继承于`unittest.TestCase`测试类的子类,并在子类中编写具体的测试函数。测试函数命必须以`test_`开头,否则不会被识别为测试函数,进而不会在运行单元测试时被运行。 + +```python +class TestSubclass(unittest.TestCase): + def test_func(self): + self.assertEqual(0, 0) + # 可以通过msg关键字参数提供测试失败时的提示消息 + self.assertEqual(0, 0, msg='modified message') + self.assertGreater(1, 0) + self.assertIn(0, [0]) + self.assertTrue(True) + # 测试是否会抛出异常 + with self.assertRaises(KeyError): + _ = dict()[1] + + # 被@unittest.skip装饰器装饰的测试类或测试函数会被跳过 + @unittest.skip(reason='just skip') + def test_skip(self): + raise Exception('I shall never be tested') +``` + +另外, `unittest.TestCase`中还有两个特殊的成员函数,他们分别会在调用每一个测试函数的前后运行。在测试前连接数据库并在测试完成后断开连接是一种常见的使用场景。 + +```python +def setUp(self): + # To do: connect to the database + pass + +def tearDown(self): + # To do: release the connection + pass + +def test_database(self): + # To do: test the database + pass +``` + +测试类编写完毕后,可以通过添加以下代码来将当前文件当成正常的Python脚本使用 + +```python +if __name__ == '__main__': + unittest.main() +``` +