1

为我的 rego 文件运行测试时出错。雷戈文件:

package authz
import abc.def

default can_tigger = false

can_tigger = true{
    needs_one_of := ["trigger_access_allowed"]
    access.allowed_for_triger(input.appId, input.user, needs_one_of[_],input.resource)
}

Rego 测试文件:

package authz

test_can_trigger_command_when_projectId_is_valid {
    can_tigger
    with input as {"projectId": "5fdf4ab1-acf6-4d5f-9604-79bda49d9431", "user": {"sub": "testUser"}}    
}

如果我在测试文件中设置值,can_tigger:= true/false那么我的测试将通过,但这样做不是编写测试的正确方法。

4

1 回答 1

0

OPA Gatekeeper Library是学习如何为 Rego 编写测试的好方法。

k8sallowedrepos 测试

test_input_allowed_container {
    input := { "review": input_review(input_container_allowed), "parameters": {"repos": ["allowed"]}}
    results := violation with input as input
    count(results) == 0
}
...
input_init_review(containers) = output {
    output = {
      "object": {
        "metadata": {
            "name": "nginx"
        },
        "spec": {
            "initContainers": containers,
        }
      }
     }
}

input_container_allowed = [
{
    "name": "nginx",
    "image": "allowed/nginx",
}]

请注意,在测试中,violation with input as input是一个 Rego 习语,它将本地“输入”变量传递给此处定义的违规,使用“输入”。它比内联操作要干净得多。

在您的情况下,您可以将测试重写为:

test_can_trigger_command_when_projectId_is_valid {
    input := {"projectId": "5fdf4ab1-acf6-4d5f-9604-79bda49d9431", "user": {"sub": "testUser"}}
    results := violation with input as input
    count(results) == 0
}
于 2021-05-11T16:54:07.043 回答