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

如何测试OPA返回的JSON决策中的键/属性值?解决未定义变量报错

Fixing "var decision is unsafe" Error in OPA Test Rules

Let's break down why you're seeing that error and how to fix it:

Why the Error Happens

Your test rule references a decision variable but never defines it—OPA has no idea where this variable comes from. OPA requires all variables used in test rules to be explicitly bound to a value (like the output of your policy function), hence the "unsafe" warning.

Your Original Policy

First, let's restate your policy for clarity:

get_user_info = decision{
    decision := {
        "allow": input.user_id == "bob",
        "user_id": input.user_id,
    }
}

Correct Test Rules

You need to bind decision to the output of your get_user_info policy function, then assert the value of the allow key. Here are two valid approaches:

Approach 1: Explicit Variable Binding

test_get_user_allowed_for_admin {
    // Bind decision to the output of your policy
    decision := get_user_info
    // Assert that the allow flag is true for user "bob"
    decision.allow == true
    // Set the test input
    with input as {"path": ["users", "kate"], "method": "GET", "user_id": "bob"}
}

Approach 2: Direct Property Access (Shorter)

You can skip the variable and directly check the allow property of the policy's output:

test_get_user_allowed_for_admin {
    get_user_info.allow == true
    with input as {"path": ["users", "kate"], "method": "GET", "user_id": "bob"}
}

Add a Negative Test Case (Optional)

To cover the denied scenario, add another test to ensure your policy behaves as expected for non-admin users:

test_get_user_denied_for_non_admin {
    get_user_info.allow == false
    with input as {"path": ["users", "kate"], "method": "GET", "user_id": "alice"}
}

How It Works

OPA test rules pass when the entire rule evaluates to true. By binding decision to your policy's output (or accessing it directly), you're telling OPA exactly where to get the decision data, eliminating the "unsafe variable" error. Then you validate that the allow value matches your expected outcome for the given input.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:51:11