痛点:每次 git push 或提交 PR 时跑全量测试太慢(尤其 Playwright E2E 测试可能需要几分钟到几十分钟),但只跑"我改的那个模块"又怕遗漏级联影响。
目标:
- 只编译/运行与改动相关的测试
- 同时保证运行必要的安全网测试(smoke / critical path)
- 一次配置,自动运行,无需每次手动选
git diff → 找改动文件 → 映射到测试文件 → 合并"必要测试" → 运行
| 问题 | 答案 |
|---|---|
| 怎么知道改了什么? | git diff |
| 怎么知道改动对应哪些测试? | 命名约定 / 依赖分析 / 覆盖率追踪 |
| 哪些是"必要测试"? | 预定义的 smoke suite(核心流程永远跑) |
原理:测试文件和源码文件遵循统一的命名约定,脚本自动匹配。
scraper/core/browser.py → tests/test_core.py 或 tests/core/test_browser.py
scraper/middleware/retry.py → tests/middleware/test_retry.py
实现:写一个 scripts/run_affected_tests.py,逻辑如下:
# 1. git diff 拿到本次改动的源文件列表
changed = subprocess.run(
["git", "diff", "--name-only", "main"],
capture_output=True, text=True
).stdout.strip().split("\n")
# 2. 文件 → 测试文件映射规则
test_candidates = set()
for f in changed:
if f.startswith("scraper/"):
# 规则1:同名测试文件
module = f.replace("scraper/", "").replace(".py", "")
test_candidates.add(f"tests/{module}/test_*.py")
test_candidates.add(f"tests/test_{Path(module).name}")
# 规则2:如果改了核心模块,连带跑集成测试
if module.startswith("core/"):
test_candidates.add("tests/integration/")
# 3. 合并 always-run 测试
always_run = ["tests/smoke/", "tests/test_browser.py"]
# 4. 运行
pytest_args = list(test_candidates) + list(always_run)
subprocess.run(["pytest", *pytest_args])优点:零依赖,逻辑透明,可随意定制规则 缺点:需要手动维护映射规则
原理:pytest-testmon 在每次测试运行时记录哪个测试执行了哪个代码文件的哪一行,下次运行时自动对比 git diff 和覆盖率数据库,选出"受影响的测试"。
安装:
pip install pytest-testmon首次运行(建立覆盖率基线):
pytest --testmon # 全量跑一次,testmon 记录数据库之后每次修改代码后:
pytest --testmon # 自动只跑受影响的测试
pytest --testmon -x # -x 遇错即停,更快配合"必要测试":
# 受影响的测试 + smoke 标记的测试始终跑
pytest --testmon -m "smoke or testmon"配置 pytest.ini:
[pytest]
addopts =
--testmon
--testmon-noselect
markers =
smoke: 安全网测试,每次必跑
slow: E2E / 浏览器测试
unit: 单元测试优点:自动追踪,无需手动映射,精确到行级 缺点:需要一次全量跑建立基线;测试必须无副作用(不能在测试间修改全局状态)
原理:给测试打标,形成"测试金字塔",改动时按层级和大图选跑。
# 标记为核心流程 —— 每次都跑
@pytest.mark.smoke
def test_browser_lifecycle(): ...
# 慢测试 —— 仅在改动涉及 core/ 或 CI 时跑
@pytest.mark.integration
@pytest.mark.slow
def test_full_scrape_flow(): ...
# 改动 middleware/retry.py 时自动选中
@pytest.mark.retry
def test_retry_backoff(): ...
# 普通单元测试 —— 模块级映射跑
@pytest.mark.core
def test_page_manager_click(): ...运行时组合:
pytest -m "smoke" # 仅必要测试
pytest -m "smoke or unit" # 必要 + 所有单元
pytest -m "smoke or (unit and changed)" # 必要 + 变更模块的单元项目 marker 体系建议:
| 标记 | 含义 | 运行策略 |
|---|---|---|
smoke |
核心流程,必须永远通过 | 每次都跑 |
unit |
纯逻辑单元测试 | 关联模块改动时跑 |
integration |
需要真实浏览器 | 改动 core/exporters 时跑 |
slow |
E2E 完整流程 | 仅 pre-push / CI 跑 |
e2e |
端到端 | 仅 CI 全量跑 |
用 pre-commit 或 pre-push hook,在 git 操作时自动跑增量测试。
.pre-commit-config.yaml:
repos:
- repo: local
hooks:
- id: affected-tests
name: run affected tests
entry: python scripts/run_affected_tests.py
language: python
stages: [pre-push] # push 时才跑,commit 不管
pass_filenames: false或者轻量级 bash hook(.git/hooks/pre-push):
#!/bin/bash
echo ">>> running affected tests..."
python scripts/run_affected_tests.py
if [ $? -ne 0 ]; then
echo "tests failed, push aborted"
exit 1
fi在 CI pipeline 中分两阶段,利用缓存加速:
# .github/workflows/test.yml
jobs:
# 阶段1:快速验证(1-2 分钟)
quick:
steps:
- run: pytest -m "smoke" --testmon
# 阶段2:完整验证(仅在阶段1通过后,或手动触发)
full:
needs: quick
steps:
- run: pytest --testmon -m "smoke or unit or integration"创建 tests/ 目录,给测试打标,配置 pytest.ini:
# pytest.ini
[pytest]
testpaths = tests
markers =
smoke: 每次必跑的安全网测试
unit: 纯逻辑单元测试
slow: 需要浏览器的慢测试
addopts = -v --tb=short安装 pytest-testmon,建立基线,日常开发即可增量跑:
pip install pytest-testmon
pytest # 首次全量建立基线
pytest --testmon # 之后只跑受影响的编写 scripts/run_affected_tests.py,实现命名约定 + 自定义映射规则:
scraper/core/改动 → 连带跑所有 integration 测试scraper/exporters/改动 → 连带跑导出相关的所有测试scraper/middleware/改动 → 只跑 middleware 单测
配置 .github/workflows/test.yml 或公司内部 CI,在 PR 时跑两步:
- 快速层:
pytest -m "smoke" --testmon(~1 分钟) - 完整层:
pytest -m "not slow"(~5 分钟,仅合并前)
本项目结构:
playwright/
├── scraper/
│ ├── core/browser.py # 浏览器管理
│ ├── middleware/{stealth,retry,rate_limit}.py
│ ├── extractors/selector.py
│ ├── pipeline/{base,steps}.py
│ ├── exporters/{json,csv}_exporter.py
│ └── utils/helpers.py
├── tasks/ # 用户脚本
└── tests/ # 待创建
测试分层设计:
tests/
├── smoke/
│ └── test_quick_scrape.py # 一键抓取全流程,每次必跑
├── unit/
│ ├── test_selector.py # Field/Selector 提取逻辑
│ ├── test_pipeline.py # Pipeline/Step 编排
│ ├── test_rate_limit.py # 限速器
│ ├── test_retry.py # 重试逻辑
│ └── test_helpers.py # 工具函数
├── integration/
│ ├── test_browser.py # 浏览器启停
│ ├── test_navigation.py # 导航 + 等待
│ ├── test_interaction.py # 点击/填表/下拉
│ └── test_export.py # 导出文件验证
└── conftest.py # fixtures: browser, page, scraper
改动 → 测试映射:
| 改了哪个模块 | 跑哪些测试 |
|---|---|
core/browser.py |
test_browser.py + smoke + 所有 integration/ |
middleware/stealth.py |
smoke + test_browser.py |
middleware/retry.py |
test_retry.py + smoke |
middleware/rate_limit.py |
test_rate_limit.py + smoke |
extractors/selector.py |
test_selector.py + test_browser.py + smoke |
pipeline/base.py |
test_pipeline.py + smoke |
pipeline/steps.py |
test_pipeline.py + 所有 integration/ + smoke |
exporters/*.py |
test_export.py + smoke |
utils/*.py |
test_helpers.py + smoke |
| 多个模块 | 所有 unit/ + smoke |
tasks/ |
不触发自动化测试 |
| 场景 | 推荐方式 | 耗时 |
|---|---|---|
| 日常开发 | pytest --testmon |
~10-30s |
| 改了核心模块 | pytest -m "smoke or unit" --testmon |
~30s-1min |
| 提交前 | scripts/run_affected_tests.py (命名约定方案) |
~1-2min |
| PR / CI | 两阶段:smoke+affected → full suite | ~2min + ~10min |
核心理念:让 90% 的日常改动在 30 秒内完成测试验证,同时确保 100% 的关键路径永远不会被跳过。