testingopen-policy-agent

Mock custom function - open-policy-agent


I have hundreds of different *.rego files, each with different rules. Every single rule needs to check for user-role and method from the input. So I decided to create a functions.rego with the following content

package abc.functions

method_and_role_valid(in, meth, role) {
 in.method == meth
 in.current_user_roles[_] == role
}

The other documents can then import this function without having to redefine it again and again, e.g.

package opa.abc.institutions.view

import data.abc.functions

default allow = false

allow {
 functions.method_and_role_valid(input, "view", "administrator")
}

This work. However, I need to write tests for each of the rules. After reading the opa guidelines on testing, especially mocking functions and data, I tried to do the follwing

package opa.abc.institutions.view

test_allow_1 {
 allow with input as {"method": "view", "current_user_roles": ["authenticated"]} with data.abc.functions.method_and_role_valid as true
}
test_deny_2 {
 not allow with input as {"method": "view", "current_user_roles": ["authenticated"]} with data.abc.functions.method_and_role_valid as false
}

This creates the error rego_type_error: undefined function data.abc.functions.method_and_role_valid

The documentation shows mocking examples for built-in functions (also replacing a function with a single boolean value), is there really no way to mock "custom" functions defined in virtual documents as I did?

Update

Thanks to @devoops

I forgot to load the functions.rego when testing. Didn't know this needs to be done explicitly.

./opa test -v test1_test.rego test1.rego functions.rego

Solution

  • Running opa test . on your code seems to work as intended:

    ❯ opa test .
    PASS: 2/2
    

    Did you forget to include all files when running the tests?