k8s.io/apiserver@v0.31.1/pkg/admission/attributes_test.go (about)

     1  /*
     2  Copyright 2018 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package admission
    18  
    19  import (
    20  	"testing"
    21  
    22  	"github.com/stretchr/testify/assert"
    23  	auditinternal "k8s.io/apiserver/pkg/apis/audit"
    24  )
    25  
    26  func TestAddAnnotation(t *testing.T) {
    27  	attr := &attributesRecord{}
    28  
    29  	// test AddAnnotation
    30  	attr.AddAnnotation("foo.admission.k8s.io/key1", "value1")
    31  	attr.AddAnnotation("foo.admission.k8s.io/key2", "value2")
    32  	annotations := attr.getAnnotations(auditinternal.LevelMetadata)
    33  	assert.Equal(t, annotations["foo.admission.k8s.io/key1"], "value1")
    34  
    35  	// test overwrite
    36  	assert.Error(t, attr.AddAnnotation("foo.admission.k8s.io/key1", "value1-overwrite"),
    37  		"admission annotations should not be allowd to be overwritten")
    38  	annotations = attr.getAnnotations(auditinternal.LevelMetadata)
    39  	assert.Equal(t, annotations["foo.admission.k8s.io/key1"], "value1", "admission annotations should not be overwritten")
    40  
    41  	// test invalid plugin names
    42  	var testCases = map[string]string{
    43  		"invalid dns subdomain": "INVALID-DNS-Subdomain/policy",
    44  		"no plugin name":        "policy",
    45  		"no key name":           "foo.admission.k8s.io",
    46  		"empty key":             "",
    47  	}
    48  	for name, invalidKey := range testCases {
    49  		err := attr.AddAnnotation(invalidKey, "value-foo")
    50  		assert.Error(t, err)
    51  		annotations = attr.getAnnotations(auditinternal.LevelMetadata)
    52  		assert.Equal(t, annotations[invalidKey], "", name+": invalid pluginName is not allowed ")
    53  	}
    54  
    55  	// test all saved annotations
    56  	assert.Equal(
    57  		t,
    58  		annotations,
    59  		map[string]string{
    60  			"foo.admission.k8s.io/key1": "value1",
    61  			"foo.admission.k8s.io/key2": "value2",
    62  		},
    63  		"unexpected final annotations",
    64  	)
    65  }