在Python的测试领域中,unittest和pytest是两个备受关注的测试框架,它们各具特色,为开发者提供了不同的测试解决方案。
**一、unittest**
unittest是Python标准库中自带的单元测试框架。它具有以下特点:
https://zhuanlan.zhihu.com/p/1980303502283654928
https://zhuanlan.zhihu.com/p/1980303502283654928/
https://zhuanlan.zhihu.com/p/1980303503839740068
https://zhuanlan.zhihu.com/p/1980303503839740068/
https://zhuanlan.zhihu.com/p/1980303499024692110
https://zhuanlan.zhihu.com/p/1980303499024692110/
https://zhuanlan.zhihu.com/p/1980303501956495215
https://zhuanlan.zhihu.com/p/1980303501956495215/
https://zhuanlan.zhihu.com/p/1980303495002361950
https://zhuanlan.zhihu.com/p/1980303495002361950/
(0)
unittest.TestCase类assertEqual、assertTrue等丰富的断言方法import unittest
class TestMathOperations(unittest.TestCase):
def setUp(self):
"""每个测试方法前执行"""
self.calculator = Calculator()
def test_addition(self):
result = self.calculator.add(2, 3)
self.assertEqual(result, 5) # 断言方法
def test_subtraction(self):
result = self.calculator.subtract(5, 3)
self.assertTrue(result == 2) # 另一种断言方式
def tearDown(self):
"""每个测试方法后执行"""
self.calculator.cleanup()
if __name__ == '__main__':
unittest.main()# 最简单的测试函数
def test_addition():
assert 1 + 2 == 3 # 使用简单的 assert 语句
# 使用 fixture
import pytest
@pytest.fixture
def sample_data():
return {"a": 1, "b": 2}
def test_dict_values(sample_data):
assert sample_data["a"] == 1
# 参数化测试
@pytest.mark.parametrize("input_a,input_b,expected", [
(1, 2, 3),
(5, 5, 10),
(-1, 1, 0)
])
def test_addition_parametrized(input_a, input_b, expected):
assert input_a + input_b == expected特性 | unittest | pytest | 优劣分析 |
|---|---|---|---|
安装 | Python 标准库 | pip install pytest | unittest 零安装,pytest 需安装 |
测试编写 | 需继承 TestCase 类 | 普通函数+装饰器 | pytest 更简洁灵活 |
断言语法 | self.assertEqual(a, b) | assert a == b | pytest 语法更 Pythonic |
夹具系统 | setUp/tearDown方法 | @pytest.fixture装饰器 | pytest 的 fixture 更强大灵活 |
参数化测试 | 需用 @parameterized扩展 | 原生支持 @pytest.mark.parametrize | pytest 原生支持,更优雅 |
测试发现 | 需指定或使用 discover | 自动发现 test_*.py和 *_test.py | pytest 更智能 |
失败信息 | 基本错误信息 | 详细的失败分析,智能对比 | pytest 调试更方便 |
插件生态 | 有限 | 丰富的插件生态系统 | pytest 扩展性强 |
并行测试 | 需第三方扩展 | 有 pytest-xdist插件 | pytest 并行测试更成熟 |
测试报告 | 基本报告 | 多种格式,支持 Allure | pytest 报告更美观 |
class TestExample(unittest.TestCase):
def setUp(self): # 方法级夹具
self.db = Database()
@classmethod
def setUpClass(cls): # 类级夹具
cls.shared_cOnnection= create_connection()
def tearDown(self):
self.db.close()@pytest.fixture(scope="function")
def db_connection():
"""函数级夹具"""
cOnn= create_connection()
yield conn # 使用yield实现setup/teardown
conn.close()
@pytest.fixture(scope="session")
def shared_config(): # 会话级夹具
return load_config()
def test_query(db_connection, shared_config): # 依赖注入
result = db_connection.query("SELECT 1")
assert resultfrom parameterized import parameterized
class TestMath(unittest.TestCase):
@parameterized.expand([
(1, 2, 3),
(5, 5, 10)
])
def test_add(self, a, b, expected):
self.assertEqual(a + b, expected)@pytest.mark.parametrize("a,b,expected", [
(1, 2, 3),
(5, 5, 10),
pytest.param(0, 0, 0, id="zero_test"), # 可指定测试ID
])
def test_add(a, b, expected):
assert a + b == expectedself.assertEqual(a, b)
self.assertTrue(x)
self.assertIn(item, list)
self.assertRaises(ValueError, func)assert a == b
assert x
assert item in list
with pytest.raises(ValueError):
func()方面 | unittest | pytest |
|---|---|---|
执行速度 | 中等 | 通常更快,支持并行 |
内存占用 | 较低 | 中等 |
插件数量 | 有限 | 丰富(1000+ 插件) |
社区活跃度 | 中等(官方维护) | 非常活跃 |
学习曲线 | 平缓 | 中等,但功能多 |
# 直接运行 unittest 测试套件
pytest tests/ # 自动识别并运行 unittest 测试
# 生成测试报告
pytest --junitxml=report.xml tests/# 在 pytest 中使用 unittest 风格的测试
class TestLegacy(unittest.TestCase):
def test_old_style(self):
self.assertEqual(1, 1)
# 在同一个项目中混合使用
def test_new_style():
assert 1 == 1# conftest.py - 全局夹具配置
import pytest
from myapp import create_app, create_db
@pytest.fixture(scope="session")
def app():
app = create_app()
yield app
@pytest.fixture(scope="function")
def client(app):
return app.test_client()
# test_api.py - 使用夹具和参数化
class TestAPI:
@pytest.mark.parametrize("user_id,expected_status", [
(1, 200),
(999, 404),
("invalid", 400)
])
def test_get_user(self, client, user_id, expected_status):
respOnse= client.get(f"/api/users/{user_id}")
assert response.status_code == expected_status决策因素 | 推荐选择 |
|---|---|
快速上手,零配置 | unittest |
功能丰富,可扩展 | pytest |
大型项目,团队协作 | pytest |
简单脚本,个人使用 | unittest |
需要高级测试特性 | pytest |
与 CI/CD 深度集成 | pytest |
维护已有代码库 | 保持原框架 |
亲~登录后才可以操作哦!
确定你的邮箱还未认证,请认证邮箱或绑定手机后进行当前操作
举报
×
侵犯我的权益
×
侵犯了我企业的权益
×
抄袭了我的内容
×
原文链接或出处
诽谤我
×
对根叔社区有害的内容
×
不规范转载
×
举报说明
暂无评论