Python进阶(1) | 单元测试
2024.01.28
VSCode: 1.85.1
Linux(ubuntu 22.04)
文章目录
1. 目的
使用 Python 实现一些小工具、库的时候,增加单元测试来保证正确性。
重读 VSCode 的 Python 官方文档, 更新个人的 Python 开发效率。
2. Python Profile
VSCode 提供了定制 profile 的功能, 个人目前理解为类似于 vim/emacs 里的模式的升级版。以前我只是配置VSCode的全局配置和当前工程配置, 而 Profile 则是建立了不同的配置,每个打开的VSCode工程都可以在不同的 profile 之间切换。
举例: 分别设置 C++ Profile 和 Python profile, 在 Python profile 和 C++ profile 中使用不同的快捷键、不同的UI布局等。
关于 profile 的完整文档在 https://code.visualstudio.com/docs/editor/profiles
官方提供了 Python 的profile,可以根据这个预定义的 profile, 继承它,创建一个自己的 Python profile:
https://code.visualstudio.com/docs/editor/profiles#_python-profile-template
3. 单元测试框架
3.1 什么是单元测试
A unit is a specific piece of code to be tested, such as a function or a class. Unit tests are then other pieces of code that specifically exercise the code unit with a full range of different inputs, including boundary and edge cases. Both the unittest and pytest frameworks can be used to write unit tests.
所谓单元,指的是一段特定的要被测试的代码,比如说一个函数、一个类。
所谓测试,指的是被测试代码A之外的代码B, 也就是说B这部分代码存在的意义,就是测试A这部分代码。
测试代码通常需要包含各种不同的输入,包括边界情况。
单元测试仅仅关注输入 和 输出, 不关注代码实现的细节。
因此,所谓单元测试,首先需要划分出单元,然后针对每个单元(或者仅对于关注的单元),编写测试代码。
For each input, you then define the function’s expected return value (or values).
对于被测试的代码的每一种输入,你需要定义它的预期结果。
With all the arguments and expected return values in hand, you now write the tests themselves, which are pieces of code that call the function with a particular input, then compare the actual return value with the expected return value (this comparison is called an assertion):
然后调用被测试的代码A: 给它传入输入, 获得它的输出结果, 并且和你预设的结果进行比对,结果一样则成功,不一样则报告失败。
https://code.visualstudio.com/docs/python/testing
3.2 选一个单元测试框架
Python 最常用的单元测试框架: unittest 和 pytest.
unittest 是 Python 标准库的模块, 也就是 Python 安装后自带的。 pytest 则需要自行安装: pip install pytest
.
3.3 编写 Python 单元测试代码
首先,是被测试的单元的代码, inc_dec.py
:
def increment(x: int):
return x + 1
def decrement(x: int):
return x - 1
然后, 是编写测试代码. 先用 unittest 写一遍:test_unittest.py
import inc_dec
import unittest
class Test_TestIncrementDecrement(unittest.TestCase):
def test_increment(self):
self.assertEqual(inc_dec.increment(3), 4)
# 这个测试用例一定会失败,是刻意做的
def test_decrement(self):
self.assertEqual(inc_dec.decrement(3), 4)
if __name__ == '__main__':
unittest.main()
再用 pytest 写一遍, 写法更简单:
import inc_dec
def test_increment():
assert inc_dec.increment(3) == 4
# 这个测试用例一定会失败,是刻意做的
def test_decrement():
assert inc_dec.decrement(3) == 4
3.4 在 VSCode 里发现单元测试
首先在 VSCode 里点击左侧的 Testing 按钮, 创建测试相关的配置: