> ## Documentation Index
> Fetch the complete documentation index at: https://docs.molesignal.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 测试规则

> 运行一次已保存的规则，查看条件是否命中。

```http theme={null}
POST /api/v1/alerts/rules/{id}/test
```

在 `now - period_secs` 到 `now` 的窗口内运行一次已保存规则的查询，并报告条件是否命中。该调用不会改变任何状态：不触碰评估状态、事件、通知或规则本身。调用需要 `alerts.manage`，请求体为空。

把 `enabled` 设为 `true` 之前，先测试规则。语句无效或数据流不存在的规则也能被保存而不报错，只有测试会暴露问题。

[APM 规则](https://docs.molesignal.com/zh-Hans/api/alerting/create-rule.md#apm-规则)不运行查询，而是读取其指标。结果只有一行，列为 `value`、`service` 和 `trace_id`；窗口内指标没有读数时没有行。

[按列拆分的规则](https://docs.molesignal.com/zh-Hans/api/alerting/create-rule.md#按列拆分的规则)在 `groups` 里列出每一组。有组命中时 `matched` 为 `true`，`value` 是第一个命中的组的值，`severity` 取各组中最高的。

[RUM 规则](https://docs.molesignal.com/zh-Hans/api/alerting/create-rule.md#rum-规则)同样读取其指标。结果只有一行，列为 `value` 和 `application`；窗口内指标没有读数时没有行，`scanned_rows` 是指标所用的行数。

```bash cURL theme={null}
curl -X POST http://localhost:5080/api/v1/alerts/rules/$RULE_ID/test \
  -H "authorization: Bearer $MS_JWT"
```

```json 200 theme={null}
{
  "matched": true,
  "value": 2.0,
  "severity": "critical",
  "columns": ["c"],
  "rows": [[2]],
  "scanned_rows": 2,
  "took_ms": 170
}
```

**响应**

| 字段 | 类型 | 说明 |
| - | - | - |
| `matched` | boolean | 条件当前是否命中。结果不考虑 `for_periods`。 |
| `value` | number 或 null | 第一行第一列的值。结果中没有数字时为 `null`。 |
| `severity` | string 或 null | 事件将使用的严重程度。`matched` 为 `false` 时为 `null`。 |
| `columns` | array | 查询结果的列名。 |
| `rows` | array | 结果的前 20 行。 |
| `scanned_rows` | integer | 查询扫描的行数。 |
| `took_ms` | integer | 查询耗时，单位为毫秒。 |
| `anomaly` | object | 仅 `anomaly` 规则返回，包含 `baseline`、`deviation`、0 到 1 的 `score` 和 `reason` 文本。 |
| `no_data` | boolean | 仅为 `true` 时返回：这次运行没有值，规则也不把缺的值当作 `0`。 |
| `groups` | array | 仅按列拆分的规则返回，按结果里的顺序。每组有 `labels`（列到取值的映射），以及 `value`、`matched` 和 `severity`。 |
| `groups_truncated` | boolean | 仅为 `true` 时返回：结果超过 100 组，其余的组没有列出。 |

**错误**

| 状态码 | 原因 |
| - | - |
| `400` | 查询无法运行，例如 SQL 无效或字段不存在，或者 `anomaly` 规则没有可用于建立基线的历史数据。 |
| `403` | 规则的数据流不存在，或 Token 缺少 `alerts.manage`。 |
| `404` | 规则不存在。 |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.