1
0
Fork 0
mirror of https://github.com/kyverno/kyverno.git synced 2025-01-20 18:52:16 +00:00
kyverno/pkg/policy/background_test.go
Jim Bugwadia 5c16ee738a
redo variable validation (#2647)
* redo variable validation

Signed-off-by: Jim Bugwadia <jim@nirmata.com>

* handle quotes for JMESPath - escaping

Signed-off-by: Jim Bugwadia <jim@nirmata.com>

* fix tests and linter issues

Signed-off-by: Jim Bugwadia <jim@nirmata.com>

* fix fmt

Signed-off-by: Jim Bugwadia <jim@nirmata.com>
2021-11-03 11:16:55 -07:00

136 lines
2.5 KiB
Go

package policy
import (
"encoding/json"
"testing"
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
"gotest.tools/assert"
)
func Test_Validation_valid_backgroundPolicy(t *testing.T) {
rawPolicy := []byte(`
{
"apiVersion": "kyverno.io/v1",
"kind": "ClusterPolicy",
"metadata": {
"name": "test-gen",
"annotations": {
"policies.kyverno.io/category": "Best Practices"
}
},
"spec": {
"rules": [
{
"match": {
"resources": {
"kinds": [
"Namespace"
]
}
},
"name": "test-gen",
"preconditions": {
"all": [
{
"key": "{{request.object.metadata.name}}",
"operator": "NotEquals",
"value": ""
}
]
},
"context": [
{
"name": "mycm",
"configMap": {
"name": "config-name",
"namespace": "default"
}
}
],
"generate": {
"kind": "ConfigMap",
"name": "{{request.object.metadata.name}}-config-name",
"namespace": "{{request.object.metadata.name}}",
"data": {
"data": {
"new": "{{ mycm.data.foo }}"
}
}
}
}
]
}
}
`)
var policy kyverno.ClusterPolicy
err := json.Unmarshal(rawPolicy, &policy)
assert.NilError(t, err)
err = ValidateVariables(&policy, true)
assert.NilError(t, err)
}
func Test_Validation_invalid_backgroundPolicy(t *testing.T) {
rawPolicy := []byte(`
{
"apiVersion": "kyverno.io/v1",
"kind": "ClusterPolicy",
"metadata": {
"name": "test-gen",
"annotations": {
"policies.kyverno.io/category": "Best Practices"
}
},
"spec": {
"rules": [
{
"match": {
"resources": {
"kinds": [
"Namespace"
]
}
},
"name": "test-gen",
"preconditions": {
"all": [
{
"key": "{{request.object.metadata.name}}",
"operator": "NotEquals",
"value": ""
}
]
},
"context": [
{
"name": "mycm",
"configMap": {
"name": "config-name",
"namespace": "default"
}
}
],
"generate": {
"kind": "ConfigMap",
"name": "{{serviceAccountName}}-config-name",
"namespace": "{{serviceAccountName}}",
"data": {
"data": {
"new": "{{ mycm.data.foo }}"
}
}
}
}
]
}
}
`)
var policy kyverno.ClusterPolicy
err := json.Unmarshal(rawPolicy, &policy)
assert.NilError(t, err)
err = ValidateVariables(&policy, true)
assert.ErrorContains(t, err, "variable serviceAccountName must match")
}