You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OPA测试mock自定义Rego函数报未定义错误问题排查

OPA自定义公共函数测试报错问题

问题背景

我有数百个不同的*.rego文件,每个文件包含不同的规则,所有规则都需要从input参数中校验用户角色(user-role)与请求方法(method)。因此我创建了内容如下的functions.rego文件用于公共逻辑复用:

package abc.functions

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

其他rego文档可以直接导入该公共函数,无需重复编写相同逻辑,使用示例如下:

package opa.abc.institutions.view

import data.abc.functions

default allow = false

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

上述逻辑可正常运行,但我需要为每条规则编写单元测试用例。在阅读OPA测试官方指南,尤其是函数与数据mock相关章节后,我尝试编写如下测试代码:

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

官方文档给出的mock示例均针对内置函数(支持将函数直接替换为单个布尔值),无法确定是否可以按上述方式mock定义在虚拟文档中的自定义函数。

解决方案

感谢devoops的解答。
报错原因是执行测试时未加载functions.rego文件,OPA测试时需要显式加载所有依赖的rego文件,正确的测试执行命令如下:

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

内容的提问来源于stack exchange,提问作者theuni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 03:51:23