python:chapter41

第四十一章:测试与调试

完成本章学习后,你将能够:

  • 编写单元测试
  • 使用pytest框架
  • 使用调试器
  • 进行性能分析
import unittest
 
def add(a, b):
    return a + b
 
class TestMath(unittest.TestCase):
    def test_add(self):
        self.assertEqual(add(2, 3), 5)
        self.assertEqual(add(-1, 1), 0)
 
    def test_add_type_error(self):
        with self.assertRaises(TypeError):
            add("a", 1)
 
if __name__ == '__main__':
    unittest.main()
# test_sample.py
import pytest
 
def add(x, y):
    return x + y
 
def test_add():
    assert add(1, 2) == 3
    assert add(-1, 1) == 0
 
@pytest.mark.parametrize("x,y,expected", [
    (1, 2, 3),
    (0, 0, 0),
    (-1, 1, 0),
])
def test_add_param(x, y, expected):
    assert add(x, y) == expected
# 使用pdb
import pdb; pdb.set_trace()
 
# 常用命令
# n - 下一行
# s - 进入函数
# c - 继续
# p variable - 打印变量
# q - 退出
 
# Python 3.7+ breakpoint()
breakpoint()

1. 为项目编写测试 2. 使用mock模拟依赖 3. 性能分析和优化

下一章:第四十二章:项目结构

该主题尚不存在

您访问的页面并不存在。如果允许,您可以使用创建该页面按钮来创建它。

  • python/chapter41.txt
  • 最后更改: 2026/04/09 14:43
  • 张叶安