单元测试
- Python 单元测试 - PegasusWang | 知乎
- Python Tutorial: Unit Testing Your Code with the unittest Module - Corey Schafer | YouTube
总的来说,单元测试有以下好处:
- 确保代码质量
- 改善代码设计,难以测试的代码一般是设计不够简洁的代码。
- 保证重构不会引入新问题,以函数为单位进行重构的时候,只需要重新跑测试就基本可以保证重构没引入新问题。
常用的单元测试框架有 unittest(Python 内置) 和 pytest。pytest 更简单直观,但 unittest 也不算太难。
unittest
TODO
pytest
pytest 最大的特点是直接用 assert,比较简洁直观。
# 测试一个 module
pytest <module>
# 测试一个 directory
pytest <directory>
pytest .
# test_pytest.py
# 因为这个文件名是 test_<something>.py,所以会被 pytest 自动包含到测试中
def add(a: float, b: float) -> float:
return a + b
def test_add():
assert add(1, 2) == 3 ## 直接 assert
# 用类组织起来
class TestAdd:
def test_1(self):
assert add(1, 2) == 3
def test_2(self):
assert add(2, 3) == 5
import pytest
def just_raise():
raise Exception
def test_raise():
with pytest.raises(Exception): # 测试 raise
just_raise()