$npx -y skills add virgo777/buddyme --skill python-testing使用 pytest、TDD 方法论、测试夹具(Fixtures)、模拟(Mocking)、参数化(Parametrization)以及覆盖率要求的 Python 测试策略。
| 1 | # Python 测试模式(Python Testing Patterns) |
| 2 | |
| 3 | 使用 pytest、测试驱动开发(TDD)方法论和最佳实践的 Python 应用程序综合测试策略。 |
| 4 | |
| 5 | ## 何时激活 |
| 6 | |
| 7 | - 编写新的 Python 代码时(遵循 TDD:红、绿、重构) |
| 8 | - 为 Python 项目设计测试套件时 |
| 9 | - 审查 Python 测试覆盖率时 |
| 10 | - 搭建测试基础设施时 |
| 11 | |
| 12 | ## 核心测试哲学 |
| 13 | |
| 14 | ### 测试驱动开发 (TDD) |
| 15 | |
| 16 | 始终遵循 TDD 循环: |
| 17 | |
| 18 | 1. **红(RED)**:为期望的行为编写一个失败的测试 |
| 19 | 2. **绿(GREEN)**:编写最少的代码使测试通过 |
| 20 | 3. **重构(REFACTOR)**:在保持测试通过的同时改进代码 |
| 21 | |
| 22 | ```python |
| 23 | # 步骤 1:编写失败的测试 (红) |
| 24 | def test_add_numbers(): |
| 25 | result = add(2, 3) |
| 26 | assert result == 5 |
| 27 | |
| 28 | # 步骤 2:编写最简实现 (绿) |
| 29 | def add(a, b): |
| 30 | return a + b |
| 31 | |
| 32 | # 步骤 3:如果需要则进行重构 (重构) |
| 33 | ``` |
| 34 | |
| 35 | ### 覆盖率要求 |
| 36 | |
| 37 | - **目标**:80% 以上的代码覆盖率 |
| 38 | - **关键路径**:要求 100% 覆盖率 |
| 39 | - 使用 `pytest --cov` 来衡量覆盖率 |
| 40 | |
| 41 | ```bash |
| 42 | pytest --cov=mypackage --cov-report=term-missing --cov-report=html |
| 43 | ``` |
| 44 | |
| 45 | ## pytest 基础 |
| 46 | |
| 47 | ### 基本测试结构 |
| 48 | |
| 49 | ```python |
| 50 | import pytest |
| 51 | |
| 52 | def test_addition(): |
| 53 | """测试基本的加法。""" |
| 54 | assert 2 + 2 == 4 |
| 55 | |
| 56 | def test_string_uppercase(): |
| 57 | """测试字符串转大写。""" |
| 58 | text = "hello" |
| 59 | assert text.upper() == "HELLO" |
| 60 | |
| 61 | def test_list_append(): |
| 62 | """测试列表追加。""" |
| 63 | items = [1, 2, 3] |
| 64 | items.append(4) |
| 65 | assert 4 in items |
| 66 | assert len(items) == 4 |
| 67 | ``` |
| 68 | |
| 69 | ### 断言(Assertions) |
| 70 | |
| 71 | ```python |
| 72 | # 相等 |
| 73 | assert result == expected |
| 74 | |
| 75 | # 不等 |
| 76 | assert result != unexpected |
| 77 | |
| 78 | # 真值性 (Truthiness) |
| 79 | assert result # 为真 (Truthy) |
| 80 | assert not result # 为假 (Falsy) |
| 81 | assert result is True # 严格为 True |
| 82 | assert result is False # 严格为 False |
| 83 | assert result is None # 严格为 None |
| 84 | |
| 85 | # 成员关系 |
| 86 | assert item in collection |
| 87 | assert item not in collection |
| 88 | |
| 89 | # 比较 |
| 90 | assert result > 0 |
| 91 | assert 0 <= result <= 100 |
| 92 | |
| 93 | # 类型检查 |
| 94 | assert isinstance(result, str) |
| 95 | |
| 96 | # 异常测试 (推荐方法) |
| 97 | with pytest.raises(ValueError): |
| 98 | raise ValueError("error message") |
| 99 | |
| 100 | # 检查异常消息 |
| 101 | with pytest.raises(ValueError, match="invalid input"): |
| 102 | raise ValueError("invalid input provided") |
| 103 | |
| 104 | # 检查异常属性 |
| 105 | with pytest.raises(ValueError) as exc_info: |
| 106 | raise ValueError("error message") |
| 107 | assert str(exc_info.value) == "error message" |
| 108 | ``` |
| 109 | |
| 110 | ## 测试夹具 (Fixtures) |
| 111 | |
| 112 | ### 基本夹具用法 |
| 113 | |
| 114 | ```python |
| 115 | import pytest |
| 116 | |
| 117 | @pytest.fixture |
| 118 | def sample_data(): |
| 119 | """提供示例数据的夹具。""" |
| 120 | return {"name": "Alice", "age": 30} |
| 121 | |
| 122 | def test_sample_data(sample_data): |
| 123 | """使用该夹具进行测试。""" |
| 124 | assert sample_data["name"] == "Alice" |
| 125 | assert sample_data["age"] == 30 |
| 126 | ``` |
| 127 | |
| 128 | ### 带有设置/拆卸 (Setup/Teardown) 的夹具 |
| 129 | |
| 130 | ```python |
| 131 | @pytest.fixture |
| 132 | def database(): |
| 133 | """带有设置和拆卸功能的夹具。""" |
| 134 | # 设置 (Setup) |
| 135 | db = Database(":memory:") |
| 136 | db.create_tables() |
| 137 | db.insert_test_data() |
| 138 | |
| 139 | yield db # 提供给测试函数 |
| 140 | |
| 141 | # 拆卸 (Teardown) |
| 142 | db.close() |
| 143 | |
| 144 | def test_database_query(database): |
| 145 | """测试数据库操作。""" |
| 146 | result = database.query("SELECT * FROM users") |
| 147 | assert len(result) > 0 |
| 148 | ``` |
| 149 | |
| 150 | ### 夹具作用域 (Scopes) |
| 151 | |
| 152 | ```python |
| 153 | # 函数作用域 (默认) - 每个测试运行一次 |
| 154 | @pytest.fixture |
| 155 | def temp_file(): |
| 156 | with open("temp.txt", "w") as f: |
| 157 | yield f |
| 158 | os.remove("temp.txt") |
| 159 | |
| 160 | # 模块作用域 - 每个模块运行一次 |
| 161 | @pytest.fixture(scope="module") |
| 162 | def module_db(): |
| 163 | db = Database(":memory:") |
| 164 | db.create_tables() |
| 165 | yield db |
| 166 | db.close() |
| 167 | |
| 168 | # 会话作用域 - 整个测试会话运行一次 |
| 169 | @pytest.fixture(scope="session") |
| 170 | def shared_resource(): |
| 171 | resource = ExpensiveResource() |
| 172 | yield resource |
| 173 | resource.cleanup() |
| 174 | ``` |
| 175 | |
| 176 | ### 带有参数的夹具 |
| 177 | |
| 178 | ```python |
| 179 | @pytest.fixture(params=[1, 2, 3]) |
| 180 | def number(request): |
| 181 | """参数化夹具。""" |
| 182 | return request.param |
| 183 | |
| 184 | def test_numbers(number): |
| 185 | """测试将运行 3 次,每个参数一次。""" |
| 186 | assert number > 0 |
| 187 | ``` |
| 188 | |
| 189 | ### 使用多个夹具 |
| 190 | |
| 191 | ```python |
| 192 | @pytest.fixture |
| 193 | def user(): |
| 194 | return User(id=1, name="Alice") |
| 195 | |
| 196 | @pytest.fixture |
| 197 | def admin(): |
| 198 | return User(id=2, name="Admin", role="admin") |
| 199 | |
| 200 | def test_user_admin_interaction(user, admin): |
| 201 | """使用多个夹具进行测试。""" |
| 202 | assert admin.can_manage(user) |
| 203 | ``` |
| 204 | |
| 205 | ### 自动使用 (Autouse) 夹具 |
| 206 | |
| 207 | ```python |
| 208 | @pytest.fixture(autouse=True) |
| 209 | def reset_config(): |
| 210 | """在每个测试之前自动运行。""" |
| 211 | Config.reset() |
| 212 | yield |
| 213 | Config.cleanup() |
| 214 | |
| 215 | def test_without_fixture_call(): |
| 216 | # reset_config 自动运行 |
| 217 | assert Config.get_setting("debug") is False |
| 218 | ``` |
| 219 | |
| 220 | ### 用于共享夹具的 Conftest.py |
| 221 | |
| 222 | ```python |
| 223 | # tests/conftest.py |
| 224 | import pytest |
| 225 | |
| 226 | @pytest.fixture |
| 227 | def client(): |
| 228 | """所有测试共享的夹具。""" |
| 229 | app = create_app(testing=True) |
| 230 | with app.test_client() as client: |
| 231 | yield client |
| 232 | |
| 233 | @pytest.fixture |
| 234 | def auth_headers(client): |
| 235 | """为 API 测试生成认证头。""" |
| 236 | response = client.post("/api/login", json={ |
| 237 | "username": "test", |
| 238 | "password": "test" |
| 239 | }) |
| 240 | token = response.json["token"] |
| 241 | return {"Authorization": f"Bearer {token}"} |
| 242 | ``` |
| 243 | |
| 244 | ## 参数化 (Parametrization) |
| 245 | |
| 246 | ### 基本参数化 |
| 247 | |
| 248 | ```python |
| 249 | @pytest.mark.parametrize("input,expected", [ |
| 250 | ("hello", "HELLO"), |
| 251 | ("world", "WORLD"), |
| 252 | ("PyThOn", "PYTHON"), |
| 253 | ]) |
| 254 | def test_uppercase(input, expected): |
| 255 | """使用不同输入运行 3 次测试。""" |
| 256 | assert input.upper() == expected |
| 257 | ``` |
| 258 | |
| 259 | ### 多个参数 |
| 260 | |
| 261 | ```python |
| 262 | @pytest.mark.parametrize("a,b,expected", [ |
| 263 | (2, 3, 5), |
| 264 | (0, 0, 0), |
| 265 | (-1, 1, 0), |
| 266 | (100, 200, 300), |
| 267 | ]) |
| 268 | def test_add(a, b, expected): |
| 269 | """使用多个输入测试加法。""" |
| 270 | assert add(a, b) == expected |
| 271 | ``` |
| 272 | |
| 273 | ### 使用 ID 进行参数化 |
| 274 | |
| 275 | ```python |
| 276 | @pytest.mark.parametrize("input,expected", [ |
| 277 | ("valid@email.com", True), |
| 278 | ("invalid", False), |
| 279 | ("@no-domain.com", False), |
| 280 | ], ids=["valid-email |