TExcelTAD
Home › Secrets & Policy as Code: Vault, SOPS, OPA & Conftest › Testing Policies with opa test

Testing Policies with opa test

A policy is code that can block every deploy in the company. A typo in a rule doesn't fail loudly: a misspelled field is simply undefined, the rule never fires, and the policy silently allows everything. Unit tests are the only way to know a rule does what it says.

Tests are rules too

A test is a rule whose name starts with test_, usually in a _test package next to the policy. with replaces input (or any part of data) for one expression:

bash · try it yourself
mkdir -p policy && cd policy
cat > db.rego <<'REGO'
package terraform.db

deny contains msg if {
	some rc in input.resource_changes
	rc.type == "aws_db_instance"
	"create" in rc.change.actions
	not rc.change.after.storage_encrypted
	msg := sprintf("%s: storage must be encrypted", [rc.address])
}

deny contains msg if {
	some rc in input.resource_changes
	rc.type == "aws_db_instance"
	rc.change.after.publicly_accessible
	msg := sprintf("%s: must not be publicly accessible", [rc.address])
}
REGO
cat > db_test.rego <<'REGO'
package terraform.db_test

import data.terraform.db

db_change(after) := {"resource_changes": [{
	"address": "aws_db_instance.main",
	"type": "aws_db_instance",
	"change": {"actions": ["create"], "after": after},
}]}

test_unencrypted_denied if {
	db.deny == {"aws_db_instance.main: storage must be encrypted"} with input as db_change({"storage_encrypted": false})
}

test_missing_flag_denied if {
	# the attribute absent entirely: must still be denied
	count(db.deny) == 1 with input as db_change({})
}

test_public_denied if {
	some msg in db.deny with input as db_change({"storage_encrypted": true, "publicly_accessible": true})
	contains(msg, "publicly accessible")
}

test_compliant_allowed if {
	count(db.deny) == 0 with input as db_change({"storage_encrypted": true, "publicly_accessible": false})
}

test_other_types_ignored if {
	count(db.deny) == 0 with input as {"resource_changes": [{"address": "aws_s3_bucket.b", "type": "aws_s3_bucket",
		"change": {"actions": ["create"], "after": {}}}]}
}
REGO
opa test . ; echo "exit $?"
PASS: 5/5
exit 0

Each policy rule has at least one test that proves it fires and one that proves it doesn't fire on compliant input. test_missing_flag_denied covers the case that matters most in practice: an attribute missing altogether.

What a failing test looks like

Introduce the classic bug, a misspelled attribute, and the tests catch it:

bash · try it yourself
mkdir -p policy && cd policy
cat > db.rego <<'REGO'
package terraform.db

deny contains msg if {
	some rc in input.resource_changes
	rc.type == "aws_db_instance"
	rc.change.after.storage_encryption == false     # typo: the attribute is storage_encrypted
	msg := sprintf("%s: storage must be encrypted", [rc.address])
}
REGO
cat > db_test.rego <<'REGO'
package terraform.db_test

import data.terraform.db

test_unencrypted_denied if {
	count(db.deny) == 1 with input as {"resource_changes": [{"address": "aws_db_instance.main",
		"type": "aws_db_instance", "change": {"actions": ["create"], "after": {"storage_encrypted": false}}}]}
}
REGO
opa test . 2>&1 | grep -vE '^-+
  

; echo "exit ${PIPESTATUS[0]}"
db_test.rego:5:
data.terraform.db_test.test_unencrypted_denied: FAIL (339.864µs)
FAIL: 1/1
exit 2

Without the test, this policy would have passed every plan, including unencrypted databases. opa test -v adds a trace of each failing test's evaluation, which shows where it stopped matching.

Coverage, formatting and strict checks

bash · try it yourself
mkdir -p policy && cd policy
cat > tags.rego <<'REGO'
package terraform.tags

required := {"owner", "env"}

deny contains msg if {
	some rc in input.resource_changes
	"create" in rc.change.actions
	missing := required - {k | some k, _ in object.get(rc.change.after, "tags", {})}
	count(missing) > 0
	msg := sprintf("%s: missing tags %v", [rc.address, sort(missing)])
}

warn contains msg if {
	some rc in input.resource_changes
	"delete" in rc.change.actions
	msg := sprintf("%s will be deleted", [rc.address])
}
REGO
cat > tags_test.rego <<'REGO'
package terraform.tags_test

import data.terraform.tags

test_missing if {
	tags.deny == {"aws_s3_bucket.b: missing tags [\"env\"]"} with input as {"resource_changes": [
		{"address": "aws_s3_bucket.b", "change": {"actions": ["create"], "after": {"tags": {"owner": "links"}}}}]}
}
REGO
opa test --coverage --format=json . | jq -r '"coverage: \(.coverage | floor)%", (.files[] | .not_covered[]? | "not covered: lines \(.start.row)-\(.end.row)")'
cat > sloppy.rego <<'REGO'
package sloppy
deny contains "x" if { input.a == 1; unused := input.b }
REGO
echo "--- not in canonical format:"
opa fmt -l .
opa fmt -w tags_test.rego && opa fmt -l tags_test.rego && echo "tags_test.rego: formatted"
echo "--- strict check:"
opa check --strict . 2>&1 | head -3
coverage: 76%
not covered: lines 13-13
not covered: lines 15-15
not covered: lines 16-16
--- not in canonical format:
sloppy.rego
tags_test.rego
tags_test.rego: formatted
--- strict check:
1 error occurred: sloppy.rego:2: rego_compile_error: assigned var unused unused
  • Coverage shows the warn rule was never exercised: no test, so no proof it works.
  • opa fmt -l lists files that aren't in canonical format: here the one-line sloppy.rego and the test file with its long input literal. opa fmt -w rewrites them; in CI, opa fmt --fail -l turns any listed file into a failure.
  • opa check --strict rejects unused variables and other likely mistakes.

In CI

yaml
# a policy repository's own pipeline (non-run)
policy-tests:
  runs-on: ubuntu-24.04
  steps:
    - uses: actions/checkout@v7
    - uses: open-policy-agent/setup-opa@v2
      with: { version: 1.21.4 }
    - run: opa fmt --fail -l policy/
    - run: opa check --strict policy/
    - run: opa test policy/ --coverage --threshold 90 > /dev/null

--threshold 90 makes opa test --coverage fail below 90 % coverage. Policies are then published (a Git tag, an OCI bundle with conftest push, or an OPA bundle) and consumed by pipelines at a pinned version, like any other dependency.

Test yourself

A rule refers to rc.change.after.storage_encryption (a typo). What happens without tests?

  1. OPA reports a type error
  2. The reference is undefined, the rule never fires, and violations pass silently
  3. The plan fails
  4. Conftest fixes the name

What does with input as {...} do in a test?

  1. Writes a file
  2. Replaces input for that expression
  3. Loads a data file
  4. Mocks OPA itself

Which command catches unused variables in policies?

  1. opa fmt
  2. opa check --strict
  3. opa eval
  4. opa build