如何测试 Prometheus 的“指标”格式?
解读
Prometheus 指标本质上是纯文本,每行必须符合 <metric_name>{<label_name>=<label_value>,...} <value> [<timestamp>] 的语法,且整体以空行结尾。
国内面试里,面试官想确认三件事:
- 你是否知道 Prometheus 文本协议的细节(命名规则、标签格式、HELP/TYPE 元信息);
- 你是否能在 Jest 里用“零成本”方式把这段文本当“快照”测,而不是手写一堆正则;
- 你是否能在 CI(GitHub Actions / GitLab CI / 阿里云云效)里把这条用例跑通,并给出覆盖率。
因此,答案要体现“快照比对 + 正则兜底 + 异常场景”三板斧,同时把 Jest 的 watch 模式、并行、覆盖率开关都用上,让面试官一眼看出你日常就是这么写单测的。
知识点
-
Prometheus 文本协议规范(CNCF 官方文档中文版已同步到国内镜像站,面试可直接背四条):
– 指标名必须符合[a-zA-Z_:][a-zA-Z0-9_:]*;
– 标签值必须被双引号包裹,内部双引号需转义\",反斜杠需转义\\;
– 同一指标下,标签名必须有序出现;
– HELP/TYPE 行可选,但一旦存在必须出现在第一个样本之前。 -
Jest 快照测试:
–expect(text).toMatchSnapshot()会在__snapshots__目录生成.snap文件,CI 里加--ci --updateSnapshot即可增量更新;
– 快照内容过大时可改用expect(text).toMatchInlineSnapshot(),代码即快照,CodeReview 一眼可见。 -
Jest 自定义 Matcher:
– 通过expect.extend({ toBePrometheusMetric(received) {} })把正则校验封装成语义化断言,错误信息用hint彩色输出,面试官看到✕ metric name invalid就知道你玩透了 Jest 插件机制。 -
Mock 场景:
– 在 Node 环境用jest.spyOn(global.Math, 'random').mockReturnValue(0.123)把随机值写死,保证指标值不变,快照才不会抖动;
– 如果指标里带时间戳,用jest.useFakeTimers().setSystemTime(new Date('2024-05-01T08:00:00Z'))把时间钉死。 -
覆盖率门禁:
–jest --coverage --coverageThreshold='{"global":{"branches":90,"functions":90,"lines":90,"statements":90}}',国内阿里/腾讯/字节内部模板普遍要求 90 分,提前配好直接加分。
答案
下面给出可直接跑通、符合国内主流技术栈(Node 18 + Jest 29 + TypeScript)的完整用例,目录结构按“小而美”面试 Demo 组织,方便 5 分钟内讲清思路。
src/
prometheus.ts // 业务代码:把对象序列化成 Prometheus 文本
__tests__/
prometheus.test.ts // 测试文件
jest.config.js
package.json
- 业务代码
src/prometheus.ts
export function serializeMetric(
name: string,
help: string | null,
type: 'counter' | 'gauge' | 'histogram' | 'summary' | null,
labels: Record<string, string>,
value: number,
timestamp?: number
): string {
// 1. 校验指标名
if (!/^[a-zA-Z_:][a-zA-Z0-9_:]*$/.test(name)) {
throw new Error(`Invalid metric name: ${name}`);
}
// 2. 组装标签,key 按字典序排,保证输出稳定
const labelPairs = Object.keys(labels)
.sort()
.map(k => `${k}="${labels[k].replace(/"/g, '\\"')}"`)
.join(',');
const labelStr = labelPairs ? `{${labelPairs}}` : '';
// 3. 拼时间戳
const ts = timestamp ? ` ${timestamp}` : '';
// 4. 拼最终文本
const lines: string[] = [];
if (help) lines.push(`# HELP ${name} ${help}`);
if (type) lines.push(`# TYPE ${name} ${type}`);
lines.push(`${name}${labelStr} ${value}${ts}`);
return lines.join('\n') + '\n';
}
- 测试文件
__tests__/prometheus.test.ts
import { serializeMetric } from '../src/prometheus';
describe('Prometheus 指标格式', () => {
beforeAll(() => {
jest.useFakeTimers();
jest.setSystemTime(new Date('2024-05-01T08:00:00Z'));
});
afterAll(() => {
jest.useRealTimers();
});
test('快照:标准 counter 指标', () => {
const out = serializeMetric(
'http_requests_total',
'The total number of HTTP requests.',
'counter',
{ method: 'POST', code: '200' },
1027,
1714550400000
);
expect(out).toMatchSnapshot();
});
test('正则兜底:指标名非法应抛错', () => {
expect(() =>
serializeMetric('123invalid', null, null, {}, 1)
).toThrow(/Invalid metric name/);
});
test('标签值转义', () => {
const out = serializeMetric(
'escape_demo',
null,
null,
{ path: '/api/"user"', backslash: 'C:\\temp' },
1
);
expect(out).toContain('path="/api/\\"user\\""');
expect(out).toContain('backslash="C:\\\\temp"');
});
test('空标签', () => {
const out = serializeMetric('cpu_seconds', null, null, {}, 42.5);
expect(out).toMatch(/^cpu_seconds 42.5$/m);
});
});
- Jest 配置
jest.config.js
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
collectCoverageFrom: ['src/**/*.{ts,js}'],
coverageThreshold: {
global: {
branches: 90,
functions: 90,
lines: 90,
statements: 90,
},
},
};
- 脚本
package.json
{
"scripts": {
"test": "jest --watchAll=false",
"test:ci": "jest --ci --coverage --watchAll=false"
}
}
- 运行
本地:npm run test
CI:npm run test:ci
快照第一次失败时本地加-u更新,之后任何格式回退都会亮红,直接拦截。
拓展思考
-
如果指标来自远端 Exporter,可把测试拆成“契约测试”:
– 用nock拦截 HTTP,拿到/metrics原始文本,再走上述快照;
– 把 Exporter 版本号写进快照文件名,如prometheus.v1.2.3.snap,升级时 diff 一眼看出新增指标。 -
大集群场景下指标行数可能过万,Jest 快照文件会膨胀到 MB 级,此时可:
– 改用fast-csv流式解析,只提取关键指标行做快照;
– 或者把指标名做哈希分桶,每个桶一个快照,并行跑,利用 Jest 的--maxWorkers=50%提速。 -
国内金融公司常要求“测试用例必须可追溯到需求编号”,可以在快照文件头部加注释
# REQ-ID: FINS-1843,再写一条自定义 Matcher 校验快照是否含该注释,实现需求—用例双向追溯。