工程笔记
评估 AI 编程助手:什么时候可以在生产环境中信任 LLM
作者 Muhammad Shahid · · 阅读约 11 分钟
快速解答
信任 AI 生成的代码要看它经受住了什么,而不是读起来怎么样。本文对八个典型生成代码 Bug 的测试中,严格的 TypeScript 和 ESLint 一个都没抓到,随代码一起写的测试也一个都没抓到,因为它们和代码有相同的假设。人工编写的边界用例测试和基于属性的测试抓住了全部八个,而且属性测试自己找到了最小的失败输入。再加上变异测试检查测试是否能察觉改动,加上针对路径、输入和依赖的安全检查、对意图的人工审查,以及受控发布。
| 技术栈 | TypeScript、Vitest 4、fast-check 4、Stryker 9、typescript-eslint(strictTypeChecked) |
|---|---|
| Bug | 八个人为植入、在生成代码中常见类型的 Bug:差一错误、舍入、日期、Unicode、路径、正则 |
| 静态检查 | tsc --strict 和 ESLint strictTypeChecked:8 个中抓到 0 个 |
| 测试 | 随代码写的测试:0/8;边界用例:8/8;属性测试:8/8 |
| 变异测试 | Stryker:173 处代码改动中,AI 测试察觉 57%,加边界和属性测试 65%,再加错误输入测试 88% |
AI 编程助手写出的代码能编译、读起来顺畅,也能通过随附的测试。正因如此,它的 Bug 才会进入生产:它们藏在没人写下来的情况里。本文不是重复这个说法,而是去验证它。我们拿八个按助手常见写法编写的小函数,每个都带有一个在 AI 生成代码中常见类型的 Bug,然后测量哪些测试策略能抓住它们:严格类型和 lint、随代码一起写的测试、人工编写的边界用例、用 fast-check 做的属性测试,以及用 Stryker 做的变异测试。Bug 是有意植入的,所以我们确切知道应该找到什么;下面每个数字都来自实际运行测试。
为什么 AI 生成的代码会以不同方式出错
人写出 Bug 时,通常也会写出漏掉它的测试,但至少问题在他的脑子里过过。生成的代码很流畅,却没有这种理解:它看起来像是处理了问题,而一起生成的测试检查的正是代码所做的同样假设。常见的出错类型有循环和分页中的差一错误、舍入和浮点数金额、不存在的日期、拉丁字母以外的文本、来自用户的文件路径、过于严格的正则表达式,以及重试和超时逻辑。这些都不会产生类型错误,所以光靠类型检查是不够的。
实验
| 函数 | Bug | 类型 |
|---|---|---|
| splitBill | 各份加起来不等于总额 | 舍入 |
| paginate | 第 1 页跳过了第一页 | 差一错误 |
| parseDate | 2 月 30 日被滚动到 3 月 | 日期 |
| slugify | 希伯来语或中文标题变成空字符串 | Unicode |
| applyDiscount | 浮点数分(17.991) | 金额 |
| safeFileName | "." 和 ".." 能通过 | 路径和安全 |
| retry | 多试了一次 | 差一错误 |
| isEmail | 拒绝有效地址 | 正则 |
助手写的代码
// Code as an AI assistant typically writes it: it reads well, passes the obvious tests,
// and each function hides one bug from a class that shows up often in generated code.
// Split a bill in cents between people.
export function splitBill(totalCents: number, people: number): number[] {
const share = Math.round(totalCents / people);
return Array.from({ length: people }, () => share); // BUG: shares may not add up to the total
}
// Return one page of results; page numbers start at 1.
export function paginate<T>(items: T[], page: number, size: number): T[] {
return items.slice(page * size, page * size + size); // BUG: skips the first page
}
// Parse a YYYY-MM-DD date.
export function parseDate(s: string): Date | null {
if (!/^\d{4}-\d{2}-\d{2}$/.test(s)) return null;
const d = new Date(s + "T00:00:00Z");
return isNaN(d.getTime()) ? null : d; // BUG: 2026-02-30 becomes 2 March instead of null
}
// Turn a title into a URL slug.
export function slugify(title: string): string {
return title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, ""); // BUG: Hebrew or Chinese titles become ""
}
// Apply a percentage discount to a price in dollars.
export function applyDiscount(price: number, percent: number): number {
return price - price * (percent / 100); // BUG: floating point, e.g. 19.99 at 10% is 17.991
}
// Make a user-supplied file name safe to store under an uploads folder.
export function safeFileName(name: string): string {
return name.replace("../", "").replace(/[/\\]/g, "_"); // BUG: removes only the first "../", and "..": "...." survives
}
// Retry an async call; attempts is the total number of tries.
export async function retry<T>(fn: () => Promise<T>, attempts: number): Promise<T> {
let lastError: unknown;
for (let i = 0; i <= attempts; i++) { // BUG: one try too many
try {
return await fn();
} catch (err) {
lastError = err;
}
}
throw lastError;
}
// Check that a string looks like an email address.
export function isEmail(s: string): boolean {
return /^[a-z0-9._]+@[a-z0-9-]+\.[a-z]+$/.test(s); // BUG: rejects "Ann+news@mail.co.uk" and capitals
}
每个函数都很短,命名良好,有注释,每个都能通过快速审查。Bug 注释是写给你看的;真实代码中不会有。
助手写的测试
// The tests an assistant typically writes next to its own code: one typical input each,
// checking the shape of the answer more than the answer.
import { describe, expect, it } from "vitest";
import { impl } from "./impl";
describe("happy path", () => {
it("splits a bill", () => expect(impl.splitBill(1000, 4)).toEqual([250, 250, 250, 250]));
it("returns a full page", () => expect(impl.paginate([...Array(100).keys()], 2, 10)).toHaveLength(10));
it("parses a date", () => expect(impl.parseDate("2026-11-12")?.getUTCDate()).toBe(12));
it("slugifies a title", () => expect(impl.slugify("Hello World!")).toBe("hello-world"));
it("applies a discount", () => expect(impl.applyDiscount(100, 10)).toBe(90));
it("keeps a normal file name", () => expect(impl.safeFileName("report.pdf")).toBe("report.pdf"));
it("retries until it works", async () => {
let n = 0;
expect(await impl.retry(async () => { if (++n < 2) throw new Error("flaky"); return "ok"; }, 3)).toBe("ok");
});
it("checks emails", () => {
expect(impl.isEmail("ann@example.com")).toBe(true);
expect(impl.isEmail("not-an-email")).toBe(false);
});
});
这些是典型的生成测试:每个函数一个普通输入,常常检查结果的形状而不是值("一页有 10 条")。八个测试在有 Bug 的代码上全部通过。它们并非没用,能抓住崩溃和明显错误,但抓不住代码和测试共有的错误假设。
严格类型和 lint 找到了什么
什么也没有。有 Bug 的文件通过了 tsc --strict,也通过了 typescript-eslint 的 strictTypeChecked 规则,没有一条警告。类型能抓住错误类型的值;这些 Bug 都是类型正确、但金额、日期或字符错误的值。保留类型检查和 linter,它们成本很低,但不要把它们当作对生成逻辑的审查。
审查者编写的边界用例测试
// Edge cases a careful reviewer writes by hand: each one needs someone to think of it.
import { describe, expect, it } from "vitest";
import { impl } from "./impl";
describe("edge cases", () => {
it("bill shares add up to the total", () => expect(impl.splitBill(1000, 3).reduce((a, b) => a + b, 0)).toBe(1000));
it("page 1 is the first page", () => expect(impl.paginate([1, 2, 3, 4, 5], 1, 2)).toEqual([1, 2]));
it("rejects 30 February", () => expect(impl.parseDate("2026-02-30")).toBeNull());
it("slugifies Hebrew", () => expect(impl.slugify("שלום עולם")).not.toBe(""));
it("discount has whole cents", () => expect(impl.applyDiscount(19.99, 10)).toBe(17.99));
it("never returns a parent-directory name", () => expect(impl.safeFileName("../..")).not.toBe(".."));
it("tries exactly the given number of times", async () => {
let n = 0;
await expect(impl.retry(async () => { n++; throw new Error("down"); }, 3, 0)).rejects.toThrow("down");
expect(n).toBe(3);
});
it("accepts plus addressing and capitals", () => expect(impl.isEmail("Ann+news@mail.co.uk")).toBe(true));
});
懂业务的审查者会写这些:不能均分的金额、第一页、2 月 30 日、希伯来语标题、带分的价格、恶意文件名、总是宕机的服务、真实世界的邮箱地址。八个测试在有 Bug 的代码上全部失败。问题在第一句话:每个测试都需要有人想到那个情况。
基于属性的测试
// Property-based tests: state a rule that must hold for every input and let fast-check search for a breaking one.
import fc from "fast-check";
import { describe, expect, it } from "vitest";
import { impl } from "./impl";
const RUNS = { numRuns: 300, seed: 42 };
describe("properties", () => {
it("bill shares always add up to the total and differ by at most 1 cent", () =>
fc.assert(fc.property(fc.integer({ min: 0, max: 1_000_000 }), fc.integer({ min: 1, max: 50 }), (total, people) => {
const shares = impl.splitBill(total, people);
expect(shares.reduce((a, b) => a + b, 0)).toBe(total);
expect(Math.max(...shares) - Math.min(...shares)).toBeLessThanOrEqual(1);
}), RUNS));
it("all pages together give back every item exactly once", () =>
fc.assert(fc.property(fc.array(fc.integer(), { maxLength: 60 }), fc.integer({ min: 1, max: 10 }), (items, size) => {
const pages = Math.ceil(items.length / size);
const all = Array.from({ length: pages }, (_, i) => impl.paginate(items, i + 1, size)).flat();
expect(all).toEqual(items);
}), RUNS));
it("a parsed date has the same year, month and day as the text", () =>
fc.assert(fc.property(fc.integer({ min: 1900, max: 2100 }), fc.integer({ min: 1, max: 12 }), fc.integer({ min: 1, max: 31 }), (y, m, d) => {
const text = y + "-" + String(m).padStart(2, "0") + "-" + String(d).padStart(2, "0");
const date = impl.parseDate(text);
if (date) expect(date.toISOString().slice(0, 10)).toBe(text);
}), RUNS));
it("any title with a letter or digit gives a non-empty slug", () =>
fc.assert(fc.property(fc.string({ unit: "grapheme", minLength: 1 }).filter((s) => /[\p{L}\p{N}]/u.test(s)), (title) => {
expect(impl.slugify(title)).not.toBe("");
}), RUNS));
it("a slug never has a double dash or a dash at either end", () =>
fc.assert(fc.property(fc.string({ unit: "grapheme" }), (title) => {
expect(impl.slugify(title)).not.toMatch(/--|^-|-$/);
}), RUNS));
it("a discounted price is a whole number of cents", () =>
fc.assert(fc.property(fc.integer({ min: 0, max: 1_000_000 }), fc.integer({ min: 0, max: 100 }), (cents, pct) => {
const out = impl.applyDiscount(cents / 100, pct);
expect(Math.abs(out * 100 - Math.round(out * 100))).toBeLessThan(1e-6);
}), RUNS));
it("a safe file name has no separators and is never '.' or '..'", () =>
fc.assert(fc.property(fc.string({ unit: fc.constantFrom(".", "/", "\\", "a", "b", "_") }), (name) => {
const out = impl.safeFileName(name);
expect(out).not.toMatch(/[/\\]/);
expect([".", ".."]).not.toContain(out);
}), RUNS));
it("retry calls the function exactly the given number of times when it always fails", () =>
fc.assert(fc.asyncProperty(fc.integer({ min: 1, max: 5 }), async (attempts) => {
let n = 0;
await impl.retry(async () => { n++; throw new Error("x"); }, attempts, 0).catch(() => {});
expect(n).toBe(attempts);
}), RUNS));
it("every generated valid address is accepted", () =>
fc.assert(fc.property(fc.emailAddress(), (email) => {
expect(impl.isEmail(email)).toBe(true);
}), RUNS));
});
属性测试陈述一条对每个输入都必须成立的规则,然后让 fast-check 生成数百个输入,寻找能打破它的那一个。"所有页合在一起正好把每个元素返回一次"并没有提到第 1 页,却找到了第 1 页的 Bug。"各份加起来总是等于总额"并没有提到 1 分钱分给两个人,却找到了它。属性失败时,fast-check 会把输入缩小到仍然失败的最小输入,所以报告是一个可读的 Bug,而不是一团随机数据。种子是固定的,所以每次运行结果完全一致。
fast-check 找到了什么
FAIL bill shares always add up to the total and differ by at most 1 cent
Counterexample: [1,2]
FAIL all pages together give back every item exactly once
Counterexample: [[0],1]
FAIL a parsed date has the same year, month and day as the text
Counterexample: [1900,2,29]
FAIL any title with a letter or digit gives a non-empty slug
Counterexample: ["¹"]
FAIL a discounted price is a whole number of cents
Counterexample: [62501,1]
FAIL a safe file name has no separators and is never '.' or '..'
Counterexample: ["."]
FAIL retry calls the function exactly the given number of times when it always fails
Counterexample: [1]
FAIL every generated valid address is accepted
Counterexample: ["a@a.a.aa"]
其中一些并不是人会首先尝试的输入。1900 年不是闰年,所以 1900 年 2 月 29 日不存在,有 Bug 的解析器悄悄把它变成了 3 月 1 日。上标 "¹" 在 Unicode 中是数字,只认 ASCII 的 slug 代码把它丢掉了。625.01 打 1% 的折扣,在浮点数中得到 618.7599。这些正是会进入生产的 Bug,因为没人想到这些输入。
测试本身好吗?变异测试
{ "testRunner": "vitest", "vitest": { "configFile": "vitest.config.ts" }, "mutate": ["src/reviewed.ts"], "reporters": ["clear-text"], "concurrency": 2, "tempDirName": ".stryker-tmp-all" }
tests the assistant wrote only:
File | total | covered | # killed | # timeout | # survived | # no cov | # errors |
All files | 57.23 | 60.00 | 99 | 0 | 66 | 8 | 0 |
+ edge cases, properties and bad-input tests:
File | total | covered | # killed | # timeout | # survived | # no cov | # errors |
All files | 88.44 | 88.95 | 153 | 0 | 19 | 1 | 0 |
抓住八个 Bug 证明测试能够失败;变异测试问的是它们是否因为正确的原因失败。Stryker 对审查后的代码做了 173 处小改动,比如把 < 改成 <=、删掉一个条件或清空一个字符串,并对每处改动运行测试。只用助手的测试时,57% 的改动被察觉。加上抓住了所有真实 Bug 的边界用例和属性测试后,也只提高到 65%:没有任何测试检查负数金额、第 0 页、空文件名或 0 次尝试会怎样,所以输入检查可以被删除而不会有测试失败。增加八个错误输入测试和一个属性后,分数提高到 88%。
// What mutation testing showed was missing: nothing checked how the functions treat bad input.
import { describe, expect, it } from "vitest";
import { impl } from "./impl";
describe("bad input", () => {
it("splitBill rejects negative, fractional and zero values", () => {
expect(() => impl.splitBill(-1, 2)).toThrow(/whole, non-negative/);
expect(() => impl.splitBill(1.5, 2)).toThrow(/whole, non-negative/);
expect(() => impl.splitBill(100, 0)).toThrow(/at least 1/);
expect(() => impl.splitBill(100, 1.5)).toThrow(/at least 1/);
});
it("paginate returns nothing for impossible pages", () => {
const items = [1, 2, 3];
for (const [page, size] of [[0, 2], [1, 0], [1.5, 2], [1, 2.5]]) expect(impl.paginate(items, page, size)).toEqual([]);
});
it("parseDate rejects month 13, month 0 and short years", () => {
for (const s of ["2026-13-01", "2026-00-10", "26-01-01", "2026-1-01", " 2026-01-01"]) expect(impl.parseDate(s)).toBeNull();
});
it("slugify handles empty, padded and full-width text", () => {
expect(impl.slugify("")).toBe("untitled");
expect(impl.slugify("--Hello--")).toBe("hello");
expect(impl.slugify("Hello World")).toBe("hello-world");
});
it("applyDiscount rejects impossible prices and percentages", () => {
for (const [p, pct] of [[-1, 10], [10, -1], [10, 101], [NaN, 10]]) expect(() => impl.applyDiscount(p, pct)).toThrow(/percent 0-100/);
expect(impl.applyDiscount(10, 100)).toBe(0);
expect(impl.applyDiscount(0.05, 50)).toBe(0.02); // the 2.5-cent discount rounds up to 3 cents
});
it("safeFileName limits length and replaces odd characters", () => {
expect(impl.safeFileName("a".repeat(300))).toHaveLength(120);
expect(impl.safeFileName("")).toBe("file");
expect(impl.safeFileName("my file?.pdf")).toBe("my_file_.pdf");
expect(impl.safeFileName("C:\\Users\\x\\.env")).toBe("env");
});
it("retry rejects zero or fractional attempts", async () => {
await expect(impl.retry(async () => 1, 0)).rejects.toThrow(/at least 1/);
await expect(impl.retry(async () => 1, 1.5)).rejects.toThrow(/at least 1/);
});
it("isEmail anchors both ends and limits length", () => {
for (const s of ["@a@b.co", "a@b.co@", "a b@c.co", "a@b", "a".repeat(250) + "@b.co"]) expect(impl.isEmail(s)).toBe(false);
});
});
剩下存活的 19 处改动中,有几处根本不可能改变行为:page < 1 可以删除,因为第 0 页本来就得到空切片。其余大多在重试延迟中,测试通过传入 0 延迟跳过了它们。这是一个判断,而不是失败:变异分数是一张"测试没有检查什么"的地图,由你决定哪些缺口重要。还要注意它没有衡量什么。通常使用的指标覆盖率,在分数提高之前早就很高了:代码行都运行了,但没有任何东西检查它们的结果。
审查后的代码
// The same functions after review, each written so that the property tests below hold.
export function splitBill(totalCents: number, people: number): number[] {
if (!Number.isInteger(totalCents) || totalCents < 0) throw new RangeError("totalCents must be a whole, non-negative number");
if (!Number.isInteger(people) || people < 1) throw new RangeError("people must be a whole number of at least 1");
const base = Math.floor(totalCents / people);
const extra = totalCents % people; // the first "extra" people pay one cent more
return Array.from({ length: people }, (_, i) => base + (i < extra ? 1 : 0));
}
export function paginate<T>(items: T[], page: number, size: number): T[] {
if (!Number.isInteger(page) || page < 1 || !Number.isInteger(size) || size < 1) return [];
return items.slice((page - 1) * size, page * size);
}
export function parseDate(s: string): Date | null {
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(s);
if (!m) return null;
const [y, mo, d] = [Number(m[1]), Number(m[2]), Number(m[3])];
const date = new Date(Date.UTC(y, mo - 1, d));
// Reject dates the calendar does not have instead of rolling them over
return date.getUTCFullYear() === y && date.getUTCMonth() === mo - 1 && date.getUTCDate() === d ? date : null;
}
export function slugify(title: string): string {
const slug = title
.normalize("NFKC")
.toLowerCase()
.replace(/[^\p{L}\p{N}]+/gu, "-") // keep letters and digits in every script
.replace(/^-+|-+$/g, "");
return slug || "untitled";
}
// Work in whole cents so floating point cannot leave 17.991; better still, store money as cents everywhere.
export function applyDiscount(price: number, percent: number): number {
if (!(price >= 0) || !(percent >= 0 && percent <= 100)) throw new RangeError("price must be >= 0 and percent 0-100");
const cents = Math.round(price * 100);
return (cents - Math.round((cents * percent) / 100)) / 100;
}
export function safeFileName(name: string): string {
const base = name.split(/[/\\]/).pop() ?? ""; // drop any directory part
const cleaned = base.replace(/[^\p{L}\p{N}._-]+/gu, "_").replace(/^\.+/, ""); // no leading dots: no "..", no hidden files
return cleaned.slice(0, 120) || "file";
}
export async function retry<T>(fn: () => Promise<T>, attempts: number, delayMs = 200): Promise<T> {
if (!Number.isInteger(attempts) || attempts < 1) throw new RangeError("attempts must be at least 1");
let lastError: unknown;
for (let i = 0; i < attempts; i++) {
try {
return await fn();
} catch (err) {
lastError = err;
if (i < attempts - 1) await new Promise((r) => setTimeout(r, delayMs * 2 ** i));
}
}
throw lastError;
}
export function isEmail(s: string): boolean {
// Deliberately loose: one @, something before it, a dot in the domain, no spaces. Confirm by sending a link.
return s.length <= 254 && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s);
}
修复和 Bug 一样有意思。账单份额利用余数分配,所以总能加回总额。日期会被重建并比对,所以日历上不存在的日子会被拒绝。slug 保留所有文字的字母和数字。金额用整数分处理。文件名去掉目录部分和开头的点。retry 按给定次数尝试,并在两次之间退避等待。邮箱检查是故意放宽的,因为检验地址的唯一可靠方法是给它发一封邮件。
生成代码的安全检查
safeFileName 的 Bug 是危险的那一个:名为 .. 的文件拼接到上传目录后,指向的是它的上级目录。凡是生成代码接触文件系统、shell、SQL 或 HTML 的地方,都要像对待用户输入一样怀疑地审查,因为它往往就是用户输入。检查助手新增的依赖(是否存在、是否有人维护、名字是不是某个流行包的拼写错误?),查找粘贴在代码中的密钥,并在 CI 中运行常规的安全扫描。AI 代码审查智能体可以在每个拉取请求上标出其中一部分问题,但它只是又一个审查者,不能代替测试。
AI 生成代码的审查流水线
把便宜的自动检查放进 CI,让每个拉取请求都运行,把人的注意力留给意图:这段代码是否完成了任务要求?没人写下来的输入会怎样?先用功能开关把生成的改动发布给一小部分用户,观察错误和业务数据,并保证一键回滚。每一个漏网的 Bug 都变成一个新的属性或边界用例测试。
什么时候可以信任 AI 生成的代码,什么时候不行
| 风险较低:正常审查即可信任 | 风险较高:信任前要严格测试 |
|---|---|
| UI 布局、样板代码、胶水代码 | 金额、日期、时区、单位 |
| 已有可靠测试覆盖的代码 | 没有测试,或测试由 AI 编写的代码 |
| 规则清晰的纯函数 | 文件路径、shell、SQL、HTML、认证 |
| 一次性脚本和原型 | 重试、并发、缓存、数据迁移 |
| 你自己也能写、能完整读懂的代码 | 你不熟悉的语言或库中的代码 |
常见错误及修复方法
| 错误 | 后果 | 修复 |
|---|---|---|
| 把 AI 写的测试当作证明 | 测试与代码有相同的错误假设 | 自己编写边界用例和属性测试 |
| 把类型检查通过当作审查 | 逻辑 Bug 悄悄通过 | 类型和 lint 是底线,不是审查 |
| 只测试英文、ASCII 输入 | 其他文字在生产中出错 | 在属性测试中生成 Unicode |
| 用浮点数表示金额 | 分出现偏差:17.991 | 从头到尾使用整数分 |
| 信任用户提供的文件名 | ".." 造成路径穿越 | 去掉目录和开头的点;字符白名单 |
| 只衡量覆盖率 | 代码行运行了,但没检查任何东西 | 变异测试显示测试实际验证了什么 |
| 一次性发布给所有人 | 罕见输入的 Bug 影响所有用户 | 功能开关和小范围发布 |
局限
这里的 Bug 是人工植入的,用来代表常见类型;它们不是真实助手输出的样本,真实生成代码的分布会不同,所以请把这些数字看作对各策略能力的说明,而不是比率。属性测试需要有人写出好的属性,这本身是一种技能。变异测试在大型代码库上很慢,所以只对重要文件或改动文件运行。而且这一切都不能代替对代码的理解:如果团队里没人能解释某个生成的函数,它就不应该进入生产。
自己运行
npm install -D typescript vitest fast-check @stryker-mutator/core @stryker-mutator/vitest-runner typescript-eslint eslint
IMPL=assistant npx vitest run # the buggy code: 23 of 33 tests fail
IMPL=reviewed npx vitest run # the reviewed code: 33 of 33 pass
npx stryker run stryker.all.json # mutation score of the full suite
npx eslint src/assistant.ts && npx tsc --noEmit -p . # both pass on the buggy code
完整项目很小:两个实现、四个测试文件和一个 Stryker 配置。把它用在你自己的生成函数上,每个函数写一个属性,看看哪些能经受住。
常见问题
上线前如何测试 AI 生成的代码?
自己编写边界用例和属性测试,运行变异测试检验这些测试,人工审查安全敏感代码,并先通过功能开关发布给一小部分用户。
AI 助手写的测试够好吗?
单靠它们不够。本文测试中,它们一个植入的 Bug 都没抓到,因为它们与代码有相同的假设。保留它们,但要加上你自己的测试。
TypeScript 严格模式能抓住 AI 代码的 Bug 吗?
它能抓住类型错误,抓不住逻辑错误。本文中严格 tsc 和 ESLint strictTypeChecked 一个 Bug 都没抓到。
什么是基于属性的测试?
一种测试,陈述一条对每个输入都必须成立的规则,例如"各份加起来等于总额",再让 fast-check 这样的库生成大量输入,寻找能打破它的输入。
什么是变异测试?
Stryker 这类工具对代码做小改动并运行测试;测试没察觉的改动就是测试的缺口。被察觉改动的比例就是变异分数。
AI 生成的代码中常见哪些 Bug?
差一错误、舍入和浮点数金额、不可能的日期、拉丁字母以外的文本、不安全的文件路径、过严的正则表达式和重试逻辑,还有编造或过时的 API。
应该让 AI 写测试吗?
可以用它起草测试,然后自己补上边界用例和属性。和代码出自同一个提示的测试往往会重复代码的错误。
如何审查 AI 生成代码的安全性?
把它构造的文件路径、shell 命令、SQL 和 HTML 当作不可信输入,检查每个新依赖,查找密钥,并在 CI 中运行安全扫描。
对 AI 代码来说,代码覆盖率够用吗?
不够。覆盖率只说明哪些行运行过,不能说明这些行出错时是否有测试会失败。变异测试衡量的正是这一点。
什么时候可以信任 AI 生成的代码?
当它被你信任的可靠测试覆盖、逻辑简单,而且你能完整读懂并解释它时。对金额、日期、路径、安全和并发要格外小心。
fast-check 的缩小(shrinking)有什么作用?
属性失败时,fast-check 会不断简化失败的输入,直到找到仍然失败的最小输入,例如 splitBill(1, 2)。
如何安全发布 AI 编写的改动?
放在功能开关后面,先发布给一小部分用户,监控错误和业务指标,并准备好快速回滚。