Python单元测试(pycharm单元测试)
1. 单元测试概述
1.1 什么是单元测试
单元测试(Unit Testing)是指对软件中的最小可测试单元进行检查和验证的过程。在Python中,最小单元通常指函数、方法或类。
1.2 单元测试的特性
- 独立性:每个测试用例应该独立运行,不依赖其他测试
- 自动化:测试应该能够自动执行和验证
- 快速性:测试执行速度要快
- 可重复性:测试结果应该稳定可重复
- 及时性:测试应该在代码编写的同时或之后立即编写
1.3 单元测试的应用场景举例
场景 | 说明 |
开发阶段 | 确保每个单元功能正确 |
重构代码 | 保证重构不引入新错误 |
持续集成 | 作为CI/CD流程的一部分 |
文档补充 | 作为代码功能的活文档 |
2. Python单元测试框架
2.1 unittest模块
Python内置的单元测试框架,基于JUnit设计。
2.1.1 基本结构
import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
def test_isupper(self):
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
if __name__ == '__main__':
unittest.main()
2.1.2 常用断言方法
表1 unittest常用断言方法
方法 | 说明 |
assertEqual(a, b) | a == b |
assertNotEqual(a, b) | a != b |
assertTrue(x) | bool(x) is True |
assertFalse(x) | bool(x) is False |
assertIs(a, b) | a is b |
assertIsNot(a, b) | a is not b |
assertIsNone(x) | x is None |
assertIsNotNone(x) | x is not None |
assertIn(a, b) | a in b |
assertNotIn(a, b) | a not in b |
assertRaises(exc, fun, *args, **kwargs) | fun(*args, **kwargs) raises exc |
2.1.3 测试固件(Test Fixtures)
class TestDatabase(unittest.TestCase):
@classmethod
def setUpClass(cls):
# 整个测试类执行前运行一次
cls.db = connect_to_database()
def setUp(self):
# 每个测试方法执行前运行
self.cursor = self.db.cursor()
def test_query(self):
self.cursor.execute("SELECT 1")
result = self.cursor.fetchone()
self.assertEqual(result, (1,))
def tearDown(self):
# 每个测试方法执行后运行
self.cursor.close()
@classmethod
def tearDownClass(cls):
# 整个测试类执行后运行一次
cls.db.close()
2.2 pytest框架
第三方测试框架,比unittest更简洁强大。
2.2.1 安装与基本使用
pip install pytest
# test_sample.py
def func(x):
return x + 1
def test_answer():
assert func(3) == 4
运行测试:
pytest test_sample.py
2.2.2 pytest特性
- 自动发现:自动发现以test_开头的文件和函数
- 丰富的断言:直接使用assert语句
- fixture系统:更灵活的测试固件
- 参数化测试:轻松实现多组数据测试
- 插件系统:丰富的插件生态
2.2.3 pytest fixture
import pytest
@pytest.fixture
def db_connection():
conn = connect_to_database()
yield conn # 测试执行时返回连接
conn.close() # 测试完成后清理
def test_query(db_connection):
cursor = db_connection.cursor()
cursor.execute("SELECT 1")
result = cursor.fetchone()
assert result == (1,)
2.2.4 参数化测试
import pytest
@pytest.mark.parametrize("input,expected", [
(3, 4),
(5, 6),
(-1, 0),
])
def test_increment(input, expected):
assert input + 1 == expected
3. 单元测试实践
3.1 测试编写原则
- FIRST原则:
- Fast(快速)
- Independent(独立)
- Repeatable(可重复)
- Self-Validating(自我验证)
- Timely(及时)
- AAA模式:
- Arrange(准备测试环境)
- Act(执行被测代码)
- Assert(验证结果)
3.2 测试覆盖率
使用coverage.py测量测试覆盖率:
pip install coverage
coverage run -m pytest
coverage report -m
表2 覆盖率指标
指标 | 说明 |
语句覆盖率 | 测试执行的代码行比例 |
分支覆盖率 | 测试执行的分支路径比例 |
条件覆盖率 | 测试执行的布尔子表达式比例 |
函数覆盖率 | 测试调用的函数比例 |
3.3 测试替身(Test Doubles)
- Dummy:仅用于填充参数,不参与实际逻辑
- Fake:简化功能的实现,如内存数据库
- Stub:提供预设的固定响应
- Mock:记录调用信息并验证行为
- Spy:记录调用信息,但执行真实逻辑
3.3.1 unittest.mock模块
from unittest.mock import Mock, patch
def test_mocking():
# 创建mock对象
mock = Mock()
mock.method.return_value = 42
# 使用mock
assert mock.method() == 42
mock.method.assert_called_once()
# 上下文管理器方式mock
with patch('module.function') as mock_func:
mock_func.return_value = 'mocked'
result = module.function()
assert result == 'mocked'
4. 实战举例
4.1 测试一个简单的计算器类
# calculator.py
class Calculator:
"""简单的计算器类"""
def add(self, a, b):
"""加法"""
return a + b
def subtract(self, a, b):
"""减法"""
return a - b
def multiply(self, a, b):
"""乘法"""
return a * b
def divide(self, a, b):
"""除法"""
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
4.1.1 使用unittest测试
# test_calculator_unittest.py
import unittest
from calculator import Calculator
class TestCalculator(unittest.TestCase):
def setUp(self):
self.calc = Calculator()
def test_add(self):
self.assertEqual(self.calc.add(2, 3), 5)
self.assertEqual(self.calc.add(-1, 1), 0)
def test_subtract(self):
self.assertEqual(self.calc.subtract(5, 3), 2)
def test_multiply(self):
self.assertEqual(self.calc.multiply(3, 4), 12)
def test_divide(self):
self.assertEqual(self.calc.divide(6, 3), 2)
with self.assertRaises(ValueError):
self.calc.divide(6, 0)
if __name__ == '__main__':
unittest.main()
4.1.2 使用pytest测试
# test_calculator_pytest.py
import pytest
from calculator import Calculator
@pytest.fixture
def calculator():
return Calculator()
def test_add(calculator):
assert calculator.add(2, 3) == 5
assert calculator.add(-1, 1) == 0
def test_subtract(calculator):
assert calculator.subtract(5, 3) == 2
def test_multiply(calculator):
assert calculator.multiply(3, 4) == 12
def test_divide(calculator):
assert calculator.divide(6, 3) == 2
with pytest.raises(ValueError):
calculator.divide(6, 0)
4.2 测试一个Flask Web应用
# app.py
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/api/add/<int:a>/<int:b>')
def add(a, b):
return jsonify({'result': a + b})
@app.route('/api/subtract/<int:a>/<int:b>')
def subtract(a, b):
return jsonify({'result': a - b})
4.2.1 使用pytest测试Flask应用
# test_app.py
import pytest
from app import app
@pytest.fixture
def client():
app.config['TESTING'] = True
with app.test_client() as client:
yield client
def test_add(client):
response = client.get('/api/add/2/3')
assert response.status_code == 200
assert response.json == {'result': 5}
def test_subtract(client):
response = client.get('/api/subtract/5/3')
assert response.status_code == 200
assert response.json == {'result': 2}
5. 进阶主题
5.1 参数化测试进阶
import pytest
from calculator import Calculator
@pytest.mark.parametrize("a,b,expected", [
(2, 3, 5),
(-1, 1, 0),
(0, 0, 0),
])
def test_add_parametrized(a, b, expected):
calc = Calculator()
assert calc.add(a, b) == expected
5.2 测试标记与筛选
@pytest.mark.slow
def test_slow_operation():
import time
time.sleep(2)
assert True
@pytest.mark.skip(reason="Not implemented yet")
def test_unimplemented():
assert False
@pytest.mark.xfail
def test_expected_failure():
assert False
运行指定标记的测试:
pytest -m slow
5.3 测试数据库应用
# test_db.py
import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
@pytest.fixture(scope="module")
def db_engine():
engine = create_engine("sqlite:///:memory:")
yield engine
engine.dispose()
@pytest.fixture
def db_session(db_engine):
connection = db_engine.connect()
transaction = connection.begin()
session = sessionmaker(bind=connection)()
yield session
session.close()
transaction.rollback()
connection.close()
def test_user_model(db_session):
from models import User
user = User(name="Test User")
db_session.add(user)
db_session.commit()
fetched = db_session.query(User).first()
assert fetched.name == "Test User"
6. 学习路线图
7. 总结
- 单元测试是保证代码质量的重要手段
- Python有内置的unittest和更强大的pytest框架
- 良好的测试应遵循FIRST原则和AAA模式
- 测试覆盖率是衡量测试完整性的指标
- Mock技术可以隔离依赖,使测试更专注
- 参数化测试可以提高测试效率
- 测试应该成为开发流程的固有部分
8. 扩展阅读
- pytest官方文档:(https://docs.pytest.org/)
- unittest官方文档:(https://docs.python.org/3/library/unittest.html)
- 测试驱动开发(TDD)实践
- 行为驱动开发(BDD)与behave框架
- 性能测试与负载测试
通过系统学习和实践单元测试,我们将能够编写更健壮、可维护的Python代码,并提高开发效率和代码质量。