如何使用httptest对Exporter的/metrics端点做单元测试并验证Content-Type
解读
在国内云原生面试中,Prometheus Exporter 的单元测试是区分“能跑起来”与“能稳定上线”的关键问题。
面试官想确认三件事:
- 你是否真的用 Go 写过 Exporter,而不是只跑过 node_exporter;
- 是否理解 /metrics 输出必须符合 Prometheus 文本协议(内容、字符集、换行、结尾空行);
- 是否能在不启监听端口的情况下完成黑盒测试,保证 CI 可重复、无端口冲突、无外部依赖。
因此,回答必须围绕“httptest + 纯内存测试 + 协议级断言”展开,并给出可直接落地的代码片段。
知识点
- httptest.NewRecorder 与 httptest.NewRequest:零端口启动,完全内存化。
- promhttp.Handler():官方提供的 http.Handler,自带 gzip 协商、过期头、Content-Type 设置。
- expfmt.ResponseFormat:用于校验服务端是否返回 text/plain; version=0.0.4; charset=utf-8,这是 Prometheus 2.x 的硬性要求。
- dto.MetricFamily:用 protobuf 解码返回体,可精准校验指标名、标签、help、type、value,避免正则误判。
- 并发安全:Exporter 内部必须注册 prometheus.Registerer,测试结束后 Unregister,防止用例相互污染。
- 错误场景:验证 404、405、Accept 头非法、gzip 解压失败等边界,体现鲁棒性。
答案
下面给出可直接粘贴到 Go 项目中的完整单测模板,覆盖“Content-Type 正确性 + 指标存在性 + 协议格式”。
package myexporter_test
import (
"compress/gzip"
"io"
"net/http"
"net/http/httptest"
"testing"
"github.com/prometheus/client_model/go"
"github.com/prometheus/common/expfmt"
"github.com/yourorg/myexporter"
)
func TestMetricsEndpoint(t *testing.T) {
// 1. 构造被测 Exporter(内部已注册 Collector)
exp := myexporter.New() // 返回 *Exporter,实现了 http.Handler
defer prometheus.DefaultRegisterer.Unregister(exp)
// 2. 构造内存级请求
req := httptest.NewRequest(http.MethodGet, "/metrics", nil)
req.Header.Set("Accept", "text/plain; version=0.0.4")
rec := httptest.NewRecorder()
// 3. 执行
exp.ServeHTTP(rec, req)
// 4. 断言响应码
if rec.Code != http.StatusOK {
t.Fatalf("want 200, got %d", rec.Code)
}
// 5. 断言 Content-Type
contentType := rec.Header().Get("Content-Type")
if contentType != "text/plain; version=0.0.4; charset=utf-8" {
t.Errorf("unexpected Content-Type: %s", contentType)
}
// 6. 解码返回体,校验指标存在且格式正确
var parser expfmt.TextParser
// 处理 gzip:promhttp 会根据 Accept-Encoding 自动 gzip,单测默认不压缩,但防御性判断
body := rec.Body.Bytes()
if rec.Header().Get("Content-Encoding") == "gzip" {
gr, err := gzip.NewReader(rec.Body)
if err != nil {
t.Fatal(err)
}
body, _ = io.ReadAll(gr)
_ = gr.Close()
}
mfs, err := parser.TextToMetricFamilies(bytes.NewReader(body))
if err != nil {
t.Fatalf("parse metrics failed: %v", err)
}
// 7. 业务断言:假设 Exporter 必须暴露 myapp_requests_total
mf, ok := mfs["myapp_requests_total"]
if !ok {
t.Fatal("myapp_requests_total not found")
}
if mf.GetType() != dto.MetricType_COUNTER {
t.Error("myapp_requests_total should be counter")
}
if len(mf.GetMetric()) == 0 {
t.Error("myapp_requests_total has no samples")
}
}
运行 go test -v,CI 零依赖,即可在 50ms 内完成一次完整的 /metrics 协议级回归。
拓展思考
- 多版本 Accept 头兼容:Prometheus 2.45 开始支持 OpenMetrics 格式(application/openmetrics-text),生产环境需同时回归两种 Accept,防止升级后抓取出错。
- 超大基数指标:若指标维度组合 >10 万,单测需 mock 数据而非全量写入,否则 OOM;可用 prometheus.NewPedanticRegistry() 提前检测重复注册。
- 性能基线:用
testing.B结合 httptest,记录 /metrics 200 次请求的内存 alloc 与 CPU,防止后续 MR 引入高基数标签导致性能回退。 - 集成测试:单测通过后,再启动真实端口(如
:0随机端口)用promtool check metrics做白盒扫描,确保无 HELP 缺失、无 TYPE 冲突,形成“内存单测 + 静态检查”双层门禁。