1

我偶然发现的测试似乎有很多相同的测试。

我正在调查与 Gatekeeper 的违规行为。

例如,此约束模板策略将测试容器来自的存储库:

package k8sallowedrepos

violation[{"msg": msg}] {
  container := input.review.object.spec.containers[_]
  satisfied := [good | repo = input.parameters.repos[_] ; good = startswith(container.image, repo)]
  not any(satisfied)
  msg := sprintf("container <%v> has an invalid image repo <%v>, allowed repos are %v", [container.name, container.image, input.parameters.repos])
}

violation[{"msg": msg}] {
  container := input.review.object.spec.initContainers[_]
  satisfied := [good | repo = input.parameters.repos[_] ; good = startswith(container.image, repo)]
  not any(satisfied)
  msg := sprintf("container <%v> has an invalid image repo <%v>, allowed repos are %v", [container.name, container.image, input.parameters.repos])
}

我会从哪里开始测试呢?

4

1 回答 1

2

如果您正在为 OPA Gatekeeper 编写自己的模板,我们建议您为这些模板中的规则编写测试,就像您为 OPA 编写的任何其他规则一样。在这种情况下,您想编写测试来执行拒绝(即,其中一个规则中的所有语句都匹配)和无结果(即,两个规则中的至少一个语句不匹配)。我们建议您尽可能使用 OPA 进行测试驱动开发 (TDD) 的能力。

package k8sallowedrepos

test_image_safety_positive {
    count(violation) == 1 with input.parameters.repos as ["hooli.com/"]
        with input.review.object.spec.containers as [
            {"name": "ok", "image": "hooli.com/web"},
            {"name": "bad", "image": "badrepo.com/web"},
        ]
}

test_image_safety_negative {
    count(violation) == 0 with input.parameters.repos as ["hooli.com/"]
        with input.review.object.spec.containers as [
            {"name": "ok", "image": "hooli.com/web"},
        ]
}

test_image_safety_init_container_positive {
    count(violation) == 1 with input.parameters.repos as ["hooli.com/"]
        with input.review.object.spec.initContainers as [
            {"name": "ok", "image": "hooli.com/web"},
            {"name": "bad", "image": "badrepo.com/web"},
        ]
}

test_image_safety_init_container_negative {
    count(violation) == 0 with input.parameters.repos as ["hooli.com/"]
        with input.review.object.spec.initContainers as [
            {"name": "ok", "image": "hooli.com/web"},
        ]
}

我们在 OPA Gatekeeper 库 (WIP) 中一直遵循的模式是将测试包含在与规则相同的包中,但在同一目录中的单独文件中(例如,src.rego 和 src_test.rego)。链接:https ://github.com/open-policy-agent/gatekeeper/tree/master/library 。请注意,最终将规则加载到集群中的 ConstraintTemplate YAML 文件应被视为构建工件。将源代码保存在磁盘上的 .rego 文件中(在版本控制中),然后从这些文件中生成 ContsraintTemplate YAML。

于 2019-12-10T20:30:21.503 回答