12 - 实战:给一个无测试的 Agent 工具库从零补测试
本篇目标
- 完整走一遍"给无测试代码补测试"的五步流程:characterization → 提取依赖 → 单元测试 → 假 LLM → 集成测试;
- 拿走一套可直接落地的 CI 门禁配置(yaml/覆盖率/mypy/ruff,及 C++ 扩展的 clang-tidy 位);
- 会写项目 README 的"测试"章节,让测试成为团队文档的一部分;
- 用 20 道高频面试题收束全系列,检验自己能否讲清"为什么"。
本章项目 agentutils(Agent 的文件工具 + LLM 问答封装)的全部代码与测试均已实测通过:13 个测试全绿,行覆盖率 96%,mypy --strict 零告警。文中所有"实测"输出都来自这次完整演练——包括测试抓出来的三个真 bug。
1. 现状:一个"能跑但没人敢动"的模块
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| import os
def read_file(path: str) -> str: root = os.environ["AGENT_ROOT"] full = os.path.join(root, path) if not os.path.abspath(full).startswith(os.path.abspath(root)): raise PermissionError("escape workspace") with open(full, encoding="utf-8") as f: return f.read()
def write_file(path: str, content: str) -> None: ...
def answer_with_notes(question, notes_reader): import openai ctx = notes_reader("AGENT_NOTES.md") client = openai.OpenAI() r = client.chat.completions.create( model=os.environ.get("AGENT_MODEL", "gpt-4o-mini"), messages=[{"role": "user", "content": f"笔记:\n{ctx}\n\n问题:{question}"}]) return r.choices[0].message.content
|
病灶盘点(对照 06 篇):隐藏依赖(AGENT_ROOT 环境变量、函数内自建 openai client)、复制粘贴(逃逸校验两份)、静态耦合(answer_with_notes 直接吃环境与 SDK)、God 倾向(文件工具与 LLM 封装混居)。任何改动(比如换模型、加路径白名单)都只能靠手工跑 Agent 试。
2. 第一步:characterization 测试——先钉死现状
按 06 篇纪律:不猜行为,用实测值钉死。before 的依赖是环境变量,monkeypatch.setenv 就够(不必上子进程):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| import pytest from agentutils.workspace import read_file, write_file
@pytest.fixture def ws(tmp_path, monkeypatch): monkeypatch.setenv("AGENT_ROOT", str(tmp_path)) return tmp_path
def test_read_ok(ws): (ws / "a.txt").write_text("hello", encoding="utf-8") assert read_file("a.txt") == "hello"
def test_read_missing_env_is_KeyError(ws, monkeypatch): monkeypatch.delenv("AGENT_ROOT") with pytest.raises(KeyError): read_file("a.txt")
def test_escape_blocked(ws): with pytest.raises(PermissionError): read_file("../etc/passwd")
def test_write_creates_dirs(ws): write_file("sub/dir/b.txt", "x") assert (ws / "sub/dir/b.txt").read_text(encoding="utf-8") == "x"
|
实测:5 passed。注意 test_read_missing_env_is_KeyError——KeyError 是"丑但真实"的现状,characterization 阶段照锁(重构后它变成更优雅的显式异常,那是改行为,单独走需求流程)。
3. 第二步:提取依赖——端口、适配器与注入
按 06 篇的 seam 手术:环境变量 → 构造函数注入;openai client → 端口 + 适配器。after 版本四个文件:
1 2 3 4 5 6 7 8
| from typing import Protocol
class NotesReader(Protocol): def read(self, path: str) -> str: ...
class LLMClient(Protocol): def chat(self, system: str, user: str) -> str: ...
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| from pathlib import Path
class Workspace: """Agent 可见的文件沙箱:一切路径解析以 root 为锚。"""
def __init__(self, root: Path): self._root = Path(root).resolve()
def _resolve(self, path: str) -> Path: full = (self._root / path).resolve() if not str(full).startswith(str(self._root)): raise PermissionError(f"path escapes workspace: {path!r}") return full
def read(self, path: str) -> str: return self._resolve(path).read_text(encoding="utf-8")
def write(self, path: str, content: str) -> None: full = self._resolve(path) full.parent.mkdir(parents=True, exist_ok=True) full.write_text(content, encoding="utf-8")
def list_dir(self, path: str = ".") -> list[str]: return sorted(p.name for p in self._resolve(path).iterdir())
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| import os from .ports import NotesReader from .workspace import Workspace
class WorkspaceNotes: def __init__(self, ws: Workspace, notes_name: str = "AGENT_NOTES.md"): self._ws, self._name = ws, notes_name def read(self, path: str) -> str: return self._ws.read(path if path == self._name else self._name)
class OpenAIClient: def __init__(self, base_url="https://api.openai.com/v1", api_key=None, model="gpt-4o-mini", http_client=None): import openai self._client = openai.OpenAI( base_url=base_url, api_key=api_key if api_key is not None else os.environ["AGENT_API_KEY"], http_client=http_client) self._model = model
def chat(self, system: str, user: str) -> str: r = self._client.chat.completions.create( model=self._model, messages=[{"role": "system", "content": system}, {"role": "user", "content": user}]) return r.choices[0].message.content or ""
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| from .ports import LLMClient, NotesReader
SYSTEM_PROMPT = "你是笔记助手,仅根据笔记回答,不知道的说不知道。" MAX_PROMPT = 8000
class NotesAgent: def __init__(self, notes: NotesReader, llm: LLMClient): self._notes, self._llm = notes, llm
def answer(self, question: str) -> str: ctx = self._notes.read("AGENT_NOTES.md") prefix, suffix = "笔记:\n", f"\n\n问题:{question}" budget = MAX_PROMPT - len(prefix) - len(suffix) ctx = ctx[:budget] return self._llm.chat(SYSTEM_PROMPT, f"{prefix}{ctx}{suffix}")
|
前后对比(重构发生在 characterization 全绿保护下):
| 维度 |
before |
after |
| 根目录依赖 |
环境变量(每次读) |
构造函数注入 Workspace(root) |
| 逃逸校验 |
两处复制粘贴 |
_resolve 单点 |
| LLM 依赖 |
函数内 openai.OpenAI() |
LLMClient 端口 + OpenAIClient 适配器 |
| 可测性 |
必须环境变量 + 真 SDK |
tmp_path + Fake 即可 |
| 行为变化 |
— |
零(characterization 移植后全绿) |
迁移期做了一次"characterization 退役":旧函数式 API 的 5 条用例逐条改写为新类 API(read_file("a.txt") → Workspace(root=tmp_path).read("a.txt")),改写完的用例升级为永久单元测试 tests/unit/test_workspace.py,原文件归档进 docs-legacy/。这就是 06 篇说的:characterization 是脚手架,不是永久房。
4. 第三步:单元测试——测试抓出的第一个 bug
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| import pytest from agentutils.workspace import Workspace
@pytest.fixture def ws(tmp_path): return Workspace(root=tmp_path)
def test_roundtrip(ws): ws.write("a.txt", "hello") assert ws.read("a.txt") == "hello"
def test_escape_via_dotdot(ws): with pytest.raises(PermissionError, match="escape"): ws.read("../outside.txt")
def test_escape_via_absolute(ws): with pytest.raises(PermissionError, match="escape"): ws.read("/etc/passwd")
def test_list_dir_sorted(ws): for name in ("b.txt", "a.txt", "c.txt"): ws.write(name, "") assert ws.list_dir() == ["a.txt", "b.txt", "c.txt"]
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| from agentutils.agent import NotesAgent, SYSTEM_PROMPT
class FakeNotes: def __init__(self, text): self._t = text def read(self, path): assert path == "AGENT_NOTES.md"; return self._t
class FakeLLM: def __init__(self, reply="ok"): self.calls = []; self._reply = reply def chat(self, system, user): self.calls.append((system, user)) return self._reply
def test_prompt_contains_notes_and_question(): llm = FakeLLM() NotesAgent(FakeNotes("会议纪要:周三发布"), llm).answer("何时发布?") system, user = llm.calls[0] assert system == SYSTEM_PROMPT and "何时发布?" in user
def test_truncates_long_notes(): llm = FakeLLM() NotesAgent(FakeNotes("x" * 20_000), llm).answer("q") assert len(llm.calls[0][1]) <= 8000
|
test_truncates_long_notes 第一次运行就红了:第一版预算公式 MAX_PROMPT - len(question) - 8 少算了一个前缀字符,len(user) == 8001。这就是测试的价值瞬间:上下文超限在真实环境里表现为"偶发 API 报错",定位要几小时;在这里是 0.1 秒的一行红字。修复后的精确预算版全绿。
5. 第四步:mock LLM 的边界——为什么不用 patch("openai...")
04 篇原则在本项目的两次落地:
- 业务测试 mock 自家端口:
FakeLLM 是 LLMClient 端口的 Fake——记录调用、返回固定值,业务分支全覆盖(上面 3 条用例),从未出现 patch("openai...") 字样;
- 不 mock 你不拥有的东西:
OpenAIClient 适配器内部对 openai SDK 的调用,不用 mock.patch 指认内部实现,而是给它一个可注入的传输层(http_client 参数,第 3 节代码)。这里有个实测教训:最初用 respx 想全局拦截 openai 的请求,结果失败——openai SDK 自建 httpx client,拦截层对它不生效,请求直接打到了真网络。把 http_client 改成构造参数后,替换回到了"构造函数注入"的正轨。又一次验证:可测性是设计出来的,不是 patch 出来的。
6. 第五步:集成测试——真文件系统与 LLM 契约
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| import pytest from agentutils.workspace import Workspace
@pytest.mark.integration def test_symlink_escape_blocked(tmp_path): outside = tmp_path.parent / "outside.txt" outside.write_text("s", encoding="utf-8") (tmp_path / "link.txt").symlink_to(outside) ws = Workspace(root=tmp_path) with pytest.raises(PermissionError): ws.read("link.txt")
@pytest.mark.integration def test_unicode_and_newline(tmp_path): ws = Workspace(root=tmp_path) ws.write("笔记.md", "# 标题\n中文内容\n") assert ws.read("笔记.md") == "# 标题\n中文内容\n"
|
test_symlink_escape_blocked 是单元层测不出的真集成问题:单元层用 tmp_path 直接读写测不出"符号链接折叠后逃逸"——Path.resolve() 才是让它现身的机制。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| import httpx, pytest from agentutils.adapters import OpenAIClient
REPLY_JSON = {"choices": [{"message": {"content": "周三发布"}}]}
def make_client(handler): calls = [] def wrapped(request): calls.append(request) return handler(request) http = httpx.Client(transport=httpx.MockTransport(wrapped)) return (OpenAIClient(base_url="https://api.example.com/v1", api_key="test-key", http_client=http), calls)
def test_openai_client_contract(): client, calls = make_client(lambda req: httpx.Response(200, json=REPLY_JSON)) assert client.chat("sys", "hi") == "周三发布" assert len(calls) == 1 assert b"gpt-4o-mini" in calls[0].read()
def test_openai_client_401_raises(): client, _ = make_client(lambda req: httpx.Response(401, json={"error": "bad"})) with pytest.raises(Exception, match="401"): client.chat("s", "u")
|
httpx.MockTransport 走真实 SDK 序列化与响应解析(只换传输),比手写 Fake 更能抓契约偏差;想再进一步就上 07 篇的本地假服务端或 testcontainers。
全量实测结果:
1 2 3 4 5 6 7 8 9 10
| $ pytest tests --cov Name Stmts Miss Cover ------------------------------------------------- src/agentutils/adapters.py 17 2 88% src/agentutils/agent.py 12 0 100% src/agentutils/ports.py 3 0 100% src/agentutils/workspace.py 18 0 100% ------------------------------------------------- TOTAL 50 2 96% 13 passed in 0.35s
|
adapters 缺的 2 行是"key 从环境读"的分支——它属于组合根,留给一次显式的集成用例或接受不覆盖(并在 README 说明),不为数字写无断言测试(01 篇)。
7. CI 门禁全配置
.github/workflows/ci.yml(Python 主体 + C++ 扩展位;若仓库含 C++ 扩展则启用 cpp job——clang-tidy 的接法 08/11 篇已给全):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| name: ci on: pull_request: push: branches: [main]
jobs: python: runs-on: ubuntu-latest strategy: fail-fast: false matrix: python-version: ["3.10", "3.12"] steps: - uses: actions/checkout@v4 - uses: astral-sh/setup-uv@v5 with: enable-cache: true python-version: ${{ matrix.python-version }} - run: uv sync --frozen - name: 静态门禁 run: | uv run ruff check --select B,S,PT,E,F . uv run mypy src --strict - name: 单元测试(PR 快车道) run: uv run pytest tests/unit -q - name: 全量 + 覆盖率门禁 run: uv run pytest tests -q --cov --cov-report=xml --cov-fail-under=90
cpp: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - run: sudo apt-get update && sudo apt-get install -y cmake g++ clang-tidy - run: > cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug -DMYLIB_BUILD_TESTS=ON -DCMAKE_CXX_CLANG_TIDY="clang-tidy;--warnings-as-errors=*" - run: cmake --build build -j$(nproc) - run: ctest --test-dir build --output-on-failure
nightly: if: github.event_name == 'schedule' runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: astral-sh/setup-uv@v5 with: { enable-cache: true } - run: uv sync --frozen - run: uv run pytest tests -q -m "integration or slow" --maxfail=3 schedule: - cron: "0 18 * * *"
|
mypy --strict 不是一步到位:按 09 篇"基线 + 增量收紧",先对 src/ 非严格跑出基线记账,新代码强制 strict。本项目最终 mypy src --strict 输出 Success: no issues found in 5 source files(那次 message.content or "" 的修复就是它逼出来的)。
8. README 测试章节模板
写进项目 README,让"怎么跑测试"零口口相传:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| ## 测试
# 本地全量(约 1 秒) uv sync --frozen && uv run pytest tests -q
# 只跑单元层(最快反馈) uv run pytest tests/unit -q
# 覆盖率与门禁 uv run pytest tests --cov --cov-fail-under=90
- 分层:tests/unit(毫秒级,无外部依赖)/ tests/integration(真实 FS、HTTP 传输桩,标记 integration) - 覆盖率门禁 90%,重点模块(workspace/agent)100%;adapters 的环境分支接受不覆盖 - flaky 测试:发现即提 issue 并标记 flaky,一周内修复或删除(见 docs/flaky-policy.md) - 修 bug 的流程:先写复现测试(红)→ 修复(绿)→ 用例永久保留
|
模板四要素:跑法命令、分层说明、门禁数字、异常处理政策——新人 clone 到第一条绿输出之间不该超过五分钟。
9. 面试高频问题清单(20 题带要点)
- 单元测试和集成测试的边界怎么定? 看真实 I/O 与真实协作;单元层测逻辑分支、集成层测真契约,比例随项目类型(金字塔 vs 奖杯)。
- 什么是好的单元测试? FIRST:快/独立/可重复/自校验/及时;红了能直接指向坏的哪个行为。
- pytest 的 assert 为什么比 unittest 强? 导入期 AST 断言重写,输出中间子表达式值;helper 里要 register_assert_rewrite。
- fixture 的作用域怎么选? 默认 function;昂贵只读资源才升 module/session;宽作用域禁放可变状态。
- conftest.py 是什么? 按目录层级自动加载的 pytest 配置/fixture 载体;子目录同名 fixture 覆盖上层,实现分层。
- Mock/Stub/Spy/Fake 的区别? Stub 管输入、Spy/Mock 管交互(事后/事前)、Fake 是有真实行为的轻实现、Dummy 填位。
- 什么时候不该用 mock? 不 mock 你不拥有的接口(第三方 SDK)——收进自家端口再造替身;状态型依赖优先 Fake。
- patch 常见的坑? patch 定义处对 from-import 无效(要 patch 使用处)、属性名/模块名写错、值拷贝在导入期固化——三类现场要能复述。
- 什么是 property-based 测试? 陈述普适性质(往返/不变量/参考模型等价),引擎生成+缩小反例;适合解析器、纯算法、有状态组件。
- TDD 的红绿重构是什么?你的实践节奏? 测试先行的心智模型;实践中"新代码先行/同期,遗留代码 characterization 先行"。
- 什么是 seam(接缝)? Feathers:不编辑现场就能改变行为的点;构造函数注入是最简 object seam,链接期替换是 C/C++ 的 link seam。
- 接手无测试的遗留代码第一步做什么? characterization 测试锁现状(值实测),再重构;改行为时先改测试。
- 测试代码要不要 DRY? setup 层大胆去重,断言层宁可重复;错误的抽象比重复贵(Sandi Metz)。
- flaky 测试怎么治理? 识别→隔离(quarantine 不阻塞但限期)→归因(sleep/端口/环境泄漏/时区清单)→超期即删;重试必须留记录。
- 覆盖率 100% 为什么不是目标? 它是"哪些行从未执行"的诊断指标;无断言测试与分支盲区不被它反映;正解是改动行覆盖门禁。
- 静态类型检查在测试体系里的位置? 零成本全量类型层测试;None 流入、Optional 返回这类 bug 的第一道闸;基线+增量 strict 落地。
- 为什么要 fuzzing?测试用例不够吗? 示例/性质测试的输入空间仍是人定义的;覆盖引导变异能到达人想不到的深层路径,配 ASan 抓内存 UB。
- 基准测试为什么忽高忽低? 频率调节/后台进程/缓存冷热/GC/常量折叠与死代码;纪律是预热、多次 repeat、报 min、同环境对比。
- C++ 测试和 Python 测试最大的差异? 替身机制(链接期 vs 运行时)、内存与 UB 需 Sanitizer 兜底、死亡测试把崩溃变规格;双语言各测各的母语。
- 你如何把测试文化带进团队? 门禁自动化(红不可合并)+ 分层反馈(PR 十分钟内)+ flaky 治理条款 + README 测试文档——机制优先于号召。
本篇小结
- 五步流程完整落地:characterization(5 绿)→ seam 手术(端口/适配器/注入)→ 单元测试(抓出截断差一 bug)→ Fake 替身测业务、可注入传输测适配器 → 集成测试(符号链接逃逸、SDK 契约);
- 三次"测试/类型检查抓 bug"的实证:截断差一(8001>8000)、
message.content 为 Optional(mypy strict)、respx 对自建 client 失效(改设计注入);
- CI 门禁双 job + nightly;覆盖率 96% 且说明缺口理由;mypy --strict 收官;
- README 测试章节四要素:跑法、分层、门禁数字、flaky 政策;
- 20 题面试清单覆盖全系列——答不出"为什么"的题,回到对应章节重读。
练习
- 把本章
agentutils 完整敲进本地仓库并跑通 13 条测试;然后给 Workspace.list_dir 补一个"空目录返回空表"的用例,体会"先想断言再想实现"。
- 给
NotesAgent 加"多轮对话记忆"(history: list[tuple[str, str]] 参数),先写三条单元测试定义行为(含超长历史截断),再实现到全绿。
- 把第 7 节 yaml 落到你的真实项目,跑一次完整 PR 流水线;对每个失败的门禁逐条归因(ruff/mypy/覆盖率),记录修复顺序。
- 给
OpenAIClient 补"429 重试"行为:先写契约测试(MockTransport 返回 429 两次再 200),再实现重试,思考重试计数器该不该注入。
- 从 20 题里挑你最没把握的 5 题,各写 200 字答案并回读对应章节校对——这一步就是你的面试冲刺清单。