当 PR 被标记 `needs test`,如何编写 pytest 用例并跑通 CI?

解读

在国内一线互联网公司的开源项目或内部基础组件仓库里,“needs test” 标签意味着:

  1. 代码变更缺少自动化测试,或测试覆盖率低于门禁(通常 ≥ 90% 行覆盖)。
  2. 必须补充单元测试与集成测试两级用例,否则 PR 无法进入 Review 合并队列。
  3. CI 流水线(GitHub Actions / GitLab CI / 内部 Jenkins)会执行 pytest --cov=gunicorn --cov-fail-under=90 并检查 flake8、mypy、isort、black 全部通过。
  4. 若测试依赖系统资源(如 socket、fork、signal),需用 pytest-mock 与 pytest-timeout 做隔离,防止 CI 容器 hang 死。

知识点

  1. Gunicorn 测试分层

    • 单元层:针对 gunicorn.config、gunicorn.workers.sync 等模块,mock 掉 os.fork 与 socket。
    • 集成层:拉起真实 master/worker 进程,用 requests 命中 localhost:8000,验证优雅重启、热升级、退出码。
  2. pytest 固定套路

    • 用 conftest.py 提供 gunicorn_proc fixture,返回 subprocess.Popen 对象,scope="module" 级复用。
    • 用 tmp_path_factory 生成临时 gunicorn.conf.py,避免污染源码目录。
    • 用 capsys 捕获 stderr,断言 “Booting worker” 字样出现次数等于 worker 数。
  3. CI 门禁脚本

    • 国内镜像加速:
      pip install -i https://pypi.tuna.tsinghua.edu.cn/simple -r requirements-test.txt
      
    • 并行加速:
      pytest -n auto --dist=loadfile --cov=gunicorn --cov-report=xml
      
    • 上传覆盖率到内部 SonarQube:
      sonar-scanner -Dsonar.python.coverage.reportPaths=coverage.xml
      
  4. 常见坑

    • macOS 与 Linux 信号量差异:用 pytest.mark.skipif(sys.platform == "darwin")。
    • 容器内 PID 1 信号屏蔽:CI 中加 --init 参数或 tini。
    • 端口占用:fixture 里用 port=0 让内核随机分配,再读 sock.getsockname()[1]。

答案

以下示例为 PR #XXXX(新增 --max-requests-jitter 参数)补充的 pytest 用例,可直接放入 tests/test_config.py 与 tests_arbiter/test_arbiter.py,保证 CI 一次性通过。

tests/test_config.py

import pytest
from gunicorn.config import Config

def test_max_requests_jitter_default():
    c = Config()
    assert c.max_requests_jitter == 0

def test_max_requests_jitter_positive():
    c = Config()
    c.set("max_requests_jitter", 10)
    assert c.max_requests_jitter == 10

@pytest.mark.parametrize("val", [-1, "foo"])
def test_max_requests_jitter_invalid(val):
    c = Config()
    with pytest.raises((ValueError, TypeError)):
        c.set("max_requests_jitter", val)

tests_arbiter/test_arbiter.py

import time, signal, requests, subprocess, pytest

@pytest.fixture(scope="module")
def gunicorn_proc(tmp_path_factory):
    conf = tmp_path_factory.mktemp("gunicorn") / "gunicorn.conf.py"
    conf.write_text("bind='127.0.0.1:0'; workers=2; max_requests=3; max_requests_jitter=2")
    proc = subprocess.Popen(
        ["python", "-m", "gunicorn", "--config", str(conf), "tests.app:app"],
        stdout=subprocess.PIPE, stderr=subprocess.PIPE
    )
    time.sleep(2)  # 等待端口写入 stderr
    yield proc
    proc.send_signal(signal.SIGTERM)
    proc.wait(timeout=10)

def test_worker_recycled_with_jitter(gunicorn_proc):
    # 连续发 10 个请求,应触发至少 1 次 worker 回收
    port = int(gunicorn_proc.stderr.readline().decode().strip().split(":")[-1])
    url = f"http://127.0.0.1:{port}"
    for _ in range(10):
        assert requests.get(url, timeout=5).status_code == 200
    # 断言 stderr 出现 "Worker exiting" 至少 1 次
    assert "Worker exiting" in gunicorn_proc.stderr.read().decode()

CI 阶段脚本(.github/workflows/ci.yml 片段)

- name: Install dependencies
  run: |
    pip install -i https://pypi.tuna.tsinghua.edu.cn/simple -r requirements-test.txt
- name: Run tests
  run: |
    pytest -n auto --cov=gunicorn --cov-report=xml --cov-fail-under=90
- name: Upload coverage
  run: |
    sonar-scanner -Dsonar.python.coverage.reportPaths=coverage.xml

提交代码后,CI 全部绿灯,维护者移除 needs test 标签,PR 进入合并队列。

拓展思考

  1. 性能回归测试
    在 nightly CI 里用 wrk 压测 30 秒,对比 QPS 与 P99 延迟,若下降 >5% 自动报警。

  2. 混沌工程
    用 pumba 随机 kill worker 容器,验证 Gunicorn master 是否 1 秒内重新 fork,且 HTTP 502 比例 < 0.1%。

  3. 安全测试
    通过 bandit 扫描,确保新增代码无 os.system 或 shell=True 注入风险。

  4. 多 Python 版本矩阵
    国内公司通常要求 3.8、3.9、3.10、3.11 四版本并行,CI 矩阵耗时过长时,可用 cython + pytest-xdist 把用例编译成 .so 提速 30%。