模拟自定义功能-open-policy-agent

问题描述 投票:0回答:1

我有数百个不同的 *.rego 文件,每个文件都有不同的规则。每个规则都需要检查输入中的用户角色和方法。所以我决定创建一个包含以下内容的

functions.rego

package abc.functions

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

其他文档可以导入此函数,而无需一次又一次地重新定义它,例如

package opa.abc.institutions.view

import data.abc.functions

default allow = false

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

这个作品。但是,我需要为每条规则编写测试。在阅读了 opa 的测试指南,尤其是模拟函数和数据后,我尝试执行以下操作

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
}

这会产生错误

rego_type_error: undefined function data.abc.functions.method_and_role_valid

文档显示了内置函数的模拟示例(也用单个布尔值替换函数),真的没有办法像我一样模拟虚拟文档中定义的“自定义”函数吗?

更新

感谢@devoops

测试时忘记加载functions.rego。不知道这需要明确完成。

./opa test -v test1_test.rego test1.rego functions.rego
testing open-policy-agent
1个回答
1
投票

在代码上运行

opa test .
似乎按预期工作:

❯ opa test .
PASS: 2/2

运行测试时您是否忘记包含所有文件?

© www.soinside.com 2019 - 2024. All rights reserved.