Unit testing Prometheus alerting rules with promtool

Learn how promtool test rules checks alert and recording rules in CI, so bad rule changes are caught before they reach production. Covers input series, expected alerts, durations and setup.

On this page

Why teams unit test Prometheus alert rules before deploy

Many teams change alert rules by hand, push them to the server, and learn about mistakes only when a page never arrives or when a typo in a threshold floods the on-call channel at 3 a.m. A rule file is code that decides who gets woken up, so it deserves the same pre-merge check as application code. The tool for that check is promtool test rules, which ships with Prometheus. It loads rule files, feeds them synthetic input series that you write by hand, evaluates the rules at the timestamps you choose, and asserts which alerts fire, with which labels and annotations, at each point in time.

The cost of this approach is engineering time, not licensing. Prometheus is licensed under Apache-2.0 and has no paid edition of the project itself, so the work of writing, reviewing and maintaining the test suite falls to your team or to a partner you hire for it. Ask who will own the tests after handover, how a test failure is triaged, and whether the suite runs in the same pipeline that validates configuration. Each new alert should arrive with at least one test that proves it fires under the failure it describes and stays quiet under normal load.

Set expectations about what these tests can prove. The Prometheus overview states that Prometheus values reliability over precision, and the tests inherit that framing. A passing unit test shows that a rule's logic behaves as you wrote it against the series you supplied. It does not show that your real exporters emit those series, that scrapes succeed during an incident, or that Alertmanager routes the notification correctly. Treat promtool results as one gate in a chain that also covers configuration validation, routing checks and an end-to-end test alert.

How promtool test rules evaluates rules against input series

This sequence explains how promtool reads a rule test file, synthesizes input series, steps through evaluation times, and compares firing alerts or recorded samples against what the test expects. The output is a pass or fail result for each test case, produced without a running Prometheus server.

  1. Load the rule files and test file

    You run promtool test rules against a test file that lists the rule files to load and an evaluation interval, which sets the step at which the rules are evaluated during the test. The rule files are the same YAML your Prometheus deployment would load, so the test exercises the rules as written. Promtool parses both files before any evaluation starts. You know this step has worked when promtool reports no syntax or rule-parsing errors and moves on to the test cases.

  2. Synthesize input series from series notation

    Each entry under input_series gives a metric name, its labels, and a series in Prometheus test notation that describes values at regular intervals. Promtool generates these samples in memory, so no scrape target, exporter, or time series database is involved. Teams usually write one input series for each metric the alert expression reads, including the labels that routing and filtering depend on. You know the inputs are correct when a simple expression run against them returns the values you planned.

  3. Select the evaluation time for each assertion

    Each alert_rule_test block names the alerting rule under test and an eval_time, which is the point on the synthetic timeline at which promtool checks the result. Because time is simulated, the test can ask what the rule reports at a moment long after the input series started, without waiting. Good tests place eval_time on both sides of a threshold and of any for duration, so that a missing firing state and an early firing state are both caught. You know the timing is right when the planned eval_time falls after the input samples that should trigger the condition.

  4. Evaluate rules across the simulated timeline

    Promtool steps through the synthetic timeline at the configured evaluation interval, evaluating each rule as Prometheus would at those timestamps. Alerting rules move through the pending and firing states according to their for duration, and recording rules write new series into the test's memory. Nothing is sent to Alertmanager or stored on disk. You know evaluation has completed when promtool has a state for every rule at each eval_time that a test case references.

  5. Compare firing alerts and labels with expectations

    For alerting rules, the exp_alerts section lists the alerts that should be firing at the eval_time, with their label sets and annotations. Promtool compares the firing alerts against that list and fails the test if an alert is missing, unexpected, or carries different labels. Checking labels here catches routing problems early, because a rule that fires with the wrong severity label will be sent to the wrong receiver in production. You know the comparison is complete when promtool reports the test as passed or prints the exact alert differences.

  6. Assert recorded samples for recording rules

    Recording rules do not fire alerts, so their test cases use exp_samples. Each entry gives the series name, its labels, and the value expected at the eval_time. Promtool compares the value that the recording rule produced in the simulated run with the one you declared. This check confirms that the aggregation, label handling, and arithmetic are correct before dashboards or downstream alerts depend on the new series. You know the check has passed when every expected sample matches the recorded value within the comparison promtool performs.

  7. Read the pass or fail result in CI

    Promtool exits with a status code that reflects the result of every test case in the file. Your CI job runs the command on each proposed rule change, so a failed assertion stops the pipeline before the change reaches a Prometheus server. The job output shows which test, which eval_time, and which expected and actual alerts or samples caused the failure. Confirm the exit behavior of your promtool version against its documentation, since the command-line output and options can change between releases.

Where promtool sits in the rule change pipeline

The pipeline starts when an engineer changes an alert or recording rule file and opens a merge request in Git. The CI job runs promtool check rules first to catch syntax and structure errors, then promtool test rules against input series and expected alerts. A failing step marks the job red and blocks the merge. Only a change that passes both checks reaches the deploy step, which loads the rules into Prometheus. Reviewers should confirm that the test suite covers the alerts being changed, not just the files that parse.

Rule changes reach Prometheus only after both promtool checks pass in CI.

What to assert for alerts, recording rules and durations

An alerting rule test asserts the state of an alert at a chosen evaluation time. In a promtool test rules file, an alert_rule_test block names the alert, the evaluation time and the expected firing alerts, with their labels and annotations. This catches defects in the expression itself, such as a wrong comparison operator, a missing by clause that drops the labels routing depends on, or an annotation template that renders the wrong instance name. Assert the full label set that Alertmanager uses for routing, including severity and team ownership, because a correct expression with the wrong labels still pages the wrong team.

  • Expected firing alerts: list every alert that should fire at the evaluation time, and use an empty list to assert that nothing fires.
  • Label set: assert the severity, team and service labels that routing and inhibition depend on.
  • Annotation text: check that templated summaries and descriptions expand to the instance or value an on-call engineer needs.
  • Negative cases: include input where the condition is just below the threshold, so an off-by-one change is caught.

Check that every alert in the rule file has at least one test that asserts it fires and one that asserts it stays silent.

Test options and when each fits

This table compares the main choices for organizing promtool tests: file layout, how input series are written, what each test asserts, and whether tests run alone or inside CI. Read each row as a trade-off between maintenance cost, coverage and run speed, then pick the option that matches how often your rules change. Most teams start with one test file per rule group, inline series for short windows, and promtool in CI from day one.

ChoiceOptionTrade-offWhen it fits
File layoutOne test file per rule groupChanges stay local and reviews are small, but many files to keep in step with renamed alertsRule groups change independently and owners review their own files
File layoutOne test file per serviceFewer files and one place to see coverage, but large diffs and merge conflicts as rules growA small number of services with rules that change together
Input seriesInline input seriesEasy to read in review and fast to run, but long ranges become hard to write and audit by handShort windows that exercise specific thresholds and for durations
Input seriesGenerated series for long rangesCovers long windows and realistic counters with less typing, but the generator logic needs its own reviewAlerts that depend on rate or sustained conditions over many minutes
AssertionsExpressions and firing state onlyQuick to write and catches threshold mistakes, but misses wrong severity or routing labelsEarly coverage of a new rule group where the expression is the main risk
AssertionsLabels and annotations includedCatches wrong severity, team labels and broken templates, at the cost of updating tests when wording changesAlerts that route to pagers or tickets and carry labels other tools depend on
CI gatingpromtool check rules aloneValidates syntax and rule structure quickly, but says nothing about whether alerts fire correctlyA fast first gate on every rule file change, before tests are written
CI gatingpromtool test rules added to CIAdds behavior checks and blocks bad changes before deploy, with test time growing as series and windows growAny rule file that pages people or drives automated actions

Common reasons unit tests pass but the alert still fails in production

A promtool test can be green while the alert never fires on a real target. The cards below cover the places where the test world and the production world diverge: timing, label shape, the pipeline before the rule, routing labels, scrape behavior, and when the tests get written.

Test windows that ignore the for duration

A rule with for: 10m only fires after the condition holds for ten minutes of evaluation time. If the test's eval_time values stop before that point, or the series stops early, the test asserts silence and passes for the wrong reason. Build each test from the rule's for value outward: place an assertion just before the threshold and another just after it, and check that the alert moves from pending to firing at the expected step.

Unit testing rules docs

Input series missing real target labels

Hand-written input_series often carry only job and instance, while production targets also expose labels such as env, region, cluster or team through relabeling. A rule that aggregates by (cluster) or filters on team can behave differently when those labels are absent. Copy the label set from a live up or target query into the test fixtures, and list every label the rule reads or groups by.

Relabeling and discovery outside the test

Relabel rules, metric_relabel_configs and service discovery shape the series before any alert rule sees them. promtool tests start from the series you write, so a dropped metric, a renamed label or a changed __name__ in the scrape config never shows up in the test. Keep a recorded sample of scraped output for each job, and review relabel changes in the same pull request as the rules that depend on them.

Label changes that break routing

Alertmanager routes match on labels such as severity and team. A test can prove that an alert fires with the right expression but not that its labels still match the route that pages the owning team. Assert the full label set in exp_alerts, including severity and team labels, and run the same label set through amtool config routes test so a rename does not send pages to the default receiver.

Assumptions about scrape interval and staleness

promtool uses the interval you set in input_series as the sample spacing, but production scrapes run at the configured scrape_interval, and a target that stops responding is marked stale after the gap rather than holding its last value. A rule using rate() over a short range can return nothing in production when scrapes are slower than the window. Match the test interval to the real scrape interval, and add a test where the series goes missing to see whether the alert resolves or stays silent.

Tests written after the rule

Tests written after a rule tend to confirm what the rule already does, including its mistakes. Writing the test first forces the expected behavior to be stated before the PromQL is tuned, which is the point where a wrong threshold or missing for gets caught. Keep one test file per rule group, require a test change in any pull request that edits a rule, and have the CI job run promtool test rules on every change.

Set up promtool tests in CI for your rule repository

This sequence moves Prometheus rule changes through version control and a CI pipeline, so that a broken rule or a failing alert test blocks the merge and the deploy. The result is a repository where every change to alerting and recording rules is checked before it reaches a running Prometheus.

  1. Match promtool to your Prometheus line

    Identify which Prometheus line runs in production, then install a promtool build from the same release line so the rule syntax and test behavior match the server. Check the current minor releases and long-term support lines on the Prometheus release cycle page before pinning a version, and confirm which line your servers run. Done when the CI image prints a promtool version that matches the production Prometheus line, and that version is pinned in your pipeline configuration rather than fetched as latest.

  2. Store rules and tests in version control

    Keep alerting rules, recording rules, the Prometheus configuration that loads them, and the promtool unit test files in the same Git repository. Use one directory per rule group and one test file per rule file, named so the pairing is obvious to reviewers. Done when a clone of the repository contains every rule file and matching test file, and a change to a rule file shows up in the same merge request as its test changes.

  3. Add the static rule check as a CI job

    Add a pipeline job that runs promtool check rules against every rule file in the repository and fails on any error. This catches YAML and PromQL syntax errors, invalid durations and malformed label syntax before any test runs. Done when the job passes on the current main branch, and when you merge a deliberately broken rule (for example, a PromQL expression with an unclosed bracket) the job fails and the error names the file and line.

  4. Add promtool test rules as a CI job

    Add a second job that runs promtool test rules against every test file, using the same pinned promtool version. Each test supplies input series, evaluation times and expected alerts or recording results, so this job verifies behavior, not just syntax. Done when the job passes on main, and when you change a threshold in a rule without updating its test, the job fails and reports the alert or series that differed from the expected output.

  5. Make both jobs required before merge

    In your Git hosting platform, mark the two promtool jobs as required status checks on the protected main branch, so no merge request can complete while either job fails. Restrict who can override or remove the requirement, and record that the setting is enabled. Done when a merge request containing the deliberately broken rule shows the job as failed and the merge button stays blocked, and a reviewer confirms the setting from the branch protection page.

  6. Gate the deploy stage on passing tests

    Configure the deploy job for rule files so it depends on both promtool jobs and runs only from the protected branch after they pass. Deploy the validated rule files and reload Prometheus through your normal mechanism, and make sure the deploy job does not run from unreviewed branches. Confirm whether your Prometheus reload endpoint is enabled before relying on it, since the lifecycle endpoints are disabled unless explicitly turned on. Done when a failing test prevents the deploy stage from starting and a passing run deploys the same commit that was tested.

  7. Rehearse the gate with a test failure

    Run one end-to-end rehearsal: open a merge request that changes an alert threshold without updating its test, confirm the test job fails, confirm the merge is blocked and the deploy does not start, then fix the test and confirm the pipeline passes. Record the result and the promtool version in the repository runbook. Done when the rehearsal shows the block at each gate and the runbook names the pinned promtool version, which is the evidence that the control works as designed.

Security and operational considerations for test pipelines

Alert rule tests are code that runs in CI, so they carry their own security and change control risks. The cards below cover what goes into test fixtures, how the promtool version is held steady, who can merge and bypass the gate, and what evidence the pipeline leaves behind for review.

Keep fixtures synthetic

Input series in rule_test files are often copied from production dashboards, which can carry real hostnames, IP addresses, account numbers or customer identifiers in label values. Write fixture series with placeholder labels such as instance="app-01.example.test" and invented job names. Scan the test directory in CI for patterns that match your internal naming scheme before merge. Illustrative: a copied customer_id label in a test file would be stored in Git history even after it is removed.

Pin the promtool version

Rule tests depend on how promtool parses rules, evaluates PromQL and handles timestamps, so an unpinned binary can change test results without any code change. Pin the exact Prometheus release used for promtool in the CI image or download step, and upgrade it through a reviewed change. Match the version to the Prometheus server version that runs in production so the tests reflect the behavior that will page people. Confirm the release you pin against the Prometheus release cycle page before choosing it.

Release cycle page

Control who merges and bypasses

A passing test suite only protects production if the gate cannot be skipped. Require the promtool job as a protected status check on the default branch, and restrict who can approve rule changes to the team that owns alerting. Review CI settings that allow administrators or pipeline variables to bypass required checks, and record each bypass as a change request. Also check that the test job cannot be edited by the same change it is meant to validate.

Protect the rule pipeline credentials

Validation jobs often need access to the Git repository and to a rule-file registry or configuration store, but they do not need production write access. Give the job read-only tokens, scope them to the rules repository, and keep them out of logs. Do not let test jobs call the Prometheus reload endpoint. Reloading requires --web.enable-lifecycle on the server, which should stay disabled unless you have a specific need for it.

Record review evidence

Change control reviewers need to see what was tested, against which tool version, and who approved the result. Keep the CI log, the promtool version output, the commit hash, the reviewer identity and any bypass record together for each rule change. Store test files in version control so the history shows which alerts were covered at each release. Ask your compliance lead which retention period applies to these records before you set the artifact expiry.

Note what the tests do not cover

The unit tests check rule logic against synthetic input. They do not add authentication, TLS or access control to Prometheus, Alertmanager or the rule files on the server. Prometheus supports TLS, client certificates and basic authentication, but those settings live in the server configuration and must be reviewed separately. Treat the test pipeline as a quality control, and track server hardening in its own review.

Prometheus security model

Questions teams ask before writing promtool tests

What does it cost to write promtool tests for Prometheus alert rules?

Prometheus and promtool are open-source under Apache-2.0, so there is no license fee. The cost is engineering time to write input series, expected alerts and CI wiring, plus the time to keep those tests current as rules change. Your team pays for that time whether it is internal staff or an outside partner. Infrastructure for the CI runner is a small recurring cost you probably already carry. When you ask for a quote, ask for the scope in writing: which rule groups are covered, how many tests are expected, who maintains the suite afterward, and what the handover includes.

How long does it take to get a first useful promtool test suite running?

The first suite usually covers a small set of high-impact alerts, not the whole rule set. Duration depends on how many rules you start with, how well the expected behavior is documented, and whether the team already runs tests in CI. Documented alert thresholds and a clear owner for each rule file shorten the first pass. Ask any partner or internal lead to break the first milestone into a named set of rule files, the CI job that runs them, and a review step, so progress is visible before the suite is complete.

What does a team need in place before writing promtool tests?

Three things make the work go smoothly: named rule owners who can state what each alert should fire on and when, a CI runner that can install promtool and run the test command on every change to rule files, and a review rule that blocks merges when tests fail. Rule owners matter most because a test asserts intent, and only the owner can say whether an alert should fire after five minutes or fifteen. Confirm the exact promtool version your pipeline uses against the Prometheus release cycle page, since test behavior should match the server version you run.

Can our own engineers write promtool tests without outside help?

Yes. Engineers who already write and review PromQL can learn the promtool test file format quickly, because it reuses the same expressions and adds input series, evaluation times and expected alerts. The harder part is deciding what each test should prove, especially for alerts with for durations and label-based routing. Teams often do well when they start with one rule file, pair two engineers on the first tests, and then copy the pattern. If no one on the team has time to own the suite, that is the signal to scope outside help.

How does the number of tests grow as our alert rules increase?

Test count should follow the alerts that matter, not a fixed ratio to rule count. Each alert usually needs a firing case, a non-firing case and, when it has a for duration, a case that proves it waits. Recording rules that feed alerts need tests too, because a wrong intermediate value breaks every alert built on it. Shared expressions can be tested once. As rule files grow, group tests by team or service so ownership stays clear and the CI run time stays manageable. Ask for a test inventory that maps each alert to its test cases.

Do promtool tests prove that an alert will page the right team?

No. promtool tests evaluate rules against the input series you write, so they show that an alert expression and its labels behave as expected. They do not test Alertmanager routing, receiver configuration or whether a notification reached a phone. Routing and receivers need their own checks, and an end-to-end test alert is the usual way to confirm delivery. Keep these layers separate in your plan so a green test run is not read as proof that on-call will be paged.

When should we ask an outside partner to help with promtool tests?

Consider outside help when the rule set is large or business-critical, when your team lacks a clear owner or CI capacity, or when the suite must be ready for an audit or a regulated change process. A partner is also useful when you want the tests, CI gate and review rules designed together and handed over with documentation. DeployOpen implements and documents self-hosted open-source platforms in infrastructure you control, and most engagements are fixed-scope with scope, deliverables and timelines agreed in writing before work starts. Ask for a written scope and a quote based on it.

Do promtool tests count as compliance evidence?

They can support evidence, but they are not evidence on their own. A passing test run shows that alert rules behaved as specified at the time of the run, and the CI history shows that changes were checked before deploy. Whether that satisfies a control depends on the framework and your assessor. Confirm with your auditor which records they want, such as merged change requests, test logs and rule owner approvals, before you design the process around them.

How DeployOpen scopes and delivers promtool test suites

Every promtool engagement starts with a written scope agreed before work begins. That scope names the rule repository, the CI platform the gate will run on, the Prometheus version the rules must pass against, and who owns each alert group. Those four decisions shape the rest of the work. A test suite written for one Prometheus line can behave differently from another, so the target version should be fixed in the scope rather than assumed. Alert ownership matters just as much, because the team that owns an alert is the one that must approve a change to its expected firing behavior. Before the scope is signed, ask who can approve test changes and whether a failing test blocks merge for every team or only for some.

Deliverables are described in general terms and agreed in the scope. They usually include a test suite of promtool test rules files covering the alert and recording rules in scope, a CI gate that runs those tests on every change to rule files, and documentation that explains how to add a test, how to update expected results, and how to run the suite locally. The exact count of files, rule groups and pipeline stages depends on the estate and is set during scoping rather than fixed in advance. DeployOpen implements these components in repositories and CI systems that the client controls, so the test code, pipeline configuration and documentation remain under the client's ownership and can be run by the client's own team after handover.

Ongoing support is available as a retainer for teams that add rules over time, move to a newer Prometheus line, or change CI platforms. Ask any provider to state in the quote what is included after handover, how changes to the test suite are requested, and how upgrades to the Prometheus version are handled. The quote should follow from the written scope, and it should separate one-time build work from any recurring support. DeployOpen does not hold certifications or partner status for the tools in this work, so the basis for trust is the delivered suite and its documentation, which the client can review and run independently.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.