
Overview
In this article, we are going to learn about how to write test cases for OPA policy.
Working Example
Let’s create a Directory called test5 and create 3 files like below:
policy.rego
package policy
default allow = false
allow {
input.user.roles[_] == "admin"
}

input.json
{
"user": {
"username": "test_user",
"roles": ["developer","admin"]
}
}

policy_test.rego
package policy_test
import data.policy.allow
test_allow_is_false_by_default {
not allow
}
test_allow_if_admin {
allow with input as {
"user": {
"roles": ["admin"]
}
}
}
test_deny_if_not_admin {
not allow with input as {
"user": {
"roles": ["developer"]
}
}
}

Testing Policy Test cases
Now test our policy set. We have written 3 test cases which are:
- The “allow” rule should be false when no input is given.
- The “allow rule should be true if input is given and user role is “admin”.
- The allow rule should be false if input is given and user role is “developer”
Now let’s test our test cases.
- Change to the directory where all our policy exists.

- Now run below command to test the test cases:
opa test .
The output:
rajeevghosh@penguin:~/OPA/test5$ opa test .
PASS: 3/3
rajeevghosh@penguin:~/OPA/test5$
Where Dot (.) denotes the present directory.

We can see that all our test cases have passed.
Testing Fail Case Scenario
- Let’s change the file “policy_test.rego” to below and ensure that other files remains unchanged.
policy_test.rego
package policy_test
import data.policy.allow
test_allow_is_false_by_default {
allow
}
test_allow_if_admin {
allow with input as {
"user": {
"roles": ["admin"]
}
}
}
test_deny_if_not_admin {
not allow with input as {
"user": {
"roles": ["developer"]
}
}
}

We have just change below section in the above code.
Before:
test_allow_is_false_by_default {
not allow
}
After the modification:
test_allow_is_false_by_default {
allow
}
Testing:
Now since we have made changes to test case code , let’s test our policy again with test cases:
- Run below code:
opa test .
The output:
rajeevghosh@penguin:~/OPA/test5$ opa test .
data.policy_test.test_allow_is_false_by_default: FAIL (1.097µs)
--------------------------------------------------------------------------------
PASS: 2/3
FAIL: 1/3
As we can see from output our 2 out of 3 test cases have passed.

This concludes our 4th tutorial on REGO and OPA.
Thank you for your shening. I am worried that I lack creative ideas. It is your enticle that makes me full of hope. Thank you. But, I have a question, can you help me? https://www.binance.com/en/register?ref=P9L9FQKY
Your article made me suddenly realize that I am writing a thesis on gate.io. After reading your article, I have a different way of thinking, thank you. However, I still have some doubts, can you help me? Thanks.