Python编程:从入门到实践(第3版)

> 📖 **一起读书吧!** 加入《Python编程:从入门到实践》共读营 👉 [点击参加](https://mp.weixin.qq.com/s/ehe2vMrfAFscRLqbM9TF-g)

本讲内容

  • unittest 标准测试框架
  • pytest 第三方测试框架
  • 测试函数和测试类
  • fixture(测试前准备)
  • 参数化测试
  • 测试覆盖率

学习目标

保证你的代码不翻车 ✅


1. unittest 标准库

1
2
3
4
# name_function.py(被测代码)
def get_formatted_name(first, middle, last):
full_name = f"{first} {middle} {last}"
return full_name.title()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# test_name_function.py(测试代码)
import unittest
from name_function import get_formatted_name

class NamesTestCase(unittest.TestCase):
"""测试 get_formatted_name()"""

def test_first_last(self):
name = get_formatted_name('janis', 'joplin', '')
self.assertEqual(name, 'Janis Joplin')

def test_first_last_middle(self):
name = get_formatted_name('wolfgang', 'mozart', 'amadeus')
self.assertEqual(name, 'Wolfgang Amadeus Mozart')

if __name__ == '__main__':
unittest.main()

运行:

1
2
3
python test_name_function.py
# Ran 2 tests in 0.001s
# OK

常用断言方法

1
2
3
4
5
6
7
8
self.assertEqual(a, b)          # a == b
self.assertNotEqual(a, b) # a != b
self.assertTrue(x) # x is True
self.assertFalse(x) # x is False
self.assertIn(item, container) # item in container
self.assertNotIn(item, container)
self.assertIsNone(x) # x is None
self.assertRaises(ValueError) # 期望抛出异常

官方文档:unittest — Unit testing framework

2. pytest 框架(更简洁)

1
pip install pytest
1
2
3
4
5
6
7
8
9
10
# test_calculator.py
def add(a, b):
return a + b

def test_add():
assert add(2, 3) == 5
assert add(-1, 1) == 0

def test_add_strings():
assert add("Hello ", "World") == "Hello World"

运行:

1
2
3
pytest                    # 运行所有 test_ 开头的文件
pytest test_calculator.py # 运行指定文件
pytest -v # 详细模式

pytest 特点

  • ✅ 不用写类,直接写函数
  • ✅ 用 assert 就够了
  • ✅ 自动发现 test_ 开头的文件和函数

pytest文档:https://docs.pytest.org/

3. 测试异常

1
2
3
4
5
6
7
8
9
10
11
# unittest
def test_invalid_input(self):
with self.assertRaises(ValueError):
int("not a number")

# pytest
import pytest

def test_invalid_input():
with pytest.raises(ValueError):
int("not a number")

4. fixture(测试前准备数据)

1
2
3
4
5
6
7
8
9
10
11
import pytest

@pytest.fixture
def sample_data():
return {"name": "晚枫", "age": 30}

def test_name(sample_data):
assert sample_data["name"] == "晚枫"

def test_age(sample_data):
assert sample_data["age"] == 30

5. 参数化测试(pytest)

一组参数 = 一个测试用例:

1
2
3
4
5
6
7
8
9
10
import pytest

@pytest.mark.parametrize("input_str,expected", [
("hello", "HELLO"),
("World", "WORLD"),
("", ""),
("123", "123"),
])
def test_upper(input_str, expected):
assert input_str.upper() == expected

运行4个用例,只写了一个函数!

6. 测试覆盖率

1
2
pip install pytest-cov
pytest --cov=my_module tests/

覆盖率告诉你:代码有多少行被执行了。100%覆盖 ≠ 没有bug,但覆盖率低一定有风险。


📚 官方文档参考


🎓 AI 编程实战课程

程序员晚枫专注AI编程培训,通过 《30讲 · AI编程训练营》,让小白也能用AI做出实际项目。