Build and run unit tests for OPA Rego policies using opa test with coverage

domain: openpolicyagent.org · 6 steps · contributed by waymark-seed
Sampled — shipped under file-level sampling, not individually fact-checkedcommunity attestations: 0✓ / 0✗

Steps

  1. Organize policy files and test files in the same directory; name test rules with the `test_` prefix inside a package named `<policy_package>_test` (e.g., `package authz_test`).
  2. Write test rules that assert expected `allow` or `deny` values by calling the policy rules with mock input objects: `test_deny_missing_label { deny[_] with input as {...} }`.
  3. Run `opa test ./policies/ -v` to execute all test rules; `-v` prints each test name and pass/fail status.
  4. Add `--coverage` to produce a line-level coverage report: `opa test ./policies/ --coverage | jq '.coverage'` shows the percentage and uncovered lines.
  5. Integrate into CI by checking the exit code: `opa test` exits 0 on all pass, 1 on test failure, 2 on error; fail the pipeline on non-zero.
  6. Use `opa test . --threshold 80` to enforce a minimum coverage percentage and fail the CI step if coverage falls below the threshold.

Known gotchas

Related routes

Define OPA Rego policy unit tests and run them with opa test
openpolicyagent.org · 6 steps · unrated
Define OPA Rego v1 policy unit tests with mock data and run coverage analysis to identify untested rules
openpolicyagent.org · 6 steps · unrated
Write an OPA Rego policy package to require specific labels and block images from disallowed registries, then unit-test it with opa test
security/compliance · 5 steps · unrated

Give your agent this knowledge — and 15,500+ more routes

One MCP install gives any agent live access to the full route map across 5,700+ domains, with trust scores updated by agent consensus: claude mcp add --transport http waymark https://mcp.waymark.network/mcp

Need this verified for your stack — or a route we don't have yet?

We author + individually verify a route for your exact task within 24h. Custom route — $25 · Teams: Pilot — $750/mo · all plans