目录

第四十一章:测试与调试

本章目标

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

unittest模块

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()

pytest框架

# 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. 性能分析和优化

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