Testing policies
opa test and table-driven tests.
Policies are code that gates real deployments, so they must be tested — and OPA has a built-in test framework. A test is a Rego rule in a _test.rego file whose name starts with test_; it sets up an input, evaluates the policy, and asserts the result. opa test runs them. Because policy is pure (input in, decision out), tests are fast and deterministic, and you should have one for every allow path and every deny path.
package exampletest_privileged_denied if {deny["container app is privileged"] with input as {"spec": {"containers": [{"name": "app", "securityContext": {"privileged": true}}]}}}test_normal_allowed if {count(deny) == 0 with input as {"spec": {"containers": [{"name": "app", "securityContext": {"privileged": false}}]}}}
$ opa test . -vdata.example.test_privileged_denied: PASS (1.2ms)data.example.test_normal_allowed: PASS (0.8ms)--------------------------------------------------PASS: 2/2
The with keyword
The key testing tool is with, which overrides input (or data) for the scope of an expression — with input as {...} runs the policy against a crafted case. This lets you drive the policy through every scenario without an external file. Write tests table-style (one per case: compliant, each violation, edge cases with missing fields) so a change that weakens a rule fails a test immediately.