OPA (Open Policy Agent): Part-4: Rego – Writing Test Cases

Share At:

Notes on Open Policy Agent and Docker Security

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:

  1. The “allow” rule should be false when no input is given.
  2. The “allow rule should be true if input is given and user role is “admin”.
  3. 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

  1. 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.

Happy Learning !!


Share At:
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Back To Top

Contact Us