You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Prometheus告警规则中for参数导致单元测试失败的修复方案

测试失败原因

Prometheus 告警规则中for字段的核心逻辑是:告警表达式首次满足触发条件后,需要连续保持触发状态达for指定的时长,才会从pending(待触发)状态转为firing(已触发)状态,而单元测试默认仅校验firing状态的告警。
结合你的配置具体分析:

  • 告警表达式sum(increase(app_receiver{...}[1m])) > 0首次满足条件的时间点为5m:你的输入序列中,对应指标在5m时才首次从0变为10,计算1分钟窗口的增量为10,刚好满足阈值要求。
  • 你设置的for: 5m要求该条件连续触发满5分钟才会生成正式告警,在5m这个评估时间点,条件刚满足,还未达到持续时长要求,因此无告警返回,测试失败。
    注释for字段后测试通过,是因为没有持续时长要求时,表达式满足条件就会立即生成firing状态的告警。
可行修复方案

这里提供两种可直接落地的修改方式,二选一即可:

方案1:延长测试评估时间,匹配持续时长要求

调整测试的评估时间到10m(首次满足条件的5m + 持续要求的5m),同时补充输入序列的采样点保证评估时表达式仍满足条件,修改后的测试用例如下:

rule_files:
  - ./../../rules/test.yml

evaluation_interval: 1m

tests:
  - interval: 1m
    input_series:
      - series: 'app_receiver{app="app_name", exception="exception"}'
        values: '0 0 0 0 0 0 0 0 0 0 0 0'
      - series: 'app_receiver{app="app_name", exception="exception"}'
        values: '0 0 0 0 0 10 20 40 60 80 100 120'
    alert_rule_test:
      - alertname: Alert name
        eval_time: 10m
        exp_alerts:
          - exp_labels:
              severity: 'critical'
              team: 'myteam'
            exp_annotations:
              summary: 'Summary.'
              book: "https://link.com"

方案2:提前指标增长时间,适配原有评估时间

调整输入序列,让指标从0m开始就有增量,保证到5m评估时已经连续满足条件达5分钟,修改后的测试用例如下:

rule_files:
  - ./../../rules/test.yml

evaluation_interval: 1m

tests:
  - interval: 1m
    input_series:
      - series: 'app_receiver{app="app_name", exception="exception"}'
        values: '0 0 0 0 0 0 0 0 0 0'
      - series: 'app_receiver{app="app_name", exception="exception"}'
        values: '10 20 30 40 50 60 70 80 90 100'
    alert_rule_test:
      - alertname: Alert name
        eval_time: 5m
        exp_alerts:
          - exp_labels:
              severity: 'critical'
              team: 'myteam'
            exp_annotations:
              summary: 'Summary.'
              book: "https://link.com"

内容的提问来源于stack exchange,提问作者Andrei Kulik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 05:09:02