add prune and remove unused packages

This commit is contained in:
Michelle Au
2019-03-08 14:54:43 -08:00
parent f59b58d164
commit 8c0accad66
17240 changed files with 27 additions and 4750030 deletions

View File

@@ -1,136 +0,0 @@
/*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package unstructured
import (
"io/ioutil"
"sync"
"testing"
"github.com/stretchr/testify/assert"
)
// TestCodecOfUnstructuredList tests that there are no data races in Encode().
// i.e. that it does not mutate the object being encoded.
func TestCodecOfUnstructuredList(t *testing.T) {
var wg sync.WaitGroup
concurrency := 10
list := UnstructuredList{
Object: map[string]interface{}{},
}
wg.Add(concurrency)
for i := 0; i < concurrency; i++ {
go func() {
defer wg.Done()
assert.NoError(t, UnstructuredJSONScheme.Encode(&list, ioutil.Discard))
}()
}
wg.Wait()
}
func TestRemoveNestedField(t *testing.T) {
obj := map[string]interface{}{
"x": map[string]interface{}{
"y": 1,
"a": "foo",
},
}
RemoveNestedField(obj, "x", "a")
assert.Len(t, obj["x"], 1)
RemoveNestedField(obj, "x", "y")
assert.Empty(t, obj["x"])
RemoveNestedField(obj, "x")
assert.Empty(t, obj)
RemoveNestedField(obj, "x") // Remove of a non-existent field
assert.Empty(t, obj)
}
func TestNestedFieldNoCopy(t *testing.T) {
target := map[string]interface{}{"foo": "bar"}
obj := map[string]interface{}{
"a": map[string]interface{}{
"b": target,
"c": nil,
"d": []interface{}{"foo"},
},
}
// case 1: field exists and is non-nil
res, exists, err := NestedFieldNoCopy(obj, "a", "b")
assert.True(t, exists)
assert.Nil(t, err)
assert.Equal(t, target, res)
target["foo"] = "baz"
assert.Equal(t, target["foo"], res.(map[string]interface{})["foo"], "result should be a reference to the expected item")
// case 2: field exists and is nil
res, exists, err = NestedFieldNoCopy(obj, "a", "c")
assert.True(t, exists)
assert.Nil(t, err)
assert.Nil(t, res)
// case 3: error traversing obj
res, exists, err = NestedFieldNoCopy(obj, "a", "d", "foo")
assert.False(t, exists)
assert.NotNil(t, err)
assert.Nil(t, res)
// case 4: field does not exist
res, exists, err = NestedFieldNoCopy(obj, "a", "e")
assert.False(t, exists)
assert.Nil(t, err)
assert.Nil(t, res)
}
func TestNestedFieldCopy(t *testing.T) {
target := map[string]interface{}{"foo": "bar"}
obj := map[string]interface{}{
"a": map[string]interface{}{
"b": target,
"c": nil,
"d": []interface{}{"foo"},
},
}
// case 1: field exists and is non-nil
res, exists, err := NestedFieldCopy(obj, "a", "b")
assert.True(t, exists)
assert.Nil(t, err)
assert.Equal(t, target, res)
target["foo"] = "baz"
assert.NotEqual(t, target["foo"], res.(map[string]interface{})["foo"], "result should be a copy of the expected item")
// case 2: field exists and is nil
res, exists, err = NestedFieldCopy(obj, "a", "c")
assert.True(t, exists)
assert.Nil(t, err)
assert.Nil(t, res)
// case 3: error traversing obj
res, exists, err = NestedFieldCopy(obj, "a", "d", "foo")
assert.False(t, exists)
assert.NotNil(t, err)
assert.Nil(t, res)
// case 4: field does not exist
res, exists, err = NestedFieldCopy(obj, "a", "e")
assert.False(t, exists)
assert.Nil(t, err)
assert.Nil(t, res)
}

View File

@@ -1,86 +0,0 @@
/*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package unstructured
import (
"testing"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestUnstructuredList(t *testing.T) {
list := &UnstructuredList{
Object: map[string]interface{}{"kind": "List", "apiVersion": "v1"},
Items: []Unstructured{
{Object: map[string]interface{}{"kind": "Pod", "apiVersion": "v1", "metadata": map[string]interface{}{"name": "test"}}},
},
}
content := list.UnstructuredContent()
items := content["items"].([]interface{})
require.Len(t, items, 1)
val, found, err := NestedFieldCopy(items[0].(map[string]interface{}), "metadata", "name")
require.True(t, found)
require.NoError(t, err)
assert.Equal(t, "test", val)
}
func TestNilDeletionTimestamp(t *testing.T) {
var u Unstructured
del := u.GetDeletionTimestamp()
if del != nil {
t.Errorf("unexpected non-nil deletion timestamp: %v", del)
}
u.SetDeletionTimestamp(u.GetDeletionTimestamp())
del = u.GetDeletionTimestamp()
if del != nil {
t.Errorf("unexpected non-nil deletion timestamp: %v", del)
}
_, ok := u.Object["metadata"]
assert.False(t, ok)
now := metav1.Now()
u.SetDeletionTimestamp(&now)
assert.Equal(t, now.Unix(), u.GetDeletionTimestamp().Unix())
u.SetDeletionTimestamp(nil)
metadata := u.Object["metadata"].(map[string]interface{})
_, ok = metadata["deletionTimestamp"]
assert.False(t, ok)
}
func TestEmptyCreationTimestampIsOmitted(t *testing.T) {
var u Unstructured
now := metav1.Now()
// set an initial creationTimestamp and ensure the field exists
u.SetCreationTimestamp(now)
metadata := u.Object["metadata"].(map[string]interface{})
creationTimestamp, exists := metadata["creationTimestamp"]
if !exists {
t.Fatalf("unexpected missing creationTimestamp")
}
// set an empty timestamp and ensure the field no longer exists
u.SetCreationTimestamp(metav1.Time{})
metadata = u.Object["metadata"].(map[string]interface{})
creationTimestamp, exists = metadata["creationTimestamp"]
if exists {
t.Errorf("unexpected creation timestamp field: %q", creationTimestamp)
}
}

View File

@@ -1,162 +0,0 @@
/*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package unstructured_test
import (
"math/rand"
"reflect"
"testing"
"github.com/stretchr/testify/assert"
"k8s.io/apimachinery/pkg/api/apitesting/fuzzer"
"k8s.io/apimachinery/pkg/api/equality"
metafuzzer "k8s.io/apimachinery/pkg/apis/meta/fuzzer"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/apimachinery/pkg/util/diff"
)
func TestNilUnstructuredContent(t *testing.T) {
var u unstructured.Unstructured
uCopy := u.DeepCopy()
content := u.UnstructuredContent()
expContent := make(map[string]interface{})
assert.EqualValues(t, expContent, content)
assert.Equal(t, uCopy, &u)
}
// TestUnstructuredMetadataRoundTrip checks that metadata accessors
// correctly set the metadata for unstructured objects.
// First, it fuzzes an empty ObjectMeta and sets this value as the metadata for an unstructured object.
// Next, it uses metadata accessor methods to set these fuzzed values to another unstructured object.
// Finally, it checks that both the unstructured objects are equal.
func TestUnstructuredMetadataRoundTrip(t *testing.T) {
scheme := runtime.NewScheme()
codecs := serializer.NewCodecFactory(scheme)
seed := rand.Int63()
fuzzer := fuzzer.FuzzerFor(metafuzzer.Funcs, rand.NewSource(seed), codecs)
N := 1000
for i := 0; i < N; i++ {
u := &unstructured.Unstructured{Object: map[string]interface{}{}}
uCopy := u.DeepCopy()
metadata := &metav1.ObjectMeta{}
fuzzer.Fuzz(metadata)
if err := setObjectMeta(u, metadata); err != nil {
t.Fatalf("unexpected error setting fuzzed ObjectMeta: %v", err)
}
setObjectMetaUsingAccessors(u, uCopy)
// TODO: remove this special casing when creationTimestamp becomes a pointer.
// Right now, creationTimestamp is a struct (metav1.Time) so omitempty holds no meaning for it.
// However, the current behaviour is to remove the field if it holds an empty struct.
// This special casing exists here because custom marshallers for metav1.Time marshal
// an empty value to "null", which gets converted to nil when converting to an unstructured map by "ToUnstructured".
if err := unstructured.SetNestedField(uCopy.UnstructuredContent(), nil, "metadata", "creationTimestamp"); err != nil {
t.Fatalf("unexpected error setting creationTimestamp as nil: %v", err)
}
if !equality.Semantic.DeepEqual(u, uCopy) {
t.Errorf("diff: %v", diff.ObjectReflectDiff(u, uCopy))
}
}
}
// TestUnstructuredMetadataOmitempty checks that ObjectMeta omitempty
// semantics are enforced for unstructured objects.
// The fuzzing test above should catch these cases but this is here just to be safe.
// Example: the metadata.clusterName field has the omitempty json tag
// so if it is set to it's zero value (""), it should be removed from the metadata map.
func TestUnstructuredMetadataOmitempty(t *testing.T) {
scheme := runtime.NewScheme()
codecs := serializer.NewCodecFactory(scheme)
seed := rand.Int63()
fuzzer := fuzzer.FuzzerFor(metafuzzer.Funcs, rand.NewSource(seed), codecs)
// fuzz to make sure we don't miss any function calls below
u := &unstructured.Unstructured{Object: map[string]interface{}{}}
metadata := &metav1.ObjectMeta{}
fuzzer.Fuzz(metadata)
if err := setObjectMeta(u, metadata); err != nil {
t.Fatalf("unexpected error setting fuzzed ObjectMeta: %v", err)
}
// set zero values for all fields in metadata explicitly
// to check that omitempty fields having zero values are never set
u.SetName("")
u.SetGenerateName("")
u.SetNamespace("")
u.SetSelfLink("")
u.SetUID("")
u.SetResourceVersion("")
u.SetGeneration(0)
u.SetCreationTimestamp(metav1.Time{})
u.SetDeletionTimestamp(nil)
u.SetDeletionGracePeriodSeconds(nil)
u.SetLabels(nil)
u.SetAnnotations(nil)
u.SetOwnerReferences(nil)
u.SetInitializers(nil)
u.SetFinalizers(nil)
u.SetClusterName("")
gotMetadata, _, err := unstructured.NestedFieldNoCopy(u.UnstructuredContent(), "metadata")
if err != nil {
t.Error(err)
}
emptyMetadata := make(map[string]interface{})
if !reflect.DeepEqual(gotMetadata, emptyMetadata) {
t.Errorf("expected %v, got %v", emptyMetadata, gotMetadata)
}
}
func setObjectMeta(u *unstructured.Unstructured, objectMeta *metav1.ObjectMeta) error {
if objectMeta == nil {
unstructured.RemoveNestedField(u.UnstructuredContent(), "metadata")
return nil
}
metadata, err := runtime.DefaultUnstructuredConverter.ToUnstructured(objectMeta)
if err != nil {
return err
}
u.UnstructuredContent()["metadata"] = metadata
return nil
}
func setObjectMetaUsingAccessors(u, uCopy *unstructured.Unstructured) {
uCopy.SetName(u.GetName())
uCopy.SetGenerateName(u.GetGenerateName())
uCopy.SetNamespace(u.GetNamespace())
uCopy.SetSelfLink(u.GetSelfLink())
uCopy.SetUID(u.GetUID())
uCopy.SetResourceVersion(u.GetResourceVersion())
uCopy.SetGeneration(u.GetGeneration())
uCopy.SetCreationTimestamp(u.GetCreationTimestamp())
uCopy.SetDeletionTimestamp(u.GetDeletionTimestamp())
uCopy.SetDeletionGracePeriodSeconds(u.GetDeletionGracePeriodSeconds())
uCopy.SetLabels(u.GetLabels())
uCopy.SetAnnotations(u.GetAnnotations())
uCopy.SetOwnerReferences(u.GetOwnerReferences())
uCopy.SetInitializers(u.GetInitializers())
uCopy.SetFinalizers(u.GetFinalizers())
uCopy.SetClusterName(u.GetClusterName())
}

View File

@@ -1,129 +0,0 @@
/*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package unstructuredscheme
import (
"fmt"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/apimachinery/pkg/runtime/serializer/json"
"k8s.io/apimachinery/pkg/runtime/serializer/versioning"
)
var (
scheme = runtime.NewScheme()
codecs = serializer.NewCodecFactory(scheme)
)
// NewUnstructuredNegotiatedSerializer returns a simple, negotiated serializer
func NewUnstructuredNegotiatedSerializer() runtime.NegotiatedSerializer {
return unstructuredNegotiatedSerializer{
scheme: scheme,
typer: NewUnstructuredObjectTyper(),
creator: NewUnstructuredCreator(),
}
}
type unstructuredNegotiatedSerializer struct {
scheme *runtime.Scheme
typer runtime.ObjectTyper
creator runtime.ObjectCreater
}
func (s unstructuredNegotiatedSerializer) SupportedMediaTypes() []runtime.SerializerInfo {
return []runtime.SerializerInfo{
{
MediaType: "application/json",
EncodesAsText: true,
Serializer: json.NewSerializer(json.DefaultMetaFactory, s.creator, s.typer, false),
PrettySerializer: json.NewSerializer(json.DefaultMetaFactory, s.creator, s.typer, true),
StreamSerializer: &runtime.StreamSerializerInfo{
EncodesAsText: true,
Serializer: json.NewSerializer(json.DefaultMetaFactory, s.creator, s.typer, false),
Framer: json.Framer,
},
},
{
MediaType: "application/yaml",
EncodesAsText: true,
Serializer: json.NewYAMLSerializer(json.DefaultMetaFactory, s.creator, s.typer),
},
}
}
func (s unstructuredNegotiatedSerializer) EncoderForVersion(encoder runtime.Encoder, gv runtime.GroupVersioner) runtime.Encoder {
return versioning.NewDefaultingCodecForScheme(s.scheme, encoder, nil, gv, nil)
}
func (s unstructuredNegotiatedSerializer) DecoderToVersion(decoder runtime.Decoder, gv runtime.GroupVersioner) runtime.Decoder {
return versioning.NewDefaultingCodecForScheme(s.scheme, nil, decoder, nil, gv)
}
type unstructuredObjectTyper struct {
}
// NewUnstructuredObjectTyper returns an object typer that can deal with unstructured things
func NewUnstructuredObjectTyper() runtime.ObjectTyper {
return unstructuredObjectTyper{}
}
func (t unstructuredObjectTyper) ObjectKinds(obj runtime.Object) ([]schema.GroupVersionKind, bool, error) {
// Delegate for things other than Unstructured.
if _, ok := obj.(runtime.Unstructured); !ok {
return nil, false, fmt.Errorf("cannot type %T", obj)
}
gvk := obj.GetObjectKind().GroupVersionKind()
if len(gvk.Kind) == 0 {
return nil, false, runtime.NewMissingKindErr("object has no kind field ")
}
if len(gvk.Version) == 0 {
return nil, false, runtime.NewMissingVersionErr("object has no apiVersion field")
}
return []schema.GroupVersionKind{obj.GetObjectKind().GroupVersionKind()}, false, nil
}
func (t unstructuredObjectTyper) Recognizes(gvk schema.GroupVersionKind) bool {
return true
}
type unstructuredCreator struct{}
// NewUnstructuredCreator returns a simple object creator that always returns an unstructured
func NewUnstructuredCreator() runtime.ObjectCreater {
return unstructuredCreator{}
}
func (c unstructuredCreator) New(kind schema.GroupVersionKind) (runtime.Object, error) {
ret := &unstructured.Unstructured{}
ret.SetGroupVersionKind(kind)
return ret, nil
}
type unstructuredDefaulter struct {
}
// NewUnstructuredDefaulter returns defaulter suitable for unstructured types that doesn't default anything
func NewUnstructuredDefaulter() runtime.ObjectDefaulter {
return unstructuredDefaulter{}
}
func (d unstructuredDefaulter) Default(in runtime.Object) {
}