Original Note

2.2 Scaling Up Unit Testing - Read

2.2 Scaling Up Unit Testing(整理版)

原始笔记Scaling up Unit Test.md 原始教程2.2 Scaling Up Unit Testing created: 2026-07-25 20:45 整理说明:本版本只围绕原笔记已有的参数化测试、pytest-cov、coverage 统计和未覆盖行显示进行整理和补充。

内容简要概括

当多个测试只在输入和预期输出上不同时,可以使用 pytest.mark.parametrize 复用同一段测试逻辑。pytest-cov 用于统计测试执行覆盖了多少代码,而 term-missing 报告还能指出没有执行到的具体行。参数化与 coverage 结合,可以提升测试扩展效率并帮助识别覆盖缺口。

pytestpytest.mark.parametrize、参数化测试、unit test、pytest-cov、code coverage、--covterm-missing、测试输入、预期输出

目录


1. 参数化单元测试

当测试代码相同、只有测试数据和预期结果不同时,可以使用参数化测试,避免为每组数据重复编写测试函数。

from inflammation.models import daily_mean

@pytest.mark.parametrize(
    "test, expected",
    [
        ([[0, 0], [0, 0], [0, 0]], [0, 0]),
        ([[1, 2], [3, 4], [5, 6]], [3, 4]),
    ],
)
def test_daily_mean(test, expected):
    """Test mean function works for array of zeroes and positive integers."""
    npt.assert_array_equal(
        daily_mean(np.array(test)),
        np.array(expected),
    )

@pytest.mark.parametrize 是应用在测试函数上的 decorator:

  • "test, expected" 定义传入测试函数的参数名称;
  • 列表中的每个 tuple 提供一组输入 test 和预期结果 expected
  • pytest 会为每组参数分别调用一次 test_daily_mean()

这样可以在保留单一测试逻辑的同时增加测试数据,减少重复代码。

2. 检查 Code Coverage

先安装 pytest-cov

python3 -m pip install pytest-cov

然后运行带 coverage 统计的测试:

python3 -m pytest --cov=inflammation.models tests/test_models.py
  • --cov=inflammation.models:统计 inflammation.models 模块被测试执行到的代码;
  • tests/test_models.py:指定要运行的测试文件。

coverage 反映测试运行时执行到的语句比例,可用于发现尚未被测试覆盖的代码区域。

3. 定位未覆盖语句

如果要查看哪些语句没有被测试执行,可运行:

python3 -m pytest \
    --cov=inflammation.models \
    --cov-report term-missing \
    tests/test_models.py

--cov-report term-missing 会在终端 coverage 报告中增加 Missing 信息,列出未覆盖的行号。它用于定位覆盖缺口,但是否需要为某一行新增测试,仍应结合代码的重要性和行为判断。