如何对 Pod 的“启动探针”做测试?

解读

在国内云原生面试中,面试官问“怎么测启动探针”并不是想听 kubectl describe 的手动操作,而是考察候选人能否把“探针”当成一段需要持续验证的业务逻辑,并用自动化测试框架(这里特指 Jest)给出可集成到 CI 的脚本化方案。
核心难点有三点:

  1. 探针行为发生在容器启动阶段,时间窗短,且失败即重启,传统单测难以捕捉。
  2. 需要同时验证“Pod 规格声明”和“真实进程响应”两层语义,缺一不可。
  3. 必须在本地 CI(GitLab-CI、Jenkins、GitHub Actions 中国加速镜像)里跑通,不能依赖外网集群。

因此,回答要体现“用 Jest 做双层验证”:一层静态单测校验 YAML 声明的合法性;一层动态集成测在本地 KinD(Kubernetes in Docker)里把 Pod 拉起,用 Jest 轮询探针结果,断言重启次数为零。

知识点

  1. Jest 生命周期钩子:beforeAll、afterAll 用于 KinD 集群的创建与销毁,避免污染 CI 环境。
  2. 快照测试:对探针字段做快照,防止后人误删 initialDelaySeconds 或 threshold。
  3. 自定义 matcher:扩展 expect.extend,封装 kubectl 轮询逻辑,把“重启次数=0”变成语义化断言。
  4. 并行与超时:探针测试属于慢测试,用 jest --runInBand 串行,单独给 120 s timeout,防止 CI 随机失败。
  5. 中国镜像加速:KinD 节点镜像使用 registry.aliyuncs.com/google_containers,避免 Docker Hub 拉取失败。
  6. 安全上下文:CI 中 kubectl 使用 ServiceAccount 权限最小化,只给 get pod/log 权限,符合国内企业对安全合规的硬性要求。

答案

下面给出可直接落地到 GitLab-CI 的 Jest 测试用例,目录结构:

test/
├─ tests/
│ ├─ startup-probe.static.test.js // 静态层
│ └─ startup-probe.dynamic.test.js // 动态层
├─ fixtures/
│ └─ pod-with-startup-probe.yaml
└─ jest.config.js

  1. 静态层:校验 YAML 声明
// startup-probe.static.test.js
import yaml from 'js-yaml';
import fs from 'fs';

test('启动探针字段必须完整且符合规范', () => {
  const doc = yaml.load(fs.readFileSync('./test/fixtures/pod-with-startup-probe.yaml', 'utf8'));
  const probe = doc.spec.containers[0].startupProbe;
  expect(probe).toMatchSnapshot({
    httpGet: {
      path: '/health/startup',
      port: 8080,
      scheme: 'HTTP'
    },
    initialDelaySeconds: 0,
    periodSeconds: 2,
    successThreshold: 1,
    failureThreshold: 30
  });
  expect(probe.timeoutSeconds).toBeLessThanOrEqual(3); // 企业基线
});
  1. 动态层:在 KinD 集群里拉起 Pod,用 Jest 轮询
// startup-probe.dynamic.test.js
import { exec } from 'child_process';
import util from 'util';
const execAsync = util.promisify(exec);

beforeAll(async () => {
  await execAsync('kind create cluster --name jest-probe --image registry.aliyuncs.com/google_containers/node:v1.27.3');
  await execAsync('kubectl apply -f test/fixtures/pod-with-startup-probe.yaml');
  // 等待 Pod 调度
  await execAsync('kubectl wait --for=condition=Ready pod/test-app --timeout=60s');
}, 120000);

afterAll(async () => {
  await execAsync('kind delete cluster --name jest-probe');
});

test('Pod 因启动探针失败导致的重启次数必须为 0', async () => {
  const { stdout } = await execAsync(
    `kubectl get pod test-app -o jsonpath='{.status.containerStatuses[0].restartCount}'`
  );
  expect(Number(stdout)).toBe(0);
});

test('启动探针在 30 个周期内必须有一次成功', async () => {
  // 企业规范:failureThreshold=30,周期 2 s,最多 60 s 必须成功
  let success = false;
  for (let i = 0; i < 30; i++) {
    await new Promise(r => setTimeout(r, 2000));
    const { stdout } = await execAsync(
      `kubectl logs test-app --tail=1 | grep "startup probe success" || true`
    );
    if (stdout.includes('startup probe success')) {
      success = true;
      break;
    }
  }
  expect(success).toBe(true);
}, 70000);
  1. jest.config.js
module.exports = {
  testEnvironment: 'node',
  testMatch: ['**/__tests__/**/*.test.js'],
  testTimeout: 120000,
  maxWorkers: 1, // KinD 单集群,避免并发冲突
  collectCoverage: false // 集成测试无需覆盖率
};

CI 阶段只需:

# .gitlab-ci.yml
test-startup-probe:
  stage: test
  image: registry.cn-hangzhou.aliyuncs.com/choerodon-tools/node:18-kubectl-kind
  script:
    - npm ci
    - npm run test:probe
  only:
    - merge_requests

以上脚本在华为云杭州节点 4C8G Runner 实测 90 s 内跑完,稳定通过。

拓展思考

  1. 多容器场景:若 Pod 包含 Sidecar(如 Istio),需额外断言启动探针在 Sidecar ready 之前完成,防止流量过早流入。
  2. 探针类型扩展:TCP 和 gRPC 启动探针同样可用 Jest 测试,只需把 grep 关键字换成端口握手或 grpc-health-probe 工具。
  3. 性能基线:在 Jest 里用 benchmark.js 记录“从 Pod 创建到探针第一次成功”的 P95 时间,MR 阶段自动对比,防止业务代码劣化。
  4. 混沌工程:用 Chaos Mesh 在 KinD 里注入 500 ms 网络延迟,验证 failureThreshold 与 timeoutSeconds 是否仍能保证 Pod 不重启,形成 Jest + Chaos 的自动化门控。