- 新增 modules/s2-01-go-test(Go 单元测试与 go test 工具链,13 章 / 60 小节) - 新增 modules/s2-02-go-project-test(Go 项目测试实战:替身、集成与基准,13 章 / 60 小节) - modules-plan.json 补齐阶段 2 的 6 个模块(其余 4 个标筹备中,保证模块编号与前后衔接正确) - index.html 的 PAGES 登记 s2-0 / s2-1 路由;阶段 1 最后一个模块的下一跳改为直接进入阶段 2 模块 1 - README 更新进度表与模块表(顺带修正阶段 2/4 的模块数) - 自检:check-chapter --strict 26 页通过、check-pages 135 页通过、check-glossary 134 页无漂移、portal 注册表通过
824 lines
52 KiB
HTML
824 lines
52 KiB
HTML
<!DOCTYPE html>
|
||
<html lang="zh-CN" data-theme="light">
|
||
<head>
|
||
<meta charset="utf-8">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||
<title>go test 工具链与命令行习惯 · Go 单元测试与 go test 工具链 · 测试开发工程师从零到成熟</title>
|
||
<meta name="description" content="Go 单元测试与 go test 工具链 第 9 章:go test 工具链与命令行习惯。">
|
||
<link rel="stylesheet" href="../../assets/doc.css">
|
||
</head>
|
||
<body>
|
||
|
||
<header class="topbar">
|
||
<div class="tb-in">
|
||
<a class="brand" href="../../index.html"><span class="logo">QA</span><div>从零到成熟<small>测试开发 · 模块详解</small></div></a>
|
||
<div class="crumbs">
|
||
<a href="../../index.html">学习路径</a><span class="sep">/</span>
|
||
<a href="../../index.html#s2">阶段 2 · 自动化</a><span class="sep">/</span>
|
||
<a href="index.html">Go 单元测试与 go test 工具链</a><span class="sep">/</span>
|
||
<b>第 9 章</b>
|
||
</div>
|
||
<div class="spacer"></div>
|
||
<button class="btn" id="tocToggle">☰ 导航</button>
|
||
<button class="btn" id="themeBtn" title="切换到深色主题">深色</button>
|
||
</div>
|
||
</header>
|
||
|
||
<div class="layout" id="layout">
|
||
<aside class="sidebar">
|
||
<h2>章节目录</h2>
|
||
<nav id="chapters"><a class="toc-a" href="01-why.html"><i class="cn">1</i>为什么测试开发的第一课是单元测试</a><div class="subnav"><a class="toc-a lv3" href="01-why.html#sec-1-1">一条线上缺陷怎么变成一条用例</a><a class="toc-a lv3" href="01-why.html#sec-1-2">单元测试在测试金字塔里的位置</a><a class="toc-a lv3" href="01-why.html#sec-1-3">单测的收益到底落在谁身上</a><a class="toc-a lv3" href="01-why.html#sec-1-4">测试开发写的单测和开发写的有什么不同</a><a class="toc-a lv3" href="01-why.html#sec-1-5">这个模块的主线与练法</a></div><a class="toc-a" href="02-basic.html"><i class="cn">2</i>测试的组织:文件、函数与包边界</a><div class="subnav"><a class="toc-a lv3" href="02-basic.html#sec-2-1">一个最小的测试文件</a><a class="toc-a lv3" href="02-basic.html#sec-2-2">包内测试与外部测试包</a><a class="toc-a lv3" href="02-basic.html#sec-2-3">go test 是怎么找到并运行测试的</a><a class="toc-a lv3" href="02-basic.html#sec-2-4">命名与签名:TestXxx、t 参数与失败即停</a><a class="toc-a lv3" href="02-basic.html#sec-2-5">测试文件组织的常见错误</a></div><a class="toc-a" href="03-table.html"><i class="cn">3</i>表驱动测试与 t.Run 子测试</a><div class="subnav"><a class="toc-a lv3" href="03-table.html#sec-3-1">从复制粘贴到用例表</a><a class="toc-a lv3" href="03-table.html#sec-3-2">用例表的结构:名字、输入、期望、期望错误</a><a class="toc-a lv3" href="03-table.html#sec-3-3">t.Run:失败能直接定位到哪条 case</a><a class="toc-a lv3" href="03-table.html#sec-3-4">子测试与 t.Parallel 的组合</a><a class="toc-a lv3" href="03-table.html#sec-3-5">用例表的常见反模式</a></div><a class="toc-a" href="04-assert.html"><i class="cn">4</i>断言、错误比对与失败信息</a><div class="subnav"><a class="toc-a lv3" href="04-assert.html#sec-4-1">标准库三件套:t.Errorf、t.Fatalf 与 t.Fatal</a><a class="toc-a lv3" href="04-assert.html#sec-4-2">辅助函数与 t.Helper()</a><a class="toc-a lv3" href="04-assert.html#sec-4-3">testify:assert 与 require 的分工</a><a class="toc-a lv3" href="04-assert.html#sec-4-4">结构体比对:cmp.Diff 与忽略字段</a><a class="toc-a lv3" href="04-assert.html#sec-4-5">错误断言:errors.Is、errors.As 与错误码</a></div><a class="toc-a" href="05-lifecycle.html"><i class="cn">5</i>生命周期、清理与并行</a><div class="subnav"><a class="toc-a lv3" href="05-lifecycle.html#sec-5-1">TestMain:全局准备、全局清理与退出码</a><a class="toc-a lv3" href="05-lifecycle.html#sec-5-2">t.Cleanup:失败与 panic 都能回收</a><a class="toc-a lv3" href="05-lifecycle.html#sec-5-3">t.TempDir 与 t.Setenv</a><a class="toc-a lv3" href="05-lifecycle.html#sec-5-4">t.Parallel:收益、限制与数据隔离</a><a class="toc-a lv3" href="05-lifecycle.html#sec-5-5">顺序依赖与共享状态</a></div><a class="toc-a" href="06-double.html"><i class="cn">6</i>测试替身:从接口到 gomock</a><div class="subnav"><a class="toc-a lv3" href="06-double.html#sec-6-1">五种替身分别在替什么</a><a class="toc-a lv3" href="06-double.html#sec-6-2">第一步永远是改设计:把依赖抽成接口</a><a class="toc-a lv3" href="06-double.html#sec-6-3">手写 fake:比生成代码更耐用的选择</a><a class="toc-a lv3" href="06-double.html#sec-6-4">gomock 与 mockgen:什么时候值得生成</a><a class="toc-a lv3" href="06-double.html#sec-6-5">替身的边界:哪些依赖不该 mock</a></div><a class="toc-a" href="07-coverage.html"><i class="cn">7</i>覆盖率:怎么跑、怎么看、怎么别被它骗</a><div class="subnav"><a class="toc-a lv3" href="07-coverage.html#sec-7-1">-coverprofile 与 go tool cover -html</a><a class="toc-a lv3" href="07-coverage.html#sec-7-2">覆盖率的口径:语句、分支与 -covermode</a><a class="toc-a lv3" href="07-coverage.html#sec-7-3">-coverpkg:跨包覆盖与真实的全量口径</a><a class="toc-a lv3" href="07-coverage.html#sec-7-4">覆盖率很高却仍然漏缺陷的四种情况</a><a class="toc-a lv3" href="07-coverage.html#sec-7-5">把覆盖率写进流水线:阈值与趋势</a></div><a class="toc-a" href="08-race-flake.html"><i class="cn">8</i>竞态、缓存与不稳定用例</a><div class="subnav"><a class="toc-a lv3" href="08-race-flake.html#sec-8-1">-race 抓的是什么:数据竞争与 happens-before</a><a class="toc-a lv3" href="08-race-flake.html#sec-8-2">结果缓存与 -count=1</a><a class="toc-a lv3" href="08-race-flake.html#sec-8-3">用例不稳定的六个来源</a><a class="toc-a lv3" href="08-race-flake.html#sec-8-4">时间与随机:注入 Clock、固定 seed</a><a class="toc-a lv3" href="08-race-flake.html#sec-8-5">从偶发失败到稳定复现的排查步骤</a></div><span class="toc-a active" aria-current="page"><i class="cn">9</i>go test 工具链与命令行习惯</span><div class="subnav current"><a class="toc-a lv3" href="#sec-9-1">常用 flag:-run、-v、-short、-timeout、-parallel</a><a class="toc-a lv3" href="#sec-9-2">go vet 与静态检查的分工</a><a class="toc-a lv3" href="#sec-9-3">-json 与 gotestsum:让结果能被机器读</a><a class="toc-a lv3" href="#sec-9-4">一个测试入口脚本该怎么写</a><a class="toc-a lv3" href="#sec-9-5">提交前的本地检查清单</a></div><a class="toc-a" href="10-maintain.html"><i class="cn">10</i>让测试代码也值得被 review</a><div class="subnav"><a class="toc-a lv3" href="10-maintain.html#sec-10-1">测试代码同样是代码</a><a class="toc-a lv3" href="10-maintain.html#sec-10-2">失败信息可定位:一条失败要能自己说话</a><a class="toc-a lv3" href="10-maintain.html#sec-10-3">禁用 time.Sleep 与魔法等待</a><a class="toc-a lv3" href="10-maintain.html#sec-10-4">命名、分组与文件拆分</a><a class="toc-a lv3" href="10-maintain.html#sec-10-5">一份可以照着念的 review 清单</a></div><a class="toc-a" href="11-lab.html"><i class="cn">11</i>实操:给一个真实 Go 包补单元测试</a><div class="subnav"><a class="toc-a lv3" href="11-lab.html#sec-11-1">任务说明与验收标准</a><a class="toc-a lv3" href="11-lab.html#sec-11-2">步骤一:读懂被测包与它的依赖</a><a class="toc-a lv3" href="11-lab.html#sec-11-3">步骤二:表驱动补齐主流程与边界</a><a class="toc-a lv3" href="11-lab.html#sec-11-4">步骤三:替身、并行与竞态排查</a><a class="toc-a lv3" href="11-lab.html#sec-11-5">交付物模板:测试报告与覆盖率</a></div><a class="toc-a" href="12-cheat.html"><i class="cn">12</i>速查表与高频坑</a><div class="subnav"><a class="toc-a lv3" href="12-cheat.html#sec-12-1">go test 命令与 flag 速查</a><a class="toc-a lv3" href="12-cheat.html#sec-12-2">断言与生命周期 API 速查</a><a class="toc-a lv3" href="12-cheat.html#sec-12-3">高频坑与反模式</a></div><a class="toc-a" href="13-checklist.html"><i class="cn">13</i>完成标准与自测</a><div class="subnav"><a class="toc-a lv3" href="13-checklist.html#sec-13-1">自测题</a><a class="toc-a lv3" href="13-checklist.html#sec-13-2">验收清单</a></div></nav>
|
||
<div class="side-foot">
|
||
<a class="btn" href="index.html">← 模块目录</a>
|
||
<a class="btn" href="../../index.html">学习路径</a>
|
||
</div>
|
||
</aside>
|
||
<div class="mask" id="mask"></div>
|
||
|
||
<main class="main-col">
|
||
<article>
|
||
<p class="chapnav">
|
||
<a href="index.html">Go 单元测试与 go test 工具链</a>
|
||
<span>·</span>
|
||
<span>第 <b class="pos">9</b> / 13 章</span>
|
||
<span>·</span>
|
||
<span>本章 5 小节</span>
|
||
</p>
|
||
|
||
<h2 id="toolchain"><span class="n">9</span>go test 工具链与命令行习惯</h2>
|
||
|
||
<p>前面八章解决的是「测试怎么写」:测试怎么组织、表驱动怎么摆、断言写在哪、替身怎么塞、覆盖率为什么骗人、竞态怎么复现。这一章解决另一半:命令怎么敲、结果怎么读。它看起来最没有技术含量,但我见过的「假绿」绝大多数出在这里。</p>
|
||
|
||
<p>一个真实的经过:本地 <code>go test ./...</code> 全绿,推上去 CI 红。查出来是两件事同时发生——本地没带 <code>-count=1</code>,跑的是上一次的缓存,那句 <code>(cached)</code> 谁也没看;CI 脚本写的是 <code>go test ./... | tee test.log</code>,取到的是 <code>tee</code> 的退出码 <code>0</code>,红绿都变成绿。<b>这类假绿比真缺陷难查,因为它从不报错,只是安静地说「通过」。</b></p>
|
||
|
||
<p>这一章讲五件事:五个必须会用的 flag(9.1)、<code>go vet</code> 与其他静态检查怎么分层(9.2)、怎么让结果能被机器读(9.3)、唯一的测试入口脚本怎么写(9.4)、提交前那 60 秒检查什么(9.5)。</p>
|
||
|
||
<div class="box tip">
|
||
<span class="bt">这一章的合格线</span>
|
||
<p>三个动作,每个都要能拿出输出当证据:① 用 <code>-v</code> 说清 <code>t.Parallel()</code> 的子用例到底并行了没有(看 <code>PAUSE</code> / <code>CONT</code> 的批次);② 演示一条「<code>go test</code> 默认抓不到、<code>go vet</code> 抓得到」的检查;③ 把 <code>go test -json</code> 喂给自己的脚本,区分「有用例失败」和「一个用例都没跑的编译失败」。</p>
|
||
<p>三个动作只用标准库;<code>gotestsum</code> 只负责渲染,装不装都不影响。</p>
|
||
</div>
|
||
|
||
<h3 id="sec-9-1">9.1 常用 flag:-run、-v、-short、-timeout、-parallel</h3>
|
||
|
||
<p>这五个 flag 都不改变「测什么」,只改变<b>跑什么、跑多久、跑完你能看到什么</b>。夹具是一个下单金额计算函数和它的表驱动测试,放在 <code>mall/internal/order</code>,金额单位统一用分,避免浮点误差:</p>
|
||
|
||
<pre data-lang="go" data-name="mall/internal/order/pay_amount.go:本章所有 flag 演示共用的夹具">package order
|
||
|
||
import "errors"
|
||
|
||
// ErrCouponNotUsable 表示券当前不可用于这一单。
|
||
var ErrCouponNotUsable = errors.New("优惠券不可用")
|
||
|
||
// Coupon 是本单要用的一张券;金额单位都是分。
|
||
type Coupon struct {
|
||
Code string
|
||
MinAmount int // 使用门槛
|
||
Discount int // 抵扣金额
|
||
Status int // 10 未使用 / 20 已使用 / 30 已过期
|
||
}
|
||
|
||
// Item 是一条订单明细。
|
||
type Item struct {
|
||
Price int
|
||
Quantity int
|
||
}
|
||
|
||
// PayAmount 计算应付金额 = 商品总额 - 券抵扣 + 运费。freight 单位为分。
|
||
func PayAmount(items []Item, c *Coupon, freight int) (int, error) {
|
||
total := 0
|
||
for _, it := range items {
|
||
total += it.Price * it.Quantity
|
||
}
|
||
if c == nil {
|
||
return total + freight, nil
|
||
}
|
||
if c.Status != 10 {
|
||
return 0, ErrCouponNotUsable
|
||
}
|
||
if total < c.MinAmount {
|
||
return 0, ErrCouponNotUsable
|
||
}
|
||
pay := total - c.Discount + freight
|
||
if pay < 0 {
|
||
pay = 0
|
||
}
|
||
return pay, nil
|
||
}</pre>
|
||
|
||
<p>这份测试有四个设计点,分别决定后面某个 flag 的行为:子用例都调了 <code>t.Parallel()</code>(<code>-parallel</code> 才有用);集成用例自己判断要不要跳过(<code>-short</code> 才有用);子用例名带中文和冒号(决定 <code>-run</code> 怎么写);循环里有一行 <code>tc := tc</code>(<code>go.mod</code> 写 <code>go 1.21</code> 时循环变量各轮共享,不拷一份会拿到最后一个用例;1.22 起改成每轮新变量,留着也无害)。</p>
|
||
|
||
<pre data-lang="go" data-name="mall/internal/order/pay_amount_test.go:一个子用例并行、一个集成用例受 -short 控制">package order
|
||
|
||
import (
|
||
"encoding/json"
|
||
"errors"
|
||
"net/http"
|
||
"os"
|
||
"testing"
|
||
)
|
||
|
||
func TestPayAmount(t *testing.T) {
|
||
cases := []struct {
|
||
name string
|
||
items []Item
|
||
coupon *Coupon
|
||
freight int
|
||
want int
|
||
wantErr error
|
||
}{
|
||
{
|
||
name: "无券:总额加运费",
|
||
items: []Item{{Price: 12000, Quantity: 1}},
|
||
freight: 800,
|
||
want: 12800,
|
||
},
|
||
{
|
||
name: "券抵扣后加运费",
|
||
items: []Item{{Price: 12000, Quantity: 1}},
|
||
coupon: &Coupon{Code: "CPN20240614001", MinAmount: 10000, Discount: 2000, Status: 10},
|
||
freight: 800,
|
||
want: 10800,
|
||
},
|
||
{
|
||
name: "券已过期:不可用",
|
||
items: []Item{{Price: 12000, Quantity: 1}},
|
||
coupon: &Coupon{Code: "CPN20240614001", MinAmount: 10000, Discount: 2000, Status: 30},
|
||
wantErr: ErrCouponNotUsable,
|
||
},
|
||
{
|
||
name: "未达门槛:不可用",
|
||
items: []Item{{Price: 9900, Quantity: 1}},
|
||
coupon: &Coupon{Code: "CPN20240614001", MinAmount: 10000, Discount: 2000, Status: 10},
|
||
wantErr: ErrCouponNotUsable,
|
||
},
|
||
}
|
||
|
||
for _, tc := range cases {
|
||
tc := tc
|
||
t.Run(tc.name, func(t *testing.T) {
|
||
t.Parallel()
|
||
got, err := PayAmount(tc.items, tc.coupon, tc.freight)
|
||
if !errors.Is(err, tc.wantErr) {
|
||
t.Fatalf("err = %v, want %v", err, tc.wantErr)
|
||
}
|
||
if err != nil {
|
||
return
|
||
}
|
||
if got != tc.want {
|
||
t.Errorf("pay = %d, want %d", got, tc.want)
|
||
}
|
||
})
|
||
}
|
||
}
|
||
|
||
// TestPayAmountAgainstCouponAPI 要连 coupon-api(8083),属于集成用例,-short 时不跑。
|
||
func TestPayAmountAgainstCouponAPI(t *testing.T) {
|
||
if testing.Short() {
|
||
t.Skip("short 模式:跳过需要 coupon-api(8083) 的用例")
|
||
}
|
||
base := os.Getenv("COUPON_API_BASE")
|
||
if base == "" {
|
||
t.Skip("未设置 COUPON_API_BASE,跳过")
|
||
}
|
||
resp, err := http.Get(base + "/api/v1/coupon/CPN20240614001")
|
||
if err != nil {
|
||
t.Fatalf("查询券失败:%v", err)
|
||
}
|
||
defer resp.Body.Close()
|
||
var body struct {
|
||
Data struct {
|
||
Status int `json:"status"`
|
||
} `json:"data"`
|
||
}
|
||
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
|
||
t.Fatalf("解析响应失败:%v", err)
|
||
}
|
||
if body.Data.Status != 10 {
|
||
t.Errorf("券状态 = %d, want 10(未使用)", body.Data.Status)
|
||
}
|
||
}</pre>
|
||
|
||
<p><b><code>-run</code>:选用例,不是选包。</b>它收一个正则,<b>按未转义的斜杠分段</b>,逐段匹配顶层用例名与子用例名。第一个坑是「未锚定」:<code>-run 'TestPayAmount/券已过期'</code> 的第一段只是部分匹配,于是 <code>TestPayAmountAgainstCouponAPI</code> 也被选中——下面这段真实输出里它确实跑了,并因为没设 <code>COUPON_API_BASE</code> 变成 SKIP。</p>
|
||
|
||
<pre data-lang="bash" data-name="-run 的未锚定匹配:想只跑一个子用例,却多跑了一个集成用例">$ go test -count=1 -v -run 'TestPayAmount/券已过期' ./internal/order
|
||
=== RUN TestPayAmount
|
||
=== RUN TestPayAmount/券已过期:不可用
|
||
=== PAUSE TestPayAmount/券已过期:不可用
|
||
=== CONT TestPayAmount/券已过期:不可用
|
||
--- PASS: TestPayAmount (0.00s)
|
||
--- PASS: TestPayAmount/券已过期:不可用 (0.00s)
|
||
=== RUN TestPayAmountAgainstCouponAPI
|
||
pay_amount_test.go:72: 未设置 COUPON_API_BASE,跳过
|
||
--- SKIP: TestPayAmountAgainstCouponAPI (0.00s)
|
||
PASS
|
||
ok mall/internal/order 2.289s
|
||
|
||
# 加锚点:两段各自锚定,只跑我要的那一个子用例
|
||
$ go test -count=1 -v -run '^TestPayAmount$/^券已过期' ./internal/order
|
||
=== RUN TestPayAmount
|
||
=== RUN TestPayAmount/券已过期:不可用
|
||
=== PAUSE TestPayAmount/券已过期:不可用
|
||
=== CONT TestPayAmount/券已过期:不可用
|
||
--- PASS: TestPayAmount (0.00s)
|
||
--- PASS: TestPayAmount/券已过期:不可用 (0.00s)
|
||
PASS
|
||
ok mall/internal/order 2.124s</pre>
|
||
|
||
<p>第二个坑是 <code>$</code> 只作用于自己那一段:写成 <code>'^TestPayAmount$/^券已过期$'</code>,第二段就要求名字以「过期」结尾,而实际是「券已过期:不可用」,输出变成 <code>testing: warning: no tests to run</code>——退出码仍是 0,看着像通过,其实一条用例都没跑。<b>所以「怎么看」的第一条是:见到 <code>no tests to run</code> 就当成配置错误,而不是当成绿。</b></p>
|
||
|
||
<p><b><code>-v</code>:回答「并行了吗」的唯一手段。</b>不加 <code>-v</code> 时,包通过的情况下测试二进制的输出会被收走,你只看到一行 <code>ok</code>。<code>t.Parallel()</code> 在输出里表现为两批行:用例先登记为 <code>=== PAUSE</code>,等父用例中非并行的部分跑完,再一起放行为 <code>=== CONT</code>。<b>同一批 <code>CONT</code> 的条数就是当时的并行度</b>:</p>
|
||
|
||
<pre data-lang="bash" data-name="-short、-timeout、-parallel 的真实输出(三份夹具:跳过用例 / 死在超时 / 四个并行子用例)"># 1) -short:集成用例被它自己跳过,-short 没有做任何事
|
||
$ go test -count=1 -short -v ./internal/order
|
||
...
|
||
=== RUN TestPayAmountAgainstCouponAPI
|
||
pay_amount_test.go:68: short 模式:跳过需要 coupon-api(8083) 的用例
|
||
--- SKIP: TestPayAmountAgainstCouponAPI (0.00s)
|
||
PASS
|
||
ok mall/internal/order 2.061s
|
||
|
||
# 2) -timeout:一个等 pay-api 回调、睡 30 秒的用例,超时后是一份协程栈
|
||
$ go test -count=1 -timeout 2s ./internal/timeoutlab
|
||
panic: test timed out after 2s
|
||
running tests:
|
||
TestWaitPayCallback (2s)
|
||
|
||
goroutine 5 [running]:
|
||
testing.(*M).startAlarm.func1()
|
||
.../src/testing/testing.go:2802 +0x354
|
||
(后面 30 余行是全部协程的调用栈,此处省略)
|
||
FAIL mall/internal/timeoutlab 3.158s
|
||
FAIL
|
||
$ echo $?
|
||
1
|
||
|
||
# 3) -parallel:四个子用例各睡 500ms,都调了 t.Parallel()
|
||
$ go test -count=1 -parallel 1 ./internal/stocklock
|
||
ok mall/internal/stocklock 3.285s
|
||
$ go test -count=1 -parallel 4 ./internal/stocklock
|
||
ok mall/internal/stocklock 1.720s</pre>
|
||
|
||
<p><b><code>-short</code>:它自己不跳过任何东西。</b><code>go help testflag</code> 的原话是「Tell long-running tests to shorten their run time」,它只做一件事:把 <code>testing.Short()</code> 变成 <code>true</code>,跳过与否由用例里的那个 <code>if</code> 决定。上面第一段输出里的 <code>--- SKIP</code> 是用例自己打的,不是 <code>go test</code> 打的——在一个没人判断 <code>testing.Short()</code> 的仓库里,<code>-short</code> 只是个空开关。</p>
|
||
|
||
<p><b><code>-timeout</code>:默认 10 分钟,超时给的是协程栈。</b><code>running tests</code> 下面列出超时那一刻还在跑的用例,括号里的 <code>(2s)</code> 是它已经跑了多久;再往下是全部协程的调用栈,<b>那 30 多行才是超时输出唯一值钱的部分</b>,它直接指出卡在 <code>time.Sleep</code> 的哪一行、谁在等锁、谁在等 channel。包级耗时 3.158s 比 <code>-timeout 2s</code> 略大是正常的:打完协程栈才退出。退出码是 1。<b>别把超时交给 CI 的作业超时</b>:作业超时是分钟级,<code>go test</code> 默认 10 分钟,叠加的结果是先白等十分钟,再收到一句「已取消」,什么证据都没有。</p>
|
||
|
||
<p><b><code>-parallel</code>:只管调了 <code>t.Parallel()</code> 的用例。</b>默认值是 <code>GOMAXPROCS</code>。上面第三段数字可以直接对账:四个子用例各睡 500ms,<code>-parallel 1</code> 串行 ≈ 2s,<code>-parallel 4</code> ≈ 0.5s,再加上各约 1.2s 的编译与启动开销,于是 <code>3.285s</code> 与 <code>1.720s</code> 相差约 1.5s(正好 3×500ms)。要和 <code>-p</code> 区分开:<b><code>-p</code> 控制同时构建运行几个包,<code>-parallel</code> 控制一个包里同时跑几个用例</b>。反过来,调得过大而用例之间共享了测试数据、端口或数据库行,就会从「更快」变成「偶发红」——第 8 章那类不稳定用例的来源之一。</p>
|
||
|
||
<p>最后补一个不在标题里、却必须每次都带的 flag:<code>-count=1</code>。Go 的测试结果是<b>带缓存</b>的,判据是「编译输入 + 测试二进制 + 一部分环境变量」,同样的命令连跑两次,第二次直接吐上一次的结果:</p>
|
||
|
||
<pre data-lang="bash" data-name="-count=1 关掉缓存:输出里的 (cached) 就是假绿的入口">$ go test ./internal/order
|
||
ok mall/internal/order 1.443s
|
||
$ go test ./internal/order
|
||
ok mall/internal/order (cached) # 一个用例都没跑
|
||
|
||
$ go test -count=1 ./internal/order
|
||
ok mall/internal/order 1.956s # 真的跑了</pre>
|
||
|
||
<p>单元测试缓存命中通常无害,但两类用例上它是灾难:<b>连真实服务的集成用例</b>(服务重启了、数据变了,缓存不知道)与<b>依赖环境变量的用例</b>(只认了其中一部分)。我的习惯是硬性的:<b>入口脚本里的 <code>go test</code> 一律带 <code>-count=1</code></b>,手动敲时想省时间才允许省。</p>
|
||
|
||
<div class="tablewrap">
|
||
<table>
|
||
<thead>
|
||
<tr><th>flag</th><th>默认</th><th>你能看到什么变化</th><th>我什么时候用它</th></tr>
|
||
</thead>
|
||
<tbody>
|
||
<tr>
|
||
<td><code>-run regexp</code></td>
|
||
<td>空(全跑)</td>
|
||
<td>只跑命中的用例,父用例也会被跑出来;一条都不命中时输出 <code>no tests to run</code>,退出码仍是 0</td>
|
||
<td>调试单个失败用例;和 <code>-v</code> 一起用时两段都加 <code>^</code> 锚定</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>-v</code></td>
|
||
<td>关</td>
|
||
<td>出现 <code>=== RUN</code>、<code>=== PAUSE</code>、<code>=== CONT</code> 与 <code>--- PASS/FAIL/SKIP</code>,并打印 <code>t.Log</code></td>
|
||
<td>看子用例与并行批次;给 CI 留证据;平时不必开</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>-short</code></td>
|
||
<td>false</td>
|
||
<td>不会自动跳过任何东西;跳过是你的用例调 <code>t.Skip</code> 打出来的</td>
|
||
<td>本地默认与 CI 每次提交;发版前再跑全量</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>-timeout d</code></td>
|
||
<td><code>10m</code></td>
|
||
<td><code>panic: test timed out after ...</code> 加全部协程栈,退出码 1</td>
|
||
<td>把超时收到单包合理值,让失败自带现场</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>-parallel n</code></td>
|
||
<td><code>GOMAXPROCS</code></td>
|
||
<td>同一批 <code>CONT</code> 的条数变化,包级耗时跟着变</td>
|
||
<td>本地提速;怀疑并行度造成偶发失败时反着调</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>-count=1</code></td>
|
||
<td>1,但仍会用缓存</td>
|
||
<td>不再出现 <code>(cached)</code>,耗时变长说明真的重跑了</td>
|
||
<td>脚本、CI,以及任何一次复核</td>
|
||
</tr>
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
|
||
<div class="box warn">
|
||
<span class="bt">这三句话最容易把人带沟里</span>
|
||
<ul>
|
||
<li>「加了 <code>-short</code> 就会跳过慢用例」——它只把开关交给 <code>testing.Short()</code>,全仓库没人判断它就是空的。</li>
|
||
<li>「CI 有作业超时,<code>-timeout</code> 不用设」——作业超时给的是一句「已取消」,<code>-timeout</code> 给的是一份协程栈,证据的价值差一个量级。</li>
|
||
<li>「<code>-parallel</code> 调大就更快」——它只影响调了 <code>t.Parallel()</code> 的用例,还可能把「环境共享」变成「偶发冲突」。</li>
|
||
</ul>
|
||
</div>
|
||
|
||
<h3 id="sec-9-2">9.2 go vet 与静态检查的分工</h3>
|
||
|
||
<p>测试代码里的错误不会让线上挂,但会让<b>你的结论错</b>,而且错得很安静。最典型的一个:在测试里起 goroutine,然后在里面调 <code>t.Fatalf</code>。<code>Fatal</code> 在非测试协程里调用是无效的——测试协程早往下走了,用例照样 PASS。<b>你得到的不是一个错误的断言,而是一个永远绿的用例。</b></p>
|
||
|
||
<p>这类问题正是 <code>go vet</code> 的目标区域。先拆掉一个误解:<code>go test</code> 自己会跑 vet,但 <code>go help testflag</code> 说的是「a curated list of checks believed to be always worth addressing」——<b>一份挑过的清单,不是 vet 的全部</b>。下面这份测试故意写了三个问题,用四种模式各跑一遍:</p>
|
||
|
||
<pre data-lang="go" data-name="mall/internal/stock/stock.go:夹具本体(测试文件用到的两个符号)">package stock
|
||
|
||
import "sync"
|
||
|
||
// Stock 是某个 SKU 的库存计数。
|
||
type Stock struct {
|
||
mu sync.Mutex
|
||
TotalQty int
|
||
LockedQty int
|
||
SoldQty int
|
||
}
|
||
|
||
// Available 返回可用量。
|
||
func (s *Stock) Available() int {
|
||
s.mu.Lock()
|
||
defer s.mu.Unlock()
|
||
return s.TotalQty - s.LockedQty - s.SoldQty
|
||
}
|
||
|
||
// NewStock 造一个库存对象。
|
||
func NewStock(total int) *Stock {
|
||
return &Stock{TotalQty: total}
|
||
}</pre>
|
||
|
||
<pre data-lang="go" data-name="mall/internal/stock/stock_test.go:三个「编译器不管、vet 管」的问题">package stock
|
||
|
||
import (
|
||
"testing"
|
||
"time"
|
||
)
|
||
|
||
func TestAvailable(t *testing.T) {
|
||
s := NewStock(100)
|
||
if got := s.Available(); got != 100 {
|
||
t.Errorf("available = %d", "SKU-1001") // ① 格式串与参数类型不匹配
|
||
}
|
||
}
|
||
|
||
func TestAvailableCopiesLock(t *testing.T) {
|
||
s := NewStock(100)
|
||
copied := *s // ② Stock 含有 sync.Mutex,这里把锁拷贝了一份
|
||
if copied.Available() != 100 {
|
||
t.Errorf("available = %d, want 100", copied.Available())
|
||
}
|
||
}
|
||
|
||
func TestLockStockAsync(t *testing.T) {
|
||
s := NewStock(100)
|
||
go func() {
|
||
time.Sleep(10 * time.Millisecond)
|
||
if s.Available() != 100 {
|
||
t.Fatalf("预占后可用量不对:%d", s.Available()) // ③ 在非测试协程里调用 Fatalf
|
||
}
|
||
}()
|
||
time.Sleep(50 * time.Millisecond)
|
||
}</pre>
|
||
|
||
<pre data-lang="bash" data-name="四种模式的对照:默认子集、-vet=off、-vet=all 与 go vet ./..."># 1) go test 的默认 vet 子集:只抓到 ①,退出码 1
|
||
$ go test -count=1 ./internal/stock
|
||
# mall/internal/stock
|
||
# [mall/internal/stock]
|
||
internal/stock/stock_test.go:11:25: (*testing.common).Errorf format %d has arg "SKU-1001" of wrong type string
|
||
FAIL mall/internal/stock [build failed]
|
||
FAIL
|
||
$ echo $?
|
||
1
|
||
|
||
# 2) 把 vet 关掉:一个用例都没跑,却拿到了一句 ok —— 彻底的假绿
|
||
$ go test -vet=off -count=1 ./internal/stock
|
||
ok mall/internal/stock 1.196s
|
||
|
||
# 3) -vet=all:三个问题一次抓全
|
||
$ go test -vet=all -count=1 ./internal/stock
|
||
# mall/internal/stock
|
||
# [mall/internal/stock]
|
||
internal/stock/stock_test.go:11:25: (*testing.common).Errorf format %d has arg "SKU-1001" of wrong type string
|
||
internal/stock/stock_test.go:17:12: assignment copies lock value to copied: mall/internal/stock.Stock contains sync.Mutex
|
||
internal/stock/stock_test.go:28:4: call to (*testing.T).Fatalf from a non-test goroutine
|
||
FAIL mall/internal/stock [build failed]
|
||
FAIL
|
||
|
||
# 4) 单独的 go vet:同样三条,退出码 1(输出顺序每次可能不同,别写依赖顺序的脚本)
|
||
$ go vet ./...
|
||
internal/stock/stock_test.go:11:25: (*testing.common).Errorf format %d has arg "SKU-1001" of wrong type string
|
||
internal/stock/stock_test.go:17:12: assignment copies lock value to copied: mall/internal/stock.Stock contains sync.Mutex
|
||
internal/stock/stock_test.go:28:4: call to (*testing.T).Fatalf from a non-test goroutine
|
||
$ echo $?
|
||
1</pre>
|
||
|
||
<p>这四段能读出三件事。<b>第一,<code>go test</code> 默认抓的东西确实不多</b>:同一个包它只报了格式串一条,锁拷贝与「测试里起协程 Fatal」都没报——「单测绿了」这句话的强度,取决于你有没有单独跑过 <code>go vet ./...</code>。<b>第二,<code>-vet=off</code> 是纯粹的假绿</b>:连用例都没执行,输出却是 <code>ok</code>;它只配用来临时判断「用例红了还是 vet 红了」,绝不能写进入口脚本。<b>第三,vet 失败以 <code>[build failed]</code> 的形式出现</b>:<code>go test</code> 把它当成构建阶段的问题,因此没有 <code>=== RUN</code>、没有覆盖率、也没有用例级失败信息。<code>[build failed]</code> 本身就是一条「怎么看」的答案:<b>见到它就别翻业务日志,第一行诊断就是结论。</b></p>
|
||
|
||
<p>那更深的检查谁来管?把门禁按「代价」和「误报率」分层,是我在团队里推的默认结构:</p>
|
||
|
||
<div class="tablewrap">
|
||
<table>
|
||
<thead>
|
||
<tr><th>工具</th><th>它管什么</th><th>典型能抓</th><th>它不管</th><th>放在哪一层</th></tr>
|
||
</thead>
|
||
<tbody>
|
||
<tr>
|
||
<td><code>gofmt -l .</code></td>
|
||
<td>代码长什么样</td>
|
||
<td>缩进、对齐、断行位置</td>
|
||
<td>任何逻辑问题</td>
|
||
<td>CI 第一道(它列文件时退出码仍是 0,必须判空)</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>go build ./...</code></td>
|
||
<td>类型与引用是否自洽</td>
|
||
<td>包路径写错、变量未使用、循环依赖</td>
|
||
<td>运行起来会发生什么</td>
|
||
<td>CI,vet 之后</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>go test</code> 的默认 vet 子集</td>
|
||
<td>一小撮高置信模式,跟着单测免费跑</td>
|
||
<td>格式串与参数不匹配(如上例 ①)</td>
|
||
<td>锁拷贝、测试协程里的 Fatal、业务逻辑</td>
|
||
<td>跟着单测,不必额外配置</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>go vet ./...</code></td>
|
||
<td>vet 的全部检查,测试代码的补漏主力</td>
|
||
<td>锁被值拷贝、测试协程里 <code>Fatal</code>、cancel 未调用、struct tag 拼错</td>
|
||
<td>并发竞态、被忽略的 error、覆盖率</td>
|
||
<td>CI,单测之前(快、几乎零误报)</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>errcheck</code> / <code>staticcheck</code>(第三方)</td>
|
||
<td>vet 之外的一批模式:被忽略的 error、可疑比较、无效分支</td>
|
||
<td>「<code>err</code> 拿到了却没看」这一类</td>
|
||
<td>业务语义;误报需要人判断</td>
|
||
<td>先只报告,存量清零后再设成门禁</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>go test -race</code></td>
|
||
<td>运行期真的发生了的数据竞争</td>
|
||
<td>两个协程同时读写同一变量</td>
|
||
<td>没被执行到的路径</td>
|
||
<td>Linux CI(Windows 上要 cgo,见 9.5)</td>
|
||
</tr>
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
|
||
<p>这张表按「谁的问题」来读:前四层失败的责任很清楚,提交者本地就能复现,修法也确定。只有 <code>errcheck</code> / <code>staticcheck</code> 那层需要先定基线——存量告警成百上千,第一天就设成门禁,结果一定是所有人加 <code>//nolint</code> 关掉它。</p>
|
||
|
||
<div class="box case">
|
||
<span class="bt">判读一次「单测任务 3 秒就红」</span>
|
||
<p>CI 的单测任务平时跑 4 分钟,某次 3 秒就红。先别翻末尾那几行 <code>FAIL</code>,先看有没有 <code>[build failed]</code>:有,就说明红在构建或 vet,<b>一个用例都没跑</b>,此时怀疑「用例数据有问题」是白问。</p>
|
||
<p>再把本地命令补到和生产一致:<code>go vet ./... && go test -count=1 -short -timeout 2m ./...</code>。第一步的红才是真红,第二步确认你不是在 <code>-vet=off</code> 或缓存下工作。两步能复现,issue 里就能贴命令和输出,而不是「请帮忙看一下」。</p>
|
||
</div>
|
||
|
||
<h3 id="sec-9-3">9.3 -json 与 gotestsum:让结果能被机器读</h3>
|
||
|
||
<p>人读日志的极限约是最后 20 行,而一次全量跑在 CI 上是几千行;你要回答的却是统计型问题:「红的是不是上次那个用例」「新增几个失败」。这些翻日志得不到答案,只能靠结构化,<code>go test</code> 提供的路是 <code>-json</code>。</p>
|
||
|
||
<p>它的输出是<b>一行一个 JSON 对象</b>,定义用 <code>go doc cmd/test2json</code> 就能看到原文:每个对象是一个 <code>TestEvent</code>,字段有 <code>Time</code>、<code>Action</code>、<code>Package</code>、<code>Test</code>、<code>Elapsed</code>、<code>Output</code>。文档里还有一句必须记住:<b><code>go test -json</code> 已经替你正确调用了 test2json</b>,只有拿单独的测试二进制跑时才用 <code>go tool test2json</code>;另外 <code>-json</code> 本身就包含 <code>-v</code> 那份信息,写 <code>-json -v</code> 不报错但没必要。</p>
|
||
|
||
<pre data-lang="json" data-name="go test -json 的两种行:用例事件(有 Time/Package/Test)与构建事件(只有 ImportPath)">{"Time":"2026-10-16T12:05:53.1349919+08:00","Action":"start","Package":"mall/internal/order"}
|
||
{"Time":"2026-10-16T12:05:55.3466113+08:00","Action":"run","Package":"mall/internal/order","Test":"TestPayAmount"}
|
||
{"Time":"2026-10-16T12:05:55.3466113+08:00","Action":"output","Package":"mall/internal/order","Test":"TestPayAmount","Output":"=== RUN TestPayAmount\n"}
|
||
{"Time":"2026-10-16T12:05:55.3466113+08:00","Action":"pause","Package":"mall/internal/order","Test":"TestPayAmount/无券:总额加运费"}
|
||
|
||
# 构建/vet 失败时走的是另一套行:字段是 ImportPath,没有 Package 和 Test
|
||
{"ImportPath":"mall/internal/stock [mall/internal/stock.test]","Action":"build-output","Output":"# mall/internal/stock\n"}
|
||
{"ImportPath":"mall/internal/stock [mall/internal/stock.test]","Action":"build-fail"}
|
||
{"Time":"2026-10-16T12:06:00.0047045+08:00","Action":"fail","Package":"mall/internal/stock","Elapsed":0,"FailedBuild":"mall/internal/stock [mall/internal/stock.test]"}</pre>
|
||
|
||
<p><code>Action</code> 的取值是有限的几个,认全它们,解析脚本就不需要猜:</p>
|
||
|
||
<div class="tablewrap">
|
||
<table>
|
||
<thead>
|
||
<tr><th>Action</th><th>含义</th><th>解析时怎么用</th></tr>
|
||
</thead>
|
||
<tbody>
|
||
<tr><td><code>start</code> / <code>run</code></td><td>包开始运行 / 用例开始运行</td><td>收集本次跑了几个包、几条用例</td></tr>
|
||
<tr><td><code>pause</code> / <code>cont</code></td><td>调了 <code>t.Parallel()</code> 的用例登记与放开</td><td>算实际并行度,或解释耗时为何不合常理</td></tr>
|
||
<tr><td><code>pass</code></td><td>用例或包通过</td><td><code>Test</code> 为空表示包级通过</td></tr>
|
||
<tr><td><code>fail</code></td><td>用例或包失败</td><td><b><code>Test</code> 为空 = 包级失败</b>(编译失败、超时、<code>TestMain</code> 非 0 退出),此时 <code>FailedBuild</code> 指向真正失败的包</td></tr>
|
||
<tr><td><code>skip</code></td><td>用例被跳过</td><td>单独统计、不计入失败;但常是「本次什么都没测」的信号</td></tr>
|
||
<tr><td><code>output</code></td><td>一行原始输出(<code>t.Log</code>、编译错误、<code>=== RUN</code>)</td><td>失败时把 <code>Output</code> 打给人看;<code>\n</code> 是行尾,要自己拼回多行</td></tr>
|
||
<tr><td><code>bench</code> / <code>build-output</code> / <code>build-fail</code></td><td>基准结果;构建与 vet 阶段的结论(这类行字段是 <code>ImportPath</code>)</td><td>丢掉构建事件,就会把「编译失败的包」当成「零失败用例的包」</td></tr>
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
|
||
<p>光有 schema 不够,得有人把它变成一句结论。下面这个程序是 <code>qa/tdcheck</code> 的第一块拼图:从标准输入读 <code>go test -json</code>,只做三件事——把包级失败与用例级失败分开数、打出失败用例名、用退出码把结论传给上游脚本。</p>
|
||
|
||
<pre data-lang="go" data-name="qa/tdcheck/cmd/testsum/main.go:把 go test -json 变成一句能进脚本的结论">// 命令 testsum 从标准输入读 go test -json 的输出,打印一份给人看的汇总。
|
||
//
|
||
// go test -json ./... | go run ./cmd/testsum
|
||
package main
|
||
|
||
import (
|
||
"bufio"
|
||
"encoding/json"
|
||
"fmt"
|
||
"os"
|
||
"sort"
|
||
)
|
||
|
||
// event 对应 go test -json 的每一行。
|
||
type event struct {
|
||
Action string `json:"Action"`
|
||
Package string `json:"Package"`
|
||
Test string `json:"Test"`
|
||
Elapsed float64 `json:"Elapsed"`
|
||
Output string `json:"Output"`
|
||
}
|
||
|
||
type failure struct {
|
||
Pkg string
|
||
Test string
|
||
Elapsed float64
|
||
}
|
||
|
||
func main() {
|
||
pkgs := map[string]bool{}
|
||
var failures []failure
|
||
|
||
sc := bufio.NewScanner(os.Stdin)
|
||
sc.Buffer(make([]byte, 0, 64*1024), 4*1024*1024)
|
||
for sc.Scan() {
|
||
var ev event
|
||
if err := json.Unmarshal(sc.Bytes(), &ev); err != nil {
|
||
continue // 极少数非 JSON 行(例如被截断的输出)直接跳过
|
||
}
|
||
if ev.Package != "" {
|
||
pkgs[ev.Package] = true
|
||
}
|
||
if ev.Action == "fail" {
|
||
failures = append(failures, failure{ev.Package, ev.Test, ev.Elapsed})
|
||
}
|
||
}
|
||
if err := sc.Err(); err != nil {
|
||
fmt.Fprintf(os.Stderr, "读取失败:%v\n", err)
|
||
os.Exit(2)
|
||
}
|
||
|
||
byPkg := map[string][]failure{}
|
||
pkgFail := map[string]bool{}
|
||
for _, f := range failures {
|
||
if f.Test == "" {
|
||
pkgFail[f.Pkg] = true // 包级失败:编译失败、超时或 TestMain 退出非 0
|
||
continue
|
||
}
|
||
byPkg[f.Pkg] = append(byPkg[f.Pkg], f)
|
||
}
|
||
|
||
names := make([]string, 0, len(pkgs))
|
||
for p := range pkgs {
|
||
names = append(names, p)
|
||
}
|
||
sort.Strings(names)
|
||
|
||
fmt.Printf("包 %d 个,包级失败 %d 个,失败用例 %d 个\n", len(names), len(pkgFail), len(failures)-len(pkgFail))
|
||
for _, p := range names {
|
||
f := byPkg[p]
|
||
mark := "ok"
|
||
if pkgFail[p] {
|
||
mark = "FAIL(包级)"
|
||
}
|
||
fmt.Printf(" %-28s %-10s 失败用例 %d\n", p, mark, len(f))
|
||
for _, x := range f {
|
||
fmt.Printf(" FAIL %s (%.2fs)\n", x.Test, x.Elapsed)
|
||
}
|
||
}
|
||
if len(failures) > 0 {
|
||
os.Exit(1)
|
||
}
|
||
}</pre>
|
||
|
||
<p>跑一次,三个包分别代表三种情况:一个有用例失败、一个全绿、一个连用例都没跑起来(就是 9.2 里那个被 vet 拦下的包):</p>
|
||
|
||
<pre data-lang="bash" data-name="把 json 喂给 testsum:包级失败与用例级失败必须分开看">$ go test -json -count=1 ./internal/order ./internal/coupon ./internal/stock | go run ./cmd/testsum
|
||
包 3 个,包级失败 2 个,失败用例 1 个
|
||
mall/internal/coupon FAIL(包级) 失败用例 1
|
||
FAIL TestCanUse (0.00s)
|
||
mall/internal/order ok 失败用例 0
|
||
mall/internal/stock FAIL(包级) 失败用例 0
|
||
$ echo $?
|
||
1</pre>
|
||
|
||
<p><b>这份输出里最值钱的一行是 <code>stock</code>。</b>它的「失败用例」是 0——vet 把它拦在构建阶段,一个用例都没跑。脚本若只统计用例级 <code>fail</code>,这行会被算成通过,流水线就在一个编译失败的仓库上亮绿灯。<b><code>Test</code> 为空的那条 <code>fail</code> 必须单独计数、单独放行。</b></p>
|
||
|
||
<p>不想自己写渲染,社区的 <code>gotestsum</code> 就是把同一份 JSON 换成更好读的格式,外加导出 JUnit:</p>
|
||
|
||
<pre data-lang="bash" data-name="gotestsum:渲染 + JUnit 导出;-- 之后才是 go test 自己的 flag">$ go install gotest.tools/gotestsum@latest
|
||
|
||
# 每个用例一行,失败的最先被看到(团队日常最常用)
|
||
$ gotestsum --format testname -- ./...
|
||
|
||
# 在 GitHub Actions 里直接生成行内注解
|
||
$ gotestsum --format github-actions -- ./...
|
||
|
||
# 给 CI 平台吃的 JUnit,外加一份原始 json 留档
|
||
$ gotestsum --junitfile report.xml --jsonfile report.json -- ./...
|
||
|
||
# 它自己的 flag 写在 -- 前面,go test 的 flag 写在 -- 后面
|
||
$ gotestsum --format testname -- -count=1 -short ./...</pre>
|
||
|
||
<p>原则只有一条:<b>换掉的是渲染,不是判定。</b>它把 JSON 画好看、产出 Jenkins 与 GitLab 都能解析的 JUnit,但「什么算失败」仍在脚本里——包级失败算不算、<code>skip</code> 算不算、失败率超过多少要拦。</p>
|
||
|
||
<h3 id="sec-9-4">9.4 一个测试入口脚本该怎么写</h3>
|
||
|
||
<p>入口脚本的目标不是「少敲几个字母」,而是<b>让本地和 CI 敲的是同一条命令</b>。这一条成立,前面三节才可能变成团队的默认行为;不成立,你永远会遇到「我本地是绿的」这种无法仲裁的争论。</p>
|
||
|
||
<p>四条原则,每条都能对应一个真实事故:</p>
|
||
|
||
<p><b>① 唯一入口 + 模式参数。</b>只暴露一个脚本,用参数区分快、全、竞态三种范围:本地不带参数是快模式,CI 每次提交也是,发版前用全量——<b>同一个脚本、同一行命令</b>,环境差异只剩配置。</p>
|
||
|
||
<p><b>② 不吞输出,也不吞退出码。</b>脚本第一行 <code>set -euo pipefail</code>:<code>-e</code> 失败立刻停(不要在一个已经红的仓库上继续跑十分钟);<code>-u</code> 未定义变量直接报错;<code>pipefail</code> 专门修那个经典事故——<code>go test ./... | tee test.log</code> 的退出码来自 <code>tee</code>,永远是 0,加上它才取管道的第一个非 0。<b>另一半纪律是不要写 <code>|| true</code></b>:你加的每一个都是在给未来的自己埋假绿。</p>
|
||
|
||
<p><b>③ 顺序按代价排。</b>格式化是毫秒级,<code>go vet</code> 是秒级,编译是十秒级,单测是分钟级,<code>-race</code> 更久。<b>便宜的先跑</b>:格式错了不必编译,静态检查红了不必跑十分钟单测。这既省时间,也让失败信息更聚焦。</p>
|
||
|
||
<p><b>④ 失败时打印「复跑命令」。</b>脚本自己知道刚才那行参数,把它打出来,任何人(包括三周后的你)都能复制粘贴复现。这比一句「单测失败了」有价值得多。</p>
|
||
|
||
<pre data-lang="bash" data-name="scripts/qa-test.sh:全仓唯一的测试入口,本地与 CI 共用">#!/usr/bin/env bash
|
||
# 全仓唯一的测试入口:本地和 CI 都调它,保证两边跑的是同一条命令。
|
||
set -euo pipefail
|
||
|
||
MODE="${1:-quick}" # quick(默认,每次提交)| full(发版前)| race(竞态)
|
||
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||
cd "$ROOT"
|
||
|
||
step() { printf '\n===== %s =====\n' "$1"; }
|
||
|
||
step "1/4 格式检查(最便宜,先跑;gofmt -l 列文件时退出码是 0,必须判空)"
|
||
unformatted="$(gofmt -l .)"
|
||
if [ -n "$unformatted" ]; then
|
||
printf '以下文件未格式化,执行 gofmt -w 后重跑:\n%s\n' "$unformatted"
|
||
exit 1
|
||
fi
|
||
|
||
step "2/4 静态检查(单测默认只跑 vet 的一个子集,挡不住锁拷贝这类问题)"
|
||
go vet ./...
|
||
|
||
step "3/4 编译"
|
||
go build ./...
|
||
|
||
case "$MODE" in
|
||
quick)
|
||
step "4/4 单元测试:跳过需要真实服务与数据库的用例"
|
||
cmd=(go test -count=1 -short -timeout 2m ./...)
|
||
;;
|
||
full)
|
||
step "4/4 全部测试:包含集成用例,超时收紧到 5m"
|
||
cmd=(go test -count=1 -timeout 5m ./...)
|
||
;;
|
||
race)
|
||
step "4/4 竞态检测(建议在 Linux CI 上跑:Windows 需要 cgo)"
|
||
cmd=(go test -count=1 -race -timeout 15m ./...)
|
||
;;
|
||
*)
|
||
printf '未知模式:%s(可选 quick | full | race)\n' "$MODE" >&2
|
||
exit 2
|
||
;;
|
||
esac
|
||
|
||
printf '+ %s\n' "${cmd[*]}"
|
||
"${cmd[@]}"
|
||
|
||
printf '\n全部通过:%s\n' "$MODE"</pre>
|
||
|
||
<p>写进 CI 时就一行:<code>./scripts/qa-test.sh quick</code>。<code>quick</code> 这个默认值也是设计的一部分——CI 不用写参数,本地不用记参数,两边自然一致。想再短一点就加个 <code>make test</code> 转发到脚本,<b>但判定逻辑只允许存在一份</b>:不要在流水线配置里再抄一遍命令。</p>
|
||
|
||
<p>脚本写完必须自测两件事:<b>红的时候真的会红</b>,<b>退出码没有被吞</b>。做法都很土——故意写坏一行,看退出码。</p>
|
||
|
||
<pre data-lang="bash" data-name="入口脚本的两项自检:会红、退出码传得出去"># 基线:干净的仓库应当是 0
|
||
$ ./scripts/qa-test.sh quick >/tmp/qa.log 2>&1; echo "exit=$?"
|
||
exit=0
|
||
|
||
# 自检一:把 internal/stock/stock_test.go 里的格式串改错,脚本必须非 0 退出
|
||
$ ./scripts/qa-test.sh quick >/tmp/qa.log 2>&1; echo "exit=$?"
|
||
exit=1
|
||
$ grep -n 'wrong type' /tmp/qa.log
|
||
internal/stock/stock_test.go:11:25: (*testing.common).Errorf format %d has arg "SKU-1001" of wrong type string
|
||
# 注意它挂在第 2 步而不是第 4 步:vet 把它拦住了,单测根本没跑
|
||
|
||
# 自检二:确认自己没有把管道退出码吞掉(这一行是现场最常被写错的地方)
|
||
$ (go test ./... | tee /tmp/t.log) >/dev/null 2>&1; echo "exit=$?"
|
||
exit=0 # tee 的退出码,永远是 0
|
||
$ (set -o pipefail; go test ./... | tee /tmp/t.log) >/dev/null 2>&1; echo "exit=$?"
|
||
exit=1 # 取到 go test 的退出码</pre>
|
||
|
||
<p>最后一件小事:脚本是 bash,Windows 上没有原生 bash,需要 Git Bash 或 WSL。<b>我倾向于不为此再写一份 PowerShell 脚本,因为第二份就意味着第二套判定逻辑。</b>真要给 Windows 同事一个入口,就用 Go 写:在 <code>qa/tdcheck</code> 里加一个 <code>testrun</code> 子命令,内部按同样顺序调用 <code>go vet ./...</code> 与 <code>go test -count=1 -short ./...</code>,退出码原样传出。跨平台、可单测,还和 <code>testsum</code> 共用一套口径。唯一的硬要求是:<b>判定规则只有一份。</b></p>
|
||
|
||
<h3 id="sec-9-5">9.5 提交前的本地检查清单</h3>
|
||
|
||
<p>把前面四节压成一张 60 秒内能过完的清单。价值不在于「我都做了」,而在于<b>每一项都有确定的期望输出</b>:没有期望值的检查只是走过场。</p>
|
||
|
||
<div class="tablewrap">
|
||
<table>
|
||
<thead>
|
||
<tr><th>检查项</th><th>命令</th><th>期望结果</th><th>常见误判</th></tr>
|
||
</thead>
|
||
<tbody>
|
||
<tr>
|
||
<td>我改动的包单独过一遍</td>
|
||
<td><code>go test -count=1 -v -run '^TestPayAmount$' ./internal/order</code></td>
|
||
<td>只有目标用例的 <code>--- PASS</code>,包结论 <code>ok</code></td>
|
||
<td><code>-run</code> 未锚定会多跑用例;<code>no tests to run</code> 时退出码仍是 0,别当成通过</td>
|
||
</tr>
|
||
<tr>
|
||
<td>全量快跑</td>
|
||
<td><code>go test -count=1 -short -timeout 2m ./...</code></td>
|
||
<td>全部 <code>ok</code>,没有 <code>FAIL</code></td>
|
||
<td><code>[no test files]</code> 与 <code>--- SKIP</code> 不算失败;出现 <code>(cached)</code> 说明 <code>-count=1</code> 漏了</td>
|
||
</tr>
|
||
<tr>
|
||
<td>格式</td>
|
||
<td><code>gofmt -l .</code></td>
|
||
<td>输出为空</td>
|
||
<td>「退出码是 0 所以没问题」——列出文件时它也是 0</td>
|
||
</tr>
|
||
<tr>
|
||
<td>静态检查与构建</td>
|
||
<td><code>go vet ./... && go build ./...</code></td>
|
||
<td>两条都无输出、退出码 0</td>
|
||
<td>用 <code>go test</code> 绿代替 vet 绿(默认子集只占一部分);把「编译通过」当成「代码没问题」</td>
|
||
</tr>
|
||
<tr>
|
||
<td>改了并发或共享状态</td>
|
||
<td><code>go test -count=1 -race ./...</code></td>
|
||
<td>无 <code>WARNING: DATA RACE</code>,退出码 0</td>
|
||
<td>Windows 上报 <code>-race requires cgo</code>(退出码 2)不是代码问题,改用 Linux CI</td>
|
||
</tr>
|
||
<tr>
|
||
<td>结果可被机器读</td>
|
||
<td><code>go test -json -count=1 ./... | go run ./cmd/testsum</code></td>
|
||
<td>「包级失败 0 个,失败用例 0 个」,退出码 0</td>
|
||
<td>只数用例级失败,把编译失败的包算成通过</td>
|
||
</tr>
|
||
<tr>
|
||
<td>入口脚本本身</td>
|
||
<td><code>./scripts/qa-test.sh quick; echo $?</code></td>
|
||
<td><code>exit=0</code>,输出里有每一步的名字</td>
|
||
<td>管道吞掉退出码;脚本里有 <code>|| true</code> 或漏了 <code>pipefail</code></td>
|
||
</tr>
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
|
||
<p>两行值得单独记住:<code>go vet ./...</code> 快、几乎零误报,抓的正是测试代码里最阴的那类问题(测试协程里的 <code>Fatal</code>、锁拷贝),<b>性价比最高</b>;入口脚本则是唯一能保证这套命令被别人复用、半年后依然生效的东西。</p>
|
||
|
||
<div class="box lab">
|
||
<span class="bt">动手 · 把自己仓库的测试入口补齐</span>
|
||
<ol class="steps">
|
||
<li>挑一个你维护的 Go 包,跑 <code>go test -count=1 -v ./...</code>,数一下有多少 <code>--- SKIP</code>。一条都没有,说明 <code>-short</code> 是空开关:给依赖外部环境的用例补上 <code>if testing.Short() { t.Skip(...) }</code>。</li>
|
||
<li>跑 <code>go vet ./...</code>,把存量告警按「测试文件 / 业务文件」分成两堆,先修测试文件那堆。</li>
|
||
<li>把 <code>go test -json -count=1 ./... | go run ./cmd/testsum</code> 做成别名,用它统计下一次 CI 失败是包级还是用例级。</li>
|
||
<li>按 9.4 的模板写下你项目的 <code>scripts/qa-test.sh</code>,故意写坏一行,确认它非 0 退出、日志里有可复制的复跑命令。</li>
|
||
<li>把 <code>-timeout</code> 从默认 10 分钟改成和包规模匹配的值,并在注释里写明理由。</li>
|
||
</ol>
|
||
<p><b>过关标准</b>:同事拉下你的分支,敲一行命令就能得到和你一样的结论,失败时能自己看懂红在哪一步。</p>
|
||
</div>
|
||
|
||
<p>这一章讲的全是「把话说清楚」:flag 说清范围,静态检查说清问题性质,<code>-json</code> 把结果交给机器,入口脚本把规则写下来,清单把期望值钉死。它们没有一行在帮你找新缺陷,但<b>它们决定你找到的缺陷有没有人信</b>。</p>
|
||
|
||
<p>到这里,<code>go test</code> 的使用已经完整:怎么选用例、怎么看并行、怎么读超时、怎么把结果交给机器。下一章解决这套东西能不能长期活下去——<span class="mark">当测试代码要和业务代码一起被评审,什么样的测试写得下去、什么样的只会变成负担。</span>那比跑通命令难得多,也是把一个包的单测变成团队资产的分界线。</p>
|
||
|
||
<!-- ============================================================ -->
|
||
</article>
|
||
|
||
<nav class="pager">
|
||
<a class="prev" href="08-race-flake.html"><span class="k">← 上一章</span><span class="v">第 8 章 · 竞态、缓存与不稳定用例</span></a>
|
||
<a class="next" href="10-maintain.html"><span class="k">下一章 →</span><span class="v">第 10 章 · 让测试代码也值得被 review</span></a>
|
||
</nav>
|
||
|
||
<p class="foot">
|
||
Go 单元测试与 go test 工具链 · 第 9 章 go test 工具链与命令行习惯<br>
|
||
<a href="index.html">模块目录</a> · <a href="../../index.html">返回学习路径</a>
|
||
</p>
|
||
</main>
|
||
</div>
|
||
|
||
<button id="toTop" title="回到顶部">↑</button>
|
||
<script src="../../assets/doc.js"></script>
|
||
<script src="../../../../assets/back.js" data-portal-back="testdev/testdev-learning-path" data-portal-label="测试开发工程师 › 测试开发从零到成熟学习路径"></script>
|
||
</body>
|
||
</html>
|