mirror of
https://github.com/ceph/ceph-csi.git
synced 2025-06-13 10:33:35 +00:00
6
vendor/k8s.io/apimachinery/pkg/OWNERS
generated
vendored
6
vendor/k8s.io/apimachinery/pkg/OWNERS
generated
vendored
@ -1,6 +0,0 @@
|
||||
approvers:
|
||||
- caesarxuchao
|
||||
- deads2k
|
||||
- lavalamp
|
||||
- smarterclayton
|
||||
- liggitt
|
116
vendor/k8s.io/apimachinery/pkg/api/apitesting/codec.go
generated
vendored
116
vendor/k8s.io/apimachinery/pkg/api/apitesting/codec.go
generated
vendored
@ -1,116 +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 apitesting
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"mime"
|
||||
"os"
|
||||
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
"k8s.io/apimachinery/pkg/runtime/schema"
|
||||
runtimeserializer "k8s.io/apimachinery/pkg/runtime/serializer"
|
||||
"k8s.io/apimachinery/pkg/runtime/serializer/recognizer"
|
||||
)
|
||||
|
||||
var (
|
||||
testCodecMediaType string
|
||||
testStorageCodecMediaType string
|
||||
)
|
||||
|
||||
// TestCodec returns the codec for the API version to test against, as set by the
|
||||
// KUBE_TEST_API_TYPE env var.
|
||||
func TestCodec(codecs runtimeserializer.CodecFactory, gvs ...schema.GroupVersion) runtime.Codec {
|
||||
if len(testCodecMediaType) != 0 {
|
||||
serializerInfo, ok := runtime.SerializerInfoForMediaType(codecs.SupportedMediaTypes(), testCodecMediaType)
|
||||
if !ok {
|
||||
panic(fmt.Sprintf("no serializer for %s", testCodecMediaType))
|
||||
}
|
||||
return codecs.CodecForVersions(serializerInfo.Serializer, codecs.UniversalDeserializer(), schema.GroupVersions(gvs), nil)
|
||||
}
|
||||
return codecs.LegacyCodec(gvs...)
|
||||
}
|
||||
|
||||
// TestStorageCodec returns the codec for the API version to test against used in storage, as set by the
|
||||
// KUBE_TEST_API_STORAGE_TYPE env var.
|
||||
func TestStorageCodec(codecs runtimeserializer.CodecFactory, gvs ...schema.GroupVersion) runtime.Codec {
|
||||
if len(testStorageCodecMediaType) != 0 {
|
||||
serializerInfo, ok := runtime.SerializerInfoForMediaType(codecs.SupportedMediaTypes(), testStorageCodecMediaType)
|
||||
if !ok {
|
||||
panic(fmt.Sprintf("no serializer for %s", testStorageCodecMediaType))
|
||||
}
|
||||
|
||||
// etcd2 only supports string data - we must wrap any result before returning
|
||||
// TODO: remove for etcd3 / make parameterizable
|
||||
serializer := serializerInfo.Serializer
|
||||
if !serializerInfo.EncodesAsText {
|
||||
serializer = runtime.NewBase64Serializer(serializer, serializer)
|
||||
}
|
||||
|
||||
decoder := recognizer.NewDecoder(serializer, codecs.UniversalDeserializer())
|
||||
return codecs.CodecForVersions(serializer, decoder, schema.GroupVersions(gvs), nil)
|
||||
|
||||
}
|
||||
return codecs.LegacyCodec(gvs...)
|
||||
}
|
||||
|
||||
func init() {
|
||||
var err error
|
||||
if apiMediaType := os.Getenv("KUBE_TEST_API_TYPE"); len(apiMediaType) > 0 {
|
||||
testCodecMediaType, _, err = mime.ParseMediaType(apiMediaType)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
if storageMediaType := os.Getenv("KUBE_TEST_API_STORAGE_TYPE"); len(storageMediaType) > 0 {
|
||||
testStorageCodecMediaType, _, err = mime.ParseMediaType(storageMediaType)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// InstallOrDieFunc mirrors install functions that require success
|
||||
type InstallOrDieFunc func(scheme *runtime.Scheme)
|
||||
|
||||
// SchemeForInstallOrDie builds a simple test scheme and codecfactory pair for easy unit testing from higher level install methods
|
||||
func SchemeForInstallOrDie(installFns ...InstallOrDieFunc) (*runtime.Scheme, runtimeserializer.CodecFactory) {
|
||||
scheme := runtime.NewScheme()
|
||||
codecFactory := runtimeserializer.NewCodecFactory(scheme)
|
||||
for _, installFn := range installFns {
|
||||
installFn(scheme)
|
||||
}
|
||||
|
||||
return scheme, codecFactory
|
||||
}
|
||||
|
||||
// InstallFunc mirrors install functions that can return an error
|
||||
type InstallFunc func(scheme *runtime.Scheme) error
|
||||
|
||||
// SchemeForOrDie builds a simple test scheme and codecfactory pair for easy unit testing from the bare registration methods.
|
||||
func SchemeForOrDie(installFns ...InstallFunc) (*runtime.Scheme, runtimeserializer.CodecFactory) {
|
||||
scheme := runtime.NewScheme()
|
||||
codecFactory := runtimeserializer.NewCodecFactory(scheme)
|
||||
for _, installFn := range installFns {
|
||||
if err := installFn(scheme); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
return scheme, codecFactory
|
||||
}
|
52
vendor/k8s.io/apimachinery/pkg/api/apitesting/fuzzer/fuzzer.go
generated
vendored
52
vendor/k8s.io/apimachinery/pkg/api/apitesting/fuzzer/fuzzer.go
generated
vendored
@ -1,52 +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 fuzzer
|
||||
|
||||
import (
|
||||
"math/rand"
|
||||
|
||||
"github.com/google/gofuzz"
|
||||
|
||||
runtimeserializer "k8s.io/apimachinery/pkg/runtime/serializer"
|
||||
)
|
||||
|
||||
// FuzzerFuncs returns a list of func(*SomeType, c fuzz.Continue) functions.
|
||||
type FuzzerFuncs func(codecs runtimeserializer.CodecFactory) []interface{}
|
||||
|
||||
// FuzzerFor can randomly populate api objects that are destined for version.
|
||||
func FuzzerFor(funcs FuzzerFuncs, src rand.Source, codecs runtimeserializer.CodecFactory) *fuzz.Fuzzer {
|
||||
f := fuzz.New().NilChance(.5).NumElements(0, 1)
|
||||
if src != nil {
|
||||
f.RandSource(src)
|
||||
}
|
||||
f.Funcs(funcs(codecs)...)
|
||||
return f
|
||||
}
|
||||
|
||||
// MergeFuzzerFuncs will merge the given funcLists, overriding early funcs with later ones if there first
|
||||
// argument has the same type.
|
||||
func MergeFuzzerFuncs(funcs ...FuzzerFuncs) FuzzerFuncs {
|
||||
return FuzzerFuncs(func(codecs runtimeserializer.CodecFactory) []interface{} {
|
||||
result := []interface{}{}
|
||||
for _, f := range funcs {
|
||||
if f != nil {
|
||||
result = append(result, f(codecs)...)
|
||||
}
|
||||
}
|
||||
return result
|
||||
})
|
||||
}
|
86
vendor/k8s.io/apimachinery/pkg/api/apitesting/fuzzer/valuefuzz.go
generated
vendored
86
vendor/k8s.io/apimachinery/pkg/api/apitesting/fuzzer/valuefuzz.go
generated
vendored
@ -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 fuzzer
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
)
|
||||
|
||||
// ValueFuzz recursively changes all basic type values in an object. Any kind of references will not
|
||||
// be touch, i.e. the addresses of slices, maps, pointers will stay unchanged.
|
||||
func ValueFuzz(obj interface{}) {
|
||||
valueFuzz(reflect.ValueOf(obj))
|
||||
}
|
||||
|
||||
func valueFuzz(obj reflect.Value) {
|
||||
switch obj.Kind() {
|
||||
case reflect.Array:
|
||||
for i := 0; i < obj.Len(); i++ {
|
||||
valueFuzz(obj.Index(i))
|
||||
}
|
||||
case reflect.Slice:
|
||||
if obj.IsNil() {
|
||||
// TODO: set non-nil value
|
||||
} else {
|
||||
for i := 0; i < obj.Len(); i++ {
|
||||
valueFuzz(obj.Index(i))
|
||||
}
|
||||
}
|
||||
case reflect.Interface, reflect.Ptr:
|
||||
if obj.IsNil() {
|
||||
// TODO: set non-nil value
|
||||
} else {
|
||||
valueFuzz(obj.Elem())
|
||||
}
|
||||
case reflect.Struct:
|
||||
for i, n := 0, obj.NumField(); i < n; i++ {
|
||||
valueFuzz(obj.Field(i))
|
||||
}
|
||||
case reflect.Map:
|
||||
if obj.IsNil() {
|
||||
// TODO: set non-nil value
|
||||
} else {
|
||||
for _, k := range obj.MapKeys() {
|
||||
// map values are not addressable. We need a copy.
|
||||
v := obj.MapIndex(k)
|
||||
copy := reflect.New(v.Type())
|
||||
copy.Elem().Set(v)
|
||||
valueFuzz(copy.Elem())
|
||||
obj.SetMapIndex(k, copy.Elem())
|
||||
}
|
||||
// TODO: set some new value
|
||||
}
|
||||
case reflect.Func: // ignore, we don't have function types in our API
|
||||
default:
|
||||
if !obj.CanSet() {
|
||||
return
|
||||
}
|
||||
switch obj.Kind() {
|
||||
case reflect.String:
|
||||
obj.SetString(obj.String() + "x")
|
||||
case reflect.Bool:
|
||||
obj.SetBool(!obj.Bool())
|
||||
case reflect.Float32, reflect.Float64:
|
||||
obj.SetFloat(obj.Float()*2.0 + 1.0)
|
||||
case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
|
||||
obj.SetInt(obj.Int() + 1)
|
||||
case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:
|
||||
obj.SetUint(obj.Uint() + 1)
|
||||
default:
|
||||
}
|
||||
}
|
||||
}
|
73
vendor/k8s.io/apimachinery/pkg/api/apitesting/fuzzer/valuefuzz_test.go
generated
vendored
73
vendor/k8s.io/apimachinery/pkg/api/apitesting/fuzzer/valuefuzz_test.go
generated
vendored
@ -1,73 +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 fuzzer
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestValueFuzz(t *testing.T) {
|
||||
type (
|
||||
Y struct {
|
||||
I int
|
||||
B bool
|
||||
F float32
|
||||
U uint
|
||||
}
|
||||
X struct {
|
||||
Ptr *X
|
||||
Y Y
|
||||
Map map[string]int
|
||||
Slice []int
|
||||
}
|
||||
)
|
||||
|
||||
x := X{
|
||||
Ptr: &X{},
|
||||
Map: map[string]int{"foo": 42},
|
||||
Slice: []int{1, 2, 3},
|
||||
}
|
||||
|
||||
p := x.Ptr
|
||||
m := x.Map
|
||||
s := x.Slice
|
||||
|
||||
ValueFuzz(x)
|
||||
|
||||
if x.Ptr.Y.I == 0 {
|
||||
t.Errorf("x.Ptr.Y.I should have changed")
|
||||
}
|
||||
|
||||
if x.Map["foo"] == 42 {
|
||||
t.Errorf("x.Map[foo] should have changed")
|
||||
}
|
||||
|
||||
if x.Slice[0] == 1 {
|
||||
t.Errorf("x.Slice[0] should have changed")
|
||||
}
|
||||
|
||||
if x.Ptr != p {
|
||||
t.Errorf("x.Ptr changed")
|
||||
}
|
||||
|
||||
m["foo"] = 7
|
||||
if x.Map["foo"] != m["foo"] {
|
||||
t.Errorf("x.Map changed")
|
||||
}
|
||||
s[0] = 7
|
||||
if x.Slice[0] != s[0] {
|
||||
t.Errorf("x.Slice changed")
|
||||
}
|
||||
}
|
415
vendor/k8s.io/apimachinery/pkg/api/apitesting/roundtrip/roundtrip.go
generated
vendored
415
vendor/k8s.io/apimachinery/pkg/api/apitesting/roundtrip/roundtrip.go
generated
vendored
@ -1,415 +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 roundtrip
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/hex"
|
||||
"math/rand"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/davecgh/go-spew/spew"
|
||||
"github.com/golang/protobuf/proto"
|
||||
"github.com/google/gofuzz"
|
||||
flag "github.com/spf13/pflag"
|
||||
|
||||
apitesting "k8s.io/apimachinery/pkg/api/apitesting"
|
||||
"k8s.io/apimachinery/pkg/api/apitesting/fuzzer"
|
||||
apiequality "k8s.io/apimachinery/pkg/api/equality"
|
||||
apimeta "k8s.io/apimachinery/pkg/api/meta"
|
||||
metafuzzer "k8s.io/apimachinery/pkg/apis/meta/fuzzer"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
"k8s.io/apimachinery/pkg/runtime/schema"
|
||||
runtimeserializer "k8s.io/apimachinery/pkg/runtime/serializer"
|
||||
"k8s.io/apimachinery/pkg/runtime/serializer/json"
|
||||
"k8s.io/apimachinery/pkg/runtime/serializer/protobuf"
|
||||
"k8s.io/apimachinery/pkg/util/diff"
|
||||
"k8s.io/apimachinery/pkg/util/sets"
|
||||
)
|
||||
|
||||
type InstallFunc func(scheme *runtime.Scheme)
|
||||
|
||||
// RoundTripTestForAPIGroup is convenient to call from your install package to make sure that a "bare" install of your group provides
|
||||
// enough information to round trip
|
||||
func RoundTripTestForAPIGroup(t *testing.T, installFn InstallFunc, fuzzingFuncs fuzzer.FuzzerFuncs) {
|
||||
scheme := runtime.NewScheme()
|
||||
installFn(scheme)
|
||||
|
||||
RoundTripTestForScheme(t, scheme, fuzzingFuncs)
|
||||
}
|
||||
|
||||
// RoundTripTestForScheme is convenient to call if you already have a scheme and want to make sure that its well-formed
|
||||
func RoundTripTestForScheme(t *testing.T, scheme *runtime.Scheme, fuzzingFuncs fuzzer.FuzzerFuncs) {
|
||||
codecFactory := runtimeserializer.NewCodecFactory(scheme)
|
||||
f := fuzzer.FuzzerFor(
|
||||
fuzzer.MergeFuzzerFuncs(metafuzzer.Funcs, fuzzingFuncs),
|
||||
rand.NewSource(rand.Int63()),
|
||||
codecFactory,
|
||||
)
|
||||
RoundTripTypesWithoutProtobuf(t, scheme, codecFactory, f, nil)
|
||||
}
|
||||
|
||||
// RoundTripProtobufTestForAPIGroup is convenient to call from your install package to make sure that a "bare" install of your group provides
|
||||
// enough information to round trip
|
||||
func RoundTripProtobufTestForAPIGroup(t *testing.T, installFn InstallFunc, fuzzingFuncs fuzzer.FuzzerFuncs) {
|
||||
scheme := runtime.NewScheme()
|
||||
installFn(scheme)
|
||||
|
||||
RoundTripProtobufTestForScheme(t, scheme, fuzzingFuncs)
|
||||
}
|
||||
|
||||
// RoundTripProtobufTestForScheme is convenient to call if you already have a scheme and want to make sure that its well-formed
|
||||
func RoundTripProtobufTestForScheme(t *testing.T, scheme *runtime.Scheme, fuzzingFuncs fuzzer.FuzzerFuncs) {
|
||||
codecFactory := runtimeserializer.NewCodecFactory(scheme)
|
||||
fuzzer := fuzzer.FuzzerFor(
|
||||
fuzzer.MergeFuzzerFuncs(metafuzzer.Funcs, fuzzingFuncs),
|
||||
rand.NewSource(rand.Int63()),
|
||||
codecFactory,
|
||||
)
|
||||
RoundTripTypes(t, scheme, codecFactory, fuzzer, nil)
|
||||
}
|
||||
|
||||
var FuzzIters = flag.Int("fuzz-iters", 20, "How many fuzzing iterations to do.")
|
||||
|
||||
// globalNonRoundTrippableTypes are kinds that are effectively reserved across all GroupVersions
|
||||
// They don't roundtrip
|
||||
var globalNonRoundTrippableTypes = sets.NewString(
|
||||
"ExportOptions",
|
||||
"GetOptions",
|
||||
// WatchEvent does not include kind and version and can only be deserialized
|
||||
// implicitly (if the caller expects the specific object). The watch call defines
|
||||
// the schema by content type, rather than via kind/version included in each
|
||||
// object.
|
||||
"WatchEvent",
|
||||
// ListOptions is now part of the meta group
|
||||
"ListOptions",
|
||||
// Delete options is only read in metav1
|
||||
"DeleteOptions",
|
||||
)
|
||||
|
||||
// RoundTripTypesWithoutProtobuf applies the round-trip test to all round-trippable Kinds
|
||||
// in the scheme. It will skip all the GroupVersionKinds in the skip list.
|
||||
func RoundTripTypesWithoutProtobuf(t *testing.T, scheme *runtime.Scheme, codecFactory runtimeserializer.CodecFactory, fuzzer *fuzz.Fuzzer, nonRoundTrippableTypes map[schema.GroupVersionKind]bool) {
|
||||
roundTripTypes(t, scheme, codecFactory, fuzzer, nonRoundTrippableTypes, true)
|
||||
}
|
||||
|
||||
func RoundTripTypes(t *testing.T, scheme *runtime.Scheme, codecFactory runtimeserializer.CodecFactory, fuzzer *fuzz.Fuzzer, nonRoundTrippableTypes map[schema.GroupVersionKind]bool) {
|
||||
roundTripTypes(t, scheme, codecFactory, fuzzer, nonRoundTrippableTypes, false)
|
||||
}
|
||||
|
||||
func roundTripTypes(t *testing.T, scheme *runtime.Scheme, codecFactory runtimeserializer.CodecFactory, fuzzer *fuzz.Fuzzer, nonRoundTrippableTypes map[schema.GroupVersionKind]bool, skipProtobuf bool) {
|
||||
for _, group := range groupsFromScheme(scheme) {
|
||||
t.Logf("starting group %q", group)
|
||||
internalVersion := schema.GroupVersion{Group: group, Version: runtime.APIVersionInternal}
|
||||
internalKindToGoType := scheme.KnownTypes(internalVersion)
|
||||
|
||||
for kind := range internalKindToGoType {
|
||||
if globalNonRoundTrippableTypes.Has(kind) {
|
||||
continue
|
||||
}
|
||||
|
||||
internalGVK := internalVersion.WithKind(kind)
|
||||
roundTripSpecificKind(t, internalGVK, scheme, codecFactory, fuzzer, nonRoundTrippableTypes, skipProtobuf)
|
||||
}
|
||||
|
||||
t.Logf("finished group %q", group)
|
||||
}
|
||||
}
|
||||
|
||||
// RoundTripExternalTypes applies the round-trip test to all external round-trippable Kinds
|
||||
// in the scheme. It will skip all the GroupVersionKinds in the nonRoundTripExternalTypes list .
|
||||
func RoundTripExternalTypes(t *testing.T, scheme *runtime.Scheme, codecFactory runtimeserializer.CodecFactory, fuzzer *fuzz.Fuzzer, nonRoundTrippableTypes map[schema.GroupVersionKind]bool) {
|
||||
kinds := scheme.AllKnownTypes()
|
||||
for gvk := range kinds {
|
||||
if gvk.Version == runtime.APIVersionInternal || globalNonRoundTrippableTypes.Has(gvk.Kind) {
|
||||
continue
|
||||
}
|
||||
|
||||
// FIXME: this is explicitly testing w/o protobuf which was failing if enabled
|
||||
// the reason for that is that protobuf is not setting Kind and APIVersion fields
|
||||
// during obj2 decode, the same then applies to DecodeInto obj3. My guess is we
|
||||
// should be setting these two fields accordingly when protobuf is passed as codec
|
||||
// to roundTrip method.
|
||||
roundTripSpecificKind(t, gvk, scheme, codecFactory, fuzzer, nonRoundTrippableTypes, true)
|
||||
}
|
||||
}
|
||||
|
||||
func RoundTripSpecificKindWithoutProtobuf(t *testing.T, gvk schema.GroupVersionKind, scheme *runtime.Scheme, codecFactory runtimeserializer.CodecFactory, fuzzer *fuzz.Fuzzer, nonRoundTrippableTypes map[schema.GroupVersionKind]bool) {
|
||||
roundTripSpecificKind(t, gvk, scheme, codecFactory, fuzzer, nonRoundTrippableTypes, true)
|
||||
}
|
||||
|
||||
func RoundTripSpecificKind(t *testing.T, gvk schema.GroupVersionKind, scheme *runtime.Scheme, codecFactory runtimeserializer.CodecFactory, fuzzer *fuzz.Fuzzer, nonRoundTrippableTypes map[schema.GroupVersionKind]bool) {
|
||||
roundTripSpecificKind(t, gvk, scheme, codecFactory, fuzzer, nonRoundTrippableTypes, false)
|
||||
}
|
||||
|
||||
func roundTripSpecificKind(t *testing.T, gvk schema.GroupVersionKind, scheme *runtime.Scheme, codecFactory runtimeserializer.CodecFactory, fuzzer *fuzz.Fuzzer, nonRoundTrippableTypes map[schema.GroupVersionKind]bool, skipProtobuf bool) {
|
||||
if nonRoundTrippableTypes[gvk] {
|
||||
t.Logf("skipping %v", gvk)
|
||||
return
|
||||
}
|
||||
t.Logf("round tripping %v", gvk)
|
||||
|
||||
// Try a few times, since runTest uses random values.
|
||||
for i := 0; i < *FuzzIters; i++ {
|
||||
if gvk.Version == runtime.APIVersionInternal {
|
||||
roundTripToAllExternalVersions(t, scheme, codecFactory, fuzzer, gvk, nonRoundTrippableTypes, skipProtobuf)
|
||||
} else {
|
||||
roundTripOfExternalType(t, scheme, codecFactory, fuzzer, gvk, skipProtobuf)
|
||||
}
|
||||
if t.Failed() {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// fuzzInternalObject fuzzes an arbitrary runtime object using the appropriate
|
||||
// fuzzer registered with the apitesting package.
|
||||
func fuzzInternalObject(t *testing.T, fuzzer *fuzz.Fuzzer, object runtime.Object) runtime.Object {
|
||||
fuzzer.Fuzz(object)
|
||||
|
||||
j, err := apimeta.TypeAccessor(object)
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error %v for %#v", err, object)
|
||||
}
|
||||
j.SetKind("")
|
||||
j.SetAPIVersion("")
|
||||
|
||||
return object
|
||||
}
|
||||
|
||||
func groupsFromScheme(scheme *runtime.Scheme) []string {
|
||||
ret := sets.String{}
|
||||
for gvk := range scheme.AllKnownTypes() {
|
||||
ret.Insert(gvk.Group)
|
||||
}
|
||||
return ret.List()
|
||||
}
|
||||
|
||||
func roundTripToAllExternalVersions(t *testing.T, scheme *runtime.Scheme, codecFactory runtimeserializer.CodecFactory, fuzzer *fuzz.Fuzzer, internalGVK schema.GroupVersionKind, nonRoundTrippableTypes map[schema.GroupVersionKind]bool, skipProtobuf bool) {
|
||||
object, err := scheme.New(internalGVK)
|
||||
if err != nil {
|
||||
t.Fatalf("Couldn't make a %v? %v", internalGVK, err)
|
||||
}
|
||||
if _, err := apimeta.TypeAccessor(object); err != nil {
|
||||
t.Fatalf("%q is not a TypeMeta and cannot be tested - add it to nonRoundTrippableInternalTypes: %v", internalGVK, err)
|
||||
}
|
||||
|
||||
fuzzInternalObject(t, fuzzer, object)
|
||||
|
||||
// find all potential serializations in the scheme.
|
||||
// TODO fix this up to handle kinds that cross registered with different names.
|
||||
for externalGVK, externalGoType := range scheme.AllKnownTypes() {
|
||||
if externalGVK.Version == runtime.APIVersionInternal {
|
||||
continue
|
||||
}
|
||||
if externalGVK.GroupKind() != internalGVK.GroupKind() {
|
||||
continue
|
||||
}
|
||||
if nonRoundTrippableTypes[externalGVK] {
|
||||
t.Logf("\tskipping %v %v", externalGVK, externalGoType)
|
||||
continue
|
||||
}
|
||||
t.Logf("\tround tripping to %v %v", externalGVK, externalGoType)
|
||||
|
||||
roundTrip(t, scheme, apitesting.TestCodec(codecFactory, externalGVK.GroupVersion()), object)
|
||||
|
||||
// TODO remove this hack after we're past the intermediate steps
|
||||
if !skipProtobuf && externalGVK.Group != "kubeadm.k8s.io" {
|
||||
s := protobuf.NewSerializer(scheme, scheme, "application/arbitrary.content.type")
|
||||
protobufCodec := codecFactory.CodecForVersions(s, s, externalGVK.GroupVersion(), nil)
|
||||
roundTrip(t, scheme, protobufCodec, object)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func roundTripOfExternalType(t *testing.T, scheme *runtime.Scheme, codecFactory runtimeserializer.CodecFactory, fuzzer *fuzz.Fuzzer, externalGVK schema.GroupVersionKind, skipProtobuf bool) {
|
||||
object, err := scheme.New(externalGVK)
|
||||
if err != nil {
|
||||
t.Fatalf("Couldn't make a %v? %v", externalGVK, err)
|
||||
}
|
||||
typeAcc, err := apimeta.TypeAccessor(object)
|
||||
if err != nil {
|
||||
t.Fatalf("%q is not a TypeMeta and cannot be tested - add it to nonRoundTrippableInternalTypes: %v", externalGVK, err)
|
||||
}
|
||||
|
||||
fuzzInternalObject(t, fuzzer, object)
|
||||
|
||||
externalGoType := reflect.TypeOf(object).PkgPath()
|
||||
t.Logf("\tround tripping external type %v %v", externalGVK, externalGoType)
|
||||
|
||||
typeAcc.SetKind(externalGVK.Kind)
|
||||
typeAcc.SetAPIVersion(externalGVK.GroupVersion().String())
|
||||
|
||||
roundTrip(t, scheme, json.NewSerializer(json.DefaultMetaFactory, scheme, scheme, false), object)
|
||||
|
||||
// TODO remove this hack after we're past the intermediate steps
|
||||
if !skipProtobuf {
|
||||
roundTrip(t, scheme, protobuf.NewSerializer(scheme, scheme, "application/protobuf"), object)
|
||||
}
|
||||
}
|
||||
|
||||
// roundTrip applies a single round-trip test to the given runtime object
|
||||
// using the given codec. The round-trip test ensures that an object can be
|
||||
// deep-copied, converted, marshaled and back without loss of data.
|
||||
//
|
||||
// For internal types this means
|
||||
//
|
||||
// internal -> external -> json/protobuf -> external -> internal.
|
||||
//
|
||||
// For external types this means
|
||||
//
|
||||
// external -> json/protobuf -> external.
|
||||
func roundTrip(t *testing.T, scheme *runtime.Scheme, codec runtime.Codec, object runtime.Object) {
|
||||
printer := spew.ConfigState{DisableMethods: true}
|
||||
original := object
|
||||
|
||||
// deep copy the original object
|
||||
object = object.DeepCopyObject()
|
||||
name := reflect.TypeOf(object).Elem().Name()
|
||||
if !apiequality.Semantic.DeepEqual(original, object) {
|
||||
t.Errorf("%v: DeepCopy altered the object, diff: %v", name, diff.ObjectReflectDiff(original, object))
|
||||
t.Errorf("%s", spew.Sdump(original))
|
||||
t.Errorf("%s", spew.Sdump(object))
|
||||
return
|
||||
}
|
||||
|
||||
// encode (serialize) the deep copy using the provided codec
|
||||
data, err := runtime.Encode(codec, object)
|
||||
if err != nil {
|
||||
if runtime.IsNotRegisteredError(err) {
|
||||
t.Logf("%v: not registered: %v (%s)", name, err, printer.Sprintf("%#v", object))
|
||||
} else {
|
||||
t.Errorf("%v: %v (%s)", name, err, printer.Sprintf("%#v", object))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// ensure that the deep copy is equal to the original; neither the deep
|
||||
// copy or conversion should alter the object
|
||||
// TODO eliminate this global
|
||||
if !apiequality.Semantic.DeepEqual(original, object) {
|
||||
t.Errorf("%v: encode altered the object, diff: %v", name, diff.ObjectReflectDiff(original, object))
|
||||
return
|
||||
}
|
||||
|
||||
// encode (serialize) a second time to verify that it was not varying
|
||||
secondData, err := runtime.Encode(codec, object)
|
||||
if err != nil {
|
||||
if runtime.IsNotRegisteredError(err) {
|
||||
t.Logf("%v: not registered: %v (%s)", name, err, printer.Sprintf("%#v", object))
|
||||
} else {
|
||||
t.Errorf("%v: %v (%s)", name, err, printer.Sprintf("%#v", object))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// serialization to the wire must be stable to ensure that we don't write twice to the DB
|
||||
// when the object hasn't changed.
|
||||
if !bytes.Equal(data, secondData) {
|
||||
t.Errorf("%v: serialization is not stable: %s", name, printer.Sprintf("%#v", object))
|
||||
}
|
||||
|
||||
// decode (deserialize) the encoded data back into an object
|
||||
obj2, err := runtime.Decode(codec, data)
|
||||
if err != nil {
|
||||
t.Errorf("%v: %v\nCodec: %#v\nData: %s\nSource: %#v", name, err, codec, dataAsString(data), printer.Sprintf("%#v", object))
|
||||
panic("failed")
|
||||
}
|
||||
|
||||
// ensure that the object produced from decoding the encoded data is equal
|
||||
// to the original object
|
||||
if !apiequality.Semantic.DeepEqual(original, obj2) {
|
||||
t.Errorf("%v: diff: %v\nCodec: %#v\nSource:\n\n%#v\n\nEncoded:\n\n%s\n\nFinal:\n\n%#v", name, diff.ObjectReflectDiff(original, obj2), codec, printer.Sprintf("%#v", original), dataAsString(data), printer.Sprintf("%#v", obj2))
|
||||
return
|
||||
}
|
||||
|
||||
// decode the encoded data into a new object (instead of letting the codec
|
||||
// create a new object)
|
||||
obj3 := reflect.New(reflect.TypeOf(object).Elem()).Interface().(runtime.Object)
|
||||
if err := runtime.DecodeInto(codec, data, obj3); err != nil {
|
||||
t.Errorf("%v: %v", name, err)
|
||||
return
|
||||
}
|
||||
|
||||
// special case for kinds which are internal and external at the same time (many in meta.k8s.io are). For those
|
||||
// runtime.DecodeInto above will return the external variant and set the APIVersion and kind, while the input
|
||||
// object might be internal. Hence, we clear those values for obj3 for that case to correctly compare.
|
||||
intAndExt, err := internalAndExternalKind(scheme, object)
|
||||
if err != nil {
|
||||
t.Errorf("%v: %v", name, err)
|
||||
return
|
||||
}
|
||||
if intAndExt {
|
||||
typeAcc, err := apimeta.TypeAccessor(object)
|
||||
if err != nil {
|
||||
t.Fatalf("%v: error accessing TypeMeta: %v", name, err)
|
||||
}
|
||||
if len(typeAcc.GetAPIVersion()) == 0 {
|
||||
typeAcc, err := apimeta.TypeAccessor(obj3)
|
||||
if err != nil {
|
||||
t.Fatalf("%v: error accessing TypeMeta: %v", name, err)
|
||||
}
|
||||
typeAcc.SetAPIVersion("")
|
||||
typeAcc.SetKind("")
|
||||
}
|
||||
}
|
||||
|
||||
// ensure that the new runtime object is equal to the original after being
|
||||
// decoded into
|
||||
if !apiequality.Semantic.DeepEqual(object, obj3) {
|
||||
t.Errorf("%v: diff: %v\nCodec: %#v", name, diff.ObjectReflectDiff(object, obj3), codec)
|
||||
return
|
||||
}
|
||||
|
||||
// do structure-preserving fuzzing of the deep-copied object. If it shares anything with the original,
|
||||
// the deep-copy was actually only a shallow copy. Then original and obj3 will be different after fuzzing.
|
||||
// NOTE: we use the encoding+decoding here as an alternative, guaranteed deep-copy to compare against.
|
||||
fuzzer.ValueFuzz(object)
|
||||
if !apiequality.Semantic.DeepEqual(original, obj3) {
|
||||
t.Errorf("%v: fuzzing a copy altered the original, diff: %v", name, diff.ObjectReflectDiff(original, obj3))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func internalAndExternalKind(scheme *runtime.Scheme, object runtime.Object) (bool, error) {
|
||||
kinds, _, err := scheme.ObjectKinds(object)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
internal, external := false, false
|
||||
for _, k := range kinds {
|
||||
if k.Version == runtime.APIVersionInternal {
|
||||
internal = true
|
||||
} else {
|
||||
external = true
|
||||
}
|
||||
}
|
||||
return internal && external, nil
|
||||
}
|
||||
|
||||
// dataAsString returns the given byte array as a string; handles detecting
|
||||
// protocol buffers.
|
||||
func dataAsString(data []byte) string {
|
||||
dataString := string(data)
|
||||
if !strings.HasPrefix(dataString, "{") {
|
||||
dataString = "\n" + hex.Dump(data)
|
||||
proto.NewBuffer(make([]byte, 0, 1024)).DebugPrint("decoded object", data)
|
||||
}
|
||||
return dataString
|
||||
}
|
49
vendor/k8s.io/apimachinery/pkg/api/equality/semantic.go
generated
vendored
49
vendor/k8s.io/apimachinery/pkg/api/equality/semantic.go
generated
vendored
@ -1,49 +0,0 @@
|
||||
/*
|
||||
Copyright 2014 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 equality
|
||||
|
||||
import (
|
||||
"k8s.io/apimachinery/pkg/api/resource"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/conversion"
|
||||
"k8s.io/apimachinery/pkg/fields"
|
||||
"k8s.io/apimachinery/pkg/labels"
|
||||
)
|
||||
|
||||
// Semantic can do semantic deep equality checks for api objects.
|
||||
// Example: apiequality.Semantic.DeepEqual(aPod, aPodWithNonNilButEmptyMaps) == true
|
||||
var Semantic = conversion.EqualitiesOrDie(
|
||||
func(a, b resource.Quantity) bool {
|
||||
// Ignore formatting, only care that numeric value stayed the same.
|
||||
// TODO: if we decide it's important, it should be safe to start comparing the format.
|
||||
//
|
||||
// Uninitialized quantities are equivalent to 0 quantities.
|
||||
return a.Cmp(b) == 0
|
||||
},
|
||||
func(a, b metav1.MicroTime) bool {
|
||||
return a.UTC() == b.UTC()
|
||||
},
|
||||
func(a, b metav1.Time) bool {
|
||||
return a.UTC() == b.UTC()
|
||||
},
|
||||
func(a, b labels.Selector) bool {
|
||||
return a.String() == b.String()
|
||||
},
|
||||
func(a, b fields.Selector) bool {
|
||||
return a.String() == b.String()
|
||||
},
|
||||
)
|
24
vendor/k8s.io/apimachinery/pkg/api/errors/OWNERS
generated
vendored
24
vendor/k8s.io/apimachinery/pkg/api/errors/OWNERS
generated
vendored
@ -1,24 +0,0 @@
|
||||
reviewers:
|
||||
- thockin
|
||||
- lavalamp
|
||||
- smarterclayton
|
||||
- wojtek-t
|
||||
- deads2k
|
||||
- brendandburns
|
||||
- derekwaynecarr
|
||||
- caesarxuchao
|
||||
- mikedanese
|
||||
- liggitt
|
||||
- nikhiljindal
|
||||
- gmarek
|
||||
- erictune
|
||||
- saad-ali
|
||||
- janetkuo
|
||||
- tallclair
|
||||
- eparis
|
||||
- dims
|
||||
- hongchaodeng
|
||||
- krousey
|
||||
- cjcullen
|
||||
- david-mcmahon
|
||||
- goltermann
|
222
vendor/k8s.io/apimachinery/pkg/api/errors/errors_test.go
generated
vendored
222
vendor/k8s.io/apimachinery/pkg/api/errors/errors_test.go
generated
vendored
@ -1,222 +0,0 @@
|
||||
/*
|
||||
Copyright 2014 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 errors
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
"k8s.io/apimachinery/pkg/runtime/schema"
|
||||
"k8s.io/apimachinery/pkg/util/validation/field"
|
||||
)
|
||||
|
||||
func resource(resource string) schema.GroupResource {
|
||||
return schema.GroupResource{Group: "", Resource: resource}
|
||||
}
|
||||
func kind(kind string) schema.GroupKind {
|
||||
return schema.GroupKind{Group: "", Kind: kind}
|
||||
}
|
||||
|
||||
func TestErrorNew(t *testing.T) {
|
||||
err := NewAlreadyExists(resource("tests"), "1")
|
||||
if !IsAlreadyExists(err) {
|
||||
t.Errorf("expected to be %s", metav1.StatusReasonAlreadyExists)
|
||||
}
|
||||
if IsConflict(err) {
|
||||
t.Errorf("expected to not be %s", metav1.StatusReasonConflict)
|
||||
}
|
||||
if IsNotFound(err) {
|
||||
t.Errorf(fmt.Sprintf("expected to not be %s", metav1.StatusReasonNotFound))
|
||||
}
|
||||
if IsInvalid(err) {
|
||||
t.Errorf("expected to not be %s", metav1.StatusReasonInvalid)
|
||||
}
|
||||
if IsBadRequest(err) {
|
||||
t.Errorf("expected to not be %s", metav1.StatusReasonBadRequest)
|
||||
}
|
||||
if IsForbidden(err) {
|
||||
t.Errorf("expected to not be %s", metav1.StatusReasonForbidden)
|
||||
}
|
||||
if IsServerTimeout(err) {
|
||||
t.Errorf("expected to not be %s", metav1.StatusReasonServerTimeout)
|
||||
}
|
||||
if IsMethodNotSupported(err) {
|
||||
t.Errorf("expected to not be %s", metav1.StatusReasonMethodNotAllowed)
|
||||
}
|
||||
|
||||
if !IsConflict(NewConflict(resource("tests"), "2", errors.New("message"))) {
|
||||
t.Errorf("expected to be conflict")
|
||||
}
|
||||
if !IsNotFound(NewNotFound(resource("tests"), "3")) {
|
||||
t.Errorf("expected to be %s", metav1.StatusReasonNotFound)
|
||||
}
|
||||
if !IsInvalid(NewInvalid(kind("Test"), "2", nil)) {
|
||||
t.Errorf("expected to be %s", metav1.StatusReasonInvalid)
|
||||
}
|
||||
if !IsBadRequest(NewBadRequest("reason")) {
|
||||
t.Errorf("expected to be %s", metav1.StatusReasonBadRequest)
|
||||
}
|
||||
if !IsForbidden(NewForbidden(resource("tests"), "2", errors.New("reason"))) {
|
||||
t.Errorf("expected to be %s", metav1.StatusReasonForbidden)
|
||||
}
|
||||
if !IsUnauthorized(NewUnauthorized("reason")) {
|
||||
t.Errorf("expected to be %s", metav1.StatusReasonUnauthorized)
|
||||
}
|
||||
if !IsServerTimeout(NewServerTimeout(resource("tests"), "reason", 0)) {
|
||||
t.Errorf("expected to be %s", metav1.StatusReasonServerTimeout)
|
||||
}
|
||||
if !IsMethodNotSupported(NewMethodNotSupported(resource("foos"), "delete")) {
|
||||
t.Errorf("expected to be %s", metav1.StatusReasonMethodNotAllowed)
|
||||
}
|
||||
|
||||
if time, ok := SuggestsClientDelay(NewServerTimeout(resource("tests"), "doing something", 10)); time != 10 || !ok {
|
||||
t.Errorf("unexpected %d", time)
|
||||
}
|
||||
if time, ok := SuggestsClientDelay(NewServerTimeout(resource("tests"), "doing something", 0)); time != 0 || !ok {
|
||||
t.Errorf("unexpected %d", time)
|
||||
}
|
||||
if time, ok := SuggestsClientDelay(NewTimeoutError("test reason", 10)); time != 10 || !ok {
|
||||
t.Errorf("unexpected %d", time)
|
||||
}
|
||||
if time, ok := SuggestsClientDelay(NewTooManyRequests("doing something", 10)); time != 10 || !ok {
|
||||
t.Errorf("unexpected %d", time)
|
||||
}
|
||||
if time, ok := SuggestsClientDelay(NewTooManyRequests("doing something", 1)); time != 1 || !ok {
|
||||
t.Errorf("unexpected %d", time)
|
||||
}
|
||||
if time, ok := SuggestsClientDelay(NewGenericServerResponse(429, "get", resource("tests"), "test", "doing something", 10, true)); time != 10 || !ok {
|
||||
t.Errorf("unexpected %d", time)
|
||||
}
|
||||
if time, ok := SuggestsClientDelay(NewGenericServerResponse(500, "get", resource("tests"), "test", "doing something", 10, true)); time != 10 || !ok {
|
||||
t.Errorf("unexpected %d", time)
|
||||
}
|
||||
if time, ok := SuggestsClientDelay(NewGenericServerResponse(429, "get", resource("tests"), "test", "doing something", 0, true)); time != 0 || ok {
|
||||
t.Errorf("unexpected %d", time)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewInvalid(t *testing.T) {
|
||||
testCases := []struct {
|
||||
Err *field.Error
|
||||
Details *metav1.StatusDetails
|
||||
}{
|
||||
{
|
||||
field.Duplicate(field.NewPath("field[0].name"), "bar"),
|
||||
&metav1.StatusDetails{
|
||||
Kind: "Kind",
|
||||
Name: "name",
|
||||
Causes: []metav1.StatusCause{{
|
||||
Type: metav1.CauseTypeFieldValueDuplicate,
|
||||
Field: "field[0].name",
|
||||
}},
|
||||
},
|
||||
},
|
||||
{
|
||||
field.Invalid(field.NewPath("field[0].name"), "bar", "detail"),
|
||||
&metav1.StatusDetails{
|
||||
Kind: "Kind",
|
||||
Name: "name",
|
||||
Causes: []metav1.StatusCause{{
|
||||
Type: metav1.CauseTypeFieldValueInvalid,
|
||||
Field: "field[0].name",
|
||||
}},
|
||||
},
|
||||
},
|
||||
{
|
||||
field.NotFound(field.NewPath("field[0].name"), "bar"),
|
||||
&metav1.StatusDetails{
|
||||
Kind: "Kind",
|
||||
Name: "name",
|
||||
Causes: []metav1.StatusCause{{
|
||||
Type: metav1.CauseTypeFieldValueNotFound,
|
||||
Field: "field[0].name",
|
||||
}},
|
||||
},
|
||||
},
|
||||
{
|
||||
field.NotSupported(field.NewPath("field[0].name"), "bar", nil),
|
||||
&metav1.StatusDetails{
|
||||
Kind: "Kind",
|
||||
Name: "name",
|
||||
Causes: []metav1.StatusCause{{
|
||||
Type: metav1.CauseTypeFieldValueNotSupported,
|
||||
Field: "field[0].name",
|
||||
}},
|
||||
},
|
||||
},
|
||||
{
|
||||
field.Required(field.NewPath("field[0].name"), ""),
|
||||
&metav1.StatusDetails{
|
||||
Kind: "Kind",
|
||||
Name: "name",
|
||||
Causes: []metav1.StatusCause{{
|
||||
Type: metav1.CauseTypeFieldValueRequired,
|
||||
Field: "field[0].name",
|
||||
}},
|
||||
},
|
||||
},
|
||||
}
|
||||
for i, testCase := range testCases {
|
||||
vErr, expected := testCase.Err, testCase.Details
|
||||
expected.Causes[0].Message = vErr.ErrorBody()
|
||||
err := NewInvalid(kind("Kind"), "name", field.ErrorList{vErr})
|
||||
status := err.ErrStatus
|
||||
if status.Code != 422 || status.Reason != metav1.StatusReasonInvalid {
|
||||
t.Errorf("%d: unexpected status: %#v", i, status)
|
||||
}
|
||||
if !reflect.DeepEqual(expected, status.Details) {
|
||||
t.Errorf("%d: expected %#v, got %#v", i, expected, status.Details)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestReasonForError(t *testing.T) {
|
||||
if e, a := metav1.StatusReasonUnknown, ReasonForError(nil); e != a {
|
||||
t.Errorf("unexpected reason type: %#v", a)
|
||||
}
|
||||
}
|
||||
|
||||
type TestType struct{}
|
||||
|
||||
func (obj *TestType) GetObjectKind() schema.ObjectKind { return schema.EmptyObjectKind }
|
||||
func (obj *TestType) DeepCopyObject() runtime.Object {
|
||||
if obj == nil {
|
||||
return nil
|
||||
}
|
||||
clone := *obj
|
||||
return &clone
|
||||
}
|
||||
|
||||
func TestFromObject(t *testing.T) {
|
||||
table := []struct {
|
||||
obj runtime.Object
|
||||
message string
|
||||
}{
|
||||
{&metav1.Status{Message: "foobar"}, "foobar"},
|
||||
{&TestType{}, "unexpected object: &{}"},
|
||||
}
|
||||
|
||||
for _, item := range table {
|
||||
if e, a := item.message, FromObject(item.obj).Error(); e != a {
|
||||
t.Errorf("Expected %v, got %v", e, a)
|
||||
}
|
||||
}
|
||||
}
|
25
vendor/k8s.io/apimachinery/pkg/api/meta/OWNERS
generated
vendored
25
vendor/k8s.io/apimachinery/pkg/api/meta/OWNERS
generated
vendored
@ -1,25 +0,0 @@
|
||||
reviewers:
|
||||
- thockin
|
||||
- smarterclayton
|
||||
- wojtek-t
|
||||
- deads2k
|
||||
- brendandburns
|
||||
- derekwaynecarr
|
||||
- caesarxuchao
|
||||
- mikedanese
|
||||
- liggitt
|
||||
- nikhiljindal
|
||||
- gmarek
|
||||
- janetkuo
|
||||
- ncdc
|
||||
- eparis
|
||||
- dims
|
||||
- krousey
|
||||
- markturansky
|
||||
- fabioy
|
||||
- resouer
|
||||
- david-mcmahon
|
||||
- mfojtik
|
||||
- jianhuiz
|
||||
- feihujiang
|
||||
- ghodss
|
51
vendor/k8s.io/apimachinery/pkg/api/meta/meta_test.go
generated
vendored
51
vendor/k8s.io/apimachinery/pkg/api/meta/meta_test.go
generated
vendored
@ -1,51 +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 meta
|
||||
|
||||
import (
|
||||
"math/rand"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
metav1beta1 "k8s.io/apimachinery/pkg/apis/meta/v1beta1"
|
||||
"k8s.io/apimachinery/pkg/util/diff"
|
||||
|
||||
fuzz "github.com/google/gofuzz"
|
||||
)
|
||||
|
||||
func TestAsPartialObjectMetadata(t *testing.T) {
|
||||
f := fuzz.New().NilChance(.5).NumElements(0, 1).RandSource(rand.NewSource(1))
|
||||
|
||||
for i := 0; i < 100; i++ {
|
||||
m := &metav1.ObjectMeta{}
|
||||
f.Fuzz(m)
|
||||
partial := AsPartialObjectMetadata(m)
|
||||
if !reflect.DeepEqual(&partial.ObjectMeta, m) {
|
||||
t.Fatalf("incomplete partial object metadata: %s", diff.ObjectReflectDiff(&partial.ObjectMeta, m))
|
||||
}
|
||||
}
|
||||
|
||||
for i := 0; i < 100; i++ {
|
||||
m := &metav1beta1.PartialObjectMetadata{}
|
||||
f.Fuzz(&m.ObjectMeta)
|
||||
partial := AsPartialObjectMetadata(m)
|
||||
if !reflect.DeepEqual(&partial.ObjectMeta, &m.ObjectMeta) {
|
||||
t.Fatalf("incomplete partial object metadata: %s", diff.ObjectReflectDiff(&partial.ObjectMeta, &m.ObjectMeta))
|
||||
}
|
||||
}
|
||||
}
|
391
vendor/k8s.io/apimachinery/pkg/api/meta/multirestmapper_test.go
generated
vendored
391
vendor/k8s.io/apimachinery/pkg/api/meta/multirestmapper_test.go
generated
vendored
@ -1,391 +0,0 @@
|
||||
/*
|
||||
Copyright 2014 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 meta
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"k8s.io/apimachinery/pkg/runtime/schema"
|
||||
)
|
||||
|
||||
func TestMultiRESTMapperResourceFor(t *testing.T) {
|
||||
tcs := []struct {
|
||||
name string
|
||||
|
||||
mapper MultiRESTMapper
|
||||
input schema.GroupVersionResource
|
||||
result schema.GroupVersionResource
|
||||
err error
|
||||
}{
|
||||
{
|
||||
name: "empty",
|
||||
mapper: MultiRESTMapper{},
|
||||
input: schema.GroupVersionResource{Resource: "foo"},
|
||||
result: schema.GroupVersionResource{},
|
||||
err: &NoResourceMatchError{PartialResource: schema.GroupVersionResource{Resource: "foo"}},
|
||||
},
|
||||
{
|
||||
name: "ignore not found",
|
||||
mapper: MultiRESTMapper{fixedRESTMapper{err: &NoResourceMatchError{PartialResource: schema.GroupVersionResource{Resource: "IGNORE_THIS"}}}},
|
||||
input: schema.GroupVersionResource{Resource: "foo"},
|
||||
result: schema.GroupVersionResource{},
|
||||
err: &NoResourceMatchError{PartialResource: schema.GroupVersionResource{Resource: "foo"}},
|
||||
},
|
||||
{
|
||||
name: "accept first failure",
|
||||
mapper: MultiRESTMapper{fixedRESTMapper{err: errors.New("fail on this")}, fixedRESTMapper{resourcesFor: []schema.GroupVersionResource{{Resource: "unused"}}}},
|
||||
input: schema.GroupVersionResource{Resource: "foo"},
|
||||
result: schema.GroupVersionResource{},
|
||||
err: errors.New("fail on this"),
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tcs {
|
||||
actualResult, actualErr := tc.mapper.ResourceFor(tc.input)
|
||||
if e, a := tc.result, actualResult; e != a {
|
||||
t.Errorf("%s: expected %v, got %v", tc.name, e, a)
|
||||
}
|
||||
switch {
|
||||
case tc.err == nil && actualErr == nil:
|
||||
case tc.err == nil:
|
||||
t.Errorf("%s: unexpected error: %v", tc.name, actualErr)
|
||||
case actualErr == nil:
|
||||
t.Errorf("%s: expected error: %v got nil", tc.name, tc.err)
|
||||
case tc.err.Error() != actualErr.Error():
|
||||
t.Errorf("%s: expected %v, got %v", tc.name, tc.err, actualErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMultiRESTMapperResourcesFor(t *testing.T) {
|
||||
tcs := []struct {
|
||||
name string
|
||||
|
||||
mapper MultiRESTMapper
|
||||
input schema.GroupVersionResource
|
||||
result []schema.GroupVersionResource
|
||||
err error
|
||||
}{
|
||||
{
|
||||
name: "empty",
|
||||
mapper: MultiRESTMapper{},
|
||||
input: schema.GroupVersionResource{Resource: "foo"},
|
||||
result: nil,
|
||||
err: &NoResourceMatchError{PartialResource: schema.GroupVersionResource{Resource: "foo"}},
|
||||
},
|
||||
{
|
||||
name: "ignore not found",
|
||||
mapper: MultiRESTMapper{fixedRESTMapper{err: &NoResourceMatchError{PartialResource: schema.GroupVersionResource{Resource: "IGNORE_THIS"}}}},
|
||||
input: schema.GroupVersionResource{Resource: "foo"},
|
||||
result: nil,
|
||||
err: &NoResourceMatchError{PartialResource: schema.GroupVersionResource{Resource: "foo"}},
|
||||
},
|
||||
{
|
||||
name: "accept first failure",
|
||||
mapper: MultiRESTMapper{fixedRESTMapper{err: errors.New("fail on this")}, fixedRESTMapper{resourcesFor: []schema.GroupVersionResource{{Resource: "unused"}}}},
|
||||
input: schema.GroupVersionResource{Resource: "foo"},
|
||||
result: nil,
|
||||
err: errors.New("fail on this"),
|
||||
},
|
||||
{
|
||||
name: "union and dedup",
|
||||
mapper: MultiRESTMapper{
|
||||
fixedRESTMapper{resourcesFor: []schema.GroupVersionResource{{Resource: "dupe"}, {Resource: "first"}}},
|
||||
fixedRESTMapper{resourcesFor: []schema.GroupVersionResource{{Resource: "dupe"}, {Resource: "second"}}},
|
||||
},
|
||||
input: schema.GroupVersionResource{Resource: "foo"},
|
||||
result: []schema.GroupVersionResource{{Resource: "dupe"}, {Resource: "first"}, {Resource: "second"}},
|
||||
},
|
||||
{
|
||||
name: "skip not and continue",
|
||||
mapper: MultiRESTMapper{
|
||||
fixedRESTMapper{err: &NoResourceMatchError{PartialResource: schema.GroupVersionResource{Resource: "IGNORE_THIS"}}},
|
||||
fixedRESTMapper{resourcesFor: []schema.GroupVersionResource{{Resource: "first"}, {Resource: "second"}}},
|
||||
},
|
||||
input: schema.GroupVersionResource{Resource: "foo"},
|
||||
result: []schema.GroupVersionResource{{Resource: "first"}, {Resource: "second"}},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tcs {
|
||||
actualResult, actualErr := tc.mapper.ResourcesFor(tc.input)
|
||||
if e, a := tc.result, actualResult; !reflect.DeepEqual(e, a) {
|
||||
t.Errorf("%s: expected %v, got %v", tc.name, e, a)
|
||||
}
|
||||
switch {
|
||||
case tc.err == nil && actualErr == nil:
|
||||
case tc.err == nil:
|
||||
t.Errorf("%s: unexpected error: %v", tc.name, actualErr)
|
||||
case actualErr == nil:
|
||||
t.Errorf("%s: expected error: %v got nil", tc.name, tc.err)
|
||||
case tc.err.Error() != actualErr.Error():
|
||||
t.Errorf("%s: expected %v, got %v", tc.name, tc.err, actualErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMultiRESTMapperKindsFor(t *testing.T) {
|
||||
tcs := []struct {
|
||||
name string
|
||||
|
||||
mapper MultiRESTMapper
|
||||
input schema.GroupVersionResource
|
||||
result []schema.GroupVersionKind
|
||||
err error
|
||||
}{
|
||||
{
|
||||
name: "empty",
|
||||
mapper: MultiRESTMapper{},
|
||||
input: schema.GroupVersionResource{Resource: "foo"},
|
||||
result: nil,
|
||||
err: &NoResourceMatchError{PartialResource: schema.GroupVersionResource{Resource: "foo"}},
|
||||
},
|
||||
{
|
||||
name: "ignore not found",
|
||||
mapper: MultiRESTMapper{fixedRESTMapper{err: &NoResourceMatchError{PartialResource: schema.GroupVersionResource{Resource: "IGNORE_THIS"}}}},
|
||||
input: schema.GroupVersionResource{Resource: "foo"},
|
||||
result: nil,
|
||||
err: &NoResourceMatchError{PartialResource: schema.GroupVersionResource{Resource: "foo"}},
|
||||
},
|
||||
{
|
||||
name: "accept first failure",
|
||||
mapper: MultiRESTMapper{fixedRESTMapper{err: errors.New("fail on this")}, fixedRESTMapper{kindsFor: []schema.GroupVersionKind{{Kind: "unused"}}}},
|
||||
input: schema.GroupVersionResource{Resource: "foo"},
|
||||
result: nil,
|
||||
err: errors.New("fail on this"),
|
||||
},
|
||||
{
|
||||
name: "union and dedup",
|
||||
mapper: MultiRESTMapper{
|
||||
fixedRESTMapper{kindsFor: []schema.GroupVersionKind{{Kind: "dupe"}, {Kind: "first"}}},
|
||||
fixedRESTMapper{kindsFor: []schema.GroupVersionKind{{Kind: "dupe"}, {Kind: "second"}}},
|
||||
},
|
||||
input: schema.GroupVersionResource{Resource: "foo"},
|
||||
result: []schema.GroupVersionKind{{Kind: "dupe"}, {Kind: "first"}, {Kind: "second"}},
|
||||
},
|
||||
{
|
||||
name: "skip not and continue",
|
||||
mapper: MultiRESTMapper{
|
||||
fixedRESTMapper{err: &NoResourceMatchError{PartialResource: schema.GroupVersionResource{Resource: "IGNORE_THIS"}}},
|
||||
fixedRESTMapper{kindsFor: []schema.GroupVersionKind{{Kind: "first"}, {Kind: "second"}}},
|
||||
},
|
||||
input: schema.GroupVersionResource{Resource: "foo"},
|
||||
result: []schema.GroupVersionKind{{Kind: "first"}, {Kind: "second"}},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tcs {
|
||||
actualResult, actualErr := tc.mapper.KindsFor(tc.input)
|
||||
if e, a := tc.result, actualResult; !reflect.DeepEqual(e, a) {
|
||||
t.Errorf("%s: expected %v, got %v", tc.name, e, a)
|
||||
}
|
||||
switch {
|
||||
case tc.err == nil && actualErr == nil:
|
||||
case tc.err == nil:
|
||||
t.Errorf("%s: unexpected error: %v", tc.name, actualErr)
|
||||
case actualErr == nil:
|
||||
t.Errorf("%s: expected error: %v got nil", tc.name, tc.err)
|
||||
case tc.err.Error() != actualErr.Error():
|
||||
t.Errorf("%s: expected %v, got %v", tc.name, tc.err, actualErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMultiRESTMapperKindFor(t *testing.T) {
|
||||
tcs := []struct {
|
||||
name string
|
||||
|
||||
mapper MultiRESTMapper
|
||||
input schema.GroupVersionResource
|
||||
result schema.GroupVersionKind
|
||||
err error
|
||||
}{
|
||||
{
|
||||
name: "empty",
|
||||
mapper: MultiRESTMapper{},
|
||||
input: schema.GroupVersionResource{Resource: "foo"},
|
||||
result: schema.GroupVersionKind{},
|
||||
err: &NoResourceMatchError{PartialResource: schema.GroupVersionResource{Resource: "foo"}},
|
||||
},
|
||||
{
|
||||
name: "ignore not found",
|
||||
mapper: MultiRESTMapper{fixedRESTMapper{err: &NoResourceMatchError{PartialResource: schema.GroupVersionResource{Resource: "IGNORE_THIS"}}}},
|
||||
input: schema.GroupVersionResource{Resource: "foo"},
|
||||
result: schema.GroupVersionKind{},
|
||||
err: &NoResourceMatchError{PartialResource: schema.GroupVersionResource{Resource: "foo"}},
|
||||
},
|
||||
{
|
||||
name: "accept first failure",
|
||||
mapper: MultiRESTMapper{fixedRESTMapper{err: errors.New("fail on this")}, fixedRESTMapper{kindsFor: []schema.GroupVersionKind{{Kind: "unused"}}}},
|
||||
input: schema.GroupVersionResource{Resource: "foo"},
|
||||
result: schema.GroupVersionKind{},
|
||||
err: errors.New("fail on this"),
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tcs {
|
||||
actualResult, actualErr := tc.mapper.KindFor(tc.input)
|
||||
if e, a := tc.result, actualResult; e != a {
|
||||
t.Errorf("%s: expected %v, got %v", tc.name, e, a)
|
||||
}
|
||||
switch {
|
||||
case tc.err == nil && actualErr == nil:
|
||||
case tc.err == nil:
|
||||
t.Errorf("%s: unexpected error: %v", tc.name, actualErr)
|
||||
case actualErr == nil:
|
||||
t.Errorf("%s: expected error: %v got nil", tc.name, tc.err)
|
||||
case tc.err.Error() != actualErr.Error():
|
||||
t.Errorf("%s: expected %v, got %v", tc.name, tc.err, actualErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMultiRESTMapperRESTMappings(t *testing.T) {
|
||||
mapping1, mapping2 := &RESTMapping{}, &RESTMapping{}
|
||||
tcs := []struct {
|
||||
name string
|
||||
|
||||
mapper MultiRESTMapper
|
||||
groupKind schema.GroupKind
|
||||
versions []string
|
||||
result []*RESTMapping
|
||||
err error
|
||||
}{
|
||||
{
|
||||
name: "empty with no versions",
|
||||
mapper: MultiRESTMapper{},
|
||||
groupKind: schema.GroupKind{Kind: "Foo"},
|
||||
result: nil,
|
||||
err: &NoKindMatchError{GroupKind: schema.GroupKind{Kind: "Foo"}},
|
||||
},
|
||||
{
|
||||
name: "empty with one version",
|
||||
mapper: MultiRESTMapper{},
|
||||
groupKind: schema.GroupKind{Kind: "Foo"},
|
||||
versions: []string{"v1beta"},
|
||||
result: nil,
|
||||
err: &NoKindMatchError{GroupKind: schema.GroupKind{Kind: "Foo"}, SearchedVersions: []string{"v1beta"}},
|
||||
},
|
||||
{
|
||||
name: "empty with multi(two) vesions",
|
||||
mapper: MultiRESTMapper{},
|
||||
groupKind: schema.GroupKind{Kind: "Foo"},
|
||||
versions: []string{"v1beta", "v2"},
|
||||
result: nil,
|
||||
err: &NoKindMatchError{GroupKind: schema.GroupKind{Kind: "Foo"}, SearchedVersions: []string{"v1beta", "v2"}},
|
||||
},
|
||||
{
|
||||
name: "ignore not found with kind not exist",
|
||||
mapper: MultiRESTMapper{fixedRESTMapper{err: &NoKindMatchError{GroupKind: schema.GroupKind{Kind: "IGNORE_THIS"}}}},
|
||||
groupKind: schema.GroupKind{Kind: "Foo"},
|
||||
versions: nil,
|
||||
result: nil,
|
||||
err: &NoKindMatchError{GroupKind: schema.GroupKind{Kind: "Foo"}},
|
||||
},
|
||||
{
|
||||
name: "ignore not found with version not exist",
|
||||
mapper: MultiRESTMapper{fixedRESTMapper{err: &NoKindMatchError{GroupKind: schema.GroupKind{Kind: "Foo"}, SearchedVersions: []string{"v1"}}}},
|
||||
groupKind: schema.GroupKind{Kind: "Foo"},
|
||||
versions: []string{"v1beta"},
|
||||
result: nil,
|
||||
err: &NoKindMatchError{GroupKind: schema.GroupKind{Kind: "Foo"}, SearchedVersions: []string{"v1beta"}},
|
||||
},
|
||||
{
|
||||
name: "ignore not found with multi versions not exist",
|
||||
mapper: MultiRESTMapper{fixedRESTMapper{err: &NoKindMatchError{GroupKind: schema.GroupKind{Kind: "Foo"}, SearchedVersions: []string{"v1"}}}},
|
||||
groupKind: schema.GroupKind{Kind: "Foo"},
|
||||
versions: []string{"v1beta", "v2"},
|
||||
result: nil,
|
||||
err: &NoKindMatchError{GroupKind: schema.GroupKind{Kind: "Foo"}, SearchedVersions: []string{"v1beta", "v2"}},
|
||||
},
|
||||
{
|
||||
name: "accept first failure",
|
||||
mapper: MultiRESTMapper{fixedRESTMapper{err: errors.New("fail on this")}, fixedRESTMapper{mappings: []*RESTMapping{mapping1}}},
|
||||
groupKind: schema.GroupKind{Kind: "Foo"},
|
||||
versions: []string{"v1beta"},
|
||||
result: nil,
|
||||
err: errors.New("fail on this"),
|
||||
},
|
||||
{
|
||||
name: "return both",
|
||||
mapper: MultiRESTMapper{fixedRESTMapper{mappings: []*RESTMapping{mapping1}}, fixedRESTMapper{mappings: []*RESTMapping{mapping2}}},
|
||||
groupKind: schema.GroupKind{Kind: "Foo"},
|
||||
versions: []string{"v1beta"},
|
||||
result: []*RESTMapping{mapping1, mapping2},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tcs {
|
||||
actualResult, actualErr := tc.mapper.RESTMappings(tc.groupKind, tc.versions...)
|
||||
if e, a := tc.result, actualResult; !reflect.DeepEqual(e, a) {
|
||||
t.Errorf("%s: expected %v, got %v", tc.name, e, a)
|
||||
}
|
||||
switch {
|
||||
case tc.err == nil && actualErr == nil:
|
||||
case tc.err == nil:
|
||||
t.Errorf("%s: unexpected error: %v", tc.name, actualErr)
|
||||
case actualErr == nil:
|
||||
t.Errorf("%s: expected error: %v got nil", tc.name, tc.err)
|
||||
case tc.err.Error() != actualErr.Error():
|
||||
t.Errorf("%s: expected %v, got %v", tc.name, tc.err, actualErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type fixedRESTMapper struct {
|
||||
resourcesFor []schema.GroupVersionResource
|
||||
kindsFor []schema.GroupVersionKind
|
||||
resourceFor schema.GroupVersionResource
|
||||
kindFor schema.GroupVersionKind
|
||||
mappings []*RESTMapping
|
||||
|
||||
err error
|
||||
}
|
||||
|
||||
func (m fixedRESTMapper) ResourceSingularizer(resource string) (singular string, err error) {
|
||||
return "", m.err
|
||||
}
|
||||
|
||||
func (m fixedRESTMapper) ResourcesFor(resource schema.GroupVersionResource) ([]schema.GroupVersionResource, error) {
|
||||
return m.resourcesFor, m.err
|
||||
}
|
||||
|
||||
func (m fixedRESTMapper) KindsFor(resource schema.GroupVersionResource) (gvk []schema.GroupVersionKind, err error) {
|
||||
return m.kindsFor, m.err
|
||||
}
|
||||
|
||||
func (m fixedRESTMapper) ResourceFor(resource schema.GroupVersionResource) (schema.GroupVersionResource, error) {
|
||||
return m.resourceFor, m.err
|
||||
}
|
||||
|
||||
func (m fixedRESTMapper) KindFor(resource schema.GroupVersionResource) (schema.GroupVersionKind, error) {
|
||||
return m.kindFor, m.err
|
||||
}
|
||||
|
||||
func (m fixedRESTMapper) RESTMapping(gk schema.GroupKind, versions ...string) (mapping *RESTMapping, err error) {
|
||||
return nil, m.err
|
||||
}
|
||||
|
||||
func (m fixedRESTMapper) RESTMappings(gk schema.GroupKind, versions ...string) (mappings []*RESTMapping, err error) {
|
||||
return m.mappings, m.err
|
||||
}
|
||||
|
||||
func (m fixedRESTMapper) ResourceIsValid(resource schema.GroupVersionResource) bool {
|
||||
return false
|
||||
}
|
409
vendor/k8s.io/apimachinery/pkg/api/meta/priority_test.go
generated
vendored
409
vendor/k8s.io/apimachinery/pkg/api/meta/priority_test.go
generated
vendored
@ -1,409 +0,0 @@
|
||||
/*
|
||||
Copyright 2016 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 meta
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"k8s.io/apimachinery/pkg/runtime/schema"
|
||||
)
|
||||
|
||||
func TestPriorityRESTMapperResourceForErrorHandling(t *testing.T) {
|
||||
tcs := []struct {
|
||||
name string
|
||||
|
||||
delegate RESTMapper
|
||||
resourcePatterns []schema.GroupVersionResource
|
||||
result schema.GroupVersionResource
|
||||
err string
|
||||
}{
|
||||
{
|
||||
name: "error",
|
||||
delegate: fixedRESTMapper{err: errors.New("delegateError")},
|
||||
err: "delegateError",
|
||||
},
|
||||
{
|
||||
name: "single hit + error",
|
||||
delegate: fixedRESTMapper{resourcesFor: []schema.GroupVersionResource{{Resource: "single-hit"}}, err: errors.New("delegateError")},
|
||||
result: schema.GroupVersionResource{Resource: "single-hit"},
|
||||
err: "delegateError",
|
||||
},
|
||||
{
|
||||
name: "group selection + error",
|
||||
delegate: fixedRESTMapper{resourcesFor: []schema.GroupVersionResource{
|
||||
{Group: "one", Version: "a", Resource: "first"},
|
||||
{Group: "two", Version: "b", Resource: "second"},
|
||||
}, err: errors.New("delegateError")},
|
||||
resourcePatterns: []schema.GroupVersionResource{
|
||||
{Group: "one", Version: AnyVersion, Resource: AnyResource},
|
||||
},
|
||||
result: schema.GroupVersionResource{Group: "one", Version: "a", Resource: "first"},
|
||||
err: "delegateError",
|
||||
},
|
||||
|
||||
{
|
||||
name: "single hit",
|
||||
delegate: fixedRESTMapper{resourcesFor: []schema.GroupVersionResource{{Resource: "single-hit"}}},
|
||||
result: schema.GroupVersionResource{Resource: "single-hit"},
|
||||
},
|
||||
{
|
||||
name: "ambiguous match",
|
||||
delegate: fixedRESTMapper{resourcesFor: []schema.GroupVersionResource{
|
||||
{Group: "one", Version: "a", Resource: "first"},
|
||||
{Group: "two", Version: "b", Resource: "second"},
|
||||
}},
|
||||
err: "matches multiple resources",
|
||||
},
|
||||
{
|
||||
name: "group selection",
|
||||
delegate: fixedRESTMapper{resourcesFor: []schema.GroupVersionResource{
|
||||
{Group: "one", Version: "a", Resource: "first"},
|
||||
{Group: "two", Version: "b", Resource: "second"},
|
||||
}},
|
||||
resourcePatterns: []schema.GroupVersionResource{
|
||||
{Group: "one", Version: AnyVersion, Resource: AnyResource},
|
||||
},
|
||||
result: schema.GroupVersionResource{Group: "one", Version: "a", Resource: "first"},
|
||||
},
|
||||
{
|
||||
name: "empty match continues",
|
||||
delegate: fixedRESTMapper{resourcesFor: []schema.GroupVersionResource{
|
||||
{Group: "one", Version: "a", Resource: "first"},
|
||||
{Group: "two", Version: "b", Resource: "second"},
|
||||
}},
|
||||
resourcePatterns: []schema.GroupVersionResource{
|
||||
{Group: "fail", Version: AnyVersion, Resource: AnyResource},
|
||||
{Group: "one", Version: AnyVersion, Resource: AnyResource},
|
||||
},
|
||||
result: schema.GroupVersionResource{Group: "one", Version: "a", Resource: "first"},
|
||||
},
|
||||
{
|
||||
name: "group followed by version selection",
|
||||
delegate: fixedRESTMapper{resourcesFor: []schema.GroupVersionResource{
|
||||
{Group: "one", Version: "a", Resource: "first"},
|
||||
{Group: "two", Version: "b", Resource: "second"},
|
||||
{Group: "one", Version: "c", Resource: "third"},
|
||||
}},
|
||||
resourcePatterns: []schema.GroupVersionResource{
|
||||
{Group: "one", Version: AnyVersion, Resource: AnyResource},
|
||||
{Group: AnyGroup, Version: "a", Resource: AnyResource},
|
||||
},
|
||||
result: schema.GroupVersionResource{Group: "one", Version: "a", Resource: "first"},
|
||||
},
|
||||
{
|
||||
name: "resource selection",
|
||||
delegate: fixedRESTMapper{resourcesFor: []schema.GroupVersionResource{
|
||||
{Group: "one", Version: "a", Resource: "first"},
|
||||
{Group: "one", Version: "a", Resource: "second"},
|
||||
}},
|
||||
resourcePatterns: []schema.GroupVersionResource{
|
||||
{Group: AnyGroup, Version: AnyVersion, Resource: "second"},
|
||||
},
|
||||
result: schema.GroupVersionResource{Group: "one", Version: "a", Resource: "second"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tcs {
|
||||
mapper := PriorityRESTMapper{Delegate: tc.delegate, ResourcePriority: tc.resourcePatterns}
|
||||
|
||||
actualResult, actualErr := mapper.ResourceFor(schema.GroupVersionResource{})
|
||||
if e, a := tc.result, actualResult; e != a {
|
||||
t.Errorf("%s: expected %v, got %v", tc.name, e, a)
|
||||
}
|
||||
if len(tc.err) == 0 && actualErr == nil {
|
||||
continue
|
||||
}
|
||||
if len(tc.err) == 0 && actualErr != nil {
|
||||
t.Errorf("%s: unexpected err: %v", tc.name, actualErr)
|
||||
continue
|
||||
}
|
||||
if len(tc.err) > 0 && actualErr == nil {
|
||||
t.Errorf("%s: missing expected err: %v", tc.name, tc.err)
|
||||
continue
|
||||
}
|
||||
if !strings.Contains(actualErr.Error(), tc.err) {
|
||||
t.Errorf("%s: expected %v, got %v", tc.name, tc.err, actualErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPriorityRESTMapperKindForErrorHandling(t *testing.T) {
|
||||
tcs := []struct {
|
||||
name string
|
||||
|
||||
delegate RESTMapper
|
||||
kindPatterns []schema.GroupVersionKind
|
||||
result schema.GroupVersionKind
|
||||
err string
|
||||
}{
|
||||
{
|
||||
name: "error",
|
||||
delegate: fixedRESTMapper{err: errors.New("delegateErr")},
|
||||
err: "delegateErr",
|
||||
},
|
||||
{
|
||||
name: "single hit + error",
|
||||
delegate: fixedRESTMapper{kindsFor: []schema.GroupVersionKind{{Kind: "single-hit"}}, err: errors.New("delegateErr")},
|
||||
result: schema.GroupVersionKind{Kind: "single-hit"},
|
||||
err: "delegateErr",
|
||||
},
|
||||
{
|
||||
name: "group selection + error",
|
||||
delegate: fixedRESTMapper{kindsFor: []schema.GroupVersionKind{
|
||||
{Group: "one", Version: "a", Kind: "first"},
|
||||
{Group: "two", Version: "b", Kind: "second"},
|
||||
}, err: errors.New("delegateErr")},
|
||||
kindPatterns: []schema.GroupVersionKind{
|
||||
{Group: "one", Version: AnyVersion, Kind: AnyKind},
|
||||
},
|
||||
result: schema.GroupVersionKind{Group: "one", Version: "a", Kind: "first"},
|
||||
err: "delegateErr",
|
||||
},
|
||||
|
||||
{
|
||||
name: "single hit",
|
||||
delegate: fixedRESTMapper{kindsFor: []schema.GroupVersionKind{{Kind: "single-hit"}}},
|
||||
result: schema.GroupVersionKind{Kind: "single-hit"},
|
||||
},
|
||||
{
|
||||
name: "ambiguous match",
|
||||
delegate: fixedRESTMapper{kindsFor: []schema.GroupVersionKind{
|
||||
{Group: "one", Version: "a", Kind: "first"},
|
||||
{Group: "two", Version: "b", Kind: "second"},
|
||||
}},
|
||||
err: "matches multiple kinds",
|
||||
},
|
||||
{
|
||||
name: "group selection",
|
||||
delegate: fixedRESTMapper{kindsFor: []schema.GroupVersionKind{
|
||||
{Group: "one", Version: "a", Kind: "first"},
|
||||
{Group: "two", Version: "b", Kind: "second"},
|
||||
}},
|
||||
kindPatterns: []schema.GroupVersionKind{
|
||||
{Group: "one", Version: AnyVersion, Kind: AnyKind},
|
||||
},
|
||||
result: schema.GroupVersionKind{Group: "one", Version: "a", Kind: "first"},
|
||||
},
|
||||
{
|
||||
name: "empty match continues",
|
||||
delegate: fixedRESTMapper{kindsFor: []schema.GroupVersionKind{
|
||||
{Group: "one", Version: "a", Kind: "first"},
|
||||
{Group: "two", Version: "b", Kind: "second"},
|
||||
}},
|
||||
kindPatterns: []schema.GroupVersionKind{
|
||||
{Group: "fail", Version: AnyVersion, Kind: AnyKind},
|
||||
{Group: "one", Version: AnyVersion, Kind: AnyKind},
|
||||
},
|
||||
result: schema.GroupVersionKind{Group: "one", Version: "a", Kind: "first"},
|
||||
},
|
||||
{
|
||||
name: "group followed by version selection",
|
||||
delegate: fixedRESTMapper{kindsFor: []schema.GroupVersionKind{
|
||||
{Group: "one", Version: "a", Kind: "first"},
|
||||
{Group: "two", Version: "b", Kind: "second"},
|
||||
{Group: "one", Version: "c", Kind: "third"},
|
||||
}},
|
||||
kindPatterns: []schema.GroupVersionKind{
|
||||
{Group: "one", Version: AnyVersion, Kind: AnyKind},
|
||||
{Group: AnyGroup, Version: "a", Kind: AnyKind},
|
||||
},
|
||||
result: schema.GroupVersionKind{Group: "one", Version: "a", Kind: "first"},
|
||||
},
|
||||
{
|
||||
name: "kind selection",
|
||||
delegate: fixedRESTMapper{kindsFor: []schema.GroupVersionKind{
|
||||
{Group: "one", Version: "a", Kind: "first"},
|
||||
{Group: "one", Version: "a", Kind: "second"},
|
||||
}},
|
||||
kindPatterns: []schema.GroupVersionKind{
|
||||
{Group: AnyGroup, Version: AnyVersion, Kind: "second"},
|
||||
},
|
||||
result: schema.GroupVersionKind{Group: "one", Version: "a", Kind: "second"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tcs {
|
||||
mapper := PriorityRESTMapper{Delegate: tc.delegate, KindPriority: tc.kindPatterns}
|
||||
|
||||
actualResult, actualErr := mapper.KindFor(schema.GroupVersionResource{})
|
||||
if e, a := tc.result, actualResult; e != a {
|
||||
t.Errorf("%s: expected %v, got %v", tc.name, e, a)
|
||||
}
|
||||
if len(tc.err) == 0 && actualErr == nil {
|
||||
continue
|
||||
}
|
||||
if len(tc.err) == 0 && actualErr != nil {
|
||||
t.Errorf("%s: unexpected err: %v", tc.name, actualErr)
|
||||
continue
|
||||
}
|
||||
if len(tc.err) > 0 && actualErr == nil {
|
||||
t.Errorf("%s: missing expected err: %v", tc.name, tc.err)
|
||||
continue
|
||||
}
|
||||
if !strings.Contains(actualErr.Error(), tc.err) {
|
||||
t.Errorf("%s: expected %v, got %v", tc.name, tc.err, actualErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPriorityRESTMapperRESTMapping(t *testing.T) {
|
||||
mapping1 := &RESTMapping{
|
||||
GroupVersionKind: schema.GroupVersionKind{Kind: "Foo", Version: "v1alpha1"},
|
||||
}
|
||||
mapping2 := &RESTMapping{
|
||||
GroupVersionKind: schema.GroupVersionKind{Kind: "Foo", Version: "v1"},
|
||||
}
|
||||
mapping3 := &RESTMapping{
|
||||
GroupVersionKind: schema.GroupVersionKind{Group: "other", Kind: "Foo", Version: "v1"},
|
||||
}
|
||||
allMappers := MultiRESTMapper{
|
||||
fixedRESTMapper{mappings: []*RESTMapping{mapping1}},
|
||||
fixedRESTMapper{mappings: []*RESTMapping{mapping2}},
|
||||
fixedRESTMapper{mappings: []*RESTMapping{mapping3}},
|
||||
}
|
||||
tcs := []struct {
|
||||
name string
|
||||
|
||||
mapper PriorityRESTMapper
|
||||
input schema.GroupKind
|
||||
result *RESTMapping
|
||||
err error
|
||||
}{
|
||||
{
|
||||
name: "empty",
|
||||
mapper: PriorityRESTMapper{Delegate: MultiRESTMapper{}},
|
||||
input: schema.GroupKind{Kind: "Foo"},
|
||||
err: &NoKindMatchError{GroupKind: schema.GroupKind{Kind: "Foo"}},
|
||||
},
|
||||
{
|
||||
name: "ignore not found",
|
||||
mapper: PriorityRESTMapper{Delegate: MultiRESTMapper{fixedRESTMapper{err: &NoKindMatchError{GroupKind: schema.GroupKind{Kind: "IGNORE_THIS"}}}}},
|
||||
input: schema.GroupKind{Kind: "Foo"},
|
||||
err: &NoKindMatchError{GroupKind: schema.GroupKind{Kind: "Foo"}},
|
||||
},
|
||||
{
|
||||
name: "accept first failure",
|
||||
mapper: PriorityRESTMapper{Delegate: MultiRESTMapper{fixedRESTMapper{err: errors.New("fail on this")}, fixedRESTMapper{mappings: []*RESTMapping{mapping1}}}},
|
||||
input: schema.GroupKind{Kind: "Foo"},
|
||||
err: errors.New("fail on this"),
|
||||
},
|
||||
{
|
||||
name: "result + error",
|
||||
mapper: PriorityRESTMapper{Delegate: fixedRESTMapper{mappings: []*RESTMapping{mapping1}, err: errors.New("fail on this")}},
|
||||
input: schema.GroupKind{Kind: "Foo"},
|
||||
result: mapping1,
|
||||
err: errors.New("fail on this"),
|
||||
},
|
||||
{
|
||||
name: "return error for ambiguous",
|
||||
mapper: PriorityRESTMapper{
|
||||
Delegate: allMappers,
|
||||
},
|
||||
input: schema.GroupKind{Kind: "Foo"},
|
||||
err: &AmbiguousKindError{
|
||||
PartialKind: schema.GroupVersionKind{Kind: "Foo"},
|
||||
MatchingKinds: []schema.GroupVersionKind{
|
||||
{Kind: "Foo", Version: "v1alpha1"},
|
||||
{Kind: "Foo", Version: "v1"},
|
||||
{Group: "other", Kind: "Foo", Version: "v1"},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "accept only item",
|
||||
mapper: PriorityRESTMapper{
|
||||
Delegate: fixedRESTMapper{mappings: []*RESTMapping{mapping1}},
|
||||
},
|
||||
input: schema.GroupKind{Kind: "Foo"},
|
||||
result: mapping1,
|
||||
},
|
||||
{
|
||||
name: "return single priority",
|
||||
mapper: PriorityRESTMapper{
|
||||
Delegate: allMappers,
|
||||
KindPriority: []schema.GroupVersionKind{{Version: "v1", Kind: AnyKind}, {Version: "v1alpha1", Kind: AnyKind}},
|
||||
},
|
||||
input: schema.GroupKind{Kind: "Foo"},
|
||||
result: mapping2,
|
||||
},
|
||||
{
|
||||
name: "return out of group match",
|
||||
mapper: PriorityRESTMapper{
|
||||
Delegate: allMappers,
|
||||
KindPriority: []schema.GroupVersionKind{{Group: AnyGroup, Version: "v1", Kind: AnyKind}, {Group: "other", Version: AnyVersion, Kind: AnyKind}},
|
||||
},
|
||||
input: schema.GroupKind{Kind: "Foo"},
|
||||
result: mapping3,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tcs {
|
||||
actualResult, actualErr := tc.mapper.RESTMapping(tc.input)
|
||||
if e, a := tc.result, actualResult; !reflect.DeepEqual(e, a) {
|
||||
t.Errorf("%s: expected %v, got %v", tc.name, e, a)
|
||||
}
|
||||
switch {
|
||||
case tc.err == nil && actualErr == nil:
|
||||
case tc.err == nil:
|
||||
t.Errorf("%s: unexpected error: %v", tc.name, actualErr)
|
||||
case actualErr == nil:
|
||||
t.Errorf("%s: expected error: %v got nil", tc.name, tc.err)
|
||||
case tc.err.Error() != actualErr.Error():
|
||||
t.Errorf("%s: expected %v, got %v", tc.name, tc.err, actualErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPriorityRESTMapperRESTMappingHonorsUserVersion(t *testing.T) {
|
||||
mappingV2alpha1 := &RESTMapping{
|
||||
GroupVersionKind: schema.GroupVersionKind{Group: "Bar", Kind: "Foo", Version: "v2alpha1"},
|
||||
}
|
||||
mappingV1 := &RESTMapping{
|
||||
GroupVersionKind: schema.GroupVersionKind{Group: "Bar", Kind: "Foo", Version: "v1"},
|
||||
}
|
||||
|
||||
allMappers := MultiRESTMapper{
|
||||
fixedRESTMapper{mappings: []*RESTMapping{mappingV2alpha1}},
|
||||
fixedRESTMapper{mappings: []*RESTMapping{mappingV1}},
|
||||
}
|
||||
|
||||
mapper := PriorityRESTMapper{
|
||||
Delegate: allMappers,
|
||||
KindPriority: []schema.GroupVersionKind{{Group: "Bar", Version: "v2alpha1", Kind: AnyKind}, {Group: "Bar", Version: AnyVersion, Kind: AnyKind}},
|
||||
}
|
||||
|
||||
outMapping1, err := mapper.RESTMapping(schema.GroupKind{Group: "Bar", Kind: "Foo"}, "v1")
|
||||
if err != nil {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if outMapping1 != mappingV1 {
|
||||
t.Errorf("asked for version %v, expected mapping for %v, got mapping for %v", "v1", mappingV1.GroupVersionKind, outMapping1.GroupVersionKind)
|
||||
}
|
||||
|
||||
outMapping2, err := mapper.RESTMapping(schema.GroupKind{Group: "Bar", Kind: "Foo"}, "v2alpha1")
|
||||
if err != nil {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if outMapping2 != mappingV2alpha1 {
|
||||
t.Errorf("asked for version %v, expected mapping for %v, got mapping for %v", "v2alpha1", mappingV2alpha1.GroupVersionKind, outMapping2.GroupVersionKind)
|
||||
}
|
||||
}
|
724
vendor/k8s.io/apimachinery/pkg/api/meta/restmapper_test.go
generated
vendored
724
vendor/k8s.io/apimachinery/pkg/api/meta/restmapper_test.go
generated
vendored
@ -1,724 +0,0 @@
|
||||
/*
|
||||
Copyright 2014 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 meta
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"k8s.io/apimachinery/pkg/runtime/schema"
|
||||
)
|
||||
|
||||
func TestRESTMapperVersionAndKindForResource(t *testing.T) {
|
||||
testGroup := "test.group"
|
||||
testVersion := "test"
|
||||
testGroupVersion := schema.GroupVersion{Group: testGroup, Version: testVersion}
|
||||
|
||||
testCases := []struct {
|
||||
Resource schema.GroupVersionResource
|
||||
GroupVersionToRegister schema.GroupVersion
|
||||
ExpectedGVK schema.GroupVersionKind
|
||||
Err bool
|
||||
}{
|
||||
{Resource: schema.GroupVersionResource{Resource: "internalobjec"}, Err: true},
|
||||
{Resource: schema.GroupVersionResource{Resource: "internalObjec"}, Err: true},
|
||||
|
||||
{Resource: schema.GroupVersionResource{Resource: "internalobject"}, ExpectedGVK: testGroupVersion.WithKind("InternalObject")},
|
||||
{Resource: schema.GroupVersionResource{Resource: "internalobjects"}, ExpectedGVK: testGroupVersion.WithKind("InternalObject")},
|
||||
}
|
||||
for i, testCase := range testCases {
|
||||
mapper := NewDefaultRESTMapper([]schema.GroupVersion{testGroupVersion})
|
||||
if len(testCase.ExpectedGVK.Kind) != 0 {
|
||||
mapper.Add(testCase.ExpectedGVK, RESTScopeNamespace)
|
||||
}
|
||||
actualGVK, err := mapper.KindFor(testCase.Resource)
|
||||
|
||||
hasErr := err != nil
|
||||
if hasErr != testCase.Err {
|
||||
t.Errorf("%d: unexpected error behavior %t: %v", i, testCase.Err, err)
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
if actualGVK != testCase.ExpectedGVK {
|
||||
t.Errorf("%d: unexpected version and kind: e=%s a=%s", i, testCase.ExpectedGVK, actualGVK)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRESTMapperGroupForResource(t *testing.T) {
|
||||
testCases := []struct {
|
||||
Resource schema.GroupVersionResource
|
||||
GroupVersionKind schema.GroupVersionKind
|
||||
Err bool
|
||||
}{
|
||||
{Resource: schema.GroupVersionResource{Resource: "myObject"}, GroupVersionKind: schema.GroupVersionKind{Group: "testapi", Version: "test", Kind: "MyObject"}},
|
||||
{Resource: schema.GroupVersionResource{Resource: "myobject"}, GroupVersionKind: schema.GroupVersionKind{Group: "testapi2", Version: "test", Kind: "MyObject"}},
|
||||
{Resource: schema.GroupVersionResource{Resource: "myObje"}, Err: true, GroupVersionKind: schema.GroupVersionKind{Group: "testapi", Version: "test", Kind: "MyObject"}},
|
||||
{Resource: schema.GroupVersionResource{Resource: "myobje"}, Err: true, GroupVersionKind: schema.GroupVersionKind{Group: "testapi", Version: "test", Kind: "MyObject"}},
|
||||
}
|
||||
for i, testCase := range testCases {
|
||||
mapper := NewDefaultRESTMapper([]schema.GroupVersion{testCase.GroupVersionKind.GroupVersion()})
|
||||
mapper.Add(testCase.GroupVersionKind, RESTScopeNamespace)
|
||||
|
||||
actualGVK, err := mapper.KindFor(testCase.Resource)
|
||||
if testCase.Err {
|
||||
if err == nil {
|
||||
t.Errorf("%d: expected error", i)
|
||||
}
|
||||
} else if err != nil {
|
||||
t.Errorf("%d: unexpected error: %v", i, err)
|
||||
} else if actualGVK != testCase.GroupVersionKind {
|
||||
t.Errorf("%d: expected group %q, got %q", i, testCase.GroupVersionKind, actualGVK)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRESTMapperKindsFor(t *testing.T) {
|
||||
testCases := []struct {
|
||||
Name string
|
||||
PreferredOrder []schema.GroupVersion
|
||||
KindsToRegister []schema.GroupVersionKind
|
||||
PartialResourceToRequest schema.GroupVersionResource
|
||||
|
||||
ExpectedKinds []schema.GroupVersionKind
|
||||
ExpectedKindErr string
|
||||
}{
|
||||
{
|
||||
// exact matches are preferred
|
||||
Name: "groups, with group exact",
|
||||
PreferredOrder: []schema.GroupVersion{
|
||||
{Group: "first-group-1", Version: "first-version"},
|
||||
{Group: "first-group", Version: "first-version"},
|
||||
},
|
||||
KindsToRegister: []schema.GroupVersionKind{
|
||||
{Group: "first-group-1", Version: "first-version", Kind: "my-kind"},
|
||||
{Group: "first-group", Version: "first-version", Kind: "my-kind"},
|
||||
},
|
||||
PartialResourceToRequest: schema.GroupVersionResource{Group: "first-group", Resource: "my-kind"},
|
||||
|
||||
ExpectedKinds: []schema.GroupVersionKind{
|
||||
{Group: "first-group", Version: "first-version", Kind: "my-kind"},
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
// group prefixes work
|
||||
Name: "groups, with group prefix",
|
||||
PreferredOrder: []schema.GroupVersion{
|
||||
{Group: "second-group", Version: "first-version"},
|
||||
{Group: "first-group", Version: "first-version"},
|
||||
},
|
||||
KindsToRegister: []schema.GroupVersionKind{
|
||||
{Group: "first-group", Version: "first-version", Kind: "my-kind"},
|
||||
{Group: "second-group", Version: "first-version", Kind: "my-kind"},
|
||||
},
|
||||
PartialResourceToRequest: schema.GroupVersionResource{Group: "first", Resource: "my-kind"},
|
||||
|
||||
ExpectedKinds: []schema.GroupVersionKind{
|
||||
{Group: "first-group", Version: "first-version", Kind: "my-kind"},
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
// group prefixes can be ambiguous
|
||||
Name: "groups, with ambiguous group prefix",
|
||||
PreferredOrder: []schema.GroupVersion{
|
||||
{Group: "first-group-1", Version: "first-version"},
|
||||
{Group: "first-group", Version: "first-version"},
|
||||
},
|
||||
KindsToRegister: []schema.GroupVersionKind{
|
||||
{Group: "first-group-1", Version: "first-version", Kind: "my-kind"},
|
||||
{Group: "first-group", Version: "first-version", Kind: "my-kind"},
|
||||
},
|
||||
PartialResourceToRequest: schema.GroupVersionResource{Group: "first", Resource: "my-kind"},
|
||||
|
||||
ExpectedKinds: []schema.GroupVersionKind{
|
||||
{Group: "first-group-1", Version: "first-version", Kind: "my-kind"},
|
||||
{Group: "first-group", Version: "first-version", Kind: "my-kind"},
|
||||
},
|
||||
ExpectedKindErr: " matches multiple kinds ",
|
||||
},
|
||||
|
||||
{
|
||||
Name: "ambiguous groups, with preference order",
|
||||
PreferredOrder: []schema.GroupVersion{
|
||||
{Group: "second-group", Version: "first-version"},
|
||||
{Group: "first-group", Version: "first-version"},
|
||||
},
|
||||
KindsToRegister: []schema.GroupVersionKind{
|
||||
{Group: "first-group", Version: "first-version", Kind: "my-kind"},
|
||||
{Group: "first-group", Version: "first-version", Kind: "your-kind"},
|
||||
{Group: "second-group", Version: "first-version", Kind: "my-kind"},
|
||||
{Group: "second-group", Version: "first-version", Kind: "your-kind"},
|
||||
},
|
||||
PartialResourceToRequest: schema.GroupVersionResource{Resource: "my-kinds"},
|
||||
|
||||
ExpectedKinds: []schema.GroupVersionKind{
|
||||
{Group: "second-group", Version: "first-version", Kind: "my-kind"},
|
||||
{Group: "first-group", Version: "first-version", Kind: "my-kind"},
|
||||
},
|
||||
ExpectedKindErr: " matches multiple kinds ",
|
||||
},
|
||||
|
||||
{
|
||||
Name: "ambiguous groups, with explicit group match",
|
||||
PreferredOrder: []schema.GroupVersion{
|
||||
{Group: "second-group", Version: "first-version"},
|
||||
{Group: "first-group", Version: "first-version"},
|
||||
},
|
||||
KindsToRegister: []schema.GroupVersionKind{
|
||||
{Group: "first-group", Version: "first-version", Kind: "my-kind"},
|
||||
{Group: "first-group", Version: "first-version", Kind: "your-kind"},
|
||||
{Group: "second-group", Version: "first-version", Kind: "my-kind"},
|
||||
{Group: "second-group", Version: "first-version", Kind: "your-kind"},
|
||||
},
|
||||
PartialResourceToRequest: schema.GroupVersionResource{Group: "first-group", Resource: "my-kinds"},
|
||||
|
||||
ExpectedKinds: []schema.GroupVersionKind{
|
||||
{Group: "first-group", Version: "first-version", Kind: "my-kind"},
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
Name: "ambiguous groups, with ambiguous version match",
|
||||
PreferredOrder: []schema.GroupVersion{
|
||||
{Group: "first-group", Version: "first-version"},
|
||||
{Group: "second-group", Version: "first-version"},
|
||||
},
|
||||
KindsToRegister: []schema.GroupVersionKind{
|
||||
{Group: "first-group", Version: "first-version", Kind: "my-kind"},
|
||||
{Group: "first-group", Version: "first-version", Kind: "your-kind"},
|
||||
{Group: "second-group", Version: "first-version", Kind: "my-kind"},
|
||||
{Group: "second-group", Version: "first-version", Kind: "your-kind"},
|
||||
},
|
||||
PartialResourceToRequest: schema.GroupVersionResource{Version: "first-version", Resource: "my-kinds"},
|
||||
|
||||
ExpectedKinds: []schema.GroupVersionKind{
|
||||
{Group: "first-group", Version: "first-version", Kind: "my-kind"},
|
||||
{Group: "second-group", Version: "first-version", Kind: "my-kind"},
|
||||
},
|
||||
ExpectedKindErr: " matches multiple kinds ",
|
||||
},
|
||||
}
|
||||
for _, testCase := range testCases {
|
||||
tcName := testCase.Name
|
||||
mapper := NewDefaultRESTMapper(testCase.PreferredOrder)
|
||||
for _, kind := range testCase.KindsToRegister {
|
||||
mapper.Add(kind, RESTScopeNamespace)
|
||||
}
|
||||
|
||||
actualKinds, err := mapper.KindsFor(testCase.PartialResourceToRequest)
|
||||
if err != nil {
|
||||
t.Errorf("%s: unexpected error: %v", tcName, err)
|
||||
continue
|
||||
}
|
||||
if !reflect.DeepEqual(testCase.ExpectedKinds, actualKinds) {
|
||||
t.Errorf("%s: expected %v, got %v", tcName, testCase.ExpectedKinds, actualKinds)
|
||||
}
|
||||
|
||||
singleKind, err := mapper.KindFor(testCase.PartialResourceToRequest)
|
||||
if err == nil && len(testCase.ExpectedKindErr) != 0 {
|
||||
t.Errorf("%s: expected error: %v", tcName, testCase.ExpectedKindErr)
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
if len(testCase.ExpectedKindErr) == 0 {
|
||||
t.Errorf("%s: unexpected error: %v", tcName, err)
|
||||
continue
|
||||
} else {
|
||||
if !strings.Contains(err.Error(), testCase.ExpectedKindErr) {
|
||||
t.Errorf("%s: expected %v, got %v", tcName, testCase.ExpectedKindErr, err)
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
} else {
|
||||
if testCase.ExpectedKinds[0] != singleKind {
|
||||
t.Errorf("%s: expected %v, got %v", tcName, testCase.ExpectedKinds[0], singleKind)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRESTMapperResourcesFor(t *testing.T) {
|
||||
testCases := []struct {
|
||||
Name string
|
||||
PreferredOrder []schema.GroupVersion
|
||||
KindsToRegister []schema.GroupVersionKind
|
||||
PluralPartialResourceToRequest schema.GroupVersionResource
|
||||
SingularPartialResourceToRequest schema.GroupVersionResource
|
||||
|
||||
ExpectedResources []schema.GroupVersionResource
|
||||
ExpectedResourceErr string
|
||||
}{
|
||||
{
|
||||
// exact matches are preferred
|
||||
Name: "groups, with group exact",
|
||||
PreferredOrder: []schema.GroupVersion{
|
||||
{Group: "first-group-1", Version: "first-version"},
|
||||
{Group: "first-group", Version: "first-version"},
|
||||
},
|
||||
KindsToRegister: []schema.GroupVersionKind{
|
||||
{Group: "first-group-1", Version: "first-version", Kind: "my-kind"},
|
||||
{Group: "first-group", Version: "first-version", Kind: "my-kind"},
|
||||
},
|
||||
PluralPartialResourceToRequest: schema.GroupVersionResource{Group: "first-group", Resource: "my-kinds"},
|
||||
SingularPartialResourceToRequest: schema.GroupVersionResource{Group: "first-group", Resource: "my-kind"},
|
||||
|
||||
ExpectedResources: []schema.GroupVersionResource{
|
||||
{Group: "first-group", Version: "first-version", Resource: "my-kinds"},
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
// group prefixes work
|
||||
Name: "groups, with group prefix",
|
||||
PreferredOrder: []schema.GroupVersion{
|
||||
{Group: "second-group", Version: "first-version"},
|
||||
{Group: "first-group", Version: "first-version"},
|
||||
},
|
||||
KindsToRegister: []schema.GroupVersionKind{
|
||||
{Group: "first-group", Version: "first-version", Kind: "my-kind"},
|
||||
{Group: "second-group", Version: "first-version", Kind: "my-kind"},
|
||||
},
|
||||
PluralPartialResourceToRequest: schema.GroupVersionResource{Group: "first", Resource: "my-kinds"},
|
||||
SingularPartialResourceToRequest: schema.GroupVersionResource{Group: "first", Resource: "my-kind"},
|
||||
|
||||
ExpectedResources: []schema.GroupVersionResource{
|
||||
{Group: "first-group", Version: "first-version", Resource: "my-kinds"},
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
// group prefixes can be ambiguous
|
||||
Name: "groups, with ambiguous group prefix",
|
||||
PreferredOrder: []schema.GroupVersion{
|
||||
{Group: "first-group-1", Version: "first-version"},
|
||||
{Group: "first-group", Version: "first-version"},
|
||||
},
|
||||
KindsToRegister: []schema.GroupVersionKind{
|
||||
{Group: "first-group-1", Version: "first-version", Kind: "my-kind"},
|
||||
{Group: "first-group", Version: "first-version", Kind: "my-kind"},
|
||||
},
|
||||
PluralPartialResourceToRequest: schema.GroupVersionResource{Group: "first", Resource: "my-kinds"},
|
||||
SingularPartialResourceToRequest: schema.GroupVersionResource{Group: "first", Resource: "my-kind"},
|
||||
|
||||
ExpectedResources: []schema.GroupVersionResource{
|
||||
{Group: "first-group-1", Version: "first-version", Resource: "my-kinds"},
|
||||
{Group: "first-group", Version: "first-version", Resource: "my-kinds"},
|
||||
},
|
||||
ExpectedResourceErr: " matches multiple resources ",
|
||||
},
|
||||
|
||||
{
|
||||
Name: "ambiguous groups, with preference order",
|
||||
PreferredOrder: []schema.GroupVersion{
|
||||
{Group: "second-group", Version: "first-version"},
|
||||
{Group: "first-group", Version: "first-version"},
|
||||
},
|
||||
KindsToRegister: []schema.GroupVersionKind{
|
||||
{Group: "first-group", Version: "first-version", Kind: "my-kind"},
|
||||
{Group: "first-group", Version: "first-version", Kind: "your-kind"},
|
||||
{Group: "second-group", Version: "first-version", Kind: "my-kind"},
|
||||
{Group: "second-group", Version: "first-version", Kind: "your-kind"},
|
||||
},
|
||||
PluralPartialResourceToRequest: schema.GroupVersionResource{Resource: "my-kinds"},
|
||||
SingularPartialResourceToRequest: schema.GroupVersionResource{Resource: "my-kind"},
|
||||
|
||||
ExpectedResources: []schema.GroupVersionResource{
|
||||
{Group: "second-group", Version: "first-version", Resource: "my-kinds"},
|
||||
{Group: "first-group", Version: "first-version", Resource: "my-kinds"},
|
||||
},
|
||||
ExpectedResourceErr: " matches multiple resources ",
|
||||
},
|
||||
|
||||
{
|
||||
Name: "ambiguous groups, with explicit group match",
|
||||
PreferredOrder: []schema.GroupVersion{
|
||||
{Group: "second-group", Version: "first-version"},
|
||||
{Group: "first-group", Version: "first-version"},
|
||||
},
|
||||
KindsToRegister: []schema.GroupVersionKind{
|
||||
{Group: "first-group", Version: "first-version", Kind: "my-kind"},
|
||||
{Group: "first-group", Version: "first-version", Kind: "your-kind"},
|
||||
{Group: "second-group", Version: "first-version", Kind: "my-kind"},
|
||||
{Group: "second-group", Version: "first-version", Kind: "your-kind"},
|
||||
},
|
||||
PluralPartialResourceToRequest: schema.GroupVersionResource{Group: "first-group", Resource: "my-kinds"},
|
||||
SingularPartialResourceToRequest: schema.GroupVersionResource{Group: "first-group", Resource: "my-kind"},
|
||||
|
||||
ExpectedResources: []schema.GroupVersionResource{
|
||||
{Group: "first-group", Version: "first-version", Resource: "my-kinds"},
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
Name: "ambiguous groups, with ambiguous version match",
|
||||
PreferredOrder: []schema.GroupVersion{
|
||||
{Group: "first-group", Version: "first-version"},
|
||||
{Group: "second-group", Version: "first-version"},
|
||||
},
|
||||
KindsToRegister: []schema.GroupVersionKind{
|
||||
{Group: "first-group", Version: "first-version", Kind: "my-kind"},
|
||||
{Group: "first-group", Version: "first-version", Kind: "your-kind"},
|
||||
{Group: "second-group", Version: "first-version", Kind: "my-kind"},
|
||||
{Group: "second-group", Version: "first-version", Kind: "your-kind"},
|
||||
},
|
||||
PluralPartialResourceToRequest: schema.GroupVersionResource{Version: "first-version", Resource: "my-kinds"},
|
||||
SingularPartialResourceToRequest: schema.GroupVersionResource{Version: "first-version", Resource: "my-kind"},
|
||||
|
||||
ExpectedResources: []schema.GroupVersionResource{
|
||||
{Group: "first-group", Version: "first-version", Resource: "my-kinds"},
|
||||
{Group: "second-group", Version: "first-version", Resource: "my-kinds"},
|
||||
},
|
||||
ExpectedResourceErr: " matches multiple resources ",
|
||||
},
|
||||
}
|
||||
for _, testCase := range testCases {
|
||||
tcName := testCase.Name
|
||||
|
||||
for _, partialResource := range []schema.GroupVersionResource{testCase.PluralPartialResourceToRequest, testCase.SingularPartialResourceToRequest} {
|
||||
mapper := NewDefaultRESTMapper(testCase.PreferredOrder)
|
||||
for _, kind := range testCase.KindsToRegister {
|
||||
mapper.Add(kind, RESTScopeNamespace)
|
||||
}
|
||||
|
||||
actualResources, err := mapper.ResourcesFor(partialResource)
|
||||
if err != nil {
|
||||
t.Errorf("%s: unexpected error: %v", tcName, err)
|
||||
continue
|
||||
}
|
||||
if !reflect.DeepEqual(testCase.ExpectedResources, actualResources) {
|
||||
t.Errorf("%s: expected %v, got %v", tcName, testCase.ExpectedResources, actualResources)
|
||||
}
|
||||
|
||||
singleResource, err := mapper.ResourceFor(partialResource)
|
||||
if err == nil && len(testCase.ExpectedResourceErr) != 0 {
|
||||
t.Errorf("%s: expected error: %v", tcName, testCase.ExpectedResourceErr)
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
if len(testCase.ExpectedResourceErr) == 0 {
|
||||
t.Errorf("%s: unexpected error: %v", tcName, err)
|
||||
continue
|
||||
} else {
|
||||
if !strings.Contains(err.Error(), testCase.ExpectedResourceErr) {
|
||||
t.Errorf("%s: expected %v, got %v", tcName, testCase.ExpectedResourceErr, err)
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
} else {
|
||||
if testCase.ExpectedResources[0] != singleResource {
|
||||
t.Errorf("%s: expected %v, got %v", tcName, testCase.ExpectedResources[0], singleResource)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestKindToResource(t *testing.T) {
|
||||
testCases := []struct {
|
||||
Kind string
|
||||
Plural, Singular string
|
||||
}{
|
||||
{Kind: "Pod", Plural: "pods", Singular: "pod"},
|
||||
|
||||
{Kind: "ReplicationController", Plural: "replicationcontrollers", Singular: "replicationcontroller"},
|
||||
|
||||
// Add "ies" when ending with "y"
|
||||
{Kind: "ImageRepository", Plural: "imagerepositories", Singular: "imagerepository"},
|
||||
// Add "es" when ending with "s"
|
||||
{Kind: "miss", Plural: "misses", Singular: "miss"},
|
||||
// Add "s" otherwise
|
||||
{Kind: "lowercase", Plural: "lowercases", Singular: "lowercase"},
|
||||
}
|
||||
for i, testCase := range testCases {
|
||||
version := schema.GroupVersion{}
|
||||
|
||||
plural, singular := UnsafeGuessKindToResource(version.WithKind(testCase.Kind))
|
||||
if singular != version.WithResource(testCase.Singular) || plural != version.WithResource(testCase.Plural) {
|
||||
t.Errorf("%d: unexpected plural and singular: %v %v", i, plural, singular)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRESTMapperResourceSingularizer(t *testing.T) {
|
||||
testGroupVersion := schema.GroupVersion{Group: "tgroup", Version: "test"}
|
||||
|
||||
testCases := []struct {
|
||||
Kind string
|
||||
Plural string
|
||||
Singular string
|
||||
}{
|
||||
{Kind: "Pod", Plural: "pods", Singular: "pod"},
|
||||
{Kind: "ReplicationController", Plural: "replicationcontrollers", Singular: "replicationcontroller"},
|
||||
{Kind: "ImageRepository", Plural: "imagerepositories", Singular: "imagerepository"},
|
||||
{Kind: "Status", Plural: "statuses", Singular: "status"},
|
||||
|
||||
{Kind: "lowercase", Plural: "lowercases", Singular: "lowercase"},
|
||||
// TODO this test is broken. This updates to reflect actual behavior. Kinds are expected to be singular
|
||||
// old (incorrect), comment: Don't add extra s if the original object is already plural
|
||||
{Kind: "lowercases", Plural: "lowercaseses", Singular: "lowercases"},
|
||||
}
|
||||
for i, testCase := range testCases {
|
||||
mapper := NewDefaultRESTMapper([]schema.GroupVersion{testGroupVersion})
|
||||
// create singular/plural mapping
|
||||
mapper.Add(testGroupVersion.WithKind(testCase.Kind), RESTScopeNamespace)
|
||||
|
||||
singular, err := mapper.ResourceSingularizer(testCase.Plural)
|
||||
if err != nil {
|
||||
t.Errorf("%d: unexpected error: %v", i, err)
|
||||
}
|
||||
if singular != testCase.Singular {
|
||||
t.Errorf("%d: mismatched singular: got %v, expected %v", i, singular, testCase.Singular)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRESTMapperRESTMapping(t *testing.T) {
|
||||
testGroup := "tgroup"
|
||||
testGroupVersion := schema.GroupVersion{Group: testGroup, Version: "test"}
|
||||
internalGroupVersion := schema.GroupVersion{Group: testGroup, Version: "test"}
|
||||
|
||||
testCases := []struct {
|
||||
Kind string
|
||||
APIGroupVersions []schema.GroupVersion
|
||||
DefaultVersions []schema.GroupVersion
|
||||
|
||||
Resource schema.GroupVersionResource
|
||||
ExpectedGroupVersion *schema.GroupVersion
|
||||
Err bool
|
||||
}{
|
||||
{Kind: "Unknown", Err: true},
|
||||
{Kind: "InternalObject", Err: true},
|
||||
|
||||
{DefaultVersions: []schema.GroupVersion{testGroupVersion}, Kind: "Unknown", Err: true},
|
||||
|
||||
{DefaultVersions: []schema.GroupVersion{testGroupVersion}, Kind: "InternalObject", APIGroupVersions: []schema.GroupVersion{{Group: testGroup, Version: "test"}}, Resource: testGroupVersion.WithResource("internalobjects")},
|
||||
{DefaultVersions: []schema.GroupVersion{testGroupVersion}, Kind: "InternalObject", APIGroupVersions: []schema.GroupVersion{{Group: testGroup, Version: "test"}}, Resource: testGroupVersion.WithResource("internalobjects")},
|
||||
|
||||
{DefaultVersions: []schema.GroupVersion{testGroupVersion}, Kind: "InternalObject", APIGroupVersions: []schema.GroupVersion{{Group: testGroup, Version: "test"}}, Resource: testGroupVersion.WithResource("internalobjects")},
|
||||
|
||||
{DefaultVersions: []schema.GroupVersion{testGroupVersion}, Kind: "InternalObject", APIGroupVersions: []schema.GroupVersion{}, Resource: internalGroupVersion.WithResource("internalobjects"), ExpectedGroupVersion: &schema.GroupVersion{Group: testGroup, Version: "test"}},
|
||||
|
||||
{DefaultVersions: []schema.GroupVersion{testGroupVersion}, Kind: "InternalObject", APIGroupVersions: []schema.GroupVersion{{Group: testGroup, Version: "test"}}, Resource: testGroupVersion.WithResource("internalobjects")},
|
||||
|
||||
// TODO: add test for a resource that exists in one version but not another
|
||||
}
|
||||
for i, testCase := range testCases {
|
||||
mapper := NewDefaultRESTMapper(testCase.DefaultVersions)
|
||||
mapper.Add(internalGroupVersion.WithKind("InternalObject"), RESTScopeNamespace)
|
||||
|
||||
preferredVersions := []string{}
|
||||
for _, gv := range testCase.APIGroupVersions {
|
||||
preferredVersions = append(preferredVersions, gv.Version)
|
||||
}
|
||||
gk := schema.GroupKind{Group: testGroup, Kind: testCase.Kind}
|
||||
|
||||
mapping, err := mapper.RESTMapping(gk, preferredVersions...)
|
||||
hasErr := err != nil
|
||||
if hasErr != testCase.Err {
|
||||
t.Errorf("%d: unexpected error behavior %t: %v", i, testCase.Err, err)
|
||||
}
|
||||
if hasErr {
|
||||
continue
|
||||
}
|
||||
if mapping.Resource != testCase.Resource {
|
||||
t.Errorf("%d: unexpected resource: %#v", i, mapping)
|
||||
}
|
||||
|
||||
groupVersion := testCase.ExpectedGroupVersion
|
||||
if groupVersion == nil {
|
||||
groupVersion = &testCase.APIGroupVersions[0]
|
||||
}
|
||||
if mapping.GroupVersionKind.GroupVersion() != *groupVersion {
|
||||
t.Errorf("%d: unexpected version: %#v", i, mapping)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
func TestRESTMapperRESTMappingSelectsVersion(t *testing.T) {
|
||||
expectedGroupVersion1 := schema.GroupVersion{Group: "tgroup", Version: "test1"}
|
||||
expectedGroupVersion2 := schema.GroupVersion{Group: "tgroup", Version: "test2"}
|
||||
expectedGroupVersion3 := schema.GroupVersion{Group: "tgroup", Version: "test3"}
|
||||
internalObjectGK := schema.GroupKind{Group: "tgroup", Kind: "InternalObject"}
|
||||
otherObjectGK := schema.GroupKind{Group: "tgroup", Kind: "OtherObject"}
|
||||
|
||||
mapper := NewDefaultRESTMapper([]schema.GroupVersion{expectedGroupVersion1, expectedGroupVersion2})
|
||||
mapper.Add(expectedGroupVersion1.WithKind("InternalObject"), RESTScopeNamespace)
|
||||
mapper.Add(expectedGroupVersion2.WithKind("OtherObject"), RESTScopeNamespace)
|
||||
|
||||
// pick default matching object kind based on search order
|
||||
mapping, err := mapper.RESTMapping(otherObjectGK)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if mapping.Resource != expectedGroupVersion2.WithResource("otherobjects") || mapping.GroupVersionKind.GroupVersion() != expectedGroupVersion2 {
|
||||
t.Errorf("unexpected mapping: %#v", mapping)
|
||||
}
|
||||
|
||||
mapping, err = mapper.RESTMapping(internalObjectGK)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if mapping.Resource != expectedGroupVersion1.WithResource("internalobjects") || mapping.GroupVersionKind.GroupVersion() != expectedGroupVersion1 {
|
||||
t.Errorf("unexpected mapping: %#v", mapping)
|
||||
}
|
||||
|
||||
// mismatch of version
|
||||
mapping, err = mapper.RESTMapping(internalObjectGK, expectedGroupVersion2.Version)
|
||||
if err == nil {
|
||||
t.Errorf("unexpected non-error")
|
||||
}
|
||||
mapping, err = mapper.RESTMapping(otherObjectGK, expectedGroupVersion1.Version)
|
||||
if err == nil {
|
||||
t.Errorf("unexpected non-error")
|
||||
}
|
||||
|
||||
// not in the search versions
|
||||
mapping, err = mapper.RESTMapping(otherObjectGK, expectedGroupVersion3.Version)
|
||||
if err == nil {
|
||||
t.Errorf("unexpected non-error")
|
||||
}
|
||||
|
||||
// explicit search order
|
||||
mapping, err = mapper.RESTMapping(otherObjectGK, expectedGroupVersion3.Version, expectedGroupVersion1.Version)
|
||||
if err == nil {
|
||||
t.Errorf("unexpected non-error")
|
||||
}
|
||||
|
||||
mapping, err = mapper.RESTMapping(otherObjectGK, expectedGroupVersion3.Version, expectedGroupVersion2.Version)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if mapping.Resource != expectedGroupVersion2.WithResource("otherobjects") || mapping.GroupVersionKind.GroupVersion() != expectedGroupVersion2 {
|
||||
t.Errorf("unexpected mapping: %#v", mapping)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRESTMapperRESTMappings(t *testing.T) {
|
||||
testGroup := "tgroup"
|
||||
testGroupVersion := schema.GroupVersion{Group: testGroup, Version: "v1"}
|
||||
|
||||
testCases := []struct {
|
||||
Kind string
|
||||
APIGroupVersions []schema.GroupVersion
|
||||
DefaultVersions []schema.GroupVersion
|
||||
AddGroupVersionKind []schema.GroupVersionKind
|
||||
|
||||
ExpectedRESTMappings []*RESTMapping
|
||||
Err bool
|
||||
}{
|
||||
{Kind: "Unknown", Err: true},
|
||||
{Kind: "InternalObject", Err: true},
|
||||
|
||||
{DefaultVersions: []schema.GroupVersion{testGroupVersion}, Kind: "Unknown", Err: true},
|
||||
|
||||
// ask for specific version - not available - thus error
|
||||
{DefaultVersions: []schema.GroupVersion{testGroupVersion}, Kind: "InternalObject", APIGroupVersions: []schema.GroupVersion{{Group: testGroup, Version: "v2"}}, Err: true},
|
||||
|
||||
// ask for specific version - available - check ExpectedRESTMappings
|
||||
{
|
||||
DefaultVersions: []schema.GroupVersion{testGroupVersion},
|
||||
Kind: "InternalObject",
|
||||
APIGroupVersions: []schema.GroupVersion{{Group: testGroup, Version: "v2"}},
|
||||
AddGroupVersionKind: []schema.GroupVersionKind{schema.GroupVersion{Group: testGroup, Version: "v2"}.WithKind("InternalObject")},
|
||||
ExpectedRESTMappings: []*RESTMapping{{Resource: schema.GroupVersionResource{Group: testGroup, Version: "v2", Resource: "internalobjects"}, GroupVersionKind: schema.GroupVersionKind{Group: testGroup, Version: "v2", Kind: "InternalObject"}}},
|
||||
},
|
||||
|
||||
// ask for specific versions - only one available - check ExpectedRESTMappings
|
||||
{
|
||||
DefaultVersions: []schema.GroupVersion{testGroupVersion},
|
||||
Kind: "InternalObject",
|
||||
APIGroupVersions: []schema.GroupVersion{{Group: testGroup, Version: "v3"}, {Group: testGroup, Version: "v2"}},
|
||||
AddGroupVersionKind: []schema.GroupVersionKind{schema.GroupVersion{Group: testGroup, Version: "v2"}.WithKind("InternalObject")},
|
||||
ExpectedRESTMappings: []*RESTMapping{{Resource: schema.GroupVersionResource{Group: testGroup, Version: "v2", Resource: "internalobjects"}, GroupVersionKind: schema.GroupVersionKind{Group: testGroup, Version: "v2", Kind: "InternalObject"}}},
|
||||
},
|
||||
|
||||
// do not ask for specific version - search through default versions - check ExpectedRESTMappings
|
||||
{
|
||||
DefaultVersions: []schema.GroupVersion{testGroupVersion, {Group: testGroup, Version: "v2"}},
|
||||
Kind: "InternalObject",
|
||||
AddGroupVersionKind: []schema.GroupVersionKind{schema.GroupVersion{Group: testGroup, Version: "v1"}.WithKind("InternalObject"), schema.GroupVersion{Group: testGroup, Version: "v2"}.WithKind("InternalObject")},
|
||||
ExpectedRESTMappings: []*RESTMapping{
|
||||
{
|
||||
Resource: schema.GroupVersionResource{Group: testGroup, Version: "v1", Resource: "internalobjects"},
|
||||
GroupVersionKind: schema.GroupVersionKind{Group: testGroup, Version: "v1", Kind: "InternalObject"},
|
||||
},
|
||||
{
|
||||
Resource: schema.GroupVersionResource{Group: testGroup, Version: "v2", Resource: "internalobjects"},
|
||||
GroupVersionKind: schema.GroupVersionKind{Group: testGroup, Version: "v2", Kind: "InternalObject"},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for i, testCase := range testCases {
|
||||
mapper := NewDefaultRESTMapper(testCase.DefaultVersions)
|
||||
for _, gvk := range testCase.AddGroupVersionKind {
|
||||
mapper.Add(gvk, RESTScopeNamespace)
|
||||
}
|
||||
|
||||
preferredVersions := []string{}
|
||||
for _, gv := range testCase.APIGroupVersions {
|
||||
preferredVersions = append(preferredVersions, gv.Version)
|
||||
}
|
||||
gk := schema.GroupKind{Group: testGroup, Kind: testCase.Kind}
|
||||
|
||||
mappings, err := mapper.RESTMappings(gk, preferredVersions...)
|
||||
hasErr := err != nil
|
||||
if hasErr != testCase.Err {
|
||||
t.Errorf("%d: unexpected error behavior %t: %v", i, testCase.Err, err)
|
||||
}
|
||||
if hasErr {
|
||||
continue
|
||||
}
|
||||
if len(mappings) != len(testCase.ExpectedRESTMappings) {
|
||||
t.Errorf("%d: unexpected number = %d of rest mappings was returned, expected = %d", i, len(mappings), len(testCase.ExpectedRESTMappings))
|
||||
}
|
||||
for j, mapping := range mappings {
|
||||
exp := testCase.ExpectedRESTMappings[j]
|
||||
if mapping.Resource != exp.Resource {
|
||||
t.Errorf("%d - %d: unexpected resource: %#v", i, j, mapping)
|
||||
}
|
||||
if mapping.GroupVersionKind != exp.GroupVersionKind {
|
||||
t.Errorf("%d - %d: unexpected GroupVersionKind: %#v", i, j, mapping)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRESTMapperReportsErrorOnBadVersion(t *testing.T) {
|
||||
expectedGroupVersion1 := schema.GroupVersion{Group: "tgroup", Version: "test1"}
|
||||
expectedGroupVersion2 := schema.GroupVersion{Group: "tgroup", Version: "test2"}
|
||||
internalObjectGK := schema.GroupKind{Group: "tgroup", Kind: "InternalObject"}
|
||||
|
||||
mapper := NewDefaultRESTMapper([]schema.GroupVersion{expectedGroupVersion1, expectedGroupVersion2})
|
||||
mapper.Add(expectedGroupVersion1.WithKind("InternalObject"), RESTScopeNamespace)
|
||||
_, err := mapper.RESTMapping(internalObjectGK, "test3")
|
||||
if err == nil {
|
||||
t.Errorf("unexpected non-error")
|
||||
}
|
||||
}
|
71
vendor/k8s.io/apimachinery/pkg/api/meta/table/table.go
generated
vendored
71
vendor/k8s.io/apimachinery/pkg/api/meta/table/table.go
generated
vendored
@ -1,71 +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 table
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"k8s.io/apimachinery/pkg/api/meta"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
metav1beta1 "k8s.io/apimachinery/pkg/apis/meta/v1beta1"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
"k8s.io/apimachinery/pkg/util/duration"
|
||||
)
|
||||
|
||||
// MetaToTableRow converts a list or object into one or more table rows. The provided rowFn is invoked for
|
||||
// each accessed item, with name and age being passed to each.
|
||||
func MetaToTableRow(obj runtime.Object, rowFn func(obj runtime.Object, m metav1.Object, name, age string) ([]interface{}, error)) ([]metav1beta1.TableRow, error) {
|
||||
if meta.IsListType(obj) {
|
||||
rows := make([]metav1beta1.TableRow, 0, 16)
|
||||
err := meta.EachListItem(obj, func(obj runtime.Object) error {
|
||||
nestedRows, err := MetaToTableRow(obj, rowFn)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rows = append(rows, nestedRows...)
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
rows := make([]metav1beta1.TableRow, 0, 1)
|
||||
m, err := meta.Accessor(obj)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
row := metav1beta1.TableRow{
|
||||
Object: runtime.RawExtension{Object: obj},
|
||||
}
|
||||
row.Cells, err = rowFn(obj, m, m.GetName(), ConvertToHumanReadableDateType(m.GetCreationTimestamp()))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rows = append(rows, row)
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
// ConvertToHumanReadableDateType returns the elapsed time since timestamp in
|
||||
// human-readable approximation.
|
||||
func ConvertToHumanReadableDateType(timestamp metav1.Time) string {
|
||||
if timestamp.IsZero() {
|
||||
return "<unknown>"
|
||||
}
|
||||
return duration.ShortHumanDuration(time.Now().Sub(timestamp.Time))
|
||||
}
|
171
vendor/k8s.io/apimachinery/pkg/api/meta/testrestmapper/test_restmapper.go
generated
vendored
171
vendor/k8s.io/apimachinery/pkg/api/meta/testrestmapper/test_restmapper.go
generated
vendored
@ -1,171 +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 testrestmapper
|
||||
|
||||
import (
|
||||
"k8s.io/apimachinery/pkg/api/meta"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
"k8s.io/apimachinery/pkg/runtime/schema"
|
||||
"k8s.io/apimachinery/pkg/util/sets"
|
||||
)
|
||||
|
||||
// TestOnlyStaticRESTMapper returns a union RESTMapper of all known types with priorities chosen in the following order:
|
||||
// 1. legacy kube group preferred version, extensions preferred version, metrics preferred version, legacy
|
||||
// kube any version, extensions any version, metrics any version, all other groups alphabetical preferred version,
|
||||
// all other groups alphabetical.
|
||||
// TODO callers of this method should be updated to build their own specific restmapper based on their scheme for their tests
|
||||
// TODO the things being tested are related to whether various cases are handled, not tied to the particular types being checked.
|
||||
func TestOnlyStaticRESTMapper(scheme *runtime.Scheme, versionPatterns ...schema.GroupVersion) meta.RESTMapper {
|
||||
unionMapper := meta.MultiRESTMapper{}
|
||||
unionedGroups := sets.NewString()
|
||||
for _, enabledVersion := range scheme.PrioritizedVersionsAllGroups() {
|
||||
if !unionedGroups.Has(enabledVersion.Group) {
|
||||
unionedGroups.Insert(enabledVersion.Group)
|
||||
unionMapper = append(unionMapper, newRESTMapper(enabledVersion.Group, scheme))
|
||||
}
|
||||
}
|
||||
|
||||
if len(versionPatterns) != 0 {
|
||||
resourcePriority := []schema.GroupVersionResource{}
|
||||
kindPriority := []schema.GroupVersionKind{}
|
||||
for _, versionPriority := range versionPatterns {
|
||||
resourcePriority = append(resourcePriority, versionPriority.WithResource(meta.AnyResource))
|
||||
kindPriority = append(kindPriority, versionPriority.WithKind(meta.AnyKind))
|
||||
}
|
||||
|
||||
return meta.PriorityRESTMapper{Delegate: unionMapper, ResourcePriority: resourcePriority, KindPriority: kindPriority}
|
||||
}
|
||||
|
||||
prioritizedGroups := []string{"", "extensions", "metrics"}
|
||||
resourcePriority, kindPriority := prioritiesForGroups(scheme, prioritizedGroups...)
|
||||
|
||||
prioritizedGroupsSet := sets.NewString(prioritizedGroups...)
|
||||
remainingGroups := sets.String{}
|
||||
for _, enabledVersion := range scheme.PrioritizedVersionsAllGroups() {
|
||||
if !prioritizedGroupsSet.Has(enabledVersion.Group) {
|
||||
remainingGroups.Insert(enabledVersion.Group)
|
||||
}
|
||||
}
|
||||
|
||||
remainingResourcePriority, remainingKindPriority := prioritiesForGroups(scheme, remainingGroups.List()...)
|
||||
resourcePriority = append(resourcePriority, remainingResourcePriority...)
|
||||
kindPriority = append(kindPriority, remainingKindPriority...)
|
||||
|
||||
return meta.PriorityRESTMapper{Delegate: unionMapper, ResourcePriority: resourcePriority, KindPriority: kindPriority}
|
||||
}
|
||||
|
||||
// prioritiesForGroups returns the resource and kind priorities for a PriorityRESTMapper, preferring the preferred version of each group first,
|
||||
// then any non-preferred version of the group second.
|
||||
func prioritiesForGroups(scheme *runtime.Scheme, groups ...string) ([]schema.GroupVersionResource, []schema.GroupVersionKind) {
|
||||
resourcePriority := []schema.GroupVersionResource{}
|
||||
kindPriority := []schema.GroupVersionKind{}
|
||||
|
||||
for _, group := range groups {
|
||||
availableVersions := scheme.PrioritizedVersionsForGroup(group)
|
||||
if len(availableVersions) > 0 {
|
||||
resourcePriority = append(resourcePriority, availableVersions[0].WithResource(meta.AnyResource))
|
||||
kindPriority = append(kindPriority, availableVersions[0].WithKind(meta.AnyKind))
|
||||
}
|
||||
}
|
||||
for _, group := range groups {
|
||||
resourcePriority = append(resourcePriority, schema.GroupVersionResource{Group: group, Version: meta.AnyVersion, Resource: meta.AnyResource})
|
||||
kindPriority = append(kindPriority, schema.GroupVersionKind{Group: group, Version: meta.AnyVersion, Kind: meta.AnyKind})
|
||||
}
|
||||
|
||||
return resourcePriority, kindPriority
|
||||
}
|
||||
|
||||
func newRESTMapper(group string, scheme *runtime.Scheme) meta.RESTMapper {
|
||||
mapper := meta.NewDefaultRESTMapper(scheme.PrioritizedVersionsForGroup(group))
|
||||
for _, gv := range scheme.PrioritizedVersionsForGroup(group) {
|
||||
for kind := range scheme.KnownTypes(gv) {
|
||||
if ignoredKinds.Has(kind) {
|
||||
continue
|
||||
}
|
||||
scope := meta.RESTScopeNamespace
|
||||
if rootScopedKinds[gv.WithKind(kind).GroupKind()] {
|
||||
scope = meta.RESTScopeRoot
|
||||
}
|
||||
mapper.Add(gv.WithKind(kind), scope)
|
||||
}
|
||||
}
|
||||
|
||||
return mapper
|
||||
}
|
||||
|
||||
// hardcoded is good enough for the test we're running
|
||||
var rootScopedKinds = map[schema.GroupKind]bool{
|
||||
{Group: "admission.k8s.io", Kind: "AdmissionReview"}: true,
|
||||
|
||||
{Group: "admissionregistration.k8s.io", Kind: "InitializerConfiguration"}: true,
|
||||
{Group: "admissionregistration.k8s.io", Kind: "ValidatingWebhookConfiguration"}: true,
|
||||
{Group: "admissionregistration.k8s.io", Kind: "MutatingWebhookConfiguration"}: true,
|
||||
|
||||
{Group: "authentication.k8s.io", Kind: "TokenReview"}: true,
|
||||
|
||||
{Group: "authorization.k8s.io", Kind: "SubjectAccessReview"}: true,
|
||||
{Group: "authorization.k8s.io", Kind: "SelfSubjectAccessReview"}: true,
|
||||
{Group: "authorization.k8s.io", Kind: "SelfSubjectRulesReview"}: true,
|
||||
|
||||
{Group: "certificates.k8s.io", Kind: "CertificateSigningRequest"}: true,
|
||||
|
||||
{Group: "", Kind: "Node"}: true,
|
||||
{Group: "", Kind: "Namespace"}: true,
|
||||
{Group: "", Kind: "PersistentVolume"}: true,
|
||||
{Group: "", Kind: "ComponentStatus"}: true,
|
||||
|
||||
{Group: "extensions", Kind: "PodSecurityPolicy"}: true,
|
||||
|
||||
{Group: "policy", Kind: "PodSecurityPolicy"}: true,
|
||||
|
||||
{Group: "extensions", Kind: "PodSecurityPolicy"}: true,
|
||||
|
||||
{Group: "rbac.authorization.k8s.io", Kind: "ClusterRole"}: true,
|
||||
{Group: "rbac.authorization.k8s.io", Kind: "ClusterRoleBinding"}: true,
|
||||
|
||||
{Group: "scheduling.k8s.io", Kind: "PriorityClass"}: true,
|
||||
|
||||
{Group: "storage.k8s.io", Kind: "StorageClass"}: true,
|
||||
{Group: "storage.k8s.io", Kind: "VolumeAttachment"}: true,
|
||||
|
||||
{Group: "apiextensions.k8s.io", Kind: "CustomResourceDefinition"}: true,
|
||||
|
||||
{Group: "apiserver.k8s.io", Kind: "AdmissionConfiguration"}: true,
|
||||
|
||||
{Group: "audit.k8s.io", Kind: "Event"}: true,
|
||||
{Group: "audit.k8s.io", Kind: "Policy"}: true,
|
||||
|
||||
{Group: "apiregistration.k8s.io", Kind: "APIService"}: true,
|
||||
|
||||
{Group: "metrics.k8s.io", Kind: "NodeMetrics"}: true,
|
||||
|
||||
{Group: "wardle.k8s.io", Kind: "Fischer"}: true,
|
||||
}
|
||||
|
||||
// hardcoded is good enough for the test we're running
|
||||
var ignoredKinds = sets.NewString(
|
||||
"ListOptions",
|
||||
"DeleteOptions",
|
||||
"Status",
|
||||
"PodLogOptions",
|
||||
"PodExecOptions",
|
||||
"PodAttachOptions",
|
||||
"PodPortForwardOptions",
|
||||
"PodProxyOptions",
|
||||
"NodeProxyOptions",
|
||||
"ServiceProxyOptions",
|
||||
)
|
16
vendor/k8s.io/apimachinery/pkg/api/resource/OWNERS
generated
vendored
16
vendor/k8s.io/apimachinery/pkg/api/resource/OWNERS
generated
vendored
@ -1,16 +0,0 @@
|
||||
reviewers:
|
||||
- thockin
|
||||
- lavalamp
|
||||
- smarterclayton
|
||||
- wojtek-t
|
||||
- derekwaynecarr
|
||||
- mikedanese
|
||||
- saad-ali
|
||||
- janetkuo
|
||||
- tallclair
|
||||
- eparis
|
||||
- jbeda
|
||||
- xiang90
|
||||
- mbohlool
|
||||
- david-mcmahon
|
||||
- goltermann
|
162
vendor/k8s.io/apimachinery/pkg/api/resource/amount_test.go
generated
vendored
162
vendor/k8s.io/apimachinery/pkg/api/resource/amount_test.go
generated
vendored
@ -1,162 +0,0 @@
|
||||
/*
|
||||
Copyright 2014 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 resource
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestInt64AmountAsInt64(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
value int64
|
||||
scale Scale
|
||||
result int64
|
||||
ok bool
|
||||
}{
|
||||
{100, 0, 100, true},
|
||||
{100, 1, 1000, true},
|
||||
{100, -5, 0, false},
|
||||
{100, 100, 0, false},
|
||||
} {
|
||||
r, ok := int64Amount{value: test.value, scale: test.scale}.AsInt64()
|
||||
if r != test.result {
|
||||
t.Errorf("%v: unexpected result: %d", test, r)
|
||||
}
|
||||
if ok != test.ok {
|
||||
t.Errorf("%v: unexpected ok: %t", test, ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestInt64AmountAdd(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
a, b, c int64Amount
|
||||
ok bool
|
||||
}{
|
||||
{int64Amount{value: 100, scale: 1}, int64Amount{value: 10, scale: 2}, int64Amount{value: 200, scale: 1}, true},
|
||||
{int64Amount{value: 100, scale: 1}, int64Amount{value: 1, scale: 2}, int64Amount{value: 110, scale: 1}, true},
|
||||
{int64Amount{value: 100, scale: 1}, int64Amount{value: 1, scale: 100}, int64Amount{value: 1, scale: 100}, false},
|
||||
{int64Amount{value: -5, scale: 2}, int64Amount{value: 50, scale: 1}, int64Amount{value: 0, scale: 1}, true},
|
||||
{int64Amount{value: -5, scale: 2}, int64Amount{value: 5, scale: 2}, int64Amount{value: 0, scale: 2}, true},
|
||||
|
||||
{int64Amount{value: mostPositive, scale: -1}, int64Amount{value: 1, scale: -1}, int64Amount{value: 0, scale: -1}, false},
|
||||
{int64Amount{value: mostPositive, scale: -1}, int64Amount{value: 0, scale: -1}, int64Amount{value: mostPositive, scale: -1}, true},
|
||||
{int64Amount{value: mostPositive / 10, scale: 1}, int64Amount{value: 10, scale: 0}, int64Amount{value: mostPositive, scale: -1}, false},
|
||||
} {
|
||||
c := test.a
|
||||
ok := c.Add(test.b)
|
||||
if ok != test.ok {
|
||||
t.Errorf("%v: unexpected ok: %t", test, ok)
|
||||
}
|
||||
if ok {
|
||||
if c != test.c {
|
||||
t.Errorf("%v: unexpected result: %d", test, c)
|
||||
}
|
||||
} else {
|
||||
if c != test.a {
|
||||
t.Errorf("%v: overflow addition mutated source: %d", test, c)
|
||||
}
|
||||
}
|
||||
|
||||
// addition is commutative
|
||||
c = test.b
|
||||
if ok := c.Add(test.a); ok != test.ok {
|
||||
t.Errorf("%v: unexpected ok: %t", test, ok)
|
||||
}
|
||||
if ok {
|
||||
if c != test.c {
|
||||
t.Errorf("%v: unexpected result: %d", test, c)
|
||||
}
|
||||
} else {
|
||||
if c != test.b {
|
||||
t.Errorf("%v: overflow addition mutated source: %d", test, c)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestInt64AsCanonicalString(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
value int64
|
||||
scale Scale
|
||||
result string
|
||||
exponent int32
|
||||
}{
|
||||
{100, 0, "100", 0},
|
||||
{100, 1, "1", 3},
|
||||
{100, -1, "10", 0},
|
||||
{10800, -10, "1080", -9},
|
||||
} {
|
||||
r, exp := int64Amount{value: test.value, scale: test.scale}.AsCanonicalBytes(nil)
|
||||
if string(r) != test.result {
|
||||
t.Errorf("%v: unexpected result: %s", test, r)
|
||||
}
|
||||
if exp != test.exponent {
|
||||
t.Errorf("%v: unexpected exponent: %d", test, exp)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAmountSign(t *testing.T) {
|
||||
table := []struct {
|
||||
i int64Amount
|
||||
expect int
|
||||
}{
|
||||
{int64Amount{value: -50, scale: 1}, -1},
|
||||
{int64Amount{value: 0, scale: 1}, 0},
|
||||
{int64Amount{value: 300, scale: 1}, 1},
|
||||
{int64Amount{value: -50, scale: -8}, -1},
|
||||
{int64Amount{value: 50, scale: -8}, 1},
|
||||
{int64Amount{value: 0, scale: -8}, 0},
|
||||
{int64Amount{value: -50, scale: 0}, -1},
|
||||
{int64Amount{value: 50, scale: 0}, 1},
|
||||
{int64Amount{value: 0, scale: 0}, 0},
|
||||
}
|
||||
for _, testCase := range table {
|
||||
if result := testCase.i.Sign(); result != testCase.expect {
|
||||
t.Errorf("i: %v, Expected: %v, Actual: %v", testCase.i, testCase.expect, result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestInt64AmountAsScaledInt64(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
i int64Amount
|
||||
scaled Scale
|
||||
result int64
|
||||
ok bool
|
||||
}{
|
||||
{"test when i.scale < scaled ", int64Amount{value: 100, scale: 0}, 5, 1, true},
|
||||
{"test when i.scale = scaled", int64Amount{value: 100, scale: 1}, 1, 100, true},
|
||||
{"test when i.scale > scaled and result doesn't overflow", int64Amount{value: 100, scale: 5}, 2, 100000, true},
|
||||
{"test when i.scale > scaled and result overflows", int64Amount{value: 876, scale: 30}, 4, 0, false},
|
||||
{"test when i.scale < 0 and fraction exists", int64Amount{value: 93, scale: -1}, 0, 10, true},
|
||||
{"test when i.scale < 0 and fraction doesn't exist", int64Amount{value: 100, scale: -1}, 0, 10, true},
|
||||
{"test when i.value < 0 and fraction exists", int64Amount{value: -1932, scale: 2}, 4, -20, true},
|
||||
{"test when i.value < 0 and fraction doesn't exists", int64Amount{value: -1900, scale: 2}, 4, -19, true},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
r, ok := test.i.AsScaledInt64(test.scaled)
|
||||
if r != test.result {
|
||||
t.Errorf("%v: expected result: %d, got result: %d", test.name, test.result, r)
|
||||
}
|
||||
if ok != test.ok {
|
||||
t.Errorf("%v: expected ok: %t, got ok: %t", test.name, test.ok, ok)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
88
vendor/k8s.io/apimachinery/pkg/api/resource/generated.proto
generated
vendored
88
vendor/k8s.io/apimachinery/pkg/api/resource/generated.proto
generated
vendored
@ -1,88 +0,0 @@
|
||||
/*
|
||||
Copyright 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.
|
||||
*/
|
||||
|
||||
|
||||
// This file was autogenerated by go-to-protobuf. Do not edit it manually!
|
||||
|
||||
syntax = 'proto2';
|
||||
|
||||
package k8s.io.apimachinery.pkg.api.resource;
|
||||
|
||||
// Package-wide variables from generator "generated".
|
||||
option go_package = "resource";
|
||||
|
||||
// Quantity is a fixed-point representation of a number.
|
||||
// It provides convenient marshaling/unmarshaling in JSON and YAML,
|
||||
// in addition to String() and Int64() accessors.
|
||||
//
|
||||
// The serialization format is:
|
||||
//
|
||||
// <quantity> ::= <signedNumber><suffix>
|
||||
// (Note that <suffix> may be empty, from the "" case in <decimalSI>.)
|
||||
// <digit> ::= 0 | 1 | ... | 9
|
||||
// <digits> ::= <digit> | <digit><digits>
|
||||
// <number> ::= <digits> | <digits>.<digits> | <digits>. | .<digits>
|
||||
// <sign> ::= "+" | "-"
|
||||
// <signedNumber> ::= <number> | <sign><number>
|
||||
// <suffix> ::= <binarySI> | <decimalExponent> | <decimalSI>
|
||||
// <binarySI> ::= Ki | Mi | Gi | Ti | Pi | Ei
|
||||
// (International System of units; See: http://physics.nist.gov/cuu/Units/binary.html)
|
||||
// <decimalSI> ::= m | "" | k | M | G | T | P | E
|
||||
// (Note that 1024 = 1Ki but 1000 = 1k; I didn't choose the capitalization.)
|
||||
// <decimalExponent> ::= "e" <signedNumber> | "E" <signedNumber>
|
||||
//
|
||||
// No matter which of the three exponent forms is used, no quantity may represent
|
||||
// a number greater than 2^63-1 in magnitude, nor may it have more than 3 decimal
|
||||
// places. Numbers larger or more precise will be capped or rounded up.
|
||||
// (E.g.: 0.1m will rounded up to 1m.)
|
||||
// This may be extended in the future if we require larger or smaller quantities.
|
||||
//
|
||||
// When a Quantity is parsed from a string, it will remember the type of suffix
|
||||
// it had, and will use the same type again when it is serialized.
|
||||
//
|
||||
// Before serializing, Quantity will be put in "canonical form".
|
||||
// This means that Exponent/suffix will be adjusted up or down (with a
|
||||
// corresponding increase or decrease in Mantissa) such that:
|
||||
// a. No precision is lost
|
||||
// b. No fractional digits will be emitted
|
||||
// c. The exponent (or suffix) is as large as possible.
|
||||
// The sign will be omitted unless the number is negative.
|
||||
//
|
||||
// Examples:
|
||||
// 1.5 will be serialized as "1500m"
|
||||
// 1.5Gi will be serialized as "1536Mi"
|
||||
//
|
||||
// Note that the quantity will NEVER be internally represented by a
|
||||
// floating point number. That is the whole point of this exercise.
|
||||
//
|
||||
// Non-canonical values will still parse as long as they are well formed,
|
||||
// but will be re-emitted in their canonical form. (So always use canonical
|
||||
// form, or don't diff.)
|
||||
//
|
||||
// This format is intended to make it difficult to use these numbers without
|
||||
// writing some sort of special handling code in the hopes that that will
|
||||
// cause implementors to also use a fixed point implementation.
|
||||
//
|
||||
// +protobuf=true
|
||||
// +protobuf.embed=string
|
||||
// +protobuf.options.marshal=false
|
||||
// +protobuf.options.(gogoproto.goproto_stringer)=false
|
||||
// +k8s:deepcopy-gen=true
|
||||
// +k8s:openapi-gen=true
|
||||
message Quantity {
|
||||
optional string string = 1;
|
||||
}
|
||||
|
211
vendor/k8s.io/apimachinery/pkg/api/resource/math_test.go
generated
vendored
211
vendor/k8s.io/apimachinery/pkg/api/resource/math_test.go
generated
vendored
@ -1,211 +0,0 @@
|
||||
/*
|
||||
Copyright 2014 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 resource
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDetectOverflowAdd(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
a, b int64
|
||||
c int64
|
||||
ok bool
|
||||
}{
|
||||
{0, 0, 0, true},
|
||||
{-1, 1, 0, true},
|
||||
{0, 1, 1, true},
|
||||
{2, 2, 4, true},
|
||||
{2, -2, 0, true},
|
||||
{-2, -2, -4, true},
|
||||
|
||||
{mostNegative, -1, 0, false},
|
||||
{mostNegative, 1, mostNegative + 1, true},
|
||||
{mostPositive, -1, mostPositive - 1, true},
|
||||
{mostPositive, 1, 0, false},
|
||||
|
||||
{mostNegative, mostPositive, -1, true},
|
||||
{mostPositive, mostNegative, -1, true},
|
||||
{mostPositive, mostPositive, 0, false},
|
||||
{mostNegative, mostNegative, 0, false},
|
||||
|
||||
{-mostPositive, mostNegative, 0, false},
|
||||
{mostNegative, -mostPositive, 0, false},
|
||||
{-mostPositive, -mostPositive, 0, false},
|
||||
} {
|
||||
c, ok := int64Add(test.a, test.b)
|
||||
if c != test.c {
|
||||
t.Errorf("%v: unexpected result: %d", test, c)
|
||||
}
|
||||
if ok != test.ok {
|
||||
t.Errorf("%v: unexpected overflow: %t", test, ok)
|
||||
}
|
||||
// addition is commutative
|
||||
d, ok2 := int64Add(test.b, test.a)
|
||||
if c != d || ok != ok2 {
|
||||
t.Errorf("%v: not commutative: %d %t", test, d, ok2)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDetectOverflowMultiply(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
a, b int64
|
||||
c int64
|
||||
ok bool
|
||||
}{
|
||||
{0, 0, 0, true},
|
||||
{-1, 1, -1, true},
|
||||
{-1, -1, 1, true},
|
||||
{1, 1, 1, true},
|
||||
{0, 1, 0, true},
|
||||
{1, 0, 0, true},
|
||||
{2, 2, 4, true},
|
||||
{2, -2, -4, true},
|
||||
{-2, -2, 4, true},
|
||||
|
||||
{mostNegative, -1, 0, false},
|
||||
{mostNegative, 1, mostNegative, true},
|
||||
{mostPositive, -1, -mostPositive, true},
|
||||
{mostPositive, 1, mostPositive, true},
|
||||
|
||||
{mostNegative, mostPositive, 0, false},
|
||||
{mostPositive, mostNegative, 0, false},
|
||||
{mostPositive, mostPositive, 1, false},
|
||||
{mostNegative, mostNegative, 0, false},
|
||||
|
||||
{-mostPositive, mostNegative, 0, false},
|
||||
{mostNegative, -mostPositive, 0, false},
|
||||
{-mostPositive, -mostPositive, 1, false},
|
||||
} {
|
||||
c, ok := int64Multiply(test.a, test.b)
|
||||
if c != test.c {
|
||||
t.Errorf("%v: unexpected result: %d", test, c)
|
||||
}
|
||||
if ok != test.ok {
|
||||
t.Errorf("%v: unexpected overflow: %t", test, ok)
|
||||
}
|
||||
// multiplication is commutative
|
||||
d, ok2 := int64Multiply(test.b, test.a)
|
||||
if c != d || ok != ok2 {
|
||||
t.Errorf("%v: not commutative: %d %t", test, d, ok2)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDetectOverflowScale(t *testing.T) {
|
||||
for _, a := range []int64{0, -1, 1, 10, -10, mostPositive, mostNegative, -mostPositive} {
|
||||
for _, b := range []int64{1, 2, 10, 100, 1000, mostPositive} {
|
||||
expect, expectOk := int64Multiply(a, b)
|
||||
|
||||
c, ok := int64MultiplyScale(a, b)
|
||||
if c != expect {
|
||||
t.Errorf("%d*%d: unexpected result: %d", a, b, c)
|
||||
}
|
||||
if ok != expectOk {
|
||||
t.Errorf("%d*%d: unexpected overflow: %t", a, b, ok)
|
||||
}
|
||||
}
|
||||
for _, test := range []struct {
|
||||
base int64
|
||||
fn func(a int64) (int64, bool)
|
||||
}{
|
||||
{10, int64MultiplyScale10},
|
||||
{100, int64MultiplyScale100},
|
||||
{1000, int64MultiplyScale1000},
|
||||
} {
|
||||
expect, expectOk := int64Multiply(a, test.base)
|
||||
c, ok := test.fn(a)
|
||||
if c != expect {
|
||||
t.Errorf("%d*%d: unexpected result: %d", a, test.base, c)
|
||||
}
|
||||
if ok != expectOk {
|
||||
t.Errorf("%d*%d: unexpected overflow: %t", a, test.base, ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoveInt64Factors(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
value int64
|
||||
max int64
|
||||
result int64
|
||||
scale int32
|
||||
}{
|
||||
{100, 10, 1, 2},
|
||||
{100, 10, 1, 2},
|
||||
{100, 100, 1, 1},
|
||||
{1, 10, 1, 0},
|
||||
} {
|
||||
r, s := removeInt64Factors(test.value, test.max)
|
||||
if r != test.result {
|
||||
t.Errorf("%v: unexpected result: %d", test, r)
|
||||
}
|
||||
if s != test.scale {
|
||||
t.Errorf("%v: unexpected scale: %d", test, s)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNegativeScaleInt64(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
base int64
|
||||
scale Scale
|
||||
result int64
|
||||
exact bool
|
||||
}{
|
||||
{1234567, 0, 1234567, true},
|
||||
{1234567, 1, 123457, false},
|
||||
{1234567, 2, 12346, false},
|
||||
{1234567, 3, 1235, false},
|
||||
{1234567, 4, 124, false},
|
||||
|
||||
{-1234567, 0, -1234567, true},
|
||||
{-1234567, 1, -123457, false},
|
||||
{-1234567, 2, -12346, false},
|
||||
{-1234567, 3, -1235, false},
|
||||
{-1234567, 4, -124, false},
|
||||
|
||||
{1000, 0, 1000, true},
|
||||
{1000, 1, 100, true},
|
||||
{1000, 2, 10, true},
|
||||
{1000, 3, 1, true},
|
||||
{1000, 4, 1, false},
|
||||
|
||||
{-1000, 0, -1000, true},
|
||||
{-1000, 1, -100, true},
|
||||
{-1000, 2, -10, true},
|
||||
{-1000, 3, -1, true},
|
||||
{-1000, 4, -1, false},
|
||||
|
||||
{0, 0, 0, true},
|
||||
{0, 1, 0, true},
|
||||
{0, 2, 0, true},
|
||||
|
||||
// negative scale is undefined behavior
|
||||
{1000, -1, 1000, true},
|
||||
} {
|
||||
result, exact := negativeScaleInt64(test.base, test.scale)
|
||||
if result != test.result {
|
||||
t.Errorf("%v: unexpected result: %d", test, result)
|
||||
}
|
||||
if exact != test.exact {
|
||||
t.Errorf("%v: unexpected exact: %t", test, exact)
|
||||
}
|
||||
}
|
||||
}
|
59
vendor/k8s.io/apimachinery/pkg/api/resource/quantity_example_test.go
generated
vendored
59
vendor/k8s.io/apimachinery/pkg/api/resource/quantity_example_test.go
generated
vendored
@ -1,59 +0,0 @@
|
||||
/*
|
||||
Copyright 2014 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 resource_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"k8s.io/apimachinery/pkg/api/resource"
|
||||
)
|
||||
|
||||
func ExampleFormat() {
|
||||
memorySize := resource.NewQuantity(5*1024*1024*1024, resource.BinarySI)
|
||||
fmt.Printf("memorySize = %v\n", memorySize)
|
||||
|
||||
diskSize := resource.NewQuantity(5*1000*1000*1000, resource.DecimalSI)
|
||||
fmt.Printf("diskSize = %v\n", diskSize)
|
||||
|
||||
cores := resource.NewMilliQuantity(5300, resource.DecimalSI)
|
||||
fmt.Printf("cores = %v\n", cores)
|
||||
|
||||
// Output:
|
||||
// memorySize = 5Gi
|
||||
// diskSize = 5G
|
||||
// cores = 5300m
|
||||
}
|
||||
|
||||
func ExampleMustParse() {
|
||||
memorySize := resource.MustParse("5Gi")
|
||||
fmt.Printf("memorySize = %v (%v)\n", memorySize.Value(), memorySize.Format)
|
||||
|
||||
diskSize := resource.MustParse("5G")
|
||||
fmt.Printf("diskSize = %v (%v)\n", diskSize.Value(), diskSize.Format)
|
||||
|
||||
cores := resource.MustParse("5300m")
|
||||
fmt.Printf("milliCores = %v (%v)\n", cores.MilliValue(), cores.Format)
|
||||
|
||||
cores2 := resource.MustParse("5.4")
|
||||
fmt.Printf("milliCores = %v (%v)\n", cores2.MilliValue(), cores2.Format)
|
||||
|
||||
// Output:
|
||||
// memorySize = 5368709120 (BinarySI)
|
||||
// diskSize = 5000000000 (DecimalSI)
|
||||
// milliCores = 5300 (DecimalSI)
|
||||
// milliCores = 5400 (DecimalSI)
|
||||
}
|
103
vendor/k8s.io/apimachinery/pkg/api/resource/quantity_proto_test.go
generated
vendored
103
vendor/k8s.io/apimachinery/pkg/api/resource/quantity_proto_test.go
generated
vendored
@ -1,103 +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 resource
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
inf "gopkg.in/inf.v0"
|
||||
)
|
||||
|
||||
func TestQuantityProtoMarshal(t *testing.T) {
|
||||
// Test when d is nil
|
||||
table := []struct {
|
||||
quantity string
|
||||
expect Quantity
|
||||
}{
|
||||
{"0", Quantity{i: int64Amount{value: 0, scale: 0}, s: "0", Format: DecimalSI}},
|
||||
{"100m", Quantity{i: int64Amount{value: 100, scale: -3}, s: "100m", Format: DecimalSI}},
|
||||
{"50m", Quantity{i: int64Amount{value: 50, scale: -3}, s: "50m", Format: DecimalSI}},
|
||||
{"10000T", Quantity{i: int64Amount{value: 10000, scale: 12}, s: "10000T", Format: DecimalSI}},
|
||||
}
|
||||
for _, testCase := range table {
|
||||
q := MustParse(testCase.quantity)
|
||||
// Won't currently get an error as MarshalTo can't return one
|
||||
result, _ := q.Marshal()
|
||||
q.MarshalTo(result)
|
||||
if q.Cmp(testCase.expect) != 0 {
|
||||
t.Errorf("Expected: %v, Actual: %v", testCase.expect, q)
|
||||
}
|
||||
}
|
||||
// Test when i is {0,0}
|
||||
table2 := []struct {
|
||||
dec *inf.Dec
|
||||
expect Quantity
|
||||
}{
|
||||
{dec(0, 0).Dec, Quantity{i: int64Amount{value: 0, scale: 0}, d: infDecAmount{dec(0, 0).Dec}, s: "0", Format: DecimalSI}},
|
||||
{dec(10, 0).Dec, Quantity{i: int64Amount{value: 0, scale: 0}, d: infDecAmount{dec(10, 0).Dec}, s: "10", Format: DecimalSI}},
|
||||
{dec(-10, 0).Dec, Quantity{i: int64Amount{value: 0, scale: 0}, d: infDecAmount{dec(-10, 0).Dec}, s: "-10", Format: DecimalSI}},
|
||||
}
|
||||
for _, testCase := range table2 {
|
||||
q := Quantity{d: infDecAmount{testCase.dec}, Format: DecimalSI}
|
||||
// Won't currently get an error as MarshalTo can't return one
|
||||
result, _ := q.Marshal()
|
||||
q.Unmarshal(result)
|
||||
if q.Cmp(testCase.expect) != 0 {
|
||||
t.Errorf("Expected: %v, Actual: %v", testCase.expect, q)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuantityProtoUnmarshal(t *testing.T) {
|
||||
// Test when d is nil
|
||||
table := []struct {
|
||||
input Quantity
|
||||
expect string
|
||||
}{
|
||||
{Quantity{i: int64Amount{value: 0, scale: 0}, s: "0", Format: DecimalSI}, "0"},
|
||||
{Quantity{i: int64Amount{value: 100, scale: -3}, s: "100m", Format: DecimalSI}, "100m"},
|
||||
{Quantity{i: int64Amount{value: 50, scale: -3}, s: "50m", Format: DecimalSI}, "50m"},
|
||||
{Quantity{i: int64Amount{value: 10000, scale: 12}, s: "10000T", Format: DecimalSI}, "10000T"},
|
||||
}
|
||||
for _, testCase := range table {
|
||||
var inputQ Quantity
|
||||
expectQ := MustParse(testCase.expect)
|
||||
inputByteArray, _ := testCase.input.Marshal()
|
||||
inputQ.Unmarshal(inputByteArray)
|
||||
if inputQ.Cmp(expectQ) != 0 {
|
||||
t.Errorf("Expected: %v, Actual: %v", inputQ, expectQ)
|
||||
}
|
||||
}
|
||||
// Test when i is {0,0}
|
||||
table2 := []struct {
|
||||
input Quantity
|
||||
expect *inf.Dec
|
||||
}{
|
||||
{Quantity{i: int64Amount{value: 0, scale: 0}, d: infDecAmount{dec(0, 0).Dec}, s: "0", Format: DecimalSI}, dec(0, 0).Dec},
|
||||
{Quantity{i: int64Amount{value: 0, scale: 0}, d: infDecAmount{dec(10, 0).Dec}, s: "10", Format: DecimalSI}, dec(10, 0).Dec},
|
||||
{Quantity{i: int64Amount{value: 0, scale: 0}, d: infDecAmount{dec(-10, 0).Dec}, s: "-10", Format: DecimalSI}, dec(-10, 0).Dec},
|
||||
}
|
||||
for _, testCase := range table2 {
|
||||
var inputQ Quantity
|
||||
expectQ := Quantity{d: infDecAmount{testCase.expect}, Format: DecimalSI}
|
||||
inputByteArray, _ := testCase.input.Marshal()
|
||||
inputQ.Unmarshal(inputByteArray)
|
||||
if inputQ.Cmp(expectQ) != 0 {
|
||||
t.Errorf("Expected: %v, Actual: %v", inputQ, expectQ)
|
||||
}
|
||||
}
|
||||
}
|
1352
vendor/k8s.io/apimachinery/pkg/api/resource/quantity_test.go
generated
vendored
1352
vendor/k8s.io/apimachinery/pkg/api/resource/quantity_test.go
generated
vendored
File diff suppressed because it is too large
Load Diff
85
vendor/k8s.io/apimachinery/pkg/api/resource/scale_int_test.go
generated
vendored
85
vendor/k8s.io/apimachinery/pkg/api/resource/scale_int_test.go
generated
vendored
@ -1,85 +0,0 @@
|
||||
/*
|
||||
Copyright 2015 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 resource
|
||||
|
||||
import (
|
||||
"math"
|
||||
"math/big"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestScaledValueInternal(t *testing.T) {
|
||||
tests := []struct {
|
||||
unscaled *big.Int
|
||||
scale int
|
||||
newScale int
|
||||
|
||||
want int64
|
||||
}{
|
||||
// remain scale
|
||||
{big.NewInt(1000), 0, 0, 1000},
|
||||
|
||||
// scale down
|
||||
{big.NewInt(1000), 0, -3, 1},
|
||||
{big.NewInt(1000), 3, 0, 1},
|
||||
{big.NewInt(0), 3, 0, 0},
|
||||
|
||||
// always round up
|
||||
{big.NewInt(999), 3, 0, 1},
|
||||
{big.NewInt(500), 3, 0, 1},
|
||||
{big.NewInt(499), 3, 0, 1},
|
||||
{big.NewInt(1), 3, 0, 1},
|
||||
// large scaled value does not lose precision
|
||||
{big.NewInt(0).Sub(maxInt64, bigOne), 1, 0, (math.MaxInt64-1)/10 + 1},
|
||||
// large intermediate result.
|
||||
{big.NewInt(1).Exp(big.NewInt(10), big.NewInt(100), nil), 100, 0, 1},
|
||||
|
||||
// scale up
|
||||
{big.NewInt(0), 0, 3, 0},
|
||||
{big.NewInt(1), 0, 3, 1000},
|
||||
{big.NewInt(1), -3, 0, 1000},
|
||||
{big.NewInt(1000), -3, 2, 100000000},
|
||||
{big.NewInt(0).Div(big.NewInt(math.MaxInt64), bigThousand), 0, 3,
|
||||
(math.MaxInt64 / 1000) * 1000},
|
||||
}
|
||||
|
||||
for i, tt := range tests {
|
||||
old := (&big.Int{}).Set(tt.unscaled)
|
||||
got := scaledValue(tt.unscaled, tt.scale, tt.newScale)
|
||||
if got != tt.want {
|
||||
t.Errorf("#%d: got = %v, want %v", i, got, tt.want)
|
||||
}
|
||||
if tt.unscaled.Cmp(old) != 0 {
|
||||
t.Errorf("#%d: unscaled = %v, want %v", i, tt.unscaled, old)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkScaledValueSmall(b *testing.B) {
|
||||
s := big.NewInt(1000)
|
||||
for i := 0; i < b.N; i++ {
|
||||
scaledValue(s, 3, 0)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkScaledValueLarge(b *testing.B) {
|
||||
s := big.NewInt(math.MaxInt64)
|
||||
s.Mul(s, big.NewInt(1000))
|
||||
for i := 0; i < b.N; i++ {
|
||||
scaledValue(s, 10, 0)
|
||||
}
|
||||
}
|
18
vendor/k8s.io/apimachinery/pkg/api/validation/doc.go
generated
vendored
18
vendor/k8s.io/apimachinery/pkg/api/validation/doc.go
generated
vendored
@ -1,18 +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 validation contains generic api type validation functions.
|
||||
package validation // import "k8s.io/apimachinery/pkg/api/validation"
|
85
vendor/k8s.io/apimachinery/pkg/api/validation/generic.go
generated
vendored
85
vendor/k8s.io/apimachinery/pkg/api/validation/generic.go
generated
vendored
@ -1,85 +0,0 @@
|
||||
/*
|
||||
Copyright 2014 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 validation
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"k8s.io/apimachinery/pkg/util/validation"
|
||||
"k8s.io/apimachinery/pkg/util/validation/field"
|
||||
)
|
||||
|
||||
const IsNegativeErrorMsg string = `must be greater than or equal to 0`
|
||||
|
||||
// ValidateNameFunc validates that the provided name is valid for a given resource type.
|
||||
// Not all resources have the same validation rules for names. Prefix is true
|
||||
// if the name will have a value appended to it. If the name is not valid,
|
||||
// this returns a list of descriptions of individual characteristics of the
|
||||
// value that were not valid. Otherwise this returns an empty list or nil.
|
||||
type ValidateNameFunc func(name string, prefix bool) []string
|
||||
|
||||
// NameIsDNSSubdomain is a ValidateNameFunc for names that must be a DNS subdomain.
|
||||
func NameIsDNSSubdomain(name string, prefix bool) []string {
|
||||
if prefix {
|
||||
name = maskTrailingDash(name)
|
||||
}
|
||||
return validation.IsDNS1123Subdomain(name)
|
||||
}
|
||||
|
||||
// NameIsDNSLabel is a ValidateNameFunc for names that must be a DNS 1123 label.
|
||||
func NameIsDNSLabel(name string, prefix bool) []string {
|
||||
if prefix {
|
||||
name = maskTrailingDash(name)
|
||||
}
|
||||
return validation.IsDNS1123Label(name)
|
||||
}
|
||||
|
||||
// NameIsDNS1035Label is a ValidateNameFunc for names that must be a DNS 952 label.
|
||||
func NameIsDNS1035Label(name string, prefix bool) []string {
|
||||
if prefix {
|
||||
name = maskTrailingDash(name)
|
||||
}
|
||||
return validation.IsDNS1035Label(name)
|
||||
}
|
||||
|
||||
// ValidateNamespaceName can be used to check whether the given namespace name is valid.
|
||||
// Prefix indicates this name will be used as part of generation, in which case
|
||||
// trailing dashes are allowed.
|
||||
var ValidateNamespaceName = NameIsDNSLabel
|
||||
|
||||
// ValidateServiceAccountName can be used to check whether the given service account name is valid.
|
||||
// Prefix indicates this name will be used as part of generation, in which case
|
||||
// trailing dashes are allowed.
|
||||
var ValidateServiceAccountName = NameIsDNSSubdomain
|
||||
|
||||
// maskTrailingDash replaces the final character of a string with a subdomain safe
|
||||
// value if is a dash.
|
||||
func maskTrailingDash(name string) string {
|
||||
if strings.HasSuffix(name, "-") {
|
||||
return name[:len(name)-2] + "a"
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
// Validates that given value is not negative.
|
||||
func ValidateNonnegativeField(value int64, fldPath *field.Path) field.ErrorList {
|
||||
allErrs := field.ErrorList{}
|
||||
if value < 0 {
|
||||
allErrs = append(allErrs, field.Invalid(fldPath, value, IsNegativeErrorMsg))
|
||||
}
|
||||
return allErrs
|
||||
}
|
308
vendor/k8s.io/apimachinery/pkg/api/validation/objectmeta.go
generated
vendored
308
vendor/k8s.io/apimachinery/pkg/api/validation/objectmeta.go
generated
vendored
@ -1,308 +0,0 @@
|
||||
/*
|
||||
Copyright 2014 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 validation
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
apiequality "k8s.io/apimachinery/pkg/api/equality"
|
||||
"k8s.io/apimachinery/pkg/api/meta"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
v1validation "k8s.io/apimachinery/pkg/apis/meta/v1/validation"
|
||||
"k8s.io/apimachinery/pkg/runtime/schema"
|
||||
"k8s.io/apimachinery/pkg/util/sets"
|
||||
"k8s.io/apimachinery/pkg/util/validation"
|
||||
"k8s.io/apimachinery/pkg/util/validation/field"
|
||||
)
|
||||
|
||||
const FieldImmutableErrorMsg string = `field is immutable`
|
||||
|
||||
const totalAnnotationSizeLimitB int = 256 * (1 << 10) // 256 kB
|
||||
|
||||
// BannedOwners is a black list of object that are not allowed to be owners.
|
||||
var BannedOwners = map[schema.GroupVersionKind]struct{}{
|
||||
{Group: "", Version: "v1", Kind: "Event"}: {},
|
||||
}
|
||||
|
||||
// ValidateClusterName can be used to check whether the given cluster name is valid.
|
||||
var ValidateClusterName = NameIsDNS1035Label
|
||||
|
||||
// ValidateAnnotations validates that a set of annotations are correctly defined.
|
||||
func ValidateAnnotations(annotations map[string]string, fldPath *field.Path) field.ErrorList {
|
||||
allErrs := field.ErrorList{}
|
||||
var totalSize int64
|
||||
for k, v := range annotations {
|
||||
for _, msg := range validation.IsQualifiedName(strings.ToLower(k)) {
|
||||
allErrs = append(allErrs, field.Invalid(fldPath, k, msg))
|
||||
}
|
||||
totalSize += (int64)(len(k)) + (int64)(len(v))
|
||||
}
|
||||
if totalSize > (int64)(totalAnnotationSizeLimitB) {
|
||||
allErrs = append(allErrs, field.TooLong(fldPath, "", totalAnnotationSizeLimitB))
|
||||
}
|
||||
return allErrs
|
||||
}
|
||||
|
||||
func validateOwnerReference(ownerReference metav1.OwnerReference, fldPath *field.Path) field.ErrorList {
|
||||
allErrs := field.ErrorList{}
|
||||
gvk := schema.FromAPIVersionAndKind(ownerReference.APIVersion, ownerReference.Kind)
|
||||
// gvk.Group is empty for the legacy group.
|
||||
if len(gvk.Version) == 0 {
|
||||
allErrs = append(allErrs, field.Invalid(fldPath.Child("apiVersion"), ownerReference.APIVersion, "version must not be empty"))
|
||||
}
|
||||
if len(gvk.Kind) == 0 {
|
||||
allErrs = append(allErrs, field.Invalid(fldPath.Child("kind"), ownerReference.Kind, "kind must not be empty"))
|
||||
}
|
||||
if len(ownerReference.Name) == 0 {
|
||||
allErrs = append(allErrs, field.Invalid(fldPath.Child("name"), ownerReference.Name, "name must not be empty"))
|
||||
}
|
||||
if len(ownerReference.UID) == 0 {
|
||||
allErrs = append(allErrs, field.Invalid(fldPath.Child("uid"), ownerReference.UID, "uid must not be empty"))
|
||||
}
|
||||
if _, ok := BannedOwners[gvk]; ok {
|
||||
allErrs = append(allErrs, field.Invalid(fldPath, ownerReference, fmt.Sprintf("%s is disallowed from being an owner", gvk)))
|
||||
}
|
||||
return allErrs
|
||||
}
|
||||
|
||||
func ValidateOwnerReferences(ownerReferences []metav1.OwnerReference, fldPath *field.Path) field.ErrorList {
|
||||
allErrs := field.ErrorList{}
|
||||
controllerName := ""
|
||||
for _, ref := range ownerReferences {
|
||||
allErrs = append(allErrs, validateOwnerReference(ref, fldPath)...)
|
||||
if ref.Controller != nil && *ref.Controller {
|
||||
if controllerName != "" {
|
||||
allErrs = append(allErrs, field.Invalid(fldPath, ownerReferences,
|
||||
fmt.Sprintf("Only one reference can have Controller set to true. Found \"true\" in references for %v and %v", controllerName, ref.Name)))
|
||||
} else {
|
||||
controllerName = ref.Name
|
||||
}
|
||||
}
|
||||
}
|
||||
return allErrs
|
||||
}
|
||||
|
||||
// Validate finalizer names
|
||||
func ValidateFinalizerName(stringValue string, fldPath *field.Path) field.ErrorList {
|
||||
allErrs := field.ErrorList{}
|
||||
for _, msg := range validation.IsQualifiedName(stringValue) {
|
||||
allErrs = append(allErrs, field.Invalid(fldPath, stringValue, msg))
|
||||
}
|
||||
|
||||
return allErrs
|
||||
}
|
||||
|
||||
func ValidateNoNewFinalizers(newFinalizers []string, oldFinalizers []string, fldPath *field.Path) field.ErrorList {
|
||||
allErrs := field.ErrorList{}
|
||||
extra := sets.NewString(newFinalizers...).Difference(sets.NewString(oldFinalizers...))
|
||||
if len(extra) != 0 {
|
||||
allErrs = append(allErrs, field.Forbidden(fldPath, fmt.Sprintf("no new finalizers can be added if the object is being deleted, found new finalizers %#v", extra.List())))
|
||||
}
|
||||
return allErrs
|
||||
}
|
||||
|
||||
func ValidateImmutableField(newVal, oldVal interface{}, fldPath *field.Path) field.ErrorList {
|
||||
allErrs := field.ErrorList{}
|
||||
if !apiequality.Semantic.DeepEqual(oldVal, newVal) {
|
||||
allErrs = append(allErrs, field.Invalid(fldPath, newVal, FieldImmutableErrorMsg))
|
||||
}
|
||||
return allErrs
|
||||
}
|
||||
|
||||
// ValidateObjectMeta validates an object's metadata on creation. It expects that name generation has already
|
||||
// been performed.
|
||||
// It doesn't return an error for rootscoped resources with namespace, because namespace should already be cleared before.
|
||||
func ValidateObjectMeta(objMeta *metav1.ObjectMeta, requiresNamespace bool, nameFn ValidateNameFunc, fldPath *field.Path) field.ErrorList {
|
||||
metadata, err := meta.Accessor(objMeta)
|
||||
if err != nil {
|
||||
allErrs := field.ErrorList{}
|
||||
allErrs = append(allErrs, field.Invalid(fldPath, objMeta, err.Error()))
|
||||
return allErrs
|
||||
}
|
||||
return ValidateObjectMetaAccessor(metadata, requiresNamespace, nameFn, fldPath)
|
||||
}
|
||||
|
||||
// ValidateObjectMeta validates an object's metadata on creation. It expects that name generation has already
|
||||
// been performed.
|
||||
// It doesn't return an error for rootscoped resources with namespace, because namespace should already be cleared before.
|
||||
func ValidateObjectMetaAccessor(meta metav1.Object, requiresNamespace bool, nameFn ValidateNameFunc, fldPath *field.Path) field.ErrorList {
|
||||
allErrs := field.ErrorList{}
|
||||
|
||||
if len(meta.GetGenerateName()) != 0 {
|
||||
for _, msg := range nameFn(meta.GetGenerateName(), true) {
|
||||
allErrs = append(allErrs, field.Invalid(fldPath.Child("generateName"), meta.GetGenerateName(), msg))
|
||||
}
|
||||
}
|
||||
// If the generated name validates, but the calculated value does not, it's a problem with generation, and we
|
||||
// report it here. This may confuse users, but indicates a programming bug and still must be validated.
|
||||
// If there are multiple fields out of which one is required then add an or as a separator
|
||||
if len(meta.GetName()) == 0 {
|
||||
allErrs = append(allErrs, field.Required(fldPath.Child("name"), "name or generateName is required"))
|
||||
} else {
|
||||
for _, msg := range nameFn(meta.GetName(), false) {
|
||||
allErrs = append(allErrs, field.Invalid(fldPath.Child("name"), meta.GetName(), msg))
|
||||
}
|
||||
}
|
||||
if requiresNamespace {
|
||||
if len(meta.GetNamespace()) == 0 {
|
||||
allErrs = append(allErrs, field.Required(fldPath.Child("namespace"), ""))
|
||||
} else {
|
||||
for _, msg := range ValidateNamespaceName(meta.GetNamespace(), false) {
|
||||
allErrs = append(allErrs, field.Invalid(fldPath.Child("namespace"), meta.GetNamespace(), msg))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if len(meta.GetNamespace()) != 0 {
|
||||
allErrs = append(allErrs, field.Forbidden(fldPath.Child("namespace"), "not allowed on this type"))
|
||||
}
|
||||
}
|
||||
if len(meta.GetClusterName()) != 0 {
|
||||
for _, msg := range ValidateClusterName(meta.GetClusterName(), false) {
|
||||
allErrs = append(allErrs, field.Invalid(fldPath.Child("clusterName"), meta.GetClusterName(), msg))
|
||||
}
|
||||
}
|
||||
allErrs = append(allErrs, ValidateNonnegativeField(meta.GetGeneration(), fldPath.Child("generation"))...)
|
||||
allErrs = append(allErrs, v1validation.ValidateLabels(meta.GetLabels(), fldPath.Child("labels"))...)
|
||||
allErrs = append(allErrs, ValidateAnnotations(meta.GetAnnotations(), fldPath.Child("annotations"))...)
|
||||
allErrs = append(allErrs, ValidateOwnerReferences(meta.GetOwnerReferences(), fldPath.Child("ownerReferences"))...)
|
||||
allErrs = append(allErrs, ValidateInitializers(meta.GetInitializers(), fldPath.Child("initializers"))...)
|
||||
allErrs = append(allErrs, ValidateFinalizers(meta.GetFinalizers(), fldPath.Child("finalizers"))...)
|
||||
return allErrs
|
||||
}
|
||||
|
||||
func ValidateInitializers(initializers *metav1.Initializers, fldPath *field.Path) field.ErrorList {
|
||||
var allErrs field.ErrorList
|
||||
if initializers == nil {
|
||||
return allErrs
|
||||
}
|
||||
for i, initializer := range initializers.Pending {
|
||||
allErrs = append(allErrs, validation.IsFullyQualifiedName(fldPath.Child("pending").Index(i).Child("name"), initializer.Name)...)
|
||||
}
|
||||
allErrs = append(allErrs, validateInitializersResult(initializers.Result, fldPath.Child("result"))...)
|
||||
return allErrs
|
||||
}
|
||||
|
||||
func validateInitializersResult(result *metav1.Status, fldPath *field.Path) field.ErrorList {
|
||||
var allErrs field.ErrorList
|
||||
if result == nil {
|
||||
return allErrs
|
||||
}
|
||||
switch result.Status {
|
||||
case metav1.StatusFailure:
|
||||
default:
|
||||
allErrs = append(allErrs, field.Invalid(fldPath.Child("status"), result.Status, "must be 'Failure'"))
|
||||
}
|
||||
return allErrs
|
||||
}
|
||||
|
||||
// ValidateFinalizers tests if the finalizers name are valid, and if there are conflicting finalizers.
|
||||
func ValidateFinalizers(finalizers []string, fldPath *field.Path) field.ErrorList {
|
||||
allErrs := field.ErrorList{}
|
||||
hasFinalizerOrphanDependents := false
|
||||
hasFinalizerDeleteDependents := false
|
||||
for _, finalizer := range finalizers {
|
||||
allErrs = append(allErrs, ValidateFinalizerName(finalizer, fldPath)...)
|
||||
if finalizer == metav1.FinalizerOrphanDependents {
|
||||
hasFinalizerOrphanDependents = true
|
||||
}
|
||||
if finalizer == metav1.FinalizerDeleteDependents {
|
||||
hasFinalizerDeleteDependents = true
|
||||
}
|
||||
}
|
||||
if hasFinalizerDeleteDependents && hasFinalizerOrphanDependents {
|
||||
allErrs = append(allErrs, field.Invalid(fldPath, finalizers, fmt.Sprintf("finalizer %s and %s cannot be both set", metav1.FinalizerOrphanDependents, metav1.FinalizerDeleteDependents)))
|
||||
}
|
||||
return allErrs
|
||||
}
|
||||
|
||||
// ValidateObjectMetaUpdate validates an object's metadata when updated
|
||||
func ValidateObjectMetaUpdate(newMeta, oldMeta *metav1.ObjectMeta, fldPath *field.Path) field.ErrorList {
|
||||
newMetadata, err := meta.Accessor(newMeta)
|
||||
if err != nil {
|
||||
allErrs := field.ErrorList{}
|
||||
allErrs = append(allErrs, field.Invalid(fldPath, newMeta, err.Error()))
|
||||
return allErrs
|
||||
}
|
||||
oldMetadata, err := meta.Accessor(oldMeta)
|
||||
if err != nil {
|
||||
allErrs := field.ErrorList{}
|
||||
allErrs = append(allErrs, field.Invalid(fldPath, oldMeta, err.Error()))
|
||||
return allErrs
|
||||
}
|
||||
return ValidateObjectMetaAccessorUpdate(newMetadata, oldMetadata, fldPath)
|
||||
}
|
||||
|
||||
func ValidateObjectMetaAccessorUpdate(newMeta, oldMeta metav1.Object, fldPath *field.Path) field.ErrorList {
|
||||
var allErrs field.ErrorList
|
||||
|
||||
// Finalizers cannot be added if the object is already being deleted.
|
||||
if oldMeta.GetDeletionTimestamp() != nil {
|
||||
allErrs = append(allErrs, ValidateNoNewFinalizers(newMeta.GetFinalizers(), oldMeta.GetFinalizers(), fldPath.Child("finalizers"))...)
|
||||
}
|
||||
|
||||
// Reject updates that don't specify a resource version
|
||||
if len(newMeta.GetResourceVersion()) == 0 {
|
||||
allErrs = append(allErrs, field.Invalid(fldPath.Child("resourceVersion"), newMeta.GetResourceVersion(), "must be specified for an update"))
|
||||
}
|
||||
|
||||
// Generation shouldn't be decremented
|
||||
if newMeta.GetGeneration() < oldMeta.GetGeneration() {
|
||||
allErrs = append(allErrs, field.Invalid(fldPath.Child("generation"), newMeta.GetGeneration(), "must not be decremented"))
|
||||
}
|
||||
|
||||
allErrs = append(allErrs, ValidateInitializersUpdate(newMeta.GetInitializers(), oldMeta.GetInitializers(), fldPath.Child("initializers"))...)
|
||||
|
||||
allErrs = append(allErrs, ValidateImmutableField(newMeta.GetName(), oldMeta.GetName(), fldPath.Child("name"))...)
|
||||
allErrs = append(allErrs, ValidateImmutableField(newMeta.GetNamespace(), oldMeta.GetNamespace(), fldPath.Child("namespace"))...)
|
||||
allErrs = append(allErrs, ValidateImmutableField(newMeta.GetUID(), oldMeta.GetUID(), fldPath.Child("uid"))...)
|
||||
allErrs = append(allErrs, ValidateImmutableField(newMeta.GetCreationTimestamp(), oldMeta.GetCreationTimestamp(), fldPath.Child("creationTimestamp"))...)
|
||||
allErrs = append(allErrs, ValidateImmutableField(newMeta.GetDeletionTimestamp(), oldMeta.GetDeletionTimestamp(), fldPath.Child("deletionTimestamp"))...)
|
||||
allErrs = append(allErrs, ValidateImmutableField(newMeta.GetDeletionGracePeriodSeconds(), oldMeta.GetDeletionGracePeriodSeconds(), fldPath.Child("deletionGracePeriodSeconds"))...)
|
||||
allErrs = append(allErrs, ValidateImmutableField(newMeta.GetClusterName(), oldMeta.GetClusterName(), fldPath.Child("clusterName"))...)
|
||||
|
||||
allErrs = append(allErrs, v1validation.ValidateLabels(newMeta.GetLabels(), fldPath.Child("labels"))...)
|
||||
allErrs = append(allErrs, ValidateAnnotations(newMeta.GetAnnotations(), fldPath.Child("annotations"))...)
|
||||
allErrs = append(allErrs, ValidateOwnerReferences(newMeta.GetOwnerReferences(), fldPath.Child("ownerReferences"))...)
|
||||
|
||||
return allErrs
|
||||
}
|
||||
|
||||
// ValidateInitializersUpdate checks the update of the metadata initializers field
|
||||
func ValidateInitializersUpdate(newInit, oldInit *metav1.Initializers, fldPath *field.Path) field.ErrorList {
|
||||
var allErrs field.ErrorList
|
||||
switch {
|
||||
case oldInit == nil && newInit != nil:
|
||||
// Initializers may not be set on new objects
|
||||
allErrs = append(allErrs, field.Invalid(fldPath, nil, "field is immutable once initialization has completed"))
|
||||
case oldInit != nil && newInit == nil:
|
||||
// this is a valid transition and means initialization was successful
|
||||
case oldInit != nil && newInit != nil:
|
||||
// validate changes to initializers
|
||||
switch {
|
||||
case oldInit.Result == nil && newInit.Result != nil:
|
||||
// setting a result is allowed
|
||||
allErrs = append(allErrs, validateInitializersResult(newInit.Result, fldPath.Child("result"))...)
|
||||
case oldInit.Result != nil:
|
||||
// setting Result implies permanent failure, and all future updates will be prevented
|
||||
allErrs = append(allErrs, ValidateImmutableField(newInit.Result, oldInit.Result, fldPath.Child("result"))...)
|
||||
default:
|
||||
// leaving the result nil is allowed
|
||||
}
|
||||
}
|
||||
return allErrs
|
||||
}
|
500
vendor/k8s.io/apimachinery/pkg/api/validation/objectmeta_test.go
generated
vendored
500
vendor/k8s.io/apimachinery/pkg/api/validation/objectmeta_test.go
generated
vendored
@ -1,500 +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 validation
|
||||
|
||||
import (
|
||||
"math/rand"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/util/validation/field"
|
||||
)
|
||||
|
||||
const (
|
||||
maxLengthErrMsg = "must be no more than"
|
||||
namePartErrMsg = "name part must consist of"
|
||||
nameErrMsg = "a qualified name must consist of"
|
||||
)
|
||||
|
||||
// Ensure custom name functions are allowed
|
||||
func TestValidateObjectMetaCustomName(t *testing.T) {
|
||||
errs := ValidateObjectMeta(
|
||||
&metav1.ObjectMeta{Name: "test", GenerateName: "foo"},
|
||||
false,
|
||||
func(s string, prefix bool) []string {
|
||||
if s == "test" {
|
||||
return nil
|
||||
}
|
||||
return []string{"name-gen"}
|
||||
},
|
||||
field.NewPath("field"))
|
||||
if len(errs) != 1 {
|
||||
t.Fatalf("unexpected errors: %v", errs)
|
||||
}
|
||||
if !strings.Contains(errs[0].Error(), "name-gen") {
|
||||
t.Errorf("unexpected error message: %v", errs)
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure namespace names follow dns label format
|
||||
func TestValidateObjectMetaNamespaces(t *testing.T) {
|
||||
errs := ValidateObjectMeta(
|
||||
&metav1.ObjectMeta{Name: "test", Namespace: "foo.bar"},
|
||||
true,
|
||||
func(s string, prefix bool) []string {
|
||||
return nil
|
||||
},
|
||||
field.NewPath("field"))
|
||||
if len(errs) != 1 {
|
||||
t.Fatalf("unexpected errors: %v", errs)
|
||||
}
|
||||
if !strings.Contains(errs[0].Error(), `Invalid value: "foo.bar"`) {
|
||||
t.Errorf("unexpected error message: %v", errs)
|
||||
}
|
||||
maxLength := 63
|
||||
letters := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
|
||||
b := make([]rune, maxLength+1)
|
||||
for i := range b {
|
||||
b[i] = letters[rand.Intn(len(letters))]
|
||||
}
|
||||
errs = ValidateObjectMeta(
|
||||
&metav1.ObjectMeta{Name: "test", Namespace: string(b)},
|
||||
true,
|
||||
func(s string, prefix bool) []string {
|
||||
return nil
|
||||
},
|
||||
field.NewPath("field"))
|
||||
if len(errs) != 2 {
|
||||
t.Fatalf("unexpected errors: %v", errs)
|
||||
}
|
||||
if !strings.Contains(errs[0].Error(), "Invalid value") || !strings.Contains(errs[1].Error(), "Invalid value") {
|
||||
t.Errorf("unexpected error message: %v", errs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateObjectMetaOwnerReferences(t *testing.T) {
|
||||
trueVar := true
|
||||
falseVar := false
|
||||
testCases := []struct {
|
||||
description string
|
||||
ownerReferences []metav1.OwnerReference
|
||||
expectError bool
|
||||
expectedErrorMessage string
|
||||
}{
|
||||
{
|
||||
description: "simple success - third party extension.",
|
||||
ownerReferences: []metav1.OwnerReference{
|
||||
{
|
||||
APIVersion: "customresourceVersion",
|
||||
Kind: "customresourceKind",
|
||||
Name: "name",
|
||||
UID: "1",
|
||||
},
|
||||
},
|
||||
expectError: false,
|
||||
expectedErrorMessage: "",
|
||||
},
|
||||
{
|
||||
description: "simple failures - event shouldn't be set as an owner",
|
||||
ownerReferences: []metav1.OwnerReference{
|
||||
{
|
||||
APIVersion: "v1",
|
||||
Kind: "Event",
|
||||
Name: "name",
|
||||
UID: "1",
|
||||
},
|
||||
},
|
||||
expectError: true,
|
||||
expectedErrorMessage: "is disallowed from being an owner",
|
||||
},
|
||||
{
|
||||
description: "simple controller ref success - one reference with Controller set",
|
||||
ownerReferences: []metav1.OwnerReference{
|
||||
{
|
||||
APIVersion: "customresourceVersion",
|
||||
Kind: "customresourceKind",
|
||||
Name: "name",
|
||||
UID: "1",
|
||||
Controller: &falseVar,
|
||||
},
|
||||
{
|
||||
APIVersion: "customresourceVersion",
|
||||
Kind: "customresourceKind",
|
||||
Name: "name",
|
||||
UID: "2",
|
||||
Controller: &trueVar,
|
||||
},
|
||||
{
|
||||
APIVersion: "customresourceVersion",
|
||||
Kind: "customresourceKind",
|
||||
Name: "name",
|
||||
UID: "3",
|
||||
Controller: &falseVar,
|
||||
},
|
||||
{
|
||||
APIVersion: "customresourceVersion",
|
||||
Kind: "customresourceKind",
|
||||
Name: "name",
|
||||
UID: "4",
|
||||
},
|
||||
},
|
||||
expectError: false,
|
||||
expectedErrorMessage: "",
|
||||
},
|
||||
{
|
||||
description: "simple controller ref failure - two references with Controller set",
|
||||
ownerReferences: []metav1.OwnerReference{
|
||||
{
|
||||
APIVersion: "customresourceVersion",
|
||||
Kind: "customresourceKind",
|
||||
Name: "name",
|
||||
UID: "1",
|
||||
Controller: &falseVar,
|
||||
},
|
||||
{
|
||||
APIVersion: "customresourceVersion",
|
||||
Kind: "customresourceKind",
|
||||
Name: "name",
|
||||
UID: "2",
|
||||
Controller: &trueVar,
|
||||
},
|
||||
{
|
||||
APIVersion: "customresourceVersion",
|
||||
Kind: "customresourceKind",
|
||||
Name: "name",
|
||||
UID: "3",
|
||||
Controller: &trueVar,
|
||||
},
|
||||
{
|
||||
APIVersion: "customresourceVersion",
|
||||
Kind: "customresourceKind",
|
||||
Name: "name",
|
||||
UID: "4",
|
||||
},
|
||||
},
|
||||
expectError: true,
|
||||
expectedErrorMessage: "Only one reference can have Controller set to true",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
errs := ValidateObjectMeta(
|
||||
&metav1.ObjectMeta{Name: "test", Namespace: "test", OwnerReferences: tc.ownerReferences},
|
||||
true,
|
||||
func(s string, prefix bool) []string {
|
||||
return nil
|
||||
},
|
||||
field.NewPath("field"))
|
||||
if len(errs) != 0 && !tc.expectError {
|
||||
t.Errorf("unexpected error: %v in test case %v", errs, tc.description)
|
||||
}
|
||||
if len(errs) == 0 && tc.expectError {
|
||||
t.Errorf("expect error in test case %v", tc.description)
|
||||
}
|
||||
if len(errs) != 0 && !strings.Contains(errs[0].Error(), tc.expectedErrorMessage) {
|
||||
t.Errorf("unexpected error message: %v in test case %v", errs, tc.description)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateObjectMetaUpdateIgnoresCreationTimestamp(t *testing.T) {
|
||||
if errs := ValidateObjectMetaUpdate(
|
||||
&metav1.ObjectMeta{Name: "test", ResourceVersion: "1"},
|
||||
&metav1.ObjectMeta{Name: "test", ResourceVersion: "1", CreationTimestamp: metav1.NewTime(time.Unix(10, 0))},
|
||||
field.NewPath("field"),
|
||||
); len(errs) != 1 {
|
||||
t.Fatalf("unexpected errors: %v", errs)
|
||||
}
|
||||
if errs := ValidateObjectMetaUpdate(
|
||||
&metav1.ObjectMeta{Name: "test", ResourceVersion: "1", CreationTimestamp: metav1.NewTime(time.Unix(10, 0))},
|
||||
&metav1.ObjectMeta{Name: "test", ResourceVersion: "1"},
|
||||
field.NewPath("field"),
|
||||
); len(errs) != 1 {
|
||||
t.Fatalf("unexpected errors: %v", errs)
|
||||
}
|
||||
if errs := ValidateObjectMetaUpdate(
|
||||
&metav1.ObjectMeta{Name: "test", ResourceVersion: "1", CreationTimestamp: metav1.NewTime(time.Unix(10, 0))},
|
||||
&metav1.ObjectMeta{Name: "test", ResourceVersion: "1", CreationTimestamp: metav1.NewTime(time.Unix(11, 0))},
|
||||
field.NewPath("field"),
|
||||
); len(errs) != 1 {
|
||||
t.Fatalf("unexpected errors: %v", errs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateFinalizersUpdate(t *testing.T) {
|
||||
testcases := map[string]struct {
|
||||
Old metav1.ObjectMeta
|
||||
New metav1.ObjectMeta
|
||||
ExpectedErr string
|
||||
}{
|
||||
"invalid adding finalizers": {
|
||||
Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &metav1.Time{}, Finalizers: []string{"x/a"}},
|
||||
New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &metav1.Time{}, Finalizers: []string{"x/a", "y/b"}},
|
||||
ExpectedErr: "y/b",
|
||||
},
|
||||
"invalid changing finalizers": {
|
||||
Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &metav1.Time{}, Finalizers: []string{"x/a"}},
|
||||
New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &metav1.Time{}, Finalizers: []string{"x/b"}},
|
||||
ExpectedErr: "x/b",
|
||||
},
|
||||
"valid removing finalizers": {
|
||||
Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &metav1.Time{}, Finalizers: []string{"x/a", "y/b"}},
|
||||
New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &metav1.Time{}, Finalizers: []string{"x/a"}},
|
||||
ExpectedErr: "",
|
||||
},
|
||||
"valid adding finalizers for objects not being deleted": {
|
||||
Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", Finalizers: []string{"x/a"}},
|
||||
New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", Finalizers: []string{"x/a", "y/b"}},
|
||||
ExpectedErr: "",
|
||||
},
|
||||
}
|
||||
for name, tc := range testcases {
|
||||
errs := ValidateObjectMetaUpdate(&tc.New, &tc.Old, field.NewPath("field"))
|
||||
if len(errs) == 0 {
|
||||
if len(tc.ExpectedErr) != 0 {
|
||||
t.Errorf("case: %q, expected error to contain %q", name, tc.ExpectedErr)
|
||||
}
|
||||
} else if e, a := tc.ExpectedErr, errs.ToAggregate().Error(); !strings.Contains(a, e) {
|
||||
t.Errorf("case: %q, expected error to contain %q, got error %q", name, e, a)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateFinalizersPreventConflictingFinalizers(t *testing.T) {
|
||||
testcases := map[string]struct {
|
||||
ObjectMeta metav1.ObjectMeta
|
||||
ExpectedErr string
|
||||
}{
|
||||
"conflicting finalizers": {
|
||||
ObjectMeta: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", Finalizers: []string{metav1.FinalizerOrphanDependents, metav1.FinalizerDeleteDependents}},
|
||||
ExpectedErr: "cannot be both set",
|
||||
},
|
||||
}
|
||||
for name, tc := range testcases {
|
||||
errs := ValidateObjectMeta(&tc.ObjectMeta, false, NameIsDNSSubdomain, field.NewPath("field"))
|
||||
if len(errs) == 0 {
|
||||
if len(tc.ExpectedErr) != 0 {
|
||||
t.Errorf("case: %q, expected error to contain %q", name, tc.ExpectedErr)
|
||||
}
|
||||
} else if e, a := tc.ExpectedErr, errs.ToAggregate().Error(); !strings.Contains(a, e) {
|
||||
t.Errorf("case: %q, expected error to contain %q, got error %q", name, e, a)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateObjectMetaUpdatePreventsDeletionFieldMutation(t *testing.T) {
|
||||
now := metav1.NewTime(time.Unix(1000, 0).UTC())
|
||||
later := metav1.NewTime(time.Unix(2000, 0).UTC())
|
||||
gracePeriodShort := int64(30)
|
||||
gracePeriodLong := int64(40)
|
||||
|
||||
testcases := map[string]struct {
|
||||
Old metav1.ObjectMeta
|
||||
New metav1.ObjectMeta
|
||||
ExpectedNew metav1.ObjectMeta
|
||||
ExpectedErrs []string
|
||||
}{
|
||||
"valid without deletion fields": {
|
||||
Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1"},
|
||||
New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1"},
|
||||
ExpectedNew: metav1.ObjectMeta{Name: "test", ResourceVersion: "1"},
|
||||
ExpectedErrs: []string{},
|
||||
},
|
||||
"valid with deletion fields": {
|
||||
Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &now, DeletionGracePeriodSeconds: &gracePeriodShort},
|
||||
New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &now, DeletionGracePeriodSeconds: &gracePeriodShort},
|
||||
ExpectedNew: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &now, DeletionGracePeriodSeconds: &gracePeriodShort},
|
||||
ExpectedErrs: []string{},
|
||||
},
|
||||
|
||||
"invalid set deletionTimestamp": {
|
||||
Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1"},
|
||||
New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &now},
|
||||
ExpectedNew: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &now},
|
||||
ExpectedErrs: []string{"field.deletionTimestamp: Invalid value: 1970-01-01 00:16:40 +0000 UTC: field is immutable"},
|
||||
},
|
||||
"invalid clear deletionTimestamp": {
|
||||
Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &now},
|
||||
New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1"},
|
||||
ExpectedNew: metav1.ObjectMeta{Name: "test", ResourceVersion: "1"},
|
||||
ExpectedErrs: []string{"field.deletionTimestamp: Invalid value: \"null\": field is immutable"},
|
||||
},
|
||||
"invalid change deletionTimestamp": {
|
||||
Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &now},
|
||||
New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &later},
|
||||
ExpectedNew: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &later},
|
||||
ExpectedErrs: []string{"field.deletionTimestamp: Invalid value: 1970-01-01 00:33:20 +0000 UTC: field is immutable"},
|
||||
},
|
||||
|
||||
"invalid set deletionGracePeriodSeconds": {
|
||||
Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1"},
|
||||
New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionGracePeriodSeconds: &gracePeriodShort},
|
||||
ExpectedNew: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionGracePeriodSeconds: &gracePeriodShort},
|
||||
ExpectedErrs: []string{"field.deletionGracePeriodSeconds: Invalid value: 30: field is immutable"},
|
||||
},
|
||||
"invalid clear deletionGracePeriodSeconds": {
|
||||
Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionGracePeriodSeconds: &gracePeriodShort},
|
||||
New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1"},
|
||||
ExpectedNew: metav1.ObjectMeta{Name: "test", ResourceVersion: "1"},
|
||||
ExpectedErrs: []string{"field.deletionGracePeriodSeconds: Invalid value: \"null\": field is immutable"},
|
||||
},
|
||||
"invalid change deletionGracePeriodSeconds": {
|
||||
Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionGracePeriodSeconds: &gracePeriodShort},
|
||||
New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionGracePeriodSeconds: &gracePeriodLong},
|
||||
ExpectedNew: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionGracePeriodSeconds: &gracePeriodLong},
|
||||
ExpectedErrs: []string{"field.deletionGracePeriodSeconds: Invalid value: 40: field is immutable"},
|
||||
},
|
||||
}
|
||||
|
||||
for k, tc := range testcases {
|
||||
errs := ValidateObjectMetaUpdate(&tc.New, &tc.Old, field.NewPath("field"))
|
||||
if len(errs) != len(tc.ExpectedErrs) {
|
||||
t.Logf("%s: Expected: %#v", k, tc.ExpectedErrs)
|
||||
t.Logf("%s: Got: %#v", k, errs)
|
||||
t.Errorf("%s: expected %d errors, got %d", k, len(tc.ExpectedErrs), len(errs))
|
||||
continue
|
||||
}
|
||||
for i := range errs {
|
||||
if errs[i].Error() != tc.ExpectedErrs[i] {
|
||||
t.Errorf("%s: error #%d: expected %q, got %q", k, i, tc.ExpectedErrs[i], errs[i].Error())
|
||||
}
|
||||
}
|
||||
if !reflect.DeepEqual(tc.New, tc.ExpectedNew) {
|
||||
t.Errorf("%s: Expected after validation:\n%#v\ngot\n%#v", k, tc.ExpectedNew, tc.New)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestObjectMetaGenerationUpdate(t *testing.T) {
|
||||
testcases := map[string]struct {
|
||||
Old metav1.ObjectMeta
|
||||
New metav1.ObjectMeta
|
||||
ExpectedErrs []string
|
||||
}{
|
||||
"invalid generation change - decremented": {
|
||||
Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", Generation: 5},
|
||||
New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", Generation: 4},
|
||||
ExpectedErrs: []string{"field.generation: Invalid value: 4: must not be decremented"},
|
||||
},
|
||||
"valid generation change - incremented by one": {
|
||||
Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", Generation: 1},
|
||||
New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", Generation: 2},
|
||||
ExpectedErrs: []string{},
|
||||
},
|
||||
"valid generation field - not updated": {
|
||||
Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", Generation: 5},
|
||||
New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", Generation: 5},
|
||||
ExpectedErrs: []string{},
|
||||
},
|
||||
}
|
||||
|
||||
for k, tc := range testcases {
|
||||
errList := []string{}
|
||||
errs := ValidateObjectMetaUpdate(&tc.New, &tc.Old, field.NewPath("field"))
|
||||
if len(errs) != len(tc.ExpectedErrs) {
|
||||
t.Logf("%s: Expected: %#v", k, tc.ExpectedErrs)
|
||||
for _, err := range errs {
|
||||
errList = append(errList, err.Error())
|
||||
}
|
||||
t.Logf("%s: Got: %#v", k, errList)
|
||||
t.Errorf("%s: expected %d errors, got %d", k, len(tc.ExpectedErrs), len(errs))
|
||||
continue
|
||||
}
|
||||
for i := range errList {
|
||||
if errList[i] != tc.ExpectedErrs[i] {
|
||||
t.Errorf("%s: error #%d: expected %q, got %q", k, i, tc.ExpectedErrs[i], errList[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure trailing slash is allowed in generate name
|
||||
func TestValidateObjectMetaTrimsTrailingSlash(t *testing.T) {
|
||||
errs := ValidateObjectMeta(
|
||||
&metav1.ObjectMeta{Name: "test", GenerateName: "foo-"},
|
||||
false,
|
||||
NameIsDNSSubdomain,
|
||||
field.NewPath("field"))
|
||||
if len(errs) != 0 {
|
||||
t.Fatalf("unexpected errors: %v", errs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateAnnotations(t *testing.T) {
|
||||
successCases := []map[string]string{
|
||||
{"simple": "bar"},
|
||||
{"now-with-dashes": "bar"},
|
||||
{"1-starts-with-num": "bar"},
|
||||
{"1234": "bar"},
|
||||
{"simple/simple": "bar"},
|
||||
{"now-with-dashes/simple": "bar"},
|
||||
{"now-with-dashes/now-with-dashes": "bar"},
|
||||
{"now.with.dots/simple": "bar"},
|
||||
{"now-with.dashes-and.dots/simple": "bar"},
|
||||
{"1-num.2-num/3-num": "bar"},
|
||||
{"1234/5678": "bar"},
|
||||
{"1.2.3.4/5678": "bar"},
|
||||
{"UpperCase123": "bar"},
|
||||
{"a": strings.Repeat("b", totalAnnotationSizeLimitB-1)},
|
||||
{
|
||||
"a": strings.Repeat("b", totalAnnotationSizeLimitB/2-1),
|
||||
"c": strings.Repeat("d", totalAnnotationSizeLimitB/2-1),
|
||||
},
|
||||
}
|
||||
for i := range successCases {
|
||||
errs := ValidateAnnotations(successCases[i], field.NewPath("field"))
|
||||
if len(errs) != 0 {
|
||||
t.Errorf("case[%d] expected success, got %#v", i, errs)
|
||||
}
|
||||
}
|
||||
|
||||
nameErrorCases := []struct {
|
||||
annotations map[string]string
|
||||
expect string
|
||||
}{
|
||||
{map[string]string{"nospecialchars^=@": "bar"}, namePartErrMsg},
|
||||
{map[string]string{"cantendwithadash-": "bar"}, namePartErrMsg},
|
||||
{map[string]string{"only/one/slash": "bar"}, nameErrMsg},
|
||||
{map[string]string{strings.Repeat("a", 254): "bar"}, maxLengthErrMsg},
|
||||
}
|
||||
for i := range nameErrorCases {
|
||||
errs := ValidateAnnotations(nameErrorCases[i].annotations, field.NewPath("field"))
|
||||
if len(errs) != 1 {
|
||||
t.Errorf("case[%d]: expected failure", i)
|
||||
} else {
|
||||
if !strings.Contains(errs[0].Detail, nameErrorCases[i].expect) {
|
||||
t.Errorf("case[%d]: error details do not include %q: %q", i, nameErrorCases[i].expect, errs[0].Detail)
|
||||
}
|
||||
}
|
||||
}
|
||||
totalSizeErrorCases := []map[string]string{
|
||||
{"a": strings.Repeat("b", totalAnnotationSizeLimitB)},
|
||||
{
|
||||
"a": strings.Repeat("b", totalAnnotationSizeLimitB/2),
|
||||
"c": strings.Repeat("d", totalAnnotationSizeLimitB/2),
|
||||
},
|
||||
}
|
||||
for i := range totalSizeErrorCases {
|
||||
errs := ValidateAnnotations(totalSizeErrorCases[i], field.NewPath("field"))
|
||||
if len(errs) != 1 {
|
||||
t.Errorf("case[%d] expected failure", i)
|
||||
}
|
||||
}
|
||||
}
|
68
vendor/k8s.io/apimachinery/pkg/api/validation/path/name.go
generated
vendored
68
vendor/k8s.io/apimachinery/pkg/api/validation/path/name.go
generated
vendored
@ -1,68 +0,0 @@
|
||||
/*
|
||||
Copyright 2015 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 path
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// NameMayNotBe specifies strings that cannot be used as names specified as path segments (like the REST API or etcd store)
|
||||
var NameMayNotBe = []string{".", ".."}
|
||||
|
||||
// NameMayNotContain specifies substrings that cannot be used in names specified as path segments (like the REST API or etcd store)
|
||||
var NameMayNotContain = []string{"/", "%"}
|
||||
|
||||
// IsValidPathSegmentName validates the name can be safely encoded as a path segment
|
||||
func IsValidPathSegmentName(name string) []string {
|
||||
for _, illegalName := range NameMayNotBe {
|
||||
if name == illegalName {
|
||||
return []string{fmt.Sprintf(`may not be '%s'`, illegalName)}
|
||||
}
|
||||
}
|
||||
|
||||
var errors []string
|
||||
for _, illegalContent := range NameMayNotContain {
|
||||
if strings.Contains(name, illegalContent) {
|
||||
errors = append(errors, fmt.Sprintf(`may not contain '%s'`, illegalContent))
|
||||
}
|
||||
}
|
||||
|
||||
return errors
|
||||
}
|
||||
|
||||
// IsValidPathSegmentPrefix validates the name can be used as a prefix for a name which will be encoded as a path segment
|
||||
// It does not check for exact matches with disallowed names, since an arbitrary suffix might make the name valid
|
||||
func IsValidPathSegmentPrefix(name string) []string {
|
||||
var errors []string
|
||||
for _, illegalContent := range NameMayNotContain {
|
||||
if strings.Contains(name, illegalContent) {
|
||||
errors = append(errors, fmt.Sprintf(`may not contain '%s'`, illegalContent))
|
||||
}
|
||||
}
|
||||
|
||||
return errors
|
||||
}
|
||||
|
||||
// ValidatePathSegmentName validates the name can be safely encoded as a path segment
|
||||
func ValidatePathSegmentName(name string, prefix bool) []string {
|
||||
if prefix {
|
||||
return IsValidPathSegmentPrefix(name)
|
||||
} else {
|
||||
return IsValidPathSegmentName(name)
|
||||
}
|
||||
}
|
168
vendor/k8s.io/apimachinery/pkg/api/validation/path/name_test.go
generated
vendored
168
vendor/k8s.io/apimachinery/pkg/api/validation/path/name_test.go
generated
vendored
@ -1,168 +0,0 @@
|
||||
/*
|
||||
Copyright 2015 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 path
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestValidatePathSegmentName(t *testing.T) {
|
||||
testcases := map[string]struct {
|
||||
Name string
|
||||
Prefix bool
|
||||
ExpectedMsg string
|
||||
}{
|
||||
"empty": {
|
||||
Name: "",
|
||||
Prefix: false,
|
||||
ExpectedMsg: "",
|
||||
},
|
||||
"empty,prefix": {
|
||||
Name: "",
|
||||
Prefix: true,
|
||||
ExpectedMsg: "",
|
||||
},
|
||||
|
||||
"valid": {
|
||||
Name: "foo.bar.baz",
|
||||
Prefix: false,
|
||||
ExpectedMsg: "",
|
||||
},
|
||||
"valid,prefix": {
|
||||
Name: "foo.bar.baz",
|
||||
Prefix: true,
|
||||
ExpectedMsg: "",
|
||||
},
|
||||
|
||||
// Make sure mixed case, non DNS subdomain characters are tolerated
|
||||
"valid complex": {
|
||||
Name: "sha256:ABCDEF012345@ABCDEF012345",
|
||||
Prefix: false,
|
||||
ExpectedMsg: "",
|
||||
},
|
||||
// Make sure non-ascii characters are tolerated
|
||||
"valid extended charset": {
|
||||
Name: "Iñtërnâtiônàlizætiøn",
|
||||
Prefix: false,
|
||||
ExpectedMsg: "",
|
||||
},
|
||||
|
||||
"dot": {
|
||||
Name: ".",
|
||||
Prefix: false,
|
||||
ExpectedMsg: ".",
|
||||
},
|
||||
"dot leading": {
|
||||
Name: ".test",
|
||||
Prefix: false,
|
||||
ExpectedMsg: "",
|
||||
},
|
||||
"dot,prefix": {
|
||||
Name: ".",
|
||||
Prefix: true,
|
||||
ExpectedMsg: "",
|
||||
},
|
||||
|
||||
"dot dot": {
|
||||
Name: "..",
|
||||
Prefix: false,
|
||||
ExpectedMsg: "..",
|
||||
},
|
||||
"dot dot leading": {
|
||||
Name: "..test",
|
||||
Prefix: false,
|
||||
ExpectedMsg: "",
|
||||
},
|
||||
"dot dot,prefix": {
|
||||
Name: "..",
|
||||
Prefix: true,
|
||||
ExpectedMsg: "",
|
||||
},
|
||||
|
||||
"slash": {
|
||||
Name: "foo/bar",
|
||||
Prefix: false,
|
||||
ExpectedMsg: "/",
|
||||
},
|
||||
"slash,prefix": {
|
||||
Name: "foo/bar",
|
||||
Prefix: true,
|
||||
ExpectedMsg: "/",
|
||||
},
|
||||
|
||||
"percent": {
|
||||
Name: "foo%bar",
|
||||
Prefix: false,
|
||||
ExpectedMsg: "%",
|
||||
},
|
||||
"percent,prefix": {
|
||||
Name: "foo%bar",
|
||||
Prefix: true,
|
||||
ExpectedMsg: "%",
|
||||
},
|
||||
}
|
||||
|
||||
for k, tc := range testcases {
|
||||
msgs := ValidatePathSegmentName(tc.Name, tc.Prefix)
|
||||
if len(tc.ExpectedMsg) == 0 && len(msgs) > 0 {
|
||||
t.Errorf("%s: expected no message, got %v", k, msgs)
|
||||
}
|
||||
if len(tc.ExpectedMsg) > 0 && len(msgs) == 0 {
|
||||
t.Errorf("%s: expected error message, got none", k)
|
||||
}
|
||||
if len(tc.ExpectedMsg) > 0 && !strings.Contains(msgs[0], tc.ExpectedMsg) {
|
||||
t.Errorf("%s: expected message containing %q, got %v", k, tc.ExpectedMsg, msgs[0])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateWithMultiErrors(t *testing.T) {
|
||||
testcases := map[string]struct {
|
||||
Name string
|
||||
Prefix bool
|
||||
ExpectedMsg []string
|
||||
}{
|
||||
"slash,percent": {
|
||||
Name: "foo//bar%",
|
||||
Prefix: false,
|
||||
ExpectedMsg: []string{"may not contain '/'", "may not contain '%'"},
|
||||
},
|
||||
"slash,percent,prefix": {
|
||||
Name: "foo//bar%",
|
||||
Prefix: true,
|
||||
ExpectedMsg: []string{"may not contain '/'", "may not contain '%'"},
|
||||
},
|
||||
}
|
||||
|
||||
for k, tc := range testcases {
|
||||
msgs := ValidatePathSegmentName(tc.Name, tc.Prefix)
|
||||
if len(tc.ExpectedMsg) == 0 && len(msgs) > 0 {
|
||||
t.Errorf("%s: expected no message, got %v", k, msgs)
|
||||
}
|
||||
if len(tc.ExpectedMsg) > 0 && len(msgs) == 0 {
|
||||
t.Errorf("%s: expected error message, got none", k)
|
||||
}
|
||||
if len(tc.ExpectedMsg) > 0 {
|
||||
for i := 0; i < len(tc.ExpectedMsg); i++ {
|
||||
if msgs[i] != tc.ExpectedMsg[i] {
|
||||
t.Errorf("%s: expected message containing %q, got %v", k, tc.ExpectedMsg[i], msgs[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
9
vendor/k8s.io/apimachinery/pkg/apis/OWNERS
generated
vendored
9
vendor/k8s.io/apimachinery/pkg/apis/OWNERS
generated
vendored
@ -1,9 +0,0 @@
|
||||
# Disable inheritance as this is an api owners file
|
||||
options:
|
||||
no_parent_owners: true
|
||||
approvers:
|
||||
- api-approvers
|
||||
reviewers:
|
||||
- api-reviewers
|
||||
labels:
|
||||
- kind/api-change
|
7
vendor/k8s.io/apimachinery/pkg/apis/config/OWNERS
generated
vendored
7
vendor/k8s.io/apimachinery/pkg/apis/config/OWNERS
generated
vendored
@ -1,7 +0,0 @@
|
||||
approvers:
|
||||
- api-approvers
|
||||
- sttts
|
||||
- luxas
|
||||
reviewers:
|
||||
- api-reviewers
|
||||
- hanxiaoshuai
|
19
vendor/k8s.io/apimachinery/pkg/apis/config/doc.go
generated
vendored
19
vendor/k8s.io/apimachinery/pkg/apis/config/doc.go
generated
vendored
@ -1,19 +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.
|
||||
*/
|
||||
|
||||
// +k8s:deepcopy-gen=package
|
||||
|
||||
package config // import "k8s.io/apimachinery/pkg/apis/config"
|
33
vendor/k8s.io/apimachinery/pkg/apis/config/types.go
generated
vendored
33
vendor/k8s.io/apimachinery/pkg/apis/config/types.go
generated
vendored
@ -1,33 +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 config
|
||||
|
||||
// ClientConnectionConfiguration contains details for constructing a client.
|
||||
type ClientConnectionConfiguration struct {
|
||||
// kubeconfig is the path to a KubeConfig file.
|
||||
Kubeconfig string
|
||||
// acceptContentTypes defines the Accept header sent by clients when connecting to a server, overriding the
|
||||
// default value of 'application/json'. This field will control all connections to the server used by a particular
|
||||
// client.
|
||||
AcceptContentTypes string
|
||||
// contentType is the content type used when sending data to the server from this client.
|
||||
ContentType string
|
||||
// qps controls the number of queries per second allowed for this connection.
|
||||
QPS float32
|
||||
// burst allows extra queries to accumulate when a client is exceeding its rate.
|
||||
Burst int32
|
||||
}
|
37
vendor/k8s.io/apimachinery/pkg/apis/config/v1alpha1/conversion.go
generated
vendored
37
vendor/k8s.io/apimachinery/pkg/apis/config/v1alpha1/conversion.go
generated
vendored
@ -1,37 +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 v1alpha1
|
||||
|
||||
import (
|
||||
"k8s.io/apimachinery/pkg/apis/config"
|
||||
"k8s.io/apimachinery/pkg/conversion"
|
||||
)
|
||||
|
||||
// Important! The public back-and-forth conversion functions for the types in this generic
|
||||
// package with ComponentConfig types need to be manually exposed like this in order for
|
||||
// other packages that reference this package to be able to call these conversion functions
|
||||
// in an autogenerated manner.
|
||||
// TODO: Fix the bug in conversion-gen so it automatically discovers these Convert_* functions
|
||||
// in autogenerated code as well.
|
||||
|
||||
func Convert_v1alpha1_ClientConnectionConfiguration_To_config_ClientConnectionConfiguration(in *ClientConnectionConfiguration, out *config.ClientConnectionConfiguration, s conversion.Scope) error {
|
||||
return autoConvert_v1alpha1_ClientConnectionConfiguration_To_config_ClientConnectionConfiguration(in, out, s)
|
||||
}
|
||||
|
||||
func Convert_config_ClientConnectionConfiguration_To_v1alpha1_ClientConnectionConfiguration(in *config.ClientConnectionConfiguration, out *ClientConnectionConfiguration, s conversion.Scope) error {
|
||||
return autoConvert_config_ClientConnectionConfiguration_To_v1alpha1_ClientConnectionConfiguration(in, out, s)
|
||||
}
|
38
vendor/k8s.io/apimachinery/pkg/apis/config/v1alpha1/defaults.go
generated
vendored
38
vendor/k8s.io/apimachinery/pkg/apis/config/v1alpha1/defaults.go
generated
vendored
@ -1,38 +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 v1alpha1
|
||||
|
||||
// RecommendedDefaultClientConnectionConfiguration defaults a pointer to a
|
||||
// ClientConnectionConfiguration struct. This will set the recommended default
|
||||
// values, but they may be subject to change between API versions. This function
|
||||
// is intentionally not registered in the scheme as a "normal" `SetDefaults_Foo`
|
||||
// function to allow consumers of this type to set whatever defaults for their
|
||||
// embedded configs. Forcing consumers to use these defaults would be problematic
|
||||
// as defaulting in the scheme is done as part of the conversion, and there would
|
||||
// be no easy way to opt-out. Instead, if you want to use this defaulting method
|
||||
// run it in your wrapper struct of this type in its `SetDefaults_` method.
|
||||
func RecommendedDefaultClientConnectionConfiguration(obj *ClientConnectionConfiguration) {
|
||||
if len(obj.ContentType) == 0 {
|
||||
obj.ContentType = "application/vnd.kubernetes.protobuf"
|
||||
}
|
||||
if obj.QPS == 0.0 {
|
||||
obj.QPS = 50.0
|
||||
}
|
||||
if obj.Burst == 0 {
|
||||
obj.Burst = 100
|
||||
}
|
||||
}
|
20
vendor/k8s.io/apimachinery/pkg/apis/config/v1alpha1/doc.go
generated
vendored
20
vendor/k8s.io/apimachinery/pkg/apis/config/v1alpha1/doc.go
generated
vendored
@ -1,20 +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.
|
||||
*/
|
||||
|
||||
// +k8s:deepcopy-gen=package
|
||||
// +k8s:conversion-gen=k8s.io/apimachinery/pkg/apis/config
|
||||
|
||||
package v1alpha1 // import "k8s.io/apimachinery/pkg/apis/config/v1alpha1"
|
31
vendor/k8s.io/apimachinery/pkg/apis/config/v1alpha1/register.go
generated
vendored
31
vendor/k8s.io/apimachinery/pkg/apis/config/v1alpha1/register.go
generated
vendored
@ -1,31 +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 v1alpha1
|
||||
|
||||
import (
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
)
|
||||
|
||||
var (
|
||||
// SchemeBuilder is the scheme builder with scheme init functions to run for this API package
|
||||
SchemeBuilder runtime.SchemeBuilder
|
||||
// localSchemeBuilder extends the SchemeBuilder instance with the external types. In this package,
|
||||
// defaulting and conversion init funcs are registered as well.
|
||||
localSchemeBuilder = &SchemeBuilder
|
||||
// AddToScheme is a global function that registers this API group & version to a scheme
|
||||
AddToScheme = localSchemeBuilder.AddToScheme
|
||||
)
|
33
vendor/k8s.io/apimachinery/pkg/apis/config/v1alpha1/types.go
generated
vendored
33
vendor/k8s.io/apimachinery/pkg/apis/config/v1alpha1/types.go
generated
vendored
@ -1,33 +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 v1alpha1
|
||||
|
||||
// ClientConnectionConfiguration contains details for constructing a client.
|
||||
type ClientConnectionConfiguration struct {
|
||||
// kubeconfig is the path to a KubeConfig file.
|
||||
Kubeconfig string `json:"kubeconfig"`
|
||||
// acceptContentTypes defines the Accept header sent by clients when connecting to a server, overriding the
|
||||
// default value of 'application/json'. This field will control all connections to the server used by a particular
|
||||
// client.
|
||||
AcceptContentTypes string `json:"acceptContentTypes"`
|
||||
// contentType is the content type used when sending data to the server from this client.
|
||||
ContentType string `json:"contentType"`
|
||||
// qps controls the number of queries per second allowed for this connection.
|
||||
QPS float32 `json:"qps"`
|
||||
// burst allows extra queries to accumulate when a client is exceeding its rate.
|
||||
Burst int32 `json:"burst"`
|
||||
}
|
75
vendor/k8s.io/apimachinery/pkg/apis/config/v1alpha1/zz_generated.conversion.go
generated
vendored
75
vendor/k8s.io/apimachinery/pkg/apis/config/v1alpha1/zz_generated.conversion.go
generated
vendored
@ -1,75 +0,0 @@
|
||||
// +build !ignore_autogenerated
|
||||
|
||||
/*
|
||||
Copyright 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.
|
||||
*/
|
||||
|
||||
// Code generated by conversion-gen. DO NOT EDIT.
|
||||
|
||||
package v1alpha1
|
||||
|
||||
import (
|
||||
config "k8s.io/apimachinery/pkg/apis/config"
|
||||
conversion "k8s.io/apimachinery/pkg/conversion"
|
||||
runtime "k8s.io/apimachinery/pkg/runtime"
|
||||
)
|
||||
|
||||
func init() {
|
||||
localSchemeBuilder.Register(RegisterConversions)
|
||||
}
|
||||
|
||||
// RegisterConversions adds conversion functions to the given scheme.
|
||||
// Public to allow building arbitrary schemes.
|
||||
func RegisterConversions(s *runtime.Scheme) error {
|
||||
if err := s.AddGeneratedConversionFunc((*ClientConnectionConfiguration)(nil), (*config.ClientConnectionConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error {
|
||||
return Convert_v1alpha1_ClientConnectionConfiguration_To_config_ClientConnectionConfiguration(a.(*ClientConnectionConfiguration), b.(*config.ClientConnectionConfiguration), scope)
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.AddGeneratedConversionFunc((*config.ClientConnectionConfiguration)(nil), (*ClientConnectionConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error {
|
||||
return Convert_config_ClientConnectionConfiguration_To_v1alpha1_ClientConnectionConfiguration(a.(*config.ClientConnectionConfiguration), b.(*ClientConnectionConfiguration), scope)
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.AddConversionFunc((*config.ClientConnectionConfiguration)(nil), (*ClientConnectionConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error {
|
||||
return Convert_config_ClientConnectionConfiguration_To_v1alpha1_ClientConnectionConfiguration(a.(*config.ClientConnectionConfiguration), b.(*ClientConnectionConfiguration), scope)
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.AddConversionFunc((*ClientConnectionConfiguration)(nil), (*config.ClientConnectionConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error {
|
||||
return Convert_v1alpha1_ClientConnectionConfiguration_To_config_ClientConnectionConfiguration(a.(*ClientConnectionConfiguration), b.(*config.ClientConnectionConfiguration), scope)
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func autoConvert_v1alpha1_ClientConnectionConfiguration_To_config_ClientConnectionConfiguration(in *ClientConnectionConfiguration, out *config.ClientConnectionConfiguration, s conversion.Scope) error {
|
||||
out.Kubeconfig = in.Kubeconfig
|
||||
out.AcceptContentTypes = in.AcceptContentTypes
|
||||
out.ContentType = in.ContentType
|
||||
out.QPS = in.QPS
|
||||
out.Burst = in.Burst
|
||||
return nil
|
||||
}
|
||||
|
||||
func autoConvert_config_ClientConnectionConfiguration_To_v1alpha1_ClientConnectionConfiguration(in *config.ClientConnectionConfiguration, out *ClientConnectionConfiguration, s conversion.Scope) error {
|
||||
out.Kubeconfig = in.Kubeconfig
|
||||
out.AcceptContentTypes = in.AcceptContentTypes
|
||||
out.ContentType = in.ContentType
|
||||
out.QPS = in.QPS
|
||||
out.Burst = in.Burst
|
||||
return nil
|
||||
}
|
37
vendor/k8s.io/apimachinery/pkg/apis/config/v1alpha1/zz_generated.deepcopy.go
generated
vendored
37
vendor/k8s.io/apimachinery/pkg/apis/config/v1alpha1/zz_generated.deepcopy.go
generated
vendored
@ -1,37 +0,0 @@
|
||||
// +build !ignore_autogenerated
|
||||
|
||||
/*
|
||||
Copyright 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.
|
||||
*/
|
||||
|
||||
// Code generated by deepcopy-gen. DO NOT EDIT.
|
||||
|
||||
package v1alpha1
|
||||
|
||||
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
|
||||
func (in *ClientConnectionConfiguration) DeepCopyInto(out *ClientConnectionConfiguration) {
|
||||
*out = *in
|
||||
return
|
||||
}
|
||||
|
||||
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClientConnectionConfiguration.
|
||||
func (in *ClientConnectionConfiguration) DeepCopy() *ClientConnectionConfiguration {
|
||||
if in == nil {
|
||||
return nil
|
||||
}
|
||||
out := new(ClientConnectionConfiguration)
|
||||
in.DeepCopyInto(out)
|
||||
return out
|
||||
}
|
31
vendor/k8s.io/apimachinery/pkg/apis/config/validation/validation.go
generated
vendored
31
vendor/k8s.io/apimachinery/pkg/apis/config/validation/validation.go
generated
vendored
@ -1,31 +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 validation
|
||||
|
||||
import (
|
||||
"k8s.io/apimachinery/pkg/apis/config"
|
||||
"k8s.io/apimachinery/pkg/util/validation/field"
|
||||
)
|
||||
|
||||
// ValidateClientConnectionConfiguration ensures validation of the ClientConnectionConfiguration struct
|
||||
func ValidateClientConnectionConfiguration(cc *config.ClientConnectionConfiguration, fldPath *field.Path) field.ErrorList {
|
||||
allErrs := field.ErrorList{}
|
||||
if cc.Burst < 0 {
|
||||
allErrs = append(allErrs, field.Invalid(fldPath.Child("burst"), cc.Burst, "must be non-negative"))
|
||||
}
|
||||
return allErrs
|
||||
}
|
66
vendor/k8s.io/apimachinery/pkg/apis/config/validation/validation_test.go
generated
vendored
66
vendor/k8s.io/apimachinery/pkg/apis/config/validation/validation_test.go
generated
vendored
@ -1,66 +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 validation
|
||||
|
||||
import (
|
||||
"k8s.io/apimachinery/pkg/apis/config"
|
||||
"k8s.io/apimachinery/pkg/util/validation/field"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestValidateClientConnectionConfiguration(t *testing.T) {
|
||||
validConfig := &config.ClientConnectionConfiguration{
|
||||
AcceptContentTypes: "application/json",
|
||||
ContentType: "application/json",
|
||||
QPS: 10,
|
||||
Burst: 10,
|
||||
}
|
||||
|
||||
qpsLessThanZero := validConfig.DeepCopy()
|
||||
qpsLessThanZero.QPS = -1
|
||||
|
||||
burstLessThanZero := validConfig.DeepCopy()
|
||||
burstLessThanZero.Burst = -1
|
||||
|
||||
scenarios := map[string]struct {
|
||||
expectedToFail bool
|
||||
config *config.ClientConnectionConfiguration
|
||||
}{
|
||||
"good": {
|
||||
expectedToFail: false,
|
||||
config: validConfig,
|
||||
},
|
||||
"good-qps-less-than-zero": {
|
||||
expectedToFail: false,
|
||||
config: qpsLessThanZero,
|
||||
},
|
||||
"bad-burst-less-then-zero": {
|
||||
expectedToFail: true,
|
||||
config: burstLessThanZero,
|
||||
},
|
||||
}
|
||||
|
||||
for name, scenario := range scenarios {
|
||||
errs := ValidateClientConnectionConfiguration(scenario.config, field.NewPath("clientConnectionConfiguration"))
|
||||
if len(errs) == 0 && scenario.expectedToFail {
|
||||
t.Errorf("Unexpected success for scenario: %s", name)
|
||||
}
|
||||
if len(errs) > 0 && !scenario.expectedToFail {
|
||||
t.Errorf("Unexpected failure for scenario: %s - %+v", name, errs)
|
||||
}
|
||||
}
|
||||
}
|
37
vendor/k8s.io/apimachinery/pkg/apis/config/zz_generated.deepcopy.go
generated
vendored
37
vendor/k8s.io/apimachinery/pkg/apis/config/zz_generated.deepcopy.go
generated
vendored
@ -1,37 +0,0 @@
|
||||
// +build !ignore_autogenerated
|
||||
|
||||
/*
|
||||
Copyright 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.
|
||||
*/
|
||||
|
||||
// Code generated by deepcopy-gen. DO NOT EDIT.
|
||||
|
||||
package config
|
||||
|
||||
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
|
||||
func (in *ClientConnectionConfiguration) DeepCopyInto(out *ClientConnectionConfiguration) {
|
||||
*out = *in
|
||||
return
|
||||
}
|
||||
|
||||
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClientConnectionConfiguration.
|
||||
func (in *ClientConnectionConfiguration) DeepCopy() *ClientConnectionConfiguration {
|
||||
if in == nil {
|
||||
return nil
|
||||
}
|
||||
out := new(ClientConnectionConfiguration)
|
||||
in.DeepCopyInto(out)
|
||||
return out
|
||||
}
|
327
vendor/k8s.io/apimachinery/pkg/apis/meta/fuzzer/fuzzer.go
generated
vendored
327
vendor/k8s.io/apimachinery/pkg/apis/meta/fuzzer/fuzzer.go
generated
vendored
@ -1,327 +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 fuzzer
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/google/gofuzz"
|
||||
|
||||
apitesting "k8s.io/apimachinery/pkg/api/apitesting"
|
||||
"k8s.io/apimachinery/pkg/api/apitesting/fuzzer"
|
||||
"k8s.io/apimachinery/pkg/api/resource"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
metav1beta1 "k8s.io/apimachinery/pkg/apis/meta/v1beta1"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
runtimeserializer "k8s.io/apimachinery/pkg/runtime/serializer"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
)
|
||||
|
||||
func genericFuzzerFuncs(codecs runtimeserializer.CodecFactory) []interface{} {
|
||||
return []interface{}{
|
||||
func(q *resource.Quantity, c fuzz.Continue) {
|
||||
*q = *resource.NewQuantity(c.Int63n(1000), resource.DecimalExponent)
|
||||
},
|
||||
func(j *int, c fuzz.Continue) {
|
||||
*j = int(c.Int31())
|
||||
},
|
||||
func(j **int, c fuzz.Continue) {
|
||||
if c.RandBool() {
|
||||
i := int(c.Int31())
|
||||
*j = &i
|
||||
} else {
|
||||
*j = nil
|
||||
}
|
||||
},
|
||||
func(j *runtime.TypeMeta, c fuzz.Continue) {
|
||||
// We have to customize the randomization of TypeMetas because their
|
||||
// APIVersion and Kind must remain blank in memory.
|
||||
j.APIVersion = ""
|
||||
j.Kind = ""
|
||||
},
|
||||
func(j *runtime.Object, c fuzz.Continue) {
|
||||
// TODO: uncomment when round trip starts from a versioned object
|
||||
if true { //c.RandBool() {
|
||||
*j = &runtime.Unknown{
|
||||
// We do not set TypeMeta here because it is not carried through a round trip
|
||||
Raw: []byte(`{"apiVersion":"unknown.group/unknown","kind":"Something","someKey":"someValue"}`),
|
||||
ContentType: runtime.ContentTypeJSON,
|
||||
}
|
||||
} else {
|
||||
types := []runtime.Object{&metav1.Status{}, &metav1.APIGroup{}}
|
||||
t := types[c.Rand.Intn(len(types))]
|
||||
c.Fuzz(t)
|
||||
*j = t
|
||||
}
|
||||
},
|
||||
func(r *runtime.RawExtension, c fuzz.Continue) {
|
||||
// Pick an arbitrary type and fuzz it
|
||||
types := []runtime.Object{&metav1.Status{}, &metav1.APIGroup{}}
|
||||
obj := types[c.Rand.Intn(len(types))]
|
||||
c.Fuzz(obj)
|
||||
|
||||
// Find a codec for converting the object to raw bytes. This is necessary for the
|
||||
// api version and kind to be correctly set be serialization.
|
||||
var codec = apitesting.TestCodec(codecs, metav1.SchemeGroupVersion)
|
||||
|
||||
// Convert the object to raw bytes
|
||||
bytes, err := runtime.Encode(codec, obj)
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("Failed to encode object: %v", err))
|
||||
}
|
||||
|
||||
// strip trailing newlines which do not survive roundtrips
|
||||
for len(bytes) >= 1 && bytes[len(bytes)-1] == 10 {
|
||||
bytes = bytes[:len(bytes)-1]
|
||||
}
|
||||
|
||||
// Set the bytes field on the RawExtension
|
||||
r.Raw = bytes
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// taken from gofuzz internals for RandString
|
||||
type charRange struct {
|
||||
first, last rune
|
||||
}
|
||||
|
||||
func (c *charRange) choose(r *rand.Rand) rune {
|
||||
count := int64(c.last - c.first + 1)
|
||||
ch := c.first + rune(r.Int63n(count))
|
||||
|
||||
return ch
|
||||
}
|
||||
|
||||
// randomLabelPart produces a valid random label value or name-part
|
||||
// of a label key.
|
||||
func randomLabelPart(c fuzz.Continue, canBeEmpty bool) string {
|
||||
validStartEnd := []charRange{{'0', '9'}, {'a', 'z'}, {'A', 'Z'}}
|
||||
validMiddle := []charRange{{'0', '9'}, {'a', 'z'}, {'A', 'Z'},
|
||||
{'.', '.'}, {'-', '-'}, {'_', '_'}}
|
||||
|
||||
partLen := c.Rand.Intn(64) // len is [0, 63]
|
||||
if !canBeEmpty {
|
||||
partLen = c.Rand.Intn(63) + 1 // len is [1, 63]
|
||||
}
|
||||
|
||||
runes := make([]rune, partLen)
|
||||
if partLen == 0 {
|
||||
return string(runes)
|
||||
}
|
||||
|
||||
runes[0] = validStartEnd[c.Rand.Intn(len(validStartEnd))].choose(c.Rand)
|
||||
for i := range runes[1:] {
|
||||
runes[i+1] = validMiddle[c.Rand.Intn(len(validMiddle))].choose(c.Rand)
|
||||
}
|
||||
runes[len(runes)-1] = validStartEnd[c.Rand.Intn(len(validStartEnd))].choose(c.Rand)
|
||||
|
||||
return string(runes)
|
||||
}
|
||||
|
||||
func randomDNSLabel(c fuzz.Continue) string {
|
||||
validStartEnd := []charRange{{'0', '9'}, {'a', 'z'}}
|
||||
validMiddle := []charRange{{'0', '9'}, {'a', 'z'}, {'-', '-'}}
|
||||
|
||||
partLen := c.Rand.Intn(63) + 1 // len is [1, 63]
|
||||
runes := make([]rune, partLen)
|
||||
|
||||
runes[0] = validStartEnd[c.Rand.Intn(len(validStartEnd))].choose(c.Rand)
|
||||
for i := range runes[1:] {
|
||||
runes[i+1] = validMiddle[c.Rand.Intn(len(validMiddle))].choose(c.Rand)
|
||||
}
|
||||
runes[len(runes)-1] = validStartEnd[c.Rand.Intn(len(validStartEnd))].choose(c.Rand)
|
||||
|
||||
return string(runes)
|
||||
}
|
||||
|
||||
func randomLabelKey(c fuzz.Continue) string {
|
||||
namePart := randomLabelPart(c, false)
|
||||
prefixPart := ""
|
||||
|
||||
usePrefix := c.RandBool()
|
||||
if usePrefix {
|
||||
// we can fit, with dots, at most 3 labels in the 253 allotted characters
|
||||
prefixPartsLen := c.Rand.Intn(2) + 1
|
||||
prefixParts := make([]string, prefixPartsLen)
|
||||
for i := range prefixParts {
|
||||
prefixParts[i] = randomDNSLabel(c)
|
||||
}
|
||||
prefixPart = strings.Join(prefixParts, ".") + "/"
|
||||
}
|
||||
|
||||
return prefixPart + namePart
|
||||
}
|
||||
|
||||
func v1FuzzerFuncs(codecs runtimeserializer.CodecFactory) []interface{} {
|
||||
|
||||
return []interface{}{
|
||||
func(j *metav1.TypeMeta, c fuzz.Continue) {
|
||||
// We have to customize the randomization of TypeMetas because their
|
||||
// APIVersion and Kind must remain blank in memory.
|
||||
j.APIVersion = ""
|
||||
j.Kind = ""
|
||||
},
|
||||
func(j *metav1.ObjectMeta, c fuzz.Continue) {
|
||||
c.FuzzNoCustom(j)
|
||||
|
||||
j.ResourceVersion = strconv.FormatUint(c.RandUint64(), 10)
|
||||
j.UID = types.UID(c.RandString())
|
||||
|
||||
var sec, nsec int64
|
||||
c.Fuzz(&sec)
|
||||
c.Fuzz(&nsec)
|
||||
j.CreationTimestamp = metav1.Unix(sec, nsec).Rfc3339Copy()
|
||||
|
||||
if j.DeletionTimestamp != nil {
|
||||
c.Fuzz(&sec)
|
||||
c.Fuzz(&nsec)
|
||||
t := metav1.Unix(sec, nsec).Rfc3339Copy()
|
||||
j.DeletionTimestamp = &t
|
||||
}
|
||||
|
||||
if len(j.Labels) == 0 {
|
||||
j.Labels = nil
|
||||
} else {
|
||||
delete(j.Labels, "")
|
||||
}
|
||||
if len(j.Annotations) == 0 {
|
||||
j.Annotations = nil
|
||||
} else {
|
||||
delete(j.Annotations, "")
|
||||
}
|
||||
if len(j.OwnerReferences) == 0 {
|
||||
j.OwnerReferences = nil
|
||||
}
|
||||
if len(j.Finalizers) == 0 {
|
||||
j.Finalizers = nil
|
||||
}
|
||||
},
|
||||
func(j *metav1.Initializers, c fuzz.Continue) {
|
||||
c.FuzzNoCustom(j)
|
||||
if len(j.Pending) == 0 {
|
||||
j.Pending = nil
|
||||
}
|
||||
},
|
||||
func(j *metav1.ListMeta, c fuzz.Continue) {
|
||||
j.ResourceVersion = strconv.FormatUint(c.RandUint64(), 10)
|
||||
j.SelfLink = c.RandString()
|
||||
},
|
||||
func(j *metav1.LabelSelector, c fuzz.Continue) {
|
||||
c.FuzzNoCustom(j)
|
||||
// we can't have an entirely empty selector, so force
|
||||
// use of MatchExpression if necessary
|
||||
if len(j.MatchLabels) == 0 && len(j.MatchExpressions) == 0 {
|
||||
j.MatchExpressions = make([]metav1.LabelSelectorRequirement, c.Rand.Intn(2)+1)
|
||||
}
|
||||
|
||||
if j.MatchLabels != nil {
|
||||
fuzzedMatchLabels := make(map[string]string, len(j.MatchLabels))
|
||||
for i := 0; i < len(j.MatchLabels); i++ {
|
||||
fuzzedMatchLabels[randomLabelKey(c)] = randomLabelPart(c, true)
|
||||
}
|
||||
j.MatchLabels = fuzzedMatchLabels
|
||||
}
|
||||
|
||||
validOperators := []metav1.LabelSelectorOperator{
|
||||
metav1.LabelSelectorOpIn,
|
||||
metav1.LabelSelectorOpNotIn,
|
||||
metav1.LabelSelectorOpExists,
|
||||
metav1.LabelSelectorOpDoesNotExist,
|
||||
}
|
||||
|
||||
if j.MatchExpressions != nil {
|
||||
// NB: the label selector parser code sorts match expressions by key, and sorts the values,
|
||||
// so we need to make sure ours are sorted as well here to preserve round-trip comparison.
|
||||
// In practice, not sorting doesn't hurt anything...
|
||||
|
||||
for i := range j.MatchExpressions {
|
||||
req := metav1.LabelSelectorRequirement{}
|
||||
c.Fuzz(&req)
|
||||
req.Key = randomLabelKey(c)
|
||||
req.Operator = validOperators[c.Rand.Intn(len(validOperators))]
|
||||
if req.Operator == metav1.LabelSelectorOpIn || req.Operator == metav1.LabelSelectorOpNotIn {
|
||||
if len(req.Values) == 0 {
|
||||
// we must have some values here, so randomly choose a short length
|
||||
req.Values = make([]string, c.Rand.Intn(2)+1)
|
||||
}
|
||||
for i := range req.Values {
|
||||
req.Values[i] = randomLabelPart(c, true)
|
||||
}
|
||||
sort.Strings(req.Values)
|
||||
} else {
|
||||
req.Values = nil
|
||||
}
|
||||
j.MatchExpressions[i] = req
|
||||
}
|
||||
|
||||
sort.Slice(j.MatchExpressions, func(a, b int) bool { return j.MatchExpressions[a].Key < j.MatchExpressions[b].Key })
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func v1alpha1FuzzerFuncs(codecs runtimeserializer.CodecFactory) []interface{} {
|
||||
return []interface{}{
|
||||
func(r *metav1beta1.TableRow, c fuzz.Continue) {
|
||||
c.Fuzz(&r.Object)
|
||||
c.Fuzz(&r.Conditions)
|
||||
if len(r.Conditions) == 0 {
|
||||
r.Conditions = nil
|
||||
}
|
||||
n := c.Intn(10)
|
||||
if n > 0 {
|
||||
r.Cells = make([]interface{}, n)
|
||||
}
|
||||
for i := range r.Cells {
|
||||
t := c.Intn(6)
|
||||
switch t {
|
||||
case 0:
|
||||
r.Cells[i] = c.RandString()
|
||||
case 1:
|
||||
r.Cells[i] = c.Int63()
|
||||
case 2:
|
||||
r.Cells[i] = c.RandBool()
|
||||
case 3:
|
||||
x := map[string]interface{}{}
|
||||
for j := c.Intn(10) + 1; j >= 0; j-- {
|
||||
x[c.RandString()] = c.RandString()
|
||||
}
|
||||
r.Cells[i] = x
|
||||
case 4:
|
||||
x := make([]interface{}, c.Intn(10))
|
||||
for i := range x {
|
||||
x[i] = c.Int63()
|
||||
}
|
||||
r.Cells[i] = x
|
||||
default:
|
||||
r.Cells[i] = nil
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
var Funcs = fuzzer.MergeFuzzerFuncs(
|
||||
genericFuzzerFuncs,
|
||||
v1FuzzerFuncs,
|
||||
v1alpha1FuzzerFuncs,
|
||||
)
|
54
vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/conversion.go
generated
vendored
54
vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/conversion.go
generated
vendored
@ -1,54 +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 internalversion
|
||||
|
||||
import (
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/conversion"
|
||||
)
|
||||
|
||||
func Convert_internalversion_ListOptions_To_v1_ListOptions(in *ListOptions, out *metav1.ListOptions, s conversion.Scope) error {
|
||||
if err := metav1.Convert_fields_Selector_To_string(&in.FieldSelector, &out.FieldSelector, s); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := metav1.Convert_labels_Selector_To_string(&in.LabelSelector, &out.LabelSelector, s); err != nil {
|
||||
return err
|
||||
}
|
||||
out.IncludeUninitialized = in.IncludeUninitialized
|
||||
out.ResourceVersion = in.ResourceVersion
|
||||
out.TimeoutSeconds = in.TimeoutSeconds
|
||||
out.Watch = in.Watch
|
||||
out.Limit = in.Limit
|
||||
out.Continue = in.Continue
|
||||
return nil
|
||||
}
|
||||
|
||||
func Convert_v1_ListOptions_To_internalversion_ListOptions(in *metav1.ListOptions, out *ListOptions, s conversion.Scope) error {
|
||||
if err := metav1.Convert_string_To_fields_Selector(&in.FieldSelector, &out.FieldSelector, s); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := metav1.Convert_string_To_labels_Selector(&in.LabelSelector, &out.LabelSelector, s); err != nil {
|
||||
return err
|
||||
}
|
||||
out.IncludeUninitialized = in.IncludeUninitialized
|
||||
out.ResourceVersion = in.ResourceVersion
|
||||
out.TimeoutSeconds = in.TimeoutSeconds
|
||||
out.Watch = in.Watch
|
||||
out.Limit = in.Limit
|
||||
out.Continue = in.Continue
|
||||
return nil
|
||||
}
|
20
vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/doc.go
generated
vendored
20
vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/doc.go
generated
vendored
@ -1,20 +0,0 @@
|
||||
/*
|
||||
Copyright 2016 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.
|
||||
*/
|
||||
|
||||
// +k8s:deepcopy-gen=package
|
||||
// +k8s:conversion-gen=k8s.io/apimachinery/pkg/apis/meta/v1
|
||||
|
||||
package internalversion
|
113
vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/register.go
generated
vendored
113
vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/register.go
generated
vendored
@ -1,113 +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 internalversion
|
||||
|
||||
import (
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
metav1beta1 "k8s.io/apimachinery/pkg/apis/meta/v1beta1"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
"k8s.io/apimachinery/pkg/runtime/schema"
|
||||
"k8s.io/apimachinery/pkg/runtime/serializer"
|
||||
)
|
||||
|
||||
// GroupName is the group name for this API.
|
||||
const GroupName = "meta.k8s.io"
|
||||
|
||||
// Scheme is the registry for any type that adheres to the meta API spec.
|
||||
var scheme = runtime.NewScheme()
|
||||
|
||||
var (
|
||||
// TODO: move SchemeBuilder with zz_generated.deepcopy.go to k8s.io/api.
|
||||
// localSchemeBuilder and AddToScheme will stay in k8s.io/kubernetes.
|
||||
SchemeBuilder runtime.SchemeBuilder
|
||||
localSchemeBuilder = &SchemeBuilder
|
||||
AddToScheme = localSchemeBuilder.AddToScheme
|
||||
)
|
||||
|
||||
// Codecs provides access to encoding and decoding for the scheme.
|
||||
var Codecs = serializer.NewCodecFactory(scheme)
|
||||
|
||||
// SchemeGroupVersion is group version used to register these objects
|
||||
var SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: runtime.APIVersionInternal}
|
||||
|
||||
// ParameterCodec handles versioning of objects that are converted to query parameters.
|
||||
var ParameterCodec = runtime.NewParameterCodec(scheme)
|
||||
|
||||
// Kind takes an unqualified kind and returns a Group qualified GroupKind
|
||||
func Kind(kind string) schema.GroupKind {
|
||||
return SchemeGroupVersion.WithKind(kind).GroupKind()
|
||||
}
|
||||
|
||||
// addToGroupVersion registers common meta types into schemas.
|
||||
func addToGroupVersion(scheme *runtime.Scheme, groupVersion schema.GroupVersion) error {
|
||||
if err := scheme.AddIgnoredConversionType(&metav1.TypeMeta{}, &metav1.TypeMeta{}); err != nil {
|
||||
return err
|
||||
}
|
||||
err := scheme.AddConversionFuncs(
|
||||
metav1.Convert_string_To_labels_Selector,
|
||||
metav1.Convert_labels_Selector_To_string,
|
||||
|
||||
metav1.Convert_string_To_fields_Selector,
|
||||
metav1.Convert_fields_Selector_To_string,
|
||||
|
||||
metav1.Convert_Map_string_To_string_To_v1_LabelSelector,
|
||||
metav1.Convert_v1_LabelSelector_To_Map_string_To_string,
|
||||
|
||||
Convert_internalversion_ListOptions_To_v1_ListOptions,
|
||||
Convert_v1_ListOptions_To_internalversion_ListOptions,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// ListOptions is the only options struct which needs conversion (it exposes labels and fields
|
||||
// as selectors for convenience). The other types have only a single representation today.
|
||||
scheme.AddKnownTypes(SchemeGroupVersion,
|
||||
&ListOptions{},
|
||||
&metav1.GetOptions{},
|
||||
&metav1.ExportOptions{},
|
||||
&metav1.DeleteOptions{},
|
||||
&metav1.CreateOptions{},
|
||||
&metav1.UpdateOptions{},
|
||||
)
|
||||
scheme.AddKnownTypes(SchemeGroupVersion,
|
||||
&metav1beta1.Table{},
|
||||
&metav1beta1.TableOptions{},
|
||||
&metav1beta1.PartialObjectMetadata{},
|
||||
&metav1beta1.PartialObjectMetadataList{},
|
||||
)
|
||||
scheme.AddKnownTypes(metav1beta1.SchemeGroupVersion,
|
||||
&metav1beta1.Table{},
|
||||
&metav1beta1.TableOptions{},
|
||||
&metav1beta1.PartialObjectMetadata{},
|
||||
&metav1beta1.PartialObjectMetadataList{},
|
||||
)
|
||||
// Allow delete options to be decoded across all version in this scheme (we may want to be more clever than this)
|
||||
scheme.AddUnversionedTypes(SchemeGroupVersion,
|
||||
&metav1.DeleteOptions{},
|
||||
&metav1.CreateOptions{},
|
||||
&metav1.UpdateOptions{})
|
||||
metav1.AddToGroupVersion(scheme, metav1.SchemeGroupVersion)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Unlike other API groups, meta internal knows about all meta external versions, but keeps
|
||||
// the logic for conversion private.
|
||||
func init() {
|
||||
if err := addToGroupVersion(scheme, SchemeGroupVersion); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
89
vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/register_test.go
generated
vendored
89
vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/register_test.go
generated
vendored
@ -1,89 +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 internalversion
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/util/diff"
|
||||
)
|
||||
|
||||
func TestListOptions(t *testing.T) {
|
||||
// verify round trip conversion
|
||||
ten := int64(10)
|
||||
in := &metav1.ListOptions{
|
||||
LabelSelector: "a=1",
|
||||
FieldSelector: "b=1",
|
||||
ResourceVersion: "10",
|
||||
TimeoutSeconds: &ten,
|
||||
Watch: true,
|
||||
}
|
||||
out := &ListOptions{}
|
||||
if err := scheme.Convert(in, out, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
actual := &metav1.ListOptions{}
|
||||
if err := scheme.Convert(out, actual, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(in, actual) {
|
||||
t.Errorf("unexpected: %s", diff.ObjectReflectDiff(in, actual))
|
||||
}
|
||||
|
||||
// verify failing conversion
|
||||
for i, failingObject := range []*metav1.ListOptions{
|
||||
{LabelSelector: "a!!!"},
|
||||
{FieldSelector: "a!!!"},
|
||||
} {
|
||||
out = &ListOptions{}
|
||||
if err := scheme.Convert(failingObject, out, nil); err == nil {
|
||||
t.Errorf("%d: unexpected conversion: %#v", i, out)
|
||||
}
|
||||
}
|
||||
|
||||
// verify kind registration
|
||||
if gvks, unversioned, err := scheme.ObjectKinds(in); err != nil || unversioned || gvks[0] != metav1.SchemeGroupVersion.WithKind("ListOptions") {
|
||||
t.Errorf("unexpected: %v %v %v", gvks[0], unversioned, err)
|
||||
}
|
||||
if gvks, unversioned, err := scheme.ObjectKinds(out); err != nil || unversioned || gvks[0] != SchemeGroupVersion.WithKind("ListOptions") {
|
||||
t.Errorf("unexpected: %v %v %v", gvks[0], unversioned, err)
|
||||
}
|
||||
|
||||
actual = &metav1.ListOptions{}
|
||||
if err := ParameterCodec.DecodeParameters(url.Values{"watch": []string{"1"}}, metav1.SchemeGroupVersion, actual); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !actual.Watch {
|
||||
t.Errorf("unexpected watch decode: %#v", actual)
|
||||
}
|
||||
|
||||
// check ParameterCodec
|
||||
query, err := ParameterCodec.EncodeParameters(in, metav1.SchemeGroupVersion)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
actual = &metav1.ListOptions{}
|
||||
if err := ParameterCodec.DecodeParameters(query, metav1.SchemeGroupVersion, actual); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(in, actual) {
|
||||
t.Errorf("unexpected: %s", diff.ObjectReflectDiff(in, actual))
|
||||
}
|
||||
}
|
28
vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/roundtrip_test.go
generated
vendored
28
vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/roundtrip_test.go
generated
vendored
@ -1,28 +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 internalversion
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"k8s.io/apimachinery/pkg/api/apitesting/roundtrip"
|
||||
"k8s.io/apimachinery/pkg/apis/meta/fuzzer"
|
||||
)
|
||||
|
||||
func TestRoundTrip(t *testing.T) {
|
||||
roundtrip.RoundTripTestForScheme(t, scheme, fuzzer.Funcs)
|
||||
}
|
70
vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/types.go
generated
vendored
70
vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/types.go
generated
vendored
@ -1,70 +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 internalversion
|
||||
|
||||
import (
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/fields"
|
||||
"k8s.io/apimachinery/pkg/labels"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
)
|
||||
|
||||
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
|
||||
|
||||
// ListOptions is the query options to a standard REST list call.
|
||||
type ListOptions struct {
|
||||
metav1.TypeMeta
|
||||
|
||||
// A selector based on labels
|
||||
LabelSelector labels.Selector
|
||||
// A selector based on fields
|
||||
FieldSelector fields.Selector
|
||||
// If true, partially initialized resources are included in the response.
|
||||
// +optional
|
||||
IncludeUninitialized bool
|
||||
// If true, watch for changes to this list
|
||||
Watch bool
|
||||
// When specified with a watch call, shows changes that occur after that particular version of a resource.
|
||||
// Defaults to changes from the beginning of history.
|
||||
// When specified for list:
|
||||
// - if unset, then the result is returned from remote storage based on quorum-read flag;
|
||||
// - if it's 0, then we simply return what we currently have in cache, no guarantee;
|
||||
// - if set to non zero, then the result is at least as fresh as given rv.
|
||||
ResourceVersion string
|
||||
// Timeout for the list/watch call.
|
||||
TimeoutSeconds *int64
|
||||
// Limit specifies the maximum number of results to return from the server. The server may
|
||||
// not support this field on all resource types, but if it does and more results remain it
|
||||
// will set the continue field on the returned list object.
|
||||
Limit int64
|
||||
// Continue is a token returned by the server that lets a client retrieve chunks of results
|
||||
// from the server by specifying limit. The server may reject requests for continuation tokens
|
||||
// it does not recognize and will return a 410 error if the token can no longer be used because
|
||||
// it has expired.
|
||||
Continue string
|
||||
}
|
||||
|
||||
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
|
||||
|
||||
// List holds a list of objects, which may not be known by the server.
|
||||
type List struct {
|
||||
metav1.TypeMeta
|
||||
// +optional
|
||||
metav1.ListMeta
|
||||
|
||||
Items []runtime.Object
|
||||
}
|
143
vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/zz_generated.conversion.go
generated
vendored
143
vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/zz_generated.conversion.go
generated
vendored
@ -1,143 +0,0 @@
|
||||
// +build !ignore_autogenerated
|
||||
|
||||
/*
|
||||
Copyright 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.
|
||||
*/
|
||||
|
||||
// Code generated by conversion-gen. DO NOT EDIT.
|
||||
|
||||
package internalversion
|
||||
|
||||
import (
|
||||
unsafe "unsafe"
|
||||
|
||||
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
conversion "k8s.io/apimachinery/pkg/conversion"
|
||||
runtime "k8s.io/apimachinery/pkg/runtime"
|
||||
)
|
||||
|
||||
func init() {
|
||||
localSchemeBuilder.Register(RegisterConversions)
|
||||
}
|
||||
|
||||
// RegisterConversions adds conversion functions to the given scheme.
|
||||
// Public to allow building arbitrary schemes.
|
||||
func RegisterConversions(s *runtime.Scheme) error {
|
||||
if err := s.AddGeneratedConversionFunc((*List)(nil), (*v1.List)(nil), func(a, b interface{}, scope conversion.Scope) error {
|
||||
return Convert_internalversion_List_To_v1_List(a.(*List), b.(*v1.List), scope)
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.AddGeneratedConversionFunc((*v1.List)(nil), (*List)(nil), func(a, b interface{}, scope conversion.Scope) error {
|
||||
return Convert_v1_List_To_internalversion_List(a.(*v1.List), b.(*List), scope)
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.AddGeneratedConversionFunc((*ListOptions)(nil), (*v1.ListOptions)(nil), func(a, b interface{}, scope conversion.Scope) error {
|
||||
return Convert_internalversion_ListOptions_To_v1_ListOptions(a.(*ListOptions), b.(*v1.ListOptions), scope)
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.AddGeneratedConversionFunc((*v1.ListOptions)(nil), (*ListOptions)(nil), func(a, b interface{}, scope conversion.Scope) error {
|
||||
return Convert_v1_ListOptions_To_internalversion_ListOptions(a.(*v1.ListOptions), b.(*ListOptions), scope)
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.AddConversionFunc((*ListOptions)(nil), (*v1.ListOptions)(nil), func(a, b interface{}, scope conversion.Scope) error {
|
||||
return Convert_internalversion_ListOptions_To_v1_ListOptions(a.(*ListOptions), b.(*v1.ListOptions), scope)
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.AddConversionFunc((*v1.ListOptions)(nil), (*ListOptions)(nil), func(a, b interface{}, scope conversion.Scope) error {
|
||||
return Convert_v1_ListOptions_To_internalversion_ListOptions(a.(*v1.ListOptions), b.(*ListOptions), scope)
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func autoConvert_internalversion_List_To_v1_List(in *List, out *v1.List, s conversion.Scope) error {
|
||||
out.ListMeta = in.ListMeta
|
||||
if in.Items != nil {
|
||||
in, out := &in.Items, &out.Items
|
||||
*out = make([]runtime.RawExtension, len(*in))
|
||||
for i := range *in {
|
||||
if err := runtime.Convert_runtime_Object_To_runtime_RawExtension(&(*in)[i], &(*out)[i], s); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
} else {
|
||||
out.Items = nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Convert_internalversion_List_To_v1_List is an autogenerated conversion function.
|
||||
func Convert_internalversion_List_To_v1_List(in *List, out *v1.List, s conversion.Scope) error {
|
||||
return autoConvert_internalversion_List_To_v1_List(in, out, s)
|
||||
}
|
||||
|
||||
func autoConvert_v1_List_To_internalversion_List(in *v1.List, out *List, s conversion.Scope) error {
|
||||
out.ListMeta = in.ListMeta
|
||||
if in.Items != nil {
|
||||
in, out := &in.Items, &out.Items
|
||||
*out = make([]runtime.Object, len(*in))
|
||||
for i := range *in {
|
||||
if err := runtime.Convert_runtime_RawExtension_To_runtime_Object(&(*in)[i], &(*out)[i], s); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
} else {
|
||||
out.Items = nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Convert_v1_List_To_internalversion_List is an autogenerated conversion function.
|
||||
func Convert_v1_List_To_internalversion_List(in *v1.List, out *List, s conversion.Scope) error {
|
||||
return autoConvert_v1_List_To_internalversion_List(in, out, s)
|
||||
}
|
||||
|
||||
func autoConvert_internalversion_ListOptions_To_v1_ListOptions(in *ListOptions, out *v1.ListOptions, s conversion.Scope) error {
|
||||
if err := v1.Convert_labels_Selector_To_string(&in.LabelSelector, &out.LabelSelector, s); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := v1.Convert_fields_Selector_To_string(&in.FieldSelector, &out.FieldSelector, s); err != nil {
|
||||
return err
|
||||
}
|
||||
out.IncludeUninitialized = in.IncludeUninitialized
|
||||
out.Watch = in.Watch
|
||||
out.ResourceVersion = in.ResourceVersion
|
||||
out.TimeoutSeconds = (*int64)(unsafe.Pointer(in.TimeoutSeconds))
|
||||
out.Limit = in.Limit
|
||||
out.Continue = in.Continue
|
||||
return nil
|
||||
}
|
||||
|
||||
func autoConvert_v1_ListOptions_To_internalversion_ListOptions(in *v1.ListOptions, out *ListOptions, s conversion.Scope) error {
|
||||
if err := v1.Convert_string_To_labels_Selector(&in.LabelSelector, &out.LabelSelector, s); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := v1.Convert_string_To_fields_Selector(&in.FieldSelector, &out.FieldSelector, s); err != nil {
|
||||
return err
|
||||
}
|
||||
out.IncludeUninitialized = in.IncludeUninitialized
|
||||
out.Watch = in.Watch
|
||||
out.ResourceVersion = in.ResourceVersion
|
||||
out.TimeoutSeconds = (*int64)(unsafe.Pointer(in.TimeoutSeconds))
|
||||
out.Limit = in.Limit
|
||||
out.Continue = in.Continue
|
||||
return nil
|
||||
}
|
96
vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/zz_generated.deepcopy.go
generated
vendored
96
vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/zz_generated.deepcopy.go
generated
vendored
@ -1,96 +0,0 @@
|
||||
// +build !ignore_autogenerated
|
||||
|
||||
/*
|
||||
Copyright 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.
|
||||
*/
|
||||
|
||||
// Code generated by deepcopy-gen. DO NOT EDIT.
|
||||
|
||||
package internalversion
|
||||
|
||||
import (
|
||||
runtime "k8s.io/apimachinery/pkg/runtime"
|
||||
)
|
||||
|
||||
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
|
||||
func (in *List) DeepCopyInto(out *List) {
|
||||
*out = *in
|
||||
out.TypeMeta = in.TypeMeta
|
||||
out.ListMeta = in.ListMeta
|
||||
if in.Items != nil {
|
||||
in, out := &in.Items, &out.Items
|
||||
*out = make([]runtime.Object, len(*in))
|
||||
for i := range *in {
|
||||
if (*in)[i] != nil {
|
||||
(*out)[i] = (*in)[i].DeepCopyObject()
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new List.
|
||||
func (in *List) DeepCopy() *List {
|
||||
if in == nil {
|
||||
return nil
|
||||
}
|
||||
out := new(List)
|
||||
in.DeepCopyInto(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
|
||||
func (in *List) DeepCopyObject() runtime.Object {
|
||||
if c := in.DeepCopy(); c != nil {
|
||||
return c
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
|
||||
func (in *ListOptions) DeepCopyInto(out *ListOptions) {
|
||||
*out = *in
|
||||
out.TypeMeta = in.TypeMeta
|
||||
if in.LabelSelector != nil {
|
||||
out.LabelSelector = in.LabelSelector.DeepCopySelector()
|
||||
}
|
||||
if in.FieldSelector != nil {
|
||||
out.FieldSelector = in.FieldSelector.DeepCopySelector()
|
||||
}
|
||||
if in.TimeoutSeconds != nil {
|
||||
in, out := &in.TimeoutSeconds, &out.TimeoutSeconds
|
||||
*out = new(int64)
|
||||
**out = **in
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ListOptions.
|
||||
func (in *ListOptions) DeepCopy() *ListOptions {
|
||||
if in == nil {
|
||||
return nil
|
||||
}
|
||||
out := new(ListOptions)
|
||||
in.DeepCopyInto(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
|
||||
func (in *ListOptions) DeepCopyObject() runtime.Object {
|
||||
if c := in.DeepCopy(); c != nil {
|
||||
return c
|
||||
}
|
||||
return nil
|
||||
}
|
31
vendor/k8s.io/apimachinery/pkg/apis/meta/v1/OWNERS
generated
vendored
31
vendor/k8s.io/apimachinery/pkg/apis/meta/v1/OWNERS
generated
vendored
@ -1,31 +0,0 @@
|
||||
reviewers:
|
||||
- thockin
|
||||
- smarterclayton
|
||||
- wojtek-t
|
||||
- deads2k
|
||||
- brendandburns
|
||||
- caesarxuchao
|
||||
- liggitt
|
||||
- nikhiljindal
|
||||
- gmarek
|
||||
- erictune
|
||||
- davidopp
|
||||
- sttts
|
||||
- quinton-hoole
|
||||
- luxas
|
||||
- janetkuo
|
||||
- justinsb
|
||||
- ncdc
|
||||
- soltysh
|
||||
- dims
|
||||
- madhusudancs
|
||||
- hongchaodeng
|
||||
- krousey
|
||||
- mml
|
||||
- mbohlool
|
||||
- david-mcmahon
|
||||
- therc
|
||||
- mqliang
|
||||
- kevin-wangzefeng
|
||||
- jianhuiz
|
||||
- feihujiang
|
133
vendor/k8s.io/apimachinery/pkg/apis/meta/v1/controller_ref_test.go
generated
vendored
133
vendor/k8s.io/apimachinery/pkg/apis/meta/v1/controller_ref_test.go
generated
vendored
@ -1,133 +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 v1
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"k8s.io/apimachinery/pkg/runtime/schema"
|
||||
)
|
||||
|
||||
type metaObj struct {
|
||||
ObjectMeta
|
||||
TypeMeta
|
||||
}
|
||||
|
||||
func TestNewControllerRef(t *testing.T) {
|
||||
gvk := schema.GroupVersionKind{
|
||||
Group: "group",
|
||||
Version: "v1",
|
||||
Kind: "Kind",
|
||||
}
|
||||
obj1 := &metaObj{
|
||||
ObjectMeta: ObjectMeta{
|
||||
Name: "name",
|
||||
UID: "uid1",
|
||||
},
|
||||
}
|
||||
controllerRef := NewControllerRef(obj1, gvk)
|
||||
if controllerRef.UID != obj1.UID {
|
||||
t.Errorf("Incorrect UID: %s", controllerRef.UID)
|
||||
}
|
||||
if controllerRef.Controller == nil || *controllerRef.Controller != true {
|
||||
t.Error("Controller must be set to true")
|
||||
}
|
||||
if controllerRef.BlockOwnerDeletion == nil || *controllerRef.BlockOwnerDeletion != true {
|
||||
t.Error("BlockOwnerDeletion must be set to true")
|
||||
}
|
||||
if controllerRef.APIVersion == "" ||
|
||||
controllerRef.Kind == "" ||
|
||||
controllerRef.Name == "" {
|
||||
t.Errorf("All controllerRef fields must be set: %v", controllerRef)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetControllerOf(t *testing.T) {
|
||||
gvk := schema.GroupVersionKind{
|
||||
Group: "group",
|
||||
Version: "v1",
|
||||
Kind: "Kind",
|
||||
}
|
||||
obj1 := &metaObj{
|
||||
ObjectMeta: ObjectMeta{
|
||||
UID: "uid1",
|
||||
Name: "name1",
|
||||
},
|
||||
}
|
||||
controllerRef := NewControllerRef(obj1, gvk)
|
||||
var falseRef = false
|
||||
obj2 := &metaObj{
|
||||
ObjectMeta: ObjectMeta{
|
||||
UID: "uid2",
|
||||
Name: "name1",
|
||||
OwnerReferences: []OwnerReference{
|
||||
{
|
||||
Name: "owner1",
|
||||
Controller: &falseRef,
|
||||
},
|
||||
*controllerRef,
|
||||
{
|
||||
Name: "owner2",
|
||||
Controller: &falseRef,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
if GetControllerOf(obj1) != nil {
|
||||
t.Error("GetControllerOf must return null")
|
||||
}
|
||||
c := GetControllerOf(obj2)
|
||||
if c.Name != controllerRef.Name || c.UID != controllerRef.UID {
|
||||
t.Errorf("Incorrect result of GetControllerOf: %v", c)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsControlledBy(t *testing.T) {
|
||||
gvk := schema.GroupVersionKind{
|
||||
Group: "group",
|
||||
Version: "v1",
|
||||
Kind: "Kind",
|
||||
}
|
||||
obj1 := &metaObj{
|
||||
ObjectMeta: ObjectMeta{
|
||||
UID: "uid1",
|
||||
},
|
||||
}
|
||||
obj2 := &metaObj{
|
||||
ObjectMeta: ObjectMeta{
|
||||
UID: "uid2",
|
||||
OwnerReferences: []OwnerReference{
|
||||
*NewControllerRef(obj1, gvk),
|
||||
},
|
||||
},
|
||||
}
|
||||
obj3 := &metaObj{
|
||||
ObjectMeta: ObjectMeta{
|
||||
UID: "uid3",
|
||||
OwnerReferences: []OwnerReference{
|
||||
*NewControllerRef(obj2, gvk),
|
||||
},
|
||||
},
|
||||
}
|
||||
if !IsControlledBy(obj2, obj1) || !IsControlledBy(obj3, obj2) {
|
||||
t.Error("Incorrect IsControlledBy result: false")
|
||||
}
|
||||
if IsControlledBy(obj3, obj1) {
|
||||
t.Error("Incorrect IsControlledBy result: true")
|
||||
}
|
||||
}
|
84
vendor/k8s.io/apimachinery/pkg/apis/meta/v1/conversion_test.go
generated
vendored
84
vendor/k8s.io/apimachinery/pkg/apis/meta/v1/conversion_test.go
generated
vendored
@ -1,84 +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 v1_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
apiequality "k8s.io/apimachinery/pkg/api/equality"
|
||||
"k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
)
|
||||
|
||||
func TestMapToLabelSelectorRoundTrip(t *testing.T) {
|
||||
// We should be able to round-trip a map-only selector through LabelSelector.
|
||||
inputs := []map[string]string{
|
||||
nil,
|
||||
{},
|
||||
{"one": "foo"},
|
||||
{"one": "foo", "two": "bar"},
|
||||
}
|
||||
for _, in := range inputs {
|
||||
ls := &v1.LabelSelector{}
|
||||
if err := v1.Convert_Map_string_To_string_To_v1_LabelSelector(&in, ls, nil); err != nil {
|
||||
t.Errorf("Convert_Map_string_To_string_To_v1_LabelSelector(%#v): %v", in, err)
|
||||
continue
|
||||
}
|
||||
out := map[string]string{}
|
||||
if err := v1.Convert_v1_LabelSelector_To_Map_string_To_string(ls, &out, nil); err != nil {
|
||||
t.Errorf("Convert_v1_LabelSelector_To_Map_string_To_string(%#v): %v", ls, err)
|
||||
continue
|
||||
}
|
||||
if !apiequality.Semantic.DeepEqual(in, out) {
|
||||
t.Errorf("map-selector conversion round-trip failed: got %v; want %v", out, in)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestConvertSliceStringToDeletionPropagation(t *testing.T) {
|
||||
tcs := []struct {
|
||||
Input []string
|
||||
Output v1.DeletionPropagation
|
||||
}{
|
||||
{
|
||||
Input: nil,
|
||||
Output: "",
|
||||
},
|
||||
{
|
||||
Input: []string{},
|
||||
Output: "",
|
||||
},
|
||||
{
|
||||
Input: []string{"foo"},
|
||||
Output: "foo",
|
||||
},
|
||||
{
|
||||
Input: []string{"bar", "foo"},
|
||||
Output: "bar",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tcs {
|
||||
var dp v1.DeletionPropagation
|
||||
if err := v1.Convert_Slice_string_To_v1_DeletionPropagation(&tc.Input, &dp, nil); err != nil {
|
||||
t.Errorf("Convert_Slice_string_To_v1_DeletionPropagation(%#v): %v", tc.Input, err)
|
||||
continue
|
||||
}
|
||||
if !apiequality.Semantic.DeepEqual(dp, tc.Output) {
|
||||
t.Errorf("slice string to DeletionPropagation conversion failed: got %v; want %v", dp, tc.Output)
|
||||
}
|
||||
}
|
||||
}
|
153
vendor/k8s.io/apimachinery/pkg/apis/meta/v1/duration_test.go
generated
vendored
153
vendor/k8s.io/apimachinery/pkg/apis/meta/v1/duration_test.go
generated
vendored
@ -1,153 +0,0 @@
|
||||
/*
|
||||
Copyright 2014 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 v1
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"sigs.k8s.io/yaml"
|
||||
)
|
||||
|
||||
type DurationHolder struct {
|
||||
D Duration `json:"d"`
|
||||
}
|
||||
|
||||
func TestDurationMarshalYAML(t *testing.T) {
|
||||
cases := []struct {
|
||||
input Duration
|
||||
result string
|
||||
}{
|
||||
{Duration{5 * time.Second}, "d: 5s\n"},
|
||||
{Duration{2 * time.Minute}, "d: 2m0s\n"},
|
||||
{Duration{time.Hour + 3*time.Millisecond}, "d: 1h0m0.003s\n"},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
input := DurationHolder{c.input}
|
||||
result, err := yaml.Marshal(&input)
|
||||
if err != nil {
|
||||
t.Errorf("Failed to marshal input: %q: %v", input, err)
|
||||
}
|
||||
if string(result) != c.result {
|
||||
t.Errorf("Failed to marshal input: %q: expected %q, got %q", input, c.result, string(result))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDurationUnmarshalYAML(t *testing.T) {
|
||||
cases := []struct {
|
||||
input string
|
||||
result Duration
|
||||
}{
|
||||
{"d: 0s\n", Duration{}},
|
||||
{"d: 5s\n", Duration{5 * time.Second}},
|
||||
{"d: 2m0s\n", Duration{2 * time.Minute}},
|
||||
{"d: 1h0m0.003s\n", Duration{time.Hour + 3*time.Millisecond}},
|
||||
|
||||
// Units with zero values can optionally be dropped
|
||||
{"d: 2m\n", Duration{2 * time.Minute}},
|
||||
{"d: 1h0.003s\n", Duration{time.Hour + 3*time.Millisecond}},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
var result DurationHolder
|
||||
if err := yaml.Unmarshal([]byte(c.input), &result); err != nil {
|
||||
t.Errorf("Failed to unmarshal input %q: %v", c.input, err)
|
||||
}
|
||||
if result.D != c.result {
|
||||
t.Errorf("Failed to unmarshal input %q: expected %q, got %q", c.input, c.result, result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDurationMarshalJSON(t *testing.T) {
|
||||
cases := []struct {
|
||||
input Duration
|
||||
result string
|
||||
}{
|
||||
{Duration{5 * time.Second}, `{"d":"5s"}`},
|
||||
{Duration{2 * time.Minute}, `{"d":"2m0s"}`},
|
||||
{Duration{time.Hour + 3*time.Millisecond}, `{"d":"1h0m0.003s"}`},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
input := DurationHolder{c.input}
|
||||
result, err := json.Marshal(&input)
|
||||
if err != nil {
|
||||
t.Errorf("Failed to marshal input: %q: %v", input, err)
|
||||
}
|
||||
if string(result) != c.result {
|
||||
t.Errorf("Failed to marshal input: %q: expected %q, got %q", input, c.result, string(result))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDurationUnmarshalJSON(t *testing.T) {
|
||||
cases := []struct {
|
||||
input string
|
||||
result Duration
|
||||
}{
|
||||
{`{"d":"0s"}`, Duration{}},
|
||||
{`{"d":"5s"}`, Duration{5 * time.Second}},
|
||||
{`{"d":"2m0s"}`, Duration{2 * time.Minute}},
|
||||
{`{"d":"1h0m0.003s"}`, Duration{time.Hour + 3*time.Millisecond}},
|
||||
|
||||
// Units with zero values can optionally be dropped
|
||||
{`{"d":"2m"}`, Duration{2 * time.Minute}},
|
||||
{`{"d":"1h0.003s"}`, Duration{time.Hour + 3*time.Millisecond}},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
var result DurationHolder
|
||||
if err := json.Unmarshal([]byte(c.input), &result); err != nil {
|
||||
t.Errorf("Failed to unmarshal input %q: %v", c.input, err)
|
||||
}
|
||||
if result.D != c.result {
|
||||
t.Errorf("Failed to unmarshal input %q: expected %q, got %q", c.input, c.result, result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDurationMarshalJSONUnmarshalYAML(t *testing.T) {
|
||||
cases := []struct {
|
||||
input Duration
|
||||
}{
|
||||
{Duration{}},
|
||||
{Duration{5 * time.Second}},
|
||||
{Duration{2 * time.Minute}},
|
||||
{Duration{time.Hour + 3*time.Millisecond}},
|
||||
}
|
||||
|
||||
for i, c := range cases {
|
||||
input := DurationHolder{c.input}
|
||||
jsonMarshalled, err := json.Marshal(&input)
|
||||
if err != nil {
|
||||
t.Errorf("%d-1: Failed to marshal input: '%v': %v", i, input, err)
|
||||
}
|
||||
|
||||
var result DurationHolder
|
||||
if err := yaml.Unmarshal(jsonMarshalled, &result); err != nil {
|
||||
t.Errorf("%d-2: Failed to unmarshal '%+v': %v", i, string(jsonMarshalled), err)
|
||||
}
|
||||
|
||||
if input.D != result.D {
|
||||
t.Errorf("%d-4: Failed to marshal input '%#v': got %#v", i, input, result)
|
||||
}
|
||||
}
|
||||
}
|
879
vendor/k8s.io/apimachinery/pkg/apis/meta/v1/generated.proto
generated
vendored
879
vendor/k8s.io/apimachinery/pkg/apis/meta/v1/generated.proto
generated
vendored
@ -1,879 +0,0 @@
|
||||
/*
|
||||
Copyright 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.
|
||||
*/
|
||||
|
||||
|
||||
// This file was autogenerated by go-to-protobuf. Do not edit it manually!
|
||||
|
||||
syntax = 'proto2';
|
||||
|
||||
package k8s.io.apimachinery.pkg.apis.meta.v1;
|
||||
|
||||
import "k8s.io/apimachinery/pkg/runtime/generated.proto";
|
||||
import "k8s.io/apimachinery/pkg/runtime/schema/generated.proto";
|
||||
|
||||
// Package-wide variables from generator "generated".
|
||||
option go_package = "v1";
|
||||
|
||||
// APIGroup contains the name, the supported versions, and the preferred version
|
||||
// of a group.
|
||||
message APIGroup {
|
||||
// name is the name of the group.
|
||||
optional string name = 1;
|
||||
|
||||
// versions are the versions supported in this group.
|
||||
repeated GroupVersionForDiscovery versions = 2;
|
||||
|
||||
// preferredVersion is the version preferred by the API server, which
|
||||
// probably is the storage version.
|
||||
// +optional
|
||||
optional GroupVersionForDiscovery preferredVersion = 3;
|
||||
|
||||
// a map of client CIDR to server address that is serving this group.
|
||||
// This is to help clients reach servers in the most network-efficient way possible.
|
||||
// Clients can use the appropriate server address as per the CIDR that they match.
|
||||
// In case of multiple matches, clients should use the longest matching CIDR.
|
||||
// The server returns only those CIDRs that it thinks that the client can match.
|
||||
// For example: the master will return an internal IP CIDR only, if the client reaches the server using an internal IP.
|
||||
// Server looks at X-Forwarded-For header or X-Real-Ip header or request.RemoteAddr (in that order) to get the client IP.
|
||||
// +optional
|
||||
repeated ServerAddressByClientCIDR serverAddressByClientCIDRs = 4;
|
||||
}
|
||||
|
||||
// APIGroupList is a list of APIGroup, to allow clients to discover the API at
|
||||
// /apis.
|
||||
message APIGroupList {
|
||||
// groups is a list of APIGroup.
|
||||
repeated APIGroup groups = 1;
|
||||
}
|
||||
|
||||
// APIResource specifies the name of a resource and whether it is namespaced.
|
||||
message APIResource {
|
||||
// name is the plural name of the resource.
|
||||
optional string name = 1;
|
||||
|
||||
// singularName is the singular name of the resource. This allows clients to handle plural and singular opaquely.
|
||||
// The singularName is more correct for reporting status on a single item and both singular and plural are allowed
|
||||
// from the kubectl CLI interface.
|
||||
optional string singularName = 6;
|
||||
|
||||
// namespaced indicates if a resource is namespaced or not.
|
||||
optional bool namespaced = 2;
|
||||
|
||||
// group is the preferred group of the resource. Empty implies the group of the containing resource list.
|
||||
// For subresources, this may have a different value, for example: Scale".
|
||||
optional string group = 8;
|
||||
|
||||
// version is the preferred version of the resource. Empty implies the version of the containing resource list
|
||||
// For subresources, this may have a different value, for example: v1 (while inside a v1beta1 version of the core resource's group)".
|
||||
optional string version = 9;
|
||||
|
||||
// kind is the kind for the resource (e.g. 'Foo' is the kind for a resource 'foo')
|
||||
optional string kind = 3;
|
||||
|
||||
// verbs is a list of supported kube verbs (this includes get, list, watch, create,
|
||||
// update, patch, delete, deletecollection, and proxy)
|
||||
optional Verbs verbs = 4;
|
||||
|
||||
// shortNames is a list of suggested short names of the resource.
|
||||
repeated string shortNames = 5;
|
||||
|
||||
// categories is a list of the grouped resources this resource belongs to (e.g. 'all')
|
||||
repeated string categories = 7;
|
||||
}
|
||||
|
||||
// APIResourceList is a list of APIResource, it is used to expose the name of the
|
||||
// resources supported in a specific group and version, and if the resource
|
||||
// is namespaced.
|
||||
message APIResourceList {
|
||||
// groupVersion is the group and version this APIResourceList is for.
|
||||
optional string groupVersion = 1;
|
||||
|
||||
// resources contains the name of the resources and if they are namespaced.
|
||||
repeated APIResource resources = 2;
|
||||
}
|
||||
|
||||
// APIVersions lists the versions that are available, to allow clients to
|
||||
// discover the API at /api, which is the root path of the legacy v1 API.
|
||||
//
|
||||
// +protobuf.options.(gogoproto.goproto_stringer)=false
|
||||
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
|
||||
message APIVersions {
|
||||
// versions are the api versions that are available.
|
||||
repeated string versions = 1;
|
||||
|
||||
// a map of client CIDR to server address that is serving this group.
|
||||
// This is to help clients reach servers in the most network-efficient way possible.
|
||||
// Clients can use the appropriate server address as per the CIDR that they match.
|
||||
// In case of multiple matches, clients should use the longest matching CIDR.
|
||||
// The server returns only those CIDRs that it thinks that the client can match.
|
||||
// For example: the master will return an internal IP CIDR only, if the client reaches the server using an internal IP.
|
||||
// Server looks at X-Forwarded-For header or X-Real-Ip header or request.RemoteAddr (in that order) to get the client IP.
|
||||
repeated ServerAddressByClientCIDR serverAddressByClientCIDRs = 2;
|
||||
}
|
||||
|
||||
// CreateOptions may be provided when creating an API object.
|
||||
message CreateOptions {
|
||||
// When present, indicates that modifications should not be
|
||||
// persisted. An invalid or unrecognized dryRun directive will
|
||||
// result in an error response and no further processing of the
|
||||
// request. Valid values are:
|
||||
// - All: all dry run stages will be processed
|
||||
// +optional
|
||||
repeated string dryRun = 1;
|
||||
|
||||
// If IncludeUninitialized is specified, the object may be
|
||||
// returned without completing initialization.
|
||||
optional bool includeUninitialized = 2;
|
||||
}
|
||||
|
||||
// DeleteOptions may be provided when deleting an API object.
|
||||
message DeleteOptions {
|
||||
// The duration in seconds before the object should be deleted. Value must be non-negative integer.
|
||||
// The value zero indicates delete immediately. If this value is nil, the default grace period for the
|
||||
// specified type will be used.
|
||||
// Defaults to a per object value if not specified. zero means delete immediately.
|
||||
// +optional
|
||||
optional int64 gracePeriodSeconds = 1;
|
||||
|
||||
// Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be
|
||||
// returned.
|
||||
// +optional
|
||||
optional Preconditions preconditions = 2;
|
||||
|
||||
// Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7.
|
||||
// Should the dependent objects be orphaned. If true/false, the "orphan"
|
||||
// finalizer will be added to/removed from the object's finalizers list.
|
||||
// Either this field or PropagationPolicy may be set, but not both.
|
||||
// +optional
|
||||
optional bool orphanDependents = 3;
|
||||
|
||||
// Whether and how garbage collection will be performed.
|
||||
// Either this field or OrphanDependents may be set, but not both.
|
||||
// The default policy is decided by the existing finalizer set in the
|
||||
// metadata.finalizers and the resource-specific default policy.
|
||||
// Acceptable values are: 'Orphan' - orphan the dependents; 'Background' -
|
||||
// allow the garbage collector to delete the dependents in the background;
|
||||
// 'Foreground' - a cascading policy that deletes all dependents in the
|
||||
// foreground.
|
||||
// +optional
|
||||
optional string propagationPolicy = 4;
|
||||
|
||||
// When present, indicates that modifications should not be
|
||||
// persisted. An invalid or unrecognized dryRun directive will
|
||||
// result in an error response and no further processing of the
|
||||
// request. Valid values are:
|
||||
// - All: all dry run stages will be processed
|
||||
// +optional
|
||||
repeated string dryRun = 5;
|
||||
}
|
||||
|
||||
// Duration is a wrapper around time.Duration which supports correct
|
||||
// marshaling to YAML and JSON. In particular, it marshals into strings, which
|
||||
// can be used as map keys in json.
|
||||
message Duration {
|
||||
optional int64 duration = 1;
|
||||
}
|
||||
|
||||
// ExportOptions is the query options to the standard REST get call.
|
||||
message ExportOptions {
|
||||
// Should this value be exported. Export strips fields that a user can not specify.
|
||||
optional bool export = 1;
|
||||
|
||||
// Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'.
|
||||
optional bool exact = 2;
|
||||
}
|
||||
|
||||
// GetOptions is the standard query options to the standard REST get call.
|
||||
message GetOptions {
|
||||
// When specified:
|
||||
// - if unset, then the result is returned from remote storage based on quorum-read flag;
|
||||
// - if it's 0, then we simply return what we currently have in cache, no guarantee;
|
||||
// - if set to non zero, then the result is at least as fresh as given rv.
|
||||
optional string resourceVersion = 1;
|
||||
|
||||
// If true, partially initialized resources are included in the response.
|
||||
// +optional
|
||||
optional bool includeUninitialized = 2;
|
||||
}
|
||||
|
||||
// GroupKind specifies a Group and a Kind, but does not force a version. This is useful for identifying
|
||||
// concepts during lookup stages without having partially valid types
|
||||
//
|
||||
// +protobuf.options.(gogoproto.goproto_stringer)=false
|
||||
message GroupKind {
|
||||
optional string group = 1;
|
||||
|
||||
optional string kind = 2;
|
||||
}
|
||||
|
||||
// GroupResource specifies a Group and a Resource, but does not force a version. This is useful for identifying
|
||||
// concepts during lookup stages without having partially valid types
|
||||
//
|
||||
// +protobuf.options.(gogoproto.goproto_stringer)=false
|
||||
message GroupResource {
|
||||
optional string group = 1;
|
||||
|
||||
optional string resource = 2;
|
||||
}
|
||||
|
||||
// GroupVersion contains the "group" and the "version", which uniquely identifies the API.
|
||||
//
|
||||
// +protobuf.options.(gogoproto.goproto_stringer)=false
|
||||
message GroupVersion {
|
||||
optional string group = 1;
|
||||
|
||||
optional string version = 2;
|
||||
}
|
||||
|
||||
// GroupVersion contains the "group/version" and "version" string of a version.
|
||||
// It is made a struct to keep extensibility.
|
||||
message GroupVersionForDiscovery {
|
||||
// groupVersion specifies the API group and version in the form "group/version"
|
||||
optional string groupVersion = 1;
|
||||
|
||||
// version specifies the version in the form of "version". This is to save
|
||||
// the clients the trouble of splitting the GroupVersion.
|
||||
optional string version = 2;
|
||||
}
|
||||
|
||||
// GroupVersionKind unambiguously identifies a kind. It doesn't anonymously include GroupVersion
|
||||
// to avoid automatic coersion. It doesn't use a GroupVersion to avoid custom marshalling
|
||||
//
|
||||
// +protobuf.options.(gogoproto.goproto_stringer)=false
|
||||
message GroupVersionKind {
|
||||
optional string group = 1;
|
||||
|
||||
optional string version = 2;
|
||||
|
||||
optional string kind = 3;
|
||||
}
|
||||
|
||||
// GroupVersionResource unambiguously identifies a resource. It doesn't anonymously include GroupVersion
|
||||
// to avoid automatic coersion. It doesn't use a GroupVersion to avoid custom marshalling
|
||||
//
|
||||
// +protobuf.options.(gogoproto.goproto_stringer)=false
|
||||
message GroupVersionResource {
|
||||
optional string group = 1;
|
||||
|
||||
optional string version = 2;
|
||||
|
||||
optional string resource = 3;
|
||||
}
|
||||
|
||||
// Initializer is information about an initializer that has not yet completed.
|
||||
message Initializer {
|
||||
// name of the process that is responsible for initializing this object.
|
||||
optional string name = 1;
|
||||
}
|
||||
|
||||
// Initializers tracks the progress of initialization.
|
||||
message Initializers {
|
||||
// Pending is a list of initializers that must execute in order before this object is visible.
|
||||
// When the last pending initializer is removed, and no failing result is set, the initializers
|
||||
// struct will be set to nil and the object is considered as initialized and visible to all
|
||||
// clients.
|
||||
// +patchMergeKey=name
|
||||
// +patchStrategy=merge
|
||||
repeated Initializer pending = 1;
|
||||
|
||||
// If result is set with the Failure field, the object will be persisted to storage and then deleted,
|
||||
// ensuring that other clients can observe the deletion.
|
||||
optional Status result = 2;
|
||||
}
|
||||
|
||||
// A label selector is a label query over a set of resources. The result of matchLabels and
|
||||
// matchExpressions are ANDed. An empty label selector matches all objects. A null
|
||||
// label selector matches no objects.
|
||||
message LabelSelector {
|
||||
// matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels
|
||||
// map is equivalent to an element of matchExpressions, whose key field is "key", the
|
||||
// operator is "In", and the values array contains only "value". The requirements are ANDed.
|
||||
// +optional
|
||||
map<string, string> matchLabels = 1;
|
||||
|
||||
// matchExpressions is a list of label selector requirements. The requirements are ANDed.
|
||||
// +optional
|
||||
repeated LabelSelectorRequirement matchExpressions = 2;
|
||||
}
|
||||
|
||||
// A label selector requirement is a selector that contains values, a key, and an operator that
|
||||
// relates the key and values.
|
||||
message LabelSelectorRequirement {
|
||||
// key is the label key that the selector applies to.
|
||||
// +patchMergeKey=key
|
||||
// +patchStrategy=merge
|
||||
optional string key = 1;
|
||||
|
||||
// operator represents a key's relationship to a set of values.
|
||||
// Valid operators are In, NotIn, Exists and DoesNotExist.
|
||||
optional string operator = 2;
|
||||
|
||||
// values is an array of string values. If the operator is In or NotIn,
|
||||
// the values array must be non-empty. If the operator is Exists or DoesNotExist,
|
||||
// the values array must be empty. This array is replaced during a strategic
|
||||
// merge patch.
|
||||
// +optional
|
||||
repeated string values = 3;
|
||||
}
|
||||
|
||||
// List holds a list of objects, which may not be known by the server.
|
||||
message List {
|
||||
// Standard list metadata.
|
||||
// More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
|
||||
// +optional
|
||||
optional ListMeta metadata = 1;
|
||||
|
||||
// List of objects
|
||||
repeated k8s.io.apimachinery.pkg.runtime.RawExtension items = 2;
|
||||
}
|
||||
|
||||
// ListMeta describes metadata that synthetic resources must have, including lists and
|
||||
// various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
|
||||
message ListMeta {
|
||||
// selfLink is a URL representing this object.
|
||||
// Populated by the system.
|
||||
// Read-only.
|
||||
// +optional
|
||||
optional string selfLink = 1;
|
||||
|
||||
// String that identifies the server's internal version of this object that
|
||||
// can be used by clients to determine when objects have changed.
|
||||
// Value must be treated as opaque by clients and passed unmodified back to the server.
|
||||
// Populated by the system.
|
||||
// Read-only.
|
||||
// More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#concurrency-control-and-consistency
|
||||
// +optional
|
||||
optional string resourceVersion = 2;
|
||||
|
||||
// continue may be set if the user set a limit on the number of items returned, and indicates that
|
||||
// the server has more data available. The value is opaque and may be used to issue another request
|
||||
// to the endpoint that served this list to retrieve the next set of available objects. Continuing a
|
||||
// consistent list may not be possible if the server configuration has changed or more than a few
|
||||
// minutes have passed. The resourceVersion field returned when using this continue value will be
|
||||
// identical to the value in the first response, unless you have received this token from an error
|
||||
// message.
|
||||
optional string continue = 3;
|
||||
}
|
||||
|
||||
// ListOptions is the query options to a standard REST list call.
|
||||
message ListOptions {
|
||||
// A selector to restrict the list of returned objects by their labels.
|
||||
// Defaults to everything.
|
||||
// +optional
|
||||
optional string labelSelector = 1;
|
||||
|
||||
// A selector to restrict the list of returned objects by their fields.
|
||||
// Defaults to everything.
|
||||
// +optional
|
||||
optional string fieldSelector = 2;
|
||||
|
||||
// If true, partially initialized resources are included in the response.
|
||||
// +optional
|
||||
optional bool includeUninitialized = 6;
|
||||
|
||||
// Watch for changes to the described resources and return them as a stream of
|
||||
// add, update, and remove notifications. Specify resourceVersion.
|
||||
// +optional
|
||||
optional bool watch = 3;
|
||||
|
||||
// When specified with a watch call, shows changes that occur after that particular version of a resource.
|
||||
// Defaults to changes from the beginning of history.
|
||||
// When specified for list:
|
||||
// - if unset, then the result is returned from remote storage based on quorum-read flag;
|
||||
// - if it's 0, then we simply return what we currently have in cache, no guarantee;
|
||||
// - if set to non zero, then the result is at least as fresh as given rv.
|
||||
// +optional
|
||||
optional string resourceVersion = 4;
|
||||
|
||||
// Timeout for the list/watch call.
|
||||
// This limits the duration of the call, regardless of any activity or inactivity.
|
||||
// +optional
|
||||
optional int64 timeoutSeconds = 5;
|
||||
|
||||
// limit is a maximum number of responses to return for a list call. If more items exist, the
|
||||
// server will set the `continue` field on the list metadata to a value that can be used with the
|
||||
// same initial query to retrieve the next set of results. Setting a limit may return fewer than
|
||||
// the requested amount of items (up to zero items) in the event all requested objects are
|
||||
// filtered out and clients should only use the presence of the continue field to determine whether
|
||||
// more results are available. Servers may choose not to support the limit argument and will return
|
||||
// all of the available results. If limit is specified and the continue field is empty, clients may
|
||||
// assume that no more results are available. This field is not supported if watch is true.
|
||||
//
|
||||
// The server guarantees that the objects returned when using continue will be identical to issuing
|
||||
// a single list call without a limit - that is, no objects created, modified, or deleted after the
|
||||
// first request is issued will be included in any subsequent continued requests. This is sometimes
|
||||
// referred to as a consistent snapshot, and ensures that a client that is using limit to receive
|
||||
// smaller chunks of a very large result can ensure they see all possible objects. If objects are
|
||||
// updated during a chunked list the version of the object that was present at the time the first list
|
||||
// result was calculated is returned.
|
||||
optional int64 limit = 7;
|
||||
|
||||
// The continue option should be set when retrieving more results from the server. Since this value is
|
||||
// server defined, clients may only use the continue value from a previous query result with identical
|
||||
// query parameters (except for the value of continue) and the server may reject a continue value it
|
||||
// does not recognize. If the specified continue value is no longer valid whether due to expiration
|
||||
// (generally five to fifteen minutes) or a configuration change on the server, the server will
|
||||
// respond with a 410 ResourceExpired error together with a continue token. If the client needs a
|
||||
// consistent list, it must restart their list without the continue field. Otherwise, the client may
|
||||
// send another list request with the token received with the 410 error, the server will respond with
|
||||
// a list starting from the next key, but from the latest snapshot, which is inconsistent from the
|
||||
// previous list results - objects that are created, modified, or deleted after the first list request
|
||||
// will be included in the response, as long as their keys are after the "next key".
|
||||
//
|
||||
// This field is not supported when watch is true. Clients may start a watch from the last
|
||||
// resourceVersion value returned by the server and not miss any modifications.
|
||||
optional string continue = 8;
|
||||
}
|
||||
|
||||
// MicroTime is version of Time with microsecond level precision.
|
||||
//
|
||||
// +protobuf.options.marshal=false
|
||||
// +protobuf.as=Timestamp
|
||||
// +protobuf.options.(gogoproto.goproto_stringer)=false
|
||||
message MicroTime {
|
||||
// Represents seconds of UTC time since Unix epoch
|
||||
// 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
|
||||
// 9999-12-31T23:59:59Z inclusive.
|
||||
optional int64 seconds = 1;
|
||||
|
||||
// Non-negative fractions of a second at nanosecond resolution. Negative
|
||||
// second values with fractions must still have non-negative nanos values
|
||||
// that count forward in time. Must be from 0 to 999,999,999
|
||||
// inclusive. This field may be limited in precision depending on context.
|
||||
optional int32 nanos = 2;
|
||||
}
|
||||
|
||||
// ObjectMeta is metadata that all persisted resources must have, which includes all objects
|
||||
// users must create.
|
||||
message ObjectMeta {
|
||||
// Name must be unique within a namespace. Is required when creating resources, although
|
||||
// some resources may allow a client to request the generation of an appropriate name
|
||||
// automatically. Name is primarily intended for creation idempotence and configuration
|
||||
// definition.
|
||||
// Cannot be updated.
|
||||
// More info: http://kubernetes.io/docs/user-guide/identifiers#names
|
||||
// +optional
|
||||
optional string name = 1;
|
||||
|
||||
// GenerateName is an optional prefix, used by the server, to generate a unique
|
||||
// name ONLY IF the Name field has not been provided.
|
||||
// If this field is used, the name returned to the client will be different
|
||||
// than the name passed. This value will also be combined with a unique suffix.
|
||||
// The provided value has the same validation rules as the Name field,
|
||||
// and may be truncated by the length of the suffix required to make the value
|
||||
// unique on the server.
|
||||
//
|
||||
// If this field is specified and the generated name exists, the server will
|
||||
// NOT return a 409 - instead, it will either return 201 Created or 500 with Reason
|
||||
// ServerTimeout indicating a unique name could not be found in the time allotted, and the client
|
||||
// should retry (optionally after the time indicated in the Retry-After header).
|
||||
//
|
||||
// Applied only if Name is not specified.
|
||||
// More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#idempotency
|
||||
// +optional
|
||||
optional string generateName = 2;
|
||||
|
||||
// Namespace defines the space within each name must be unique. An empty namespace is
|
||||
// equivalent to the "default" namespace, but "default" is the canonical representation.
|
||||
// Not all objects are required to be scoped to a namespace - the value of this field for
|
||||
// those objects will be empty.
|
||||
//
|
||||
// Must be a DNS_LABEL.
|
||||
// Cannot be updated.
|
||||
// More info: http://kubernetes.io/docs/user-guide/namespaces
|
||||
// +optional
|
||||
optional string namespace = 3;
|
||||
|
||||
// SelfLink is a URL representing this object.
|
||||
// Populated by the system.
|
||||
// Read-only.
|
||||
// +optional
|
||||
optional string selfLink = 4;
|
||||
|
||||
// UID is the unique in time and space value for this object. It is typically generated by
|
||||
// the server on successful creation of a resource and is not allowed to change on PUT
|
||||
// operations.
|
||||
//
|
||||
// Populated by the system.
|
||||
// Read-only.
|
||||
// More info: http://kubernetes.io/docs/user-guide/identifiers#uids
|
||||
// +optional
|
||||
optional string uid = 5;
|
||||
|
||||
// An opaque value that represents the internal version of this object that can
|
||||
// be used by clients to determine when objects have changed. May be used for optimistic
|
||||
// concurrency, change detection, and the watch operation on a resource or set of resources.
|
||||
// Clients must treat these values as opaque and passed unmodified back to the server.
|
||||
// They may only be valid for a particular resource or set of resources.
|
||||
//
|
||||
// Populated by the system.
|
||||
// Read-only.
|
||||
// Value must be treated as opaque by clients and .
|
||||
// More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#concurrency-control-and-consistency
|
||||
// +optional
|
||||
optional string resourceVersion = 6;
|
||||
|
||||
// A sequence number representing a specific generation of the desired state.
|
||||
// Populated by the system. Read-only.
|
||||
// +optional
|
||||
optional int64 generation = 7;
|
||||
|
||||
// CreationTimestamp is a timestamp representing the server time when this object was
|
||||
// created. It is not guaranteed to be set in happens-before order across separate operations.
|
||||
// Clients may not set this value. It is represented in RFC3339 form and is in UTC.
|
||||
//
|
||||
// Populated by the system.
|
||||
// Read-only.
|
||||
// Null for lists.
|
||||
// More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
|
||||
// +optional
|
||||
optional Time creationTimestamp = 8;
|
||||
|
||||
// DeletionTimestamp is RFC 3339 date and time at which this resource will be deleted. This
|
||||
// field is set by the server when a graceful deletion is requested by the user, and is not
|
||||
// directly settable by a client. The resource is expected to be deleted (no longer visible
|
||||
// from resource lists, and not reachable by name) after the time in this field, once the
|
||||
// finalizers list is empty. As long as the finalizers list contains items, deletion is blocked.
|
||||
// Once the deletionTimestamp is set, this value may not be unset or be set further into the
|
||||
// future, although it may be shortened or the resource may be deleted prior to this time.
|
||||
// For example, a user may request that a pod is deleted in 30 seconds. The Kubelet will react
|
||||
// by sending a graceful termination signal to the containers in the pod. After that 30 seconds,
|
||||
// the Kubelet will send a hard termination signal (SIGKILL) to the container and after cleanup,
|
||||
// remove the pod from the API. In the presence of network partitions, this object may still
|
||||
// exist after this timestamp, until an administrator or automated process can determine the
|
||||
// resource is fully terminated.
|
||||
// If not set, graceful deletion of the object has not been requested.
|
||||
//
|
||||
// Populated by the system when a graceful deletion is requested.
|
||||
// Read-only.
|
||||
// More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
|
||||
// +optional
|
||||
optional Time deletionTimestamp = 9;
|
||||
|
||||
// Number of seconds allowed for this object to gracefully terminate before
|
||||
// it will be removed from the system. Only set when deletionTimestamp is also set.
|
||||
// May only be shortened.
|
||||
// Read-only.
|
||||
// +optional
|
||||
optional int64 deletionGracePeriodSeconds = 10;
|
||||
|
||||
// Map of string keys and values that can be used to organize and categorize
|
||||
// (scope and select) objects. May match selectors of replication controllers
|
||||
// and services.
|
||||
// More info: http://kubernetes.io/docs/user-guide/labels
|
||||
// +optional
|
||||
map<string, string> labels = 11;
|
||||
|
||||
// Annotations is an unstructured key value map stored with a resource that may be
|
||||
// set by external tools to store and retrieve arbitrary metadata. They are not
|
||||
// queryable and should be preserved when modifying objects.
|
||||
// More info: http://kubernetes.io/docs/user-guide/annotations
|
||||
// +optional
|
||||
map<string, string> annotations = 12;
|
||||
|
||||
// List of objects depended by this object. If ALL objects in the list have
|
||||
// been deleted, this object will be garbage collected. If this object is managed by a controller,
|
||||
// then an entry in this list will point to this controller, with the controller field set to true.
|
||||
// There cannot be more than one managing controller.
|
||||
// +optional
|
||||
// +patchMergeKey=uid
|
||||
// +patchStrategy=merge
|
||||
repeated OwnerReference ownerReferences = 13;
|
||||
|
||||
// An initializer is a controller which enforces some system invariant at object creation time.
|
||||
// This field is a list of initializers that have not yet acted on this object. If nil or empty,
|
||||
// this object has been completely initialized. Otherwise, the object is considered uninitialized
|
||||
// and is hidden (in list/watch and get calls) from clients that haven't explicitly asked to
|
||||
// observe uninitialized objects.
|
||||
//
|
||||
// When an object is created, the system will populate this list with the current set of initializers.
|
||||
// Only privileged users may set or modify this list. Once it is empty, it may not be modified further
|
||||
// by any user.
|
||||
optional Initializers initializers = 16;
|
||||
|
||||
// Must be empty before the object is deleted from the registry. Each entry
|
||||
// is an identifier for the responsible component that will remove the entry
|
||||
// from the list. If the deletionTimestamp of the object is non-nil, entries
|
||||
// in this list can only be removed.
|
||||
// +optional
|
||||
// +patchStrategy=merge
|
||||
repeated string finalizers = 14;
|
||||
|
||||
// The name of the cluster which the object belongs to.
|
||||
// This is used to distinguish resources with same name and namespace in different clusters.
|
||||
// This field is not set anywhere right now and apiserver is going to ignore it if set in create or update request.
|
||||
// +optional
|
||||
optional string clusterName = 15;
|
||||
}
|
||||
|
||||
// OwnerReference contains enough information to let you identify an owning
|
||||
// object. An owning object must be in the same namespace as the dependent, or
|
||||
// be cluster-scoped, so there is no namespace field.
|
||||
message OwnerReference {
|
||||
// API version of the referent.
|
||||
optional string apiVersion = 5;
|
||||
|
||||
// Kind of the referent.
|
||||
// More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
|
||||
optional string kind = 1;
|
||||
|
||||
// Name of the referent.
|
||||
// More info: http://kubernetes.io/docs/user-guide/identifiers#names
|
||||
optional string name = 3;
|
||||
|
||||
// UID of the referent.
|
||||
// More info: http://kubernetes.io/docs/user-guide/identifiers#uids
|
||||
optional string uid = 4;
|
||||
|
||||
// If true, this reference points to the managing controller.
|
||||
// +optional
|
||||
optional bool controller = 6;
|
||||
|
||||
// If true, AND if the owner has the "foregroundDeletion" finalizer, then
|
||||
// the owner cannot be deleted from the key-value store until this
|
||||
// reference is removed.
|
||||
// Defaults to false.
|
||||
// To set this field, a user needs "delete" permission of the owner,
|
||||
// otherwise 422 (Unprocessable Entity) will be returned.
|
||||
// +optional
|
||||
optional bool blockOwnerDeletion = 7;
|
||||
}
|
||||
|
||||
// Patch is provided to give a concrete name and type to the Kubernetes PATCH request body.
|
||||
message Patch {
|
||||
}
|
||||
|
||||
// Preconditions must be fulfilled before an operation (update, delete, etc.) is carried out.
|
||||
message Preconditions {
|
||||
// Specifies the target UID.
|
||||
// +optional
|
||||
optional string uid = 1;
|
||||
}
|
||||
|
||||
// RootPaths lists the paths available at root.
|
||||
// For example: "/healthz", "/apis".
|
||||
message RootPaths {
|
||||
// paths are the paths available at root.
|
||||
repeated string paths = 1;
|
||||
}
|
||||
|
||||
// ServerAddressByClientCIDR helps the client to determine the server address that they should use, depending on the clientCIDR that they match.
|
||||
message ServerAddressByClientCIDR {
|
||||
// The CIDR with which clients can match their IP to figure out the server address that they should use.
|
||||
optional string clientCIDR = 1;
|
||||
|
||||
// Address of this server, suitable for a client that matches the above CIDR.
|
||||
// This can be a hostname, hostname:port, IP or IP:port.
|
||||
optional string serverAddress = 2;
|
||||
}
|
||||
|
||||
// Status is a return value for calls that don't return other objects.
|
||||
message Status {
|
||||
// Standard list metadata.
|
||||
// More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
|
||||
// +optional
|
||||
optional ListMeta metadata = 1;
|
||||
|
||||
// Status of the operation.
|
||||
// One of: "Success" or "Failure".
|
||||
// More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status
|
||||
// +optional
|
||||
optional string status = 2;
|
||||
|
||||
// A human-readable description of the status of this operation.
|
||||
// +optional
|
||||
optional string message = 3;
|
||||
|
||||
// A machine-readable description of why this operation is in the
|
||||
// "Failure" status. If this value is empty there
|
||||
// is no information available. A Reason clarifies an HTTP status
|
||||
// code but does not override it.
|
||||
// +optional
|
||||
optional string reason = 4;
|
||||
|
||||
// Extended data associated with the reason. Each reason may define its
|
||||
// own extended details. This field is optional and the data returned
|
||||
// is not guaranteed to conform to any schema except that defined by
|
||||
// the reason type.
|
||||
// +optional
|
||||
optional StatusDetails details = 5;
|
||||
|
||||
// Suggested HTTP return code for this status, 0 if not set.
|
||||
// +optional
|
||||
optional int32 code = 6;
|
||||
}
|
||||
|
||||
// StatusCause provides more information about an api.Status failure, including
|
||||
// cases when multiple errors are encountered.
|
||||
message StatusCause {
|
||||
// A machine-readable description of the cause of the error. If this value is
|
||||
// empty there is no information available.
|
||||
// +optional
|
||||
optional string reason = 1;
|
||||
|
||||
// A human-readable description of the cause of the error. This field may be
|
||||
// presented as-is to a reader.
|
||||
// +optional
|
||||
optional string message = 2;
|
||||
|
||||
// The field of the resource that has caused this error, as named by its JSON
|
||||
// serialization. May include dot and postfix notation for nested attributes.
|
||||
// Arrays are zero-indexed. Fields may appear more than once in an array of
|
||||
// causes due to fields having multiple errors.
|
||||
// Optional.
|
||||
//
|
||||
// Examples:
|
||||
// "name" - the field "name" on the current resource
|
||||
// "items[0].name" - the field "name" on the first array entry in "items"
|
||||
// +optional
|
||||
optional string field = 3;
|
||||
}
|
||||
|
||||
// StatusDetails is a set of additional properties that MAY be set by the
|
||||
// server to provide additional information about a response. The Reason
|
||||
// field of a Status object defines what attributes will be set. Clients
|
||||
// must ignore fields that do not match the defined type of each attribute,
|
||||
// and should assume that any attribute may be empty, invalid, or under
|
||||
// defined.
|
||||
message StatusDetails {
|
||||
// The name attribute of the resource associated with the status StatusReason
|
||||
// (when there is a single name which can be described).
|
||||
// +optional
|
||||
optional string name = 1;
|
||||
|
||||
// The group attribute of the resource associated with the status StatusReason.
|
||||
// +optional
|
||||
optional string group = 2;
|
||||
|
||||
// The kind attribute of the resource associated with the status StatusReason.
|
||||
// On some operations may differ from the requested resource Kind.
|
||||
// More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
|
||||
// +optional
|
||||
optional string kind = 3;
|
||||
|
||||
// UID of the resource.
|
||||
// (when there is a single resource which can be described).
|
||||
// More info: http://kubernetes.io/docs/user-guide/identifiers#uids
|
||||
// +optional
|
||||
optional string uid = 6;
|
||||
|
||||
// The Causes array includes more details associated with the StatusReason
|
||||
// failure. Not all StatusReasons may provide detailed causes.
|
||||
// +optional
|
||||
repeated StatusCause causes = 4;
|
||||
|
||||
// If specified, the time in seconds before the operation should be retried. Some errors may indicate
|
||||
// the client must take an alternate action - for those errors this field may indicate how long to wait
|
||||
// before taking the alternate action.
|
||||
// +optional
|
||||
optional int32 retryAfterSeconds = 5;
|
||||
}
|
||||
|
||||
// Time is a wrapper around time.Time which supports correct
|
||||
// marshaling to YAML and JSON. Wrappers are provided for many
|
||||
// of the factory methods that the time package offers.
|
||||
//
|
||||
// +protobuf.options.marshal=false
|
||||
// +protobuf.as=Timestamp
|
||||
// +protobuf.options.(gogoproto.goproto_stringer)=false
|
||||
message Time {
|
||||
// Represents seconds of UTC time since Unix epoch
|
||||
// 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
|
||||
// 9999-12-31T23:59:59Z inclusive.
|
||||
optional int64 seconds = 1;
|
||||
|
||||
// Non-negative fractions of a second at nanosecond resolution. Negative
|
||||
// second values with fractions must still have non-negative nanos values
|
||||
// that count forward in time. Must be from 0 to 999,999,999
|
||||
// inclusive. This field may be limited in precision depending on context.
|
||||
optional int32 nanos = 2;
|
||||
}
|
||||
|
||||
// Timestamp is a struct that is equivalent to Time, but intended for
|
||||
// protobuf marshalling/unmarshalling. It is generated into a serialization
|
||||
// that matches Time. Do not use in Go structs.
|
||||
message Timestamp {
|
||||
// Represents seconds of UTC time since Unix epoch
|
||||
// 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
|
||||
// 9999-12-31T23:59:59Z inclusive.
|
||||
optional int64 seconds = 1;
|
||||
|
||||
// Non-negative fractions of a second at nanosecond resolution. Negative
|
||||
// second values with fractions must still have non-negative nanos values
|
||||
// that count forward in time. Must be from 0 to 999,999,999
|
||||
// inclusive. This field may be limited in precision depending on context.
|
||||
optional int32 nanos = 2;
|
||||
}
|
||||
|
||||
// TypeMeta describes an individual object in an API response or request
|
||||
// with strings representing the type of the object and its API schema version.
|
||||
// Structures that are versioned or persisted should inline TypeMeta.
|
||||
//
|
||||
// +k8s:deepcopy-gen=false
|
||||
message TypeMeta {
|
||||
// Kind is a string value representing the REST resource this object represents.
|
||||
// Servers may infer this from the endpoint the client submits requests to.
|
||||
// Cannot be updated.
|
||||
// In CamelCase.
|
||||
// More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
|
||||
// +optional
|
||||
optional string kind = 1;
|
||||
|
||||
// APIVersion defines the versioned schema of this representation of an object.
|
||||
// Servers should convert recognized schemas to the latest internal value, and
|
||||
// may reject unrecognized values.
|
||||
// More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources
|
||||
// +optional
|
||||
optional string apiVersion = 2;
|
||||
}
|
||||
|
||||
// UpdateOptions may be provided when updating an API object.
|
||||
message UpdateOptions {
|
||||
// When present, indicates that modifications should not be
|
||||
// persisted. An invalid or unrecognized dryRun directive will
|
||||
// result in an error response and no further processing of the
|
||||
// request. Valid values are:
|
||||
// - All: all dry run stages will be processed
|
||||
// +optional
|
||||
repeated string dryRun = 1;
|
||||
}
|
||||
|
||||
// Verbs masks the value so protobuf can generate
|
||||
//
|
||||
// +protobuf.nullable=true
|
||||
// +protobuf.options.(gogoproto.goproto_stringer)=false
|
||||
message Verbs {
|
||||
// items, if empty, will result in an empty slice
|
||||
|
||||
repeated string items = 1;
|
||||
}
|
||||
|
||||
// Event represents a single event to a watched resource.
|
||||
//
|
||||
// +protobuf=true
|
||||
// +k8s:deepcopy-gen=true
|
||||
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
|
||||
message WatchEvent {
|
||||
optional string type = 1;
|
||||
|
||||
// Object is:
|
||||
// * If Type is Added or Modified: the new state of the object.
|
||||
// * If Type is Deleted: the state of the object immediately before deletion.
|
||||
// * If Type is Error: *Status is recommended; other types may make sense
|
||||
// depending on context.
|
||||
optional k8s.io.apimachinery.pkg.runtime.RawExtension object = 2;
|
||||
}
|
||||
|
79
vendor/k8s.io/apimachinery/pkg/apis/meta/v1/group_version_test.go
generated
vendored
79
vendor/k8s.io/apimachinery/pkg/apis/meta/v1/group_version_test.go
generated
vendored
@ -1,79 +0,0 @@
|
||||
/*
|
||||
Copyright 2015 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 v1
|
||||
|
||||
import (
|
||||
gojson "encoding/json"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"k8s.io/apimachinery/pkg/runtime/serializer/json"
|
||||
)
|
||||
|
||||
type GroupVersionHolder struct {
|
||||
GV GroupVersion `json:"val"`
|
||||
}
|
||||
|
||||
func TestGroupVersionUnmarshalJSON(t *testing.T) {
|
||||
cases := []struct {
|
||||
input []byte
|
||||
expect GroupVersion
|
||||
}{
|
||||
{[]byte(`{"val": "v1"}`), GroupVersion{"", "v1"}},
|
||||
{[]byte(`{"val": "extensions/v1beta1"}`), GroupVersion{"extensions", "v1beta1"}},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
var result GroupVersionHolder
|
||||
// test golang lib's JSON codec
|
||||
if err := gojson.Unmarshal([]byte(c.input), &result); err != nil {
|
||||
t.Errorf("JSON codec failed to unmarshal input '%v': %v", c.input, err)
|
||||
}
|
||||
if !reflect.DeepEqual(result.GV, c.expect) {
|
||||
t.Errorf("JSON codec failed to unmarshal input '%s': expected %+v, got %+v", c.input, c.expect, result.GV)
|
||||
}
|
||||
// test the json-iterator codec
|
||||
iter := json.CaseSensitiveJsonIterator()
|
||||
if err := iter.Unmarshal(c.input, &result); err != nil {
|
||||
t.Errorf("json-iterator codec failed to unmarshal input '%v': %v", c.input, err)
|
||||
}
|
||||
if !reflect.DeepEqual(result.GV, c.expect) {
|
||||
t.Errorf("json-iterator codec failed to unmarshal input '%s': expected %+v, got %+v", c.input, c.expect, result.GV)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGroupVersionMarshalJSON(t *testing.T) {
|
||||
cases := []struct {
|
||||
input GroupVersion
|
||||
expect []byte
|
||||
}{
|
||||
{GroupVersion{"", "v1"}, []byte(`{"val":"v1"}`)},
|
||||
{GroupVersion{"extensions", "v1beta1"}, []byte(`{"val":"extensions/v1beta1"}`)},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
input := GroupVersionHolder{c.input}
|
||||
result, err := gojson.Marshal(&input)
|
||||
if err != nil {
|
||||
t.Errorf("Failed to marshal input '%v': %v", input, err)
|
||||
}
|
||||
if !reflect.DeepEqual(result, c.expect) {
|
||||
t.Errorf("Failed to marshal input '%+v': expected: %s, got: %s", input, c.expect, result)
|
||||
}
|
||||
}
|
||||
}
|
161
vendor/k8s.io/apimachinery/pkg/apis/meta/v1/helpers_test.go
generated
vendored
161
vendor/k8s.io/apimachinery/pkg/apis/meta/v1/helpers_test.go
generated
vendored
@ -1,161 +0,0 @@
|
||||
/*
|
||||
Copyright 2016 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 v1
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"k8s.io/apimachinery/pkg/labels"
|
||||
)
|
||||
|
||||
func TestLabelSelectorAsSelector(t *testing.T) {
|
||||
matchLabels := map[string]string{"foo": "bar"}
|
||||
matchExpressions := []LabelSelectorRequirement{{
|
||||
Key: "baz",
|
||||
Operator: LabelSelectorOpIn,
|
||||
Values: []string{"qux", "norf"},
|
||||
}}
|
||||
mustParse := func(s string) labels.Selector {
|
||||
out, e := labels.Parse(s)
|
||||
if e != nil {
|
||||
panic(e)
|
||||
}
|
||||
return out
|
||||
}
|
||||
tc := []struct {
|
||||
in *LabelSelector
|
||||
out labels.Selector
|
||||
expectErr bool
|
||||
}{
|
||||
{in: nil, out: labels.Nothing()},
|
||||
{in: &LabelSelector{}, out: labels.Everything()},
|
||||
{
|
||||
in: &LabelSelector{MatchLabels: matchLabels},
|
||||
out: mustParse("foo=bar"),
|
||||
},
|
||||
{
|
||||
in: &LabelSelector{MatchExpressions: matchExpressions},
|
||||
out: mustParse("baz in (norf,qux)"),
|
||||
},
|
||||
{
|
||||
in: &LabelSelector{MatchLabels: matchLabels, MatchExpressions: matchExpressions},
|
||||
out: mustParse("baz in (norf,qux),foo=bar"),
|
||||
},
|
||||
{
|
||||
in: &LabelSelector{
|
||||
MatchExpressions: []LabelSelectorRequirement{{
|
||||
Key: "baz",
|
||||
Operator: LabelSelectorOpExists,
|
||||
Values: []string{"qux", "norf"},
|
||||
}},
|
||||
},
|
||||
expectErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for i, tc := range tc {
|
||||
inCopy := tc.in.DeepCopy()
|
||||
out, err := LabelSelectorAsSelector(tc.in)
|
||||
// after calling LabelSelectorAsSelector, tc.in shouldn't be modified
|
||||
if !reflect.DeepEqual(inCopy, tc.in) {
|
||||
t.Errorf("[%v]expected:\n\t%#v\nbut got:\n\t%#v", i, inCopy, tc.in)
|
||||
}
|
||||
if err == nil && tc.expectErr {
|
||||
t.Errorf("[%v]expected error but got none.", i)
|
||||
}
|
||||
if err != nil && !tc.expectErr {
|
||||
t.Errorf("[%v]did not expect error but got: %v", i, err)
|
||||
}
|
||||
// fmt.Sprint() over String() as nil.String() will panic
|
||||
if fmt.Sprint(out) != fmt.Sprint(tc.out) {
|
||||
t.Errorf("[%v]expected:\n\t%s\nbut got:\n\t%s", i, fmt.Sprint(tc.out), fmt.Sprint(out))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLabelSelectorAsMap(t *testing.T) {
|
||||
matchLabels := map[string]string{"foo": "bar"}
|
||||
matchExpressions := func(operator LabelSelectorOperator, values []string) []LabelSelectorRequirement {
|
||||
return []LabelSelectorRequirement{{
|
||||
Key: "baz",
|
||||
Operator: operator,
|
||||
Values: values,
|
||||
}}
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
in *LabelSelector
|
||||
out map[string]string
|
||||
errString string
|
||||
}{
|
||||
{in: nil, out: nil},
|
||||
{
|
||||
in: &LabelSelector{MatchLabels: matchLabels},
|
||||
out: map[string]string{"foo": "bar"},
|
||||
},
|
||||
{
|
||||
in: &LabelSelector{MatchLabels: matchLabels, MatchExpressions: matchExpressions(LabelSelectorOpIn, []string{"norf"})},
|
||||
out: map[string]string{"foo": "bar", "baz": "norf"},
|
||||
},
|
||||
{
|
||||
in: &LabelSelector{MatchExpressions: matchExpressions(LabelSelectorOpIn, []string{"norf"})},
|
||||
out: map[string]string{"baz": "norf"},
|
||||
},
|
||||
{
|
||||
in: &LabelSelector{MatchLabels: matchLabels, MatchExpressions: matchExpressions(LabelSelectorOpIn, []string{"norf", "qux"})},
|
||||
out: map[string]string{"foo": "bar"},
|
||||
errString: "without a single value cannot be converted",
|
||||
},
|
||||
{
|
||||
in: &LabelSelector{MatchExpressions: matchExpressions(LabelSelectorOpNotIn, []string{"norf", "qux"})},
|
||||
out: map[string]string{},
|
||||
errString: "cannot be converted",
|
||||
},
|
||||
{
|
||||
in: &LabelSelector{MatchLabels: matchLabels, MatchExpressions: matchExpressions(LabelSelectorOpExists, []string{})},
|
||||
out: map[string]string{"foo": "bar"},
|
||||
errString: "cannot be converted",
|
||||
},
|
||||
{
|
||||
in: &LabelSelector{MatchExpressions: matchExpressions(LabelSelectorOpDoesNotExist, []string{})},
|
||||
out: map[string]string{},
|
||||
errString: "cannot be converted",
|
||||
},
|
||||
}
|
||||
|
||||
for i, tc := range tests {
|
||||
out, err := LabelSelectorAsMap(tc.in)
|
||||
if err == nil && len(tc.errString) > 0 {
|
||||
t.Errorf("[%v]expected error but got none.", i)
|
||||
continue
|
||||
}
|
||||
if err != nil && len(tc.errString) == 0 {
|
||||
t.Errorf("[%v]did not expect error but got: %v", i, err)
|
||||
continue
|
||||
}
|
||||
if err != nil && len(tc.errString) > 0 && !strings.Contains(err.Error(), tc.errString) {
|
||||
t.Errorf("[%v]expected error with %q but got: %v", i, tc.errString, err)
|
||||
continue
|
||||
}
|
||||
if !reflect.DeepEqual(out, tc.out) {
|
||||
t.Errorf("[%v]expected:\n\t%+v\nbut got:\n\t%+v", i, tc.out, out)
|
||||
}
|
||||
}
|
||||
}
|
123
vendor/k8s.io/apimachinery/pkg/apis/meta/v1/labels_test.go
generated
vendored
123
vendor/k8s.io/apimachinery/pkg/apis/meta/v1/labels_test.go
generated
vendored
@ -1,123 +0,0 @@
|
||||
/*
|
||||
Copyright 2016 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 v1
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCloneSelectorAndAddLabel(t *testing.T) {
|
||||
labels := map[string]string{
|
||||
"foo1": "bar1",
|
||||
"foo2": "bar2",
|
||||
"foo3": "bar3",
|
||||
}
|
||||
matchExpressions := []LabelSelectorRequirement{
|
||||
{Key: "foo", Operator: LabelSelectorOpIn, Values: []string{"foo"}},
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
labels map[string]string
|
||||
labelKey string
|
||||
labelValue string
|
||||
want map[string]string
|
||||
}{
|
||||
{
|
||||
labels: labels,
|
||||
want: labels,
|
||||
},
|
||||
{
|
||||
labels: labels,
|
||||
labelKey: "foo4",
|
||||
labelValue: "89",
|
||||
want: map[string]string{
|
||||
"foo1": "bar1",
|
||||
"foo2": "bar2",
|
||||
"foo3": "bar3",
|
||||
"foo4": "89",
|
||||
},
|
||||
},
|
||||
{
|
||||
labels: nil,
|
||||
labelKey: "foo4",
|
||||
labelValue: "12",
|
||||
want: map[string]string{
|
||||
"foo4": "12",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
ls_in := LabelSelector{MatchLabels: tc.labels, MatchExpressions: matchExpressions}
|
||||
ls_out := LabelSelector{MatchLabels: tc.want, MatchExpressions: matchExpressions}
|
||||
|
||||
got := CloneSelectorAndAddLabel(&ls_in, tc.labelKey, tc.labelValue)
|
||||
if !reflect.DeepEqual(got, &ls_out) {
|
||||
t.Errorf("got %v, want %v", got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddLabelToSelector(t *testing.T) {
|
||||
labels := map[string]string{
|
||||
"foo1": "bar1",
|
||||
"foo2": "bar2",
|
||||
"foo3": "bar3",
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
labels map[string]string
|
||||
labelKey string
|
||||
labelValue string
|
||||
want map[string]string
|
||||
}{
|
||||
{
|
||||
labels: labels,
|
||||
want: labels,
|
||||
},
|
||||
{
|
||||
labels: labels,
|
||||
labelKey: "foo4",
|
||||
labelValue: "89",
|
||||
want: map[string]string{
|
||||
"foo1": "bar1",
|
||||
"foo2": "bar2",
|
||||
"foo3": "bar3",
|
||||
"foo4": "89",
|
||||
},
|
||||
},
|
||||
{
|
||||
labels: nil,
|
||||
labelKey: "foo4",
|
||||
labelValue: "12",
|
||||
want: map[string]string{
|
||||
"foo4": "12",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
ls_in := LabelSelector{MatchLabels: tc.labels}
|
||||
ls_out := LabelSelector{MatchLabels: tc.want}
|
||||
|
||||
got := AddLabelToSelector(&ls_in, tc.labelKey, tc.labelValue)
|
||||
if !reflect.DeepEqual(got, &ls_out) {
|
||||
t.Errorf("got %v, want %v", got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
139
vendor/k8s.io/apimachinery/pkg/apis/meta/v1/micro_time_test.go
generated
vendored
139
vendor/k8s.io/apimachinery/pkg/apis/meta/v1/micro_time_test.go
generated
vendored
@ -1,139 +0,0 @@
|
||||
/*
|
||||
Copyright 2016 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 v1
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"sigs.k8s.io/yaml"
|
||||
)
|
||||
|
||||
type MicroTimeHolder struct {
|
||||
T MicroTime `json:"t"`
|
||||
}
|
||||
|
||||
func TestMicroTimeMarshalYAML(t *testing.T) {
|
||||
cases := []struct {
|
||||
input MicroTime
|
||||
result string
|
||||
}{
|
||||
{MicroTime{}, "t: null\n"},
|
||||
{DateMicro(1998, time.May, 5, 1, 5, 5, 50, time.FixedZone("test", -4*60*60)), "t: \"1998-05-05T05:05:05.000000Z\"\n"},
|
||||
{DateMicro(1998, time.May, 5, 5, 5, 5, 0, time.UTC), "t: \"1998-05-05T05:05:05.000000Z\"\n"},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
input := MicroTimeHolder{c.input}
|
||||
result, err := yaml.Marshal(&input)
|
||||
if err != nil {
|
||||
t.Errorf("Failed to marshal input: '%v': %v", input, err)
|
||||
}
|
||||
if string(result) != c.result {
|
||||
t.Errorf("Failed to marshal input: '%v': expected %+v, got %q", input, c.result, string(result))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMicroTimeUnmarshalYAML(t *testing.T) {
|
||||
cases := []struct {
|
||||
input string
|
||||
result MicroTime
|
||||
}{
|
||||
{"t: null\n", MicroTime{}},
|
||||
{"t: 1998-05-05T05:05:05.000000Z\n", MicroTime{Date(1998, time.May, 5, 5, 5, 5, 0, time.UTC).Local()}},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
var result MicroTimeHolder
|
||||
if err := yaml.Unmarshal([]byte(c.input), &result); err != nil {
|
||||
t.Errorf("Failed to unmarshal input '%v': %v", c.input, err)
|
||||
}
|
||||
if result.T != c.result {
|
||||
t.Errorf("Failed to unmarshal input '%v': expected %+v, got %+v", c.input, c.result, result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMicroTimeMarshalJSON(t *testing.T) {
|
||||
cases := []struct {
|
||||
input MicroTime
|
||||
result string
|
||||
}{
|
||||
{MicroTime{}, "{\"t\":null}"},
|
||||
{DateMicro(1998, time.May, 5, 5, 5, 5, 50, time.UTC), "{\"t\":\"1998-05-05T05:05:05.000000Z\"}"},
|
||||
{DateMicro(1998, time.May, 5, 5, 5, 5, 0, time.UTC), "{\"t\":\"1998-05-05T05:05:05.000000Z\"}"},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
input := MicroTimeHolder{c.input}
|
||||
result, err := json.Marshal(&input)
|
||||
if err != nil {
|
||||
t.Errorf("Failed to marshal input: '%v': %v", input, err)
|
||||
}
|
||||
if string(result) != c.result {
|
||||
t.Errorf("Failed to marshal input: '%v': expected %+v, got %q", input, c.result, string(result))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMicroTimeUnmarshalJSON(t *testing.T) {
|
||||
cases := []struct {
|
||||
input string
|
||||
result MicroTime
|
||||
}{
|
||||
{"{\"t\":null}", MicroTime{}},
|
||||
{"{\"t\":\"1998-05-05T05:05:05.000000Z\"}", MicroTime{Date(1998, time.May, 5, 5, 5, 5, 0, time.UTC).Local()}},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
var result MicroTimeHolder
|
||||
if err := json.Unmarshal([]byte(c.input), &result); err != nil {
|
||||
t.Errorf("Failed to unmarshal input '%v': %v", c.input, err)
|
||||
}
|
||||
if result.T != c.result {
|
||||
t.Errorf("Failed to unmarshal input '%v': expected %+v, got %+v", c.input, c.result, result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMicroTimeProto(t *testing.T) {
|
||||
cases := []struct {
|
||||
input MicroTime
|
||||
}{
|
||||
{MicroTime{}},
|
||||
{DateMicro(1998, time.May, 5, 1, 5, 5, 50, time.Local)},
|
||||
{DateMicro(1998, time.May, 5, 5, 5, 5, 0, time.Local)},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
input := c.input
|
||||
data, err := input.Marshal()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to marshal input: '%v': %v", input, err)
|
||||
}
|
||||
time := MicroTime{}
|
||||
if err := time.Unmarshal(data); err != nil {
|
||||
t.Fatalf("Failed to unmarshal output: '%v': %v", input, err)
|
||||
}
|
||||
if !reflect.DeepEqual(input, time) {
|
||||
t.Errorf("Marshal->Unmarshal is not idempotent: '%v' vs '%v'", input, time)
|
||||
}
|
||||
}
|
||||
}
|
197
vendor/k8s.io/apimachinery/pkg/apis/meta/v1/time_test.go
generated
vendored
197
vendor/k8s.io/apimachinery/pkg/apis/meta/v1/time_test.go
generated
vendored
@ -1,197 +0,0 @@
|
||||
/*
|
||||
Copyright 2014 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 v1
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"sigs.k8s.io/yaml"
|
||||
)
|
||||
|
||||
type TimeHolder struct {
|
||||
T Time `json:"t"`
|
||||
}
|
||||
|
||||
func TestTimeMarshalYAML(t *testing.T) {
|
||||
cases := []struct {
|
||||
input Time
|
||||
result string
|
||||
}{
|
||||
{Time{}, "t: null\n"},
|
||||
{Date(1998, time.May, 5, 1, 5, 5, 50, time.FixedZone("test", -4*60*60)), "t: \"1998-05-05T05:05:05Z\"\n"},
|
||||
{Date(1998, time.May, 5, 5, 5, 5, 0, time.UTC), "t: \"1998-05-05T05:05:05Z\"\n"},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
input := TimeHolder{c.input}
|
||||
result, err := yaml.Marshal(&input)
|
||||
if err != nil {
|
||||
t.Errorf("Failed to marshal input: '%v': %v", input, err)
|
||||
}
|
||||
if string(result) != c.result {
|
||||
t.Errorf("Failed to marshal input: '%v': expected %+v, got %q", input, c.result, string(result))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTimeUnmarshalYAML(t *testing.T) {
|
||||
cases := []struct {
|
||||
input string
|
||||
result Time
|
||||
}{
|
||||
{"t: null\n", Time{}},
|
||||
{"t: 1998-05-05T05:05:05Z\n", Time{Date(1998, time.May, 5, 5, 5, 5, 0, time.UTC).Local()}},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
var result TimeHolder
|
||||
if err := yaml.Unmarshal([]byte(c.input), &result); err != nil {
|
||||
t.Errorf("Failed to unmarshal input '%v': %v", c.input, err)
|
||||
}
|
||||
if result.T != c.result {
|
||||
t.Errorf("Failed to unmarshal input '%v': expected %+v, got %+v", c.input, c.result, result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTimeMarshalJSON(t *testing.T) {
|
||||
cases := []struct {
|
||||
input Time
|
||||
result string
|
||||
}{
|
||||
{Time{}, "{\"t\":null}"},
|
||||
{Date(1998, time.May, 5, 5, 5, 5, 50, time.UTC), "{\"t\":\"1998-05-05T05:05:05Z\"}"},
|
||||
{Date(1998, time.May, 5, 5, 5, 5, 0, time.UTC), "{\"t\":\"1998-05-05T05:05:05Z\"}"},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
input := TimeHolder{c.input}
|
||||
result, err := json.Marshal(&input)
|
||||
if err != nil {
|
||||
t.Errorf("Failed to marshal input: '%v': %v", input, err)
|
||||
}
|
||||
if string(result) != c.result {
|
||||
t.Errorf("Failed to marshal input: '%v': expected %+v, got %q", input, c.result, string(result))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTimeUnmarshalJSON(t *testing.T) {
|
||||
cases := []struct {
|
||||
input string
|
||||
result Time
|
||||
}{
|
||||
{"{\"t\":null}", Time{}},
|
||||
{"{\"t\":\"1998-05-05T05:05:05Z\"}", Time{Date(1998, time.May, 5, 5, 5, 5, 0, time.UTC).Local()}},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
var result TimeHolder
|
||||
if err := json.Unmarshal([]byte(c.input), &result); err != nil {
|
||||
t.Errorf("Failed to unmarshal input '%v': %v", c.input, err)
|
||||
}
|
||||
if result.T != c.result {
|
||||
t.Errorf("Failed to unmarshal input '%v': expected %+v, got %+v", c.input, c.result, result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTimeMarshalJSONUnmarshalYAML(t *testing.T) {
|
||||
cases := []struct {
|
||||
input Time
|
||||
}{
|
||||
{Time{}},
|
||||
{Date(1998, time.May, 5, 5, 5, 5, 50, time.Local).Rfc3339Copy()},
|
||||
{Date(1998, time.May, 5, 5, 5, 5, 0, time.Local).Rfc3339Copy()},
|
||||
}
|
||||
|
||||
for i, c := range cases {
|
||||
input := TimeHolder{c.input}
|
||||
jsonMarshalled, err := json.Marshal(&input)
|
||||
if err != nil {
|
||||
t.Errorf("%d-1: Failed to marshal input: '%v': %v", i, input, err)
|
||||
}
|
||||
|
||||
var result TimeHolder
|
||||
err = yaml.Unmarshal(jsonMarshalled, &result)
|
||||
if err != nil {
|
||||
t.Errorf("%d-2: Failed to unmarshal '%+v': %v", i, string(jsonMarshalled), err)
|
||||
}
|
||||
|
||||
iN, iO := input.T.Zone()
|
||||
oN, oO := result.T.Zone()
|
||||
if iN != oN || iO != oO {
|
||||
t.Errorf("%d-3: Time zones differ before and after serialization %s:%d %s:%d", i, iN, iO, oN, oO)
|
||||
}
|
||||
|
||||
if input.T.UnixNano() != result.T.UnixNano() {
|
||||
t.Errorf("%d-4: Failed to marshal input '%#v': got %#v", i, input, result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTimeProto(t *testing.T) {
|
||||
cases := []struct {
|
||||
input Time
|
||||
}{
|
||||
{Time{}},
|
||||
{Date(1998, time.May, 5, 1, 5, 5, 0, time.Local)},
|
||||
{Date(1998, time.May, 5, 5, 5, 5, 0, time.Local)},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
input := c.input
|
||||
data, err := input.Marshal()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to marshal input: '%v': %v", input, err)
|
||||
}
|
||||
time := Time{}
|
||||
if err := time.Unmarshal(data); err != nil {
|
||||
t.Fatalf("Failed to unmarshal output: '%v': %v", input, err)
|
||||
}
|
||||
if !reflect.DeepEqual(input, time) {
|
||||
t.Errorf("Marshal->Unmarshal is not idempotent: '%v' vs '%v'", input, time)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTimeEqual(t *testing.T) {
|
||||
t1 := NewTime(time.Now())
|
||||
cases := []struct {
|
||||
name string
|
||||
x *Time
|
||||
y *Time
|
||||
result bool
|
||||
}{
|
||||
{"nil =? nil", nil, nil, true},
|
||||
{"!nil =? !nil", &t1, &t1, true},
|
||||
{"nil =? !nil", nil, &t1, false},
|
||||
{"!nil =? nil", &t1, nil, false},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
result := c.x.Equal(c.y)
|
||||
if result != c.result {
|
||||
t.Errorf("Failed equality test for '%v', '%v': expected %+v, got %+v", c.x, c.y, c.result, result)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
135
vendor/k8s.io/apimachinery/pkg/apis/meta/v1/types_test.go
generated
vendored
135
vendor/k8s.io/apimachinery/pkg/apis/meta/v1/types_test.go
generated
vendored
@ -1,135 +0,0 @@
|
||||
/*
|
||||
Copyright 2016 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 v1
|
||||
|
||||
import (
|
||||
gojson "encoding/json"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"k8s.io/apimachinery/pkg/runtime/serializer/json"
|
||||
)
|
||||
|
||||
func TestVerbsMarshalJSON(t *testing.T) {
|
||||
cases := []struct {
|
||||
input APIResource
|
||||
result string
|
||||
}{
|
||||
{APIResource{}, `{"name":"","singularName":"","namespaced":false,"kind":"","verbs":null}`},
|
||||
{APIResource{Verbs: Verbs([]string{})}, `{"name":"","singularName":"","namespaced":false,"kind":"","verbs":[]}`},
|
||||
{APIResource{Verbs: Verbs([]string{"delete"})}, `{"name":"","singularName":"","namespaced":false,"kind":"","verbs":["delete"]}`},
|
||||
}
|
||||
|
||||
for i, c := range cases {
|
||||
result, err := gojson.Marshal(&c.input)
|
||||
if err != nil {
|
||||
t.Errorf("[%d] Failed to marshal input: '%v': %v", i, c.input, err)
|
||||
}
|
||||
if string(result) != c.result {
|
||||
t.Errorf("[%d] Failed to marshal input: '%v': expected '%v', got '%v'", i, c.input, c.result, string(result))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerbsJsonIterUnmarshalJSON(t *testing.T) {
|
||||
cases := []struct {
|
||||
input string
|
||||
result APIResource
|
||||
}{
|
||||
{`{}`, APIResource{}},
|
||||
{`{"verbs":null}`, APIResource{}},
|
||||
{`{"verbs":[]}`, APIResource{Verbs: Verbs([]string{})}},
|
||||
{`{"verbs":["delete"]}`, APIResource{Verbs: Verbs([]string{"delete"})}},
|
||||
}
|
||||
|
||||
iter := json.CaseSensitiveJsonIterator()
|
||||
for i, c := range cases {
|
||||
var result APIResource
|
||||
if err := iter.Unmarshal([]byte(c.input), &result); err != nil {
|
||||
t.Errorf("[%d] Failed to unmarshal input '%v': %v", i, c.input, err)
|
||||
}
|
||||
if !reflect.DeepEqual(result, c.result) {
|
||||
t.Errorf("[%d] Failed to unmarshal input '%v': expected %+v, got %+v", i, c.input, c.result, result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestMarshalJSONWithOmit tests that we don't have regressions regarding nil and empty slices with "omit"
|
||||
func TestMarshalJSONWithOmit(t *testing.T) {
|
||||
cases := []struct {
|
||||
input LabelSelector
|
||||
result string
|
||||
}{
|
||||
{LabelSelector{}, `{}`},
|
||||
{LabelSelector{MatchExpressions: []LabelSelectorRequirement{}}, `{}`},
|
||||
{LabelSelector{MatchExpressions: []LabelSelectorRequirement{{}}}, `{"matchExpressions":[{"key":"","operator":""}]}`},
|
||||
}
|
||||
|
||||
for i, c := range cases {
|
||||
result, err := gojson.Marshal(&c.input)
|
||||
if err != nil {
|
||||
t.Errorf("[%d] Failed to marshal input: '%v': %v", i, c.input, err)
|
||||
}
|
||||
if string(result) != c.result {
|
||||
t.Errorf("[%d] Failed to marshal input: '%v': expected '%v', got '%v'", i, c.input, c.result, string(result))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerbsUnmarshalJSON(t *testing.T) {
|
||||
cases := []struct {
|
||||
input string
|
||||
result APIResource
|
||||
}{
|
||||
{`{}`, APIResource{}},
|
||||
{`{"verbs":null}`, APIResource{}},
|
||||
{`{"verbs":[]}`, APIResource{Verbs: Verbs([]string{})}},
|
||||
{`{"verbs":["delete"]}`, APIResource{Verbs: Verbs([]string{"delete"})}},
|
||||
}
|
||||
|
||||
for i, c := range cases {
|
||||
var result APIResource
|
||||
if err := gojson.Unmarshal([]byte(c.input), &result); err != nil {
|
||||
t.Errorf("[%d] Failed to unmarshal input '%v': %v", i, c.input, err)
|
||||
}
|
||||
if !reflect.DeepEqual(result, c.result) {
|
||||
t.Errorf("[%d] Failed to unmarshal input '%v': expected %+v, got %+v", i, c.input, c.result, result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerbsProto(t *testing.T) {
|
||||
cases := []APIResource{
|
||||
{},
|
||||
{Verbs: Verbs([]string{})},
|
||||
{Verbs: Verbs([]string{"delete"})},
|
||||
}
|
||||
|
||||
for _, input := range cases {
|
||||
data, err := input.Marshal()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to marshal input: '%v': %v", input, err)
|
||||
}
|
||||
resource := APIResource{}
|
||||
if err := resource.Unmarshal(data); err != nil {
|
||||
t.Fatalf("Failed to unmarshal output: '%v': %v", input, err)
|
||||
}
|
||||
if !reflect.DeepEqual(input, resource) {
|
||||
t.Errorf("Marshal->Unmarshal is not idempotent: '%v' vs '%v'", input, resource)
|
||||
}
|
||||
}
|
||||
}
|
136
vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers_test.go
generated
vendored
136
vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers_test.go
generated
vendored
@ -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)
|
||||
}
|
86
vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured_list_test.go
generated
vendored
86
vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured_list_test.go
generated
vendored
@ -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)
|
||||
}
|
||||
}
|
162
vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured_test.go
generated
vendored
162
vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured_test.go
generated
vendored
@ -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())
|
||||
}
|
129
vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructuredscheme/scheme.go
generated
vendored
129
vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructuredscheme/scheme.go
generated
vendored
@ -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) {
|
||||
}
|
110
vendor/k8s.io/apimachinery/pkg/apis/meta/v1/validation/validation.go
generated
vendored
110
vendor/k8s.io/apimachinery/pkg/apis/meta/v1/validation/validation.go
generated
vendored
@ -1,110 +0,0 @@
|
||||
/*
|
||||
Copyright 2015 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 validation
|
||||
|
||||
import (
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/util/sets"
|
||||
"k8s.io/apimachinery/pkg/util/validation"
|
||||
"k8s.io/apimachinery/pkg/util/validation/field"
|
||||
)
|
||||
|
||||
func ValidateLabelSelector(ps *metav1.LabelSelector, fldPath *field.Path) field.ErrorList {
|
||||
allErrs := field.ErrorList{}
|
||||
if ps == nil {
|
||||
return allErrs
|
||||
}
|
||||
allErrs = append(allErrs, ValidateLabels(ps.MatchLabels, fldPath.Child("matchLabels"))...)
|
||||
for i, expr := range ps.MatchExpressions {
|
||||
allErrs = append(allErrs, ValidateLabelSelectorRequirement(expr, fldPath.Child("matchExpressions").Index(i))...)
|
||||
}
|
||||
return allErrs
|
||||
}
|
||||
|
||||
func ValidateLabelSelectorRequirement(sr metav1.LabelSelectorRequirement, fldPath *field.Path) field.ErrorList {
|
||||
allErrs := field.ErrorList{}
|
||||
switch sr.Operator {
|
||||
case metav1.LabelSelectorOpIn, metav1.LabelSelectorOpNotIn:
|
||||
if len(sr.Values) == 0 {
|
||||
allErrs = append(allErrs, field.Required(fldPath.Child("values"), "must be specified when `operator` is 'In' or 'NotIn'"))
|
||||
}
|
||||
case metav1.LabelSelectorOpExists, metav1.LabelSelectorOpDoesNotExist:
|
||||
if len(sr.Values) > 0 {
|
||||
allErrs = append(allErrs, field.Forbidden(fldPath.Child("values"), "may not be specified when `operator` is 'Exists' or 'DoesNotExist'"))
|
||||
}
|
||||
default:
|
||||
allErrs = append(allErrs, field.Invalid(fldPath.Child("operator"), sr.Operator, "not a valid selector operator"))
|
||||
}
|
||||
allErrs = append(allErrs, ValidateLabelName(sr.Key, fldPath.Child("key"))...)
|
||||
return allErrs
|
||||
}
|
||||
|
||||
// ValidateLabelName validates that the label name is correctly defined.
|
||||
func ValidateLabelName(labelName string, fldPath *field.Path) field.ErrorList {
|
||||
allErrs := field.ErrorList{}
|
||||
for _, msg := range validation.IsQualifiedName(labelName) {
|
||||
allErrs = append(allErrs, field.Invalid(fldPath, labelName, msg))
|
||||
}
|
||||
return allErrs
|
||||
}
|
||||
|
||||
// ValidateLabels validates that a set of labels are correctly defined.
|
||||
func ValidateLabels(labels map[string]string, fldPath *field.Path) field.ErrorList {
|
||||
allErrs := field.ErrorList{}
|
||||
for k, v := range labels {
|
||||
allErrs = append(allErrs, ValidateLabelName(k, fldPath)...)
|
||||
for _, msg := range validation.IsValidLabelValue(v) {
|
||||
allErrs = append(allErrs, field.Invalid(fldPath, v, msg))
|
||||
}
|
||||
}
|
||||
return allErrs
|
||||
}
|
||||
|
||||
func ValidateDeleteOptions(options *metav1.DeleteOptions) field.ErrorList {
|
||||
allErrs := field.ErrorList{}
|
||||
if options.OrphanDependents != nil && options.PropagationPolicy != nil {
|
||||
allErrs = append(allErrs, field.Invalid(field.NewPath("propagationPolicy"), options.PropagationPolicy, "orphanDependents and deletionPropagation cannot be both set"))
|
||||
}
|
||||
if options.PropagationPolicy != nil &&
|
||||
*options.PropagationPolicy != metav1.DeletePropagationForeground &&
|
||||
*options.PropagationPolicy != metav1.DeletePropagationBackground &&
|
||||
*options.PropagationPolicy != metav1.DeletePropagationOrphan {
|
||||
allErrs = append(allErrs, field.NotSupported(field.NewPath("propagationPolicy"), options.PropagationPolicy, []string{string(metav1.DeletePropagationForeground), string(metav1.DeletePropagationBackground), string(metav1.DeletePropagationOrphan), "nil"}))
|
||||
}
|
||||
allErrs = append(allErrs, validateDryRun(field.NewPath("dryRun"), options.DryRun)...)
|
||||
return allErrs
|
||||
}
|
||||
|
||||
func ValidateCreateOptions(options *metav1.CreateOptions) field.ErrorList {
|
||||
return validateDryRun(field.NewPath("dryRun"), options.DryRun)
|
||||
}
|
||||
|
||||
func ValidateUpdateOptions(options *metav1.UpdateOptions) field.ErrorList {
|
||||
return validateDryRun(field.NewPath("dryRun"), options.DryRun)
|
||||
}
|
||||
|
||||
var allowedDryRunValues = sets.NewString(metav1.DryRunAll)
|
||||
|
||||
func validateDryRun(fldPath *field.Path, dryRun []string) field.ErrorList {
|
||||
allErrs := field.ErrorList{}
|
||||
if !allowedDryRunValues.HasAll(dryRun...) {
|
||||
allErrs = append(allErrs, field.NotSupported(fldPath, dryRun, allowedDryRunValues.List()))
|
||||
}
|
||||
return allErrs
|
||||
}
|
||||
|
||||
const UninitializedStatusUpdateErrorMsg string = `must not update status when the object is uninitialized`
|
127
vendor/k8s.io/apimachinery/pkg/apis/meta/v1/validation/validation_test.go
generated
vendored
127
vendor/k8s.io/apimachinery/pkg/apis/meta/v1/validation/validation_test.go
generated
vendored
@ -1,127 +0,0 @@
|
||||
/*
|
||||
Copyright 2016 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 validation
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"k8s.io/apimachinery/pkg/util/validation/field"
|
||||
)
|
||||
|
||||
func TestValidateLabels(t *testing.T) {
|
||||
successCases := []map[string]string{
|
||||
{"simple": "bar"},
|
||||
{"now-with-dashes": "bar"},
|
||||
{"1-starts-with-num": "bar"},
|
||||
{"1234": "bar"},
|
||||
{"simple/simple": "bar"},
|
||||
{"now-with-dashes/simple": "bar"},
|
||||
{"now-with-dashes/now-with-dashes": "bar"},
|
||||
{"now.with.dots/simple": "bar"},
|
||||
{"now-with.dashes-and.dots/simple": "bar"},
|
||||
{"1-num.2-num/3-num": "bar"},
|
||||
{"1234/5678": "bar"},
|
||||
{"1.2.3.4/5678": "bar"},
|
||||
{"UpperCaseAreOK123": "bar"},
|
||||
{"goodvalue": "123_-.BaR"},
|
||||
}
|
||||
for i := range successCases {
|
||||
errs := ValidateLabels(successCases[i], field.NewPath("field"))
|
||||
if len(errs) != 0 {
|
||||
t.Errorf("case[%d] expected success, got %#v", i, errs)
|
||||
}
|
||||
}
|
||||
|
||||
namePartErrMsg := "name part must consist of"
|
||||
nameErrMsg := "a qualified name must consist of"
|
||||
labelErrMsg := "a valid label must be an empty string or consist of"
|
||||
maxLengthErrMsg := "must be no more than"
|
||||
|
||||
labelNameErrorCases := []struct {
|
||||
labels map[string]string
|
||||
expect string
|
||||
}{
|
||||
{map[string]string{"nospecialchars^=@": "bar"}, namePartErrMsg},
|
||||
{map[string]string{"cantendwithadash-": "bar"}, namePartErrMsg},
|
||||
{map[string]string{"only/one/slash": "bar"}, nameErrMsg},
|
||||
{map[string]string{strings.Repeat("a", 254): "bar"}, maxLengthErrMsg},
|
||||
}
|
||||
for i := range labelNameErrorCases {
|
||||
errs := ValidateLabels(labelNameErrorCases[i].labels, field.NewPath("field"))
|
||||
if len(errs) != 1 {
|
||||
t.Errorf("case[%d]: expected failure", i)
|
||||
} else {
|
||||
if !strings.Contains(errs[0].Detail, labelNameErrorCases[i].expect) {
|
||||
t.Errorf("case[%d]: error details do not include %q: %q", i, labelNameErrorCases[i].expect, errs[0].Detail)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
labelValueErrorCases := []struct {
|
||||
labels map[string]string
|
||||
expect string
|
||||
}{
|
||||
{map[string]string{"toolongvalue": strings.Repeat("a", 64)}, maxLengthErrMsg},
|
||||
{map[string]string{"backslashesinvalue": "some\\bad\\value"}, labelErrMsg},
|
||||
{map[string]string{"nocommasallowed": "bad,value"}, labelErrMsg},
|
||||
{map[string]string{"strangecharsinvalue": "?#$notsogood"}, labelErrMsg},
|
||||
}
|
||||
for i := range labelValueErrorCases {
|
||||
errs := ValidateLabels(labelValueErrorCases[i].labels, field.NewPath("field"))
|
||||
if len(errs) != 1 {
|
||||
t.Errorf("case[%d]: expected failure", i)
|
||||
} else {
|
||||
if !strings.Contains(errs[0].Detail, labelValueErrorCases[i].expect) {
|
||||
t.Errorf("case[%d]: error details do not include %q: %q", i, labelValueErrorCases[i].expect, errs[0].Detail)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidDryRun(t *testing.T) {
|
||||
tests := [][]string{
|
||||
{},
|
||||
{"All"},
|
||||
{"All", "All"},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(fmt.Sprintf("%v", test), func(t *testing.T) {
|
||||
if errs := validateDryRun(field.NewPath("dryRun"), test); len(errs) != 0 {
|
||||
t.Errorf("%v should be a valid dry-run value: %v", test, errs)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvalidDryRun(t *testing.T) {
|
||||
tests := [][]string{
|
||||
{"False"},
|
||||
{"All", "False"},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(fmt.Sprintf("%v", test), func(t *testing.T) {
|
||||
if len(validateDryRun(field.NewPath("dryRun"), test)) == 0 {
|
||||
t.Errorf("%v shouldn't be a valid dry-run value", test)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
}
|
57
vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/generated.proto
generated
vendored
57
vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/generated.proto
generated
vendored
@ -1,57 +0,0 @@
|
||||
/*
|
||||
Copyright 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.
|
||||
*/
|
||||
|
||||
|
||||
// This file was autogenerated by go-to-protobuf. Do not edit it manually!
|
||||
|
||||
syntax = 'proto2';
|
||||
|
||||
package k8s.io.apimachinery.pkg.apis.meta.v1beta1;
|
||||
|
||||
import "k8s.io/apimachinery/pkg/apis/meta/v1/generated.proto";
|
||||
import "k8s.io/apimachinery/pkg/runtime/generated.proto";
|
||||
import "k8s.io/apimachinery/pkg/runtime/schema/generated.proto";
|
||||
|
||||
// Package-wide variables from generator "generated".
|
||||
option go_package = "v1beta1";
|
||||
|
||||
// PartialObjectMetadata is a generic representation of any object with ObjectMeta. It allows clients
|
||||
// to get access to a particular ObjectMeta schema without knowing the details of the version.
|
||||
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
|
||||
message PartialObjectMetadata {
|
||||
// Standard object's metadata.
|
||||
// More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
|
||||
// +optional
|
||||
optional k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1;
|
||||
}
|
||||
|
||||
// PartialObjectMetadataList contains a list of objects containing only their metadata
|
||||
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
|
||||
message PartialObjectMetadataList {
|
||||
// items contains each of the included items.
|
||||
repeated PartialObjectMetadata items = 1;
|
||||
}
|
||||
|
||||
// TableOptions are used when a Table is requested by the caller.
|
||||
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
|
||||
message TableOptions {
|
||||
// includeObject decides whether to include each object along with its columnar information.
|
||||
// Specifying "None" will return no object, specifying "Object" will return the full object contents, and
|
||||
// specifying "Metadata" (the default) will return the object's metadata in the PartialObjectMetadata kind
|
||||
// in version v1beta1 of the meta.k8s.io API group.
|
||||
optional string includeObject = 1;
|
||||
}
|
||||
|
22
vendor/k8s.io/apimachinery/pkg/apis/testapigroup/doc.go
generated
vendored
22
vendor/k8s.io/apimachinery/pkg/apis/testapigroup/doc.go
generated
vendored
@ -1,22 +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.
|
||||
*/
|
||||
|
||||
// +k8s:deepcopy-gen=package
|
||||
// +groupName=testapigroup.apimachinery.k8s.io
|
||||
//
|
||||
// package testapigroup contains an testapigroup API used to demonstrate how to create api groups. Moreover, this is
|
||||
// used within tests.
|
||||
package testapigroup // import "k8s.io/apimachinery/pkg/apis/testapigroup"
|
99
vendor/k8s.io/apimachinery/pkg/apis/testapigroup/fuzzer/fuzzer.go
generated
vendored
99
vendor/k8s.io/apimachinery/pkg/apis/testapigroup/fuzzer/fuzzer.go
generated
vendored
@ -1,99 +0,0 @@
|
||||
/*
|
||||
Copyright 2015 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 fuzzer
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/google/gofuzz"
|
||||
|
||||
apitesting "k8s.io/apimachinery/pkg/api/apitesting"
|
||||
"k8s.io/apimachinery/pkg/api/apitesting/fuzzer"
|
||||
"k8s.io/apimachinery/pkg/apis/testapigroup"
|
||||
"k8s.io/apimachinery/pkg/apis/testapigroup/v1"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
runtimeserializer "k8s.io/apimachinery/pkg/runtime/serializer"
|
||||
)
|
||||
|
||||
// overrideMetaFuncs override some generic fuzzer funcs from k8s.io/apimachinery in order to have more realistic
|
||||
// values in a Kubernetes context.
|
||||
func overrideMetaFuncs(codecs runtimeserializer.CodecFactory) []interface{} {
|
||||
return []interface{}{
|
||||
func(j *runtime.Object, c fuzz.Continue) {
|
||||
// TODO: uncomment when round trip starts from a versioned object
|
||||
if true { //c.RandBool() {
|
||||
*j = &runtime.Unknown{
|
||||
// We do not set TypeMeta here because it is not carried through a round trip
|
||||
Raw: []byte(`{"apiVersion":"unknown.group/unknown","kind":"Something","someKey":"someValue"}`),
|
||||
ContentType: runtime.ContentTypeJSON,
|
||||
}
|
||||
} else {
|
||||
types := []runtime.Object{&testapigroup.Carp{}}
|
||||
t := types[c.Rand.Intn(len(types))]
|
||||
c.Fuzz(t)
|
||||
*j = t
|
||||
}
|
||||
},
|
||||
func(r *runtime.RawExtension, c fuzz.Continue) {
|
||||
// Pick an arbitrary type and fuzz it
|
||||
types := []runtime.Object{&testapigroup.Carp{}}
|
||||
obj := types[c.Rand.Intn(len(types))]
|
||||
c.Fuzz(obj)
|
||||
|
||||
// Convert the object to raw bytes
|
||||
bytes, err := runtime.Encode(apitesting.TestCodec(codecs, v1.SchemeGroupVersion), obj)
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("Failed to encode object: %v", err))
|
||||
}
|
||||
|
||||
// Set the bytes field on the RawExtension
|
||||
r.Raw = bytes
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func testapigroupFuncs(codecs runtimeserializer.CodecFactory) []interface{} {
|
||||
return []interface{}{
|
||||
func(s *testapigroup.CarpSpec, c fuzz.Continue) {
|
||||
c.FuzzNoCustom(s)
|
||||
// has a default value
|
||||
ttl := int64(30)
|
||||
if c.RandBool() {
|
||||
ttl = int64(c.Uint32())
|
||||
}
|
||||
s.TerminationGracePeriodSeconds = &ttl
|
||||
|
||||
if s.SchedulerName == "" {
|
||||
s.SchedulerName = "default-scheduler"
|
||||
}
|
||||
},
|
||||
func(j *testapigroup.CarpPhase, c fuzz.Continue) {
|
||||
statuses := []testapigroup.CarpPhase{"Pending", "Running", "Succeeded", "Failed", "Unknown"}
|
||||
*j = statuses[c.Rand.Intn(len(statuses))]
|
||||
},
|
||||
func(rp *testapigroup.RestartPolicy, c fuzz.Continue) {
|
||||
policies := []testapigroup.RestartPolicy{"Always", "Never", "OnFailure"}
|
||||
*rp = policies[c.Rand.Intn(len(policies))]
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Funcs returns the fuzzer functions for the testapigroup.
|
||||
var Funcs = fuzzer.MergeFuzzerFuncs(
|
||||
overrideMetaFuncs,
|
||||
testapigroupFuncs,
|
||||
)
|
33
vendor/k8s.io/apimachinery/pkg/apis/testapigroup/install/install.go
generated
vendored
33
vendor/k8s.io/apimachinery/pkg/apis/testapigroup/install/install.go
generated
vendored
@ -1,33 +0,0 @@
|
||||
/*
|
||||
Copyright 2016 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 install installs the certificates API group, making it available as
|
||||
// an option to all of the API encoding/decoding machinery.
|
||||
package install
|
||||
|
||||
import (
|
||||
"k8s.io/apimachinery/pkg/apis/testapigroup"
|
||||
"k8s.io/apimachinery/pkg/apis/testapigroup/v1"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
|
||||
)
|
||||
|
||||
// Install registers the API group and adds types to a scheme
|
||||
func Install(scheme *runtime.Scheme) {
|
||||
utilruntime.Must(testapigroup.AddToScheme(scheme))
|
||||
utilruntime.Must(v1.AddToScheme(scheme))
|
||||
utilruntime.Must(scheme.SetVersionPriority(v1.SchemeGroupVersion))
|
||||
}
|
28
vendor/k8s.io/apimachinery/pkg/apis/testapigroup/install/roundtrip_test.go
generated
vendored
28
vendor/k8s.io/apimachinery/pkg/apis/testapigroup/install/roundtrip_test.go
generated
vendored
@ -1,28 +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 install
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"k8s.io/apimachinery/pkg/api/apitesting/roundtrip"
|
||||
testapigroupfuzzer "k8s.io/apimachinery/pkg/apis/testapigroup/fuzzer"
|
||||
)
|
||||
|
||||
func TestRoundTrip(t *testing.T) {
|
||||
roundtrip.RoundTripTestForAPIGroup(t, Install, testapigroupfuzzer.Funcs)
|
||||
}
|
51
vendor/k8s.io/apimachinery/pkg/apis/testapigroup/register.go
generated
vendored
51
vendor/k8s.io/apimachinery/pkg/apis/testapigroup/register.go
generated
vendored
@ -1,51 +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 testapigroup
|
||||
|
||||
import (
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
"k8s.io/apimachinery/pkg/runtime/schema"
|
||||
)
|
||||
|
||||
var (
|
||||
SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes)
|
||||
AddToScheme = SchemeBuilder.AddToScheme
|
||||
)
|
||||
|
||||
// GroupName is the group name use in this package
|
||||
const GroupName = "testapigroup.apimachinery.k8s.io"
|
||||
|
||||
// SchemeGroupVersion is group version used to register these objects
|
||||
var SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: runtime.APIVersionInternal}
|
||||
|
||||
// Kind takes an unqualified kind and returns a Group qualified GroupKind
|
||||
func Kind(kind string) schema.GroupKind {
|
||||
return SchemeGroupVersion.WithKind(kind).GroupKind()
|
||||
}
|
||||
|
||||
// Resource takes an unqualified resource and returns a Group qualified GroupResource
|
||||
func Resource(resource string) schema.GroupResource {
|
||||
return SchemeGroupVersion.WithResource(resource).GroupResource()
|
||||
}
|
||||
|
||||
// Adds the list of known types to the given scheme.
|
||||
func addKnownTypes(scheme *runtime.Scheme) error {
|
||||
scheme.AddKnownTypes(SchemeGroupVersion,
|
||||
&Carp{},
|
||||
)
|
||||
return nil
|
||||
}
|
138
vendor/k8s.io/apimachinery/pkg/apis/testapigroup/types.go
generated
vendored
138
vendor/k8s.io/apimachinery/pkg/apis/testapigroup/types.go
generated
vendored
@ -1,138 +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 testapigroup
|
||||
|
||||
import (
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
)
|
||||
|
||||
type (
|
||||
ConditionStatus string
|
||||
CarpConditionType string
|
||||
CarpPhase string
|
||||
RestartPolicy string
|
||||
)
|
||||
|
||||
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
|
||||
|
||||
// Carp is a collection of containers, used as either input (create, update) or as output (list, get).
|
||||
type Carp struct {
|
||||
metav1.TypeMeta
|
||||
// +optional
|
||||
metav1.ObjectMeta
|
||||
|
||||
// Spec defines the behavior of a carp.
|
||||
// +optional
|
||||
Spec CarpSpec
|
||||
|
||||
// Status represents the current information about a carp. This data may not be up
|
||||
// to date.
|
||||
// +optional
|
||||
Status CarpStatus
|
||||
}
|
||||
|
||||
// CarpStatus represents information about the status of a carp. Status may trail the actual
|
||||
// state of a system.
|
||||
type CarpStatus struct {
|
||||
// +optional
|
||||
Phase CarpPhase
|
||||
// +optional
|
||||
Conditions []CarpCondition
|
||||
// A human readable message indicating details about why the carp is in this state.
|
||||
// +optional
|
||||
Message string
|
||||
// A brief CamelCase message indicating details about why the carp is in this state. e.g. 'OutOfDisk'
|
||||
// +optional
|
||||
Reason string
|
||||
|
||||
// +optional
|
||||
HostIP string
|
||||
// +optional
|
||||
CarpIP string
|
||||
|
||||
// Date and time at which the object was acknowledged by the Kubelet.
|
||||
// This is before the Kubelet pulled the container image(s) for the carp.
|
||||
// +optional
|
||||
StartTime *metav1.Time
|
||||
}
|
||||
|
||||
type CarpCondition struct {
|
||||
Type CarpConditionType
|
||||
Status ConditionStatus
|
||||
// +optional
|
||||
LastProbeTime metav1.Time
|
||||
// +optional
|
||||
LastTransitionTime metav1.Time
|
||||
// +optional
|
||||
Reason string
|
||||
// +optional
|
||||
Message string
|
||||
}
|
||||
|
||||
// CarpSpec is a description of a carp
|
||||
type CarpSpec struct {
|
||||
// +optional
|
||||
RestartPolicy RestartPolicy
|
||||
// Optional duration in seconds the carp needs to terminate gracefully. May be decreased in delete request.
|
||||
// Value must be non-negative integer. The value zero indicates delete immediately.
|
||||
// If this value is nil, the default grace period will be used instead.
|
||||
// The grace period is the duration in seconds after the processes running in the carp are sent
|
||||
// a termination signal and the time when the processes are forcibly halted with a kill signal.
|
||||
// Set this value longer than the expected cleanup time for your process.
|
||||
// +optional
|
||||
TerminationGracePeriodSeconds *int64
|
||||
// Optional duration in seconds relative to the StartTime that the carp may be active on a node
|
||||
// before the system actively tries to terminate the carp; value must be positive integer
|
||||
// +optional
|
||||
ActiveDeadlineSeconds *int64
|
||||
// NodeSelector is a selector which must be true for the carp to fit on a node
|
||||
// +optional
|
||||
NodeSelector map[string]string
|
||||
|
||||
// ServiceAccountName is the name of the ServiceAccount to use to run this carp
|
||||
// The carp will be allowed to use secrets referenced by the ServiceAccount
|
||||
ServiceAccountName string
|
||||
|
||||
// NodeName is a request to schedule this carp onto a specific node. If it is non-empty,
|
||||
// the scheduler simply schedules this carp onto that node, assuming that it fits resource
|
||||
// requirements.
|
||||
// +optional
|
||||
NodeName string
|
||||
// Specifies the hostname of the Carp.
|
||||
// If not specified, the carp's hostname will be set to a system-defined value.
|
||||
// +optional
|
||||
Hostname string
|
||||
// If specified, the fully qualified Carp hostname will be "<hostname>.<subdomain>.<carp namespace>.svc.<cluster domain>".
|
||||
// If not specified, the carp will not have a domainname at all.
|
||||
// +optional
|
||||
Subdomain string
|
||||
// If specified, the carp will be dispatched by specified scheduler.
|
||||
// If not specified, the carp will be dispatched by default scheduler.
|
||||
// +optional
|
||||
SchedulerName string
|
||||
}
|
||||
|
||||
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
|
||||
|
||||
// CarpList is a list of Carps.
|
||||
type CarpList struct {
|
||||
metav1.TypeMeta
|
||||
// +optional
|
||||
metav1.ListMeta
|
||||
|
||||
Items []Carp
|
||||
}
|
26
vendor/k8s.io/apimachinery/pkg/apis/testapigroup/v1/conversion.go
generated
vendored
26
vendor/k8s.io/apimachinery/pkg/apis/testapigroup/v1/conversion.go
generated
vendored
@ -1,26 +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 v1
|
||||
|
||||
import (
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
)
|
||||
|
||||
func addConversionFuncs(scheme *runtime.Scheme) error {
|
||||
// Add non-generated conversion functions here. Currently there are none.
|
||||
return nil
|
||||
}
|
26
vendor/k8s.io/apimachinery/pkg/apis/testapigroup/v1/defaults.go
generated
vendored
26
vendor/k8s.io/apimachinery/pkg/apis/testapigroup/v1/defaults.go
generated
vendored
@ -1,26 +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 v1
|
||||
|
||||
import (
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
)
|
||||
|
||||
func addDefaultingFuncs(scheme *runtime.Scheme) error {
|
||||
// return RegisterDefaults(scheme)
|
||||
return nil
|
||||
}
|
24
vendor/k8s.io/apimachinery/pkg/apis/testapigroup/v1/doc.go
generated
vendored
24
vendor/k8s.io/apimachinery/pkg/apis/testapigroup/v1/doc.go
generated
vendored
@ -1,24 +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.
|
||||
*/
|
||||
|
||||
// +k8s:deepcopy-gen=package
|
||||
// +k8s:conversion-gen=k8s.io/apimachinery/pkg/apis/testapigroup
|
||||
// +k8s:openapi-gen=false
|
||||
// +k8s:defaulter-gen=TypeMeta
|
||||
|
||||
// +groupName=testapigroup.apimachinery.k8s.io
|
||||
|
||||
package v1 // import "k8s.io/apimachinery/pkg/apis/testapigroup/v1"
|
1991
vendor/k8s.io/apimachinery/pkg/apis/testapigroup/v1/generated.pb.go
generated
vendored
1991
vendor/k8s.io/apimachinery/pkg/apis/testapigroup/v1/generated.pb.go
generated
vendored
File diff suppressed because it is too large
Load Diff
211
vendor/k8s.io/apimachinery/pkg/apis/testapigroup/v1/generated.proto
generated
vendored
211
vendor/k8s.io/apimachinery/pkg/apis/testapigroup/v1/generated.proto
generated
vendored
@ -1,211 +0,0 @@
|
||||
/*
|
||||
Copyright 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.
|
||||
*/
|
||||
|
||||
|
||||
// This file was autogenerated by go-to-protobuf. Do not edit it manually!
|
||||
|
||||
syntax = 'proto2';
|
||||
|
||||
package k8s.io.apimachinery.pkg.apis.testapigroup.v1;
|
||||
|
||||
import "k8s.io/apimachinery/pkg/apis/meta/v1/generated.proto";
|
||||
import "k8s.io/apimachinery/pkg/runtime/generated.proto";
|
||||
import "k8s.io/apimachinery/pkg/runtime/schema/generated.proto";
|
||||
|
||||
// Package-wide variables from generator "generated".
|
||||
option go_package = "v1";
|
||||
|
||||
// Carp is a collection of containers, used as either input (create, update) or as output (list, get).
|
||||
message Carp {
|
||||
// Standard object's metadata.
|
||||
// More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
|
||||
// +optional
|
||||
optional k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1;
|
||||
|
||||
// Specification of the desired behavior of the carp.
|
||||
// More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status
|
||||
// +optional
|
||||
optional CarpSpec spec = 2;
|
||||
|
||||
// Most recently observed status of the carp.
|
||||
// This data may not be up to date.
|
||||
// Populated by the system.
|
||||
// Read-only.
|
||||
// More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status
|
||||
// +optional
|
||||
optional CarpStatus status = 3;
|
||||
}
|
||||
|
||||
message CarpCondition {
|
||||
// Type is the type of the condition.
|
||||
// Currently only Ready.
|
||||
// More info: http://kubernetes.io/docs/user-guide/carp-states#carp-conditions
|
||||
optional string type = 1;
|
||||
|
||||
// Status is the status of the condition.
|
||||
// Can be True, False, Unknown.
|
||||
// More info: http://kubernetes.io/docs/user-guide/carp-states#carp-conditions
|
||||
optional string status = 2;
|
||||
|
||||
// Last time we probed the condition.
|
||||
// +optional
|
||||
optional k8s.io.apimachinery.pkg.apis.meta.v1.Time lastProbeTime = 3;
|
||||
|
||||
// Last time the condition transitioned from one status to another.
|
||||
// +optional
|
||||
optional k8s.io.apimachinery.pkg.apis.meta.v1.Time lastTransitionTime = 4;
|
||||
|
||||
// Unique, one-word, CamelCase reason for the condition's last transition.
|
||||
// +optional
|
||||
optional string reason = 5;
|
||||
|
||||
// Human-readable message indicating details about last transition.
|
||||
// +optional
|
||||
optional string message = 6;
|
||||
}
|
||||
|
||||
// CarpList is a list of Carps.
|
||||
message CarpList {
|
||||
// Standard list metadata.
|
||||
// More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
|
||||
// +optional
|
||||
optional k8s.io.apimachinery.pkg.apis.meta.v1.ListMeta metadata = 1;
|
||||
|
||||
// List of carps.
|
||||
// More info: http://kubernetes.io/docs/user-guide/carps
|
||||
repeated Carp items = 2;
|
||||
}
|
||||
|
||||
// CarpSpec is a description of a carp
|
||||
message CarpSpec {
|
||||
// Restart policy for all containers within the carp.
|
||||
// One of Always, OnFailure, Never.
|
||||
// Default to Always.
|
||||
// More info: http://kubernetes.io/docs/user-guide/carp-states#restartpolicy
|
||||
// +optional
|
||||
optional string restartPolicy = 3;
|
||||
|
||||
// Optional duration in seconds the carp needs to terminate gracefully. May be decreased in delete request.
|
||||
// Value must be non-negative integer. The value zero indicates delete immediately.
|
||||
// If this value is nil, the default grace period will be used instead.
|
||||
// The grace period is the duration in seconds after the processes running in the carp are sent
|
||||
// a termination signal and the time when the processes are forcibly halted with a kill signal.
|
||||
// Set this value longer than the expected cleanup time for your process.
|
||||
// Defaults to 30 seconds.
|
||||
// +optional
|
||||
optional int64 terminationGracePeriodSeconds = 4;
|
||||
|
||||
// Optional duration in seconds the carp may be active on the node relative to
|
||||
// StartTime before the system will actively try to mark it failed and kill associated containers.
|
||||
// Value must be a positive integer.
|
||||
// +optional
|
||||
optional int64 activeDeadlineSeconds = 5;
|
||||
|
||||
// NodeSelector is a selector which must be true for the carp to fit on a node.
|
||||
// Selector which must match a node's labels for the carp to be scheduled on that node.
|
||||
// More info: http://kubernetes.io/docs/user-guide/node-selection/README
|
||||
// +optional
|
||||
map<string, string> nodeSelector = 7;
|
||||
|
||||
// ServiceAccountName is the name of the ServiceAccount to use to run this carp.
|
||||
// More info: https://git.k8s.io/community/contributors/design-proposals/auth/service_accounts.md
|
||||
// +optional
|
||||
optional string serviceAccountName = 8;
|
||||
|
||||
// DeprecatedServiceAccount is a depreciated alias for ServiceAccountName.
|
||||
// Deprecated: Use serviceAccountName instead.
|
||||
// +k8s:conversion-gen=false
|
||||
// +optional
|
||||
optional string serviceAccount = 9;
|
||||
|
||||
// NodeName is a request to schedule this carp onto a specific node. If it is non-empty,
|
||||
// the scheduler simply schedules this carp onto that node, assuming that it fits resource
|
||||
// requirements.
|
||||
// +optional
|
||||
optional string nodeName = 10;
|
||||
|
||||
// Host networking requested for this carp. Use the host's network namespace.
|
||||
// If this option is set, the ports that will be used must be specified.
|
||||
// Default to false.
|
||||
// +k8s:conversion-gen=false
|
||||
// +optional
|
||||
optional bool hostNetwork = 11;
|
||||
|
||||
// Use the host's pid namespace.
|
||||
// Optional: Default to false.
|
||||
// +k8s:conversion-gen=false
|
||||
// +optional
|
||||
optional bool hostPID = 12;
|
||||
|
||||
// Use the host's ipc namespace.
|
||||
// Optional: Default to false.
|
||||
// +k8s:conversion-gen=false
|
||||
// +optional
|
||||
optional bool hostIPC = 13;
|
||||
|
||||
// Specifies the hostname of the Carp
|
||||
// If not specified, the carp's hostname will be set to a system-defined value.
|
||||
// +optional
|
||||
optional string hostname = 16;
|
||||
|
||||
// If specified, the fully qualified Carp hostname will be "<hostname>.<subdomain>.<carp namespace>.svc.<cluster domain>".
|
||||
// If not specified, the carp will not have a domainname at all.
|
||||
// +optional
|
||||
optional string subdomain = 17;
|
||||
|
||||
// If specified, the carp will be dispatched by specified scheduler.
|
||||
// If not specified, the carp will be dispatched by default scheduler.
|
||||
// +optional
|
||||
optional string schedulername = 19;
|
||||
}
|
||||
|
||||
// CarpStatus represents information about the status of a carp. Status may trail the actual
|
||||
// state of a system.
|
||||
message CarpStatus {
|
||||
// Current condition of the carp.
|
||||
// More info: http://kubernetes.io/docs/user-guide/carp-states#carp-phase
|
||||
// +optional
|
||||
optional string phase = 1;
|
||||
|
||||
// Current service state of carp.
|
||||
// More info: http://kubernetes.io/docs/user-guide/carp-states#carp-conditions
|
||||
// +optional
|
||||
repeated CarpCondition conditions = 2;
|
||||
|
||||
// A human readable message indicating details about why the carp is in this condition.
|
||||
// +optional
|
||||
optional string message = 3;
|
||||
|
||||
// A brief CamelCase message indicating details about why the carp is in this state.
|
||||
// e.g. 'OutOfDisk'
|
||||
// +optional
|
||||
optional string reason = 4;
|
||||
|
||||
// IP address of the host to which the carp is assigned. Empty if not yet scheduled.
|
||||
// +optional
|
||||
optional string hostIP = 5;
|
||||
|
||||
// IP address allocated to the carp. Routable at least within the cluster.
|
||||
// Empty if not yet allocated.
|
||||
// +optional
|
||||
optional string carpIP = 6;
|
||||
|
||||
// RFC 3339 date and time at which the object was acknowledged by the Kubelet.
|
||||
// This is before the Kubelet pulled the container image(s) for the carp.
|
||||
// +optional
|
||||
optional k8s.io.apimachinery.pkg.apis.meta.v1.Time startTime = 7;
|
||||
}
|
||||
|
63
vendor/k8s.io/apimachinery/pkg/apis/testapigroup/v1/register.go
generated
vendored
63
vendor/k8s.io/apimachinery/pkg/apis/testapigroup/v1/register.go
generated
vendored
@ -1,63 +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 v1
|
||||
|
||||
import (
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
"k8s.io/apimachinery/pkg/runtime/schema"
|
||||
)
|
||||
|
||||
// GroupName is the group name use in this package
|
||||
const GroupName = "testapigroup.apimachinery.k8s.io"
|
||||
|
||||
// SchemeGroupVersion is group version used to register these objects
|
||||
var SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: "v1"}
|
||||
|
||||
// Kind takes an unqualified kind and returns a Group qualified GroupKind
|
||||
func Kind(kind string) schema.GroupKind {
|
||||
return SchemeGroupVersion.WithKind(kind).GroupKind()
|
||||
}
|
||||
|
||||
// Resource takes an unqualified resource and returns a Group qualified GroupResource
|
||||
func Resource(resource string) schema.GroupResource {
|
||||
return SchemeGroupVersion.WithResource(resource).GroupResource()
|
||||
}
|
||||
|
||||
var (
|
||||
// TODO: move SchemeBuilder with zz_generated.deepcopy.go to k8s.io/api.
|
||||
// localSchemeBuilder and AddToScheme will stay in k8s.io/kubernetes.
|
||||
SchemeBuilder runtime.SchemeBuilder
|
||||
localSchemeBuilder = &SchemeBuilder
|
||||
AddToScheme = localSchemeBuilder.AddToScheme
|
||||
)
|
||||
|
||||
func init() {
|
||||
// We only register manually written functions here. The registration of the
|
||||
// generated functions takes place in the generated files. The separation
|
||||
// makes the code compile even when the generated files are missing.
|
||||
localSchemeBuilder.Register(addKnownTypes, addConversionFuncs, addDefaultingFuncs)
|
||||
}
|
||||
|
||||
// Adds the list of known types to the given scheme.
|
||||
func addKnownTypes(scheme *runtime.Scheme) error {
|
||||
scheme.AddKnownTypes(SchemeGroupVersion,
|
||||
&Carp{},
|
||||
)
|
||||
metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
|
||||
return nil
|
||||
}
|
196
vendor/k8s.io/apimachinery/pkg/apis/testapigroup/v1/types.go
generated
vendored
196
vendor/k8s.io/apimachinery/pkg/apis/testapigroup/v1/types.go
generated
vendored
@ -1,196 +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 v1
|
||||
|
||||
import (
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
)
|
||||
|
||||
type (
|
||||
ConditionStatus string
|
||||
CarpConditionType string
|
||||
CarpPhase string
|
||||
RestartPolicy string
|
||||
)
|
||||
|
||||
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
|
||||
|
||||
// Carp is a collection of containers, used as either input (create, update) or as output (list, get).
|
||||
type Carp struct {
|
||||
metav1.TypeMeta `json:",inline"`
|
||||
// Standard object's metadata.
|
||||
// More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
|
||||
// +optional
|
||||
metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
|
||||
|
||||
// Specification of the desired behavior of the carp.
|
||||
// More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status
|
||||
// +optional
|
||||
Spec CarpSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"`
|
||||
|
||||
// Most recently observed status of the carp.
|
||||
// This data may not be up to date.
|
||||
// Populated by the system.
|
||||
// Read-only.
|
||||
// More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status
|
||||
// +optional
|
||||
Status CarpStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"`
|
||||
}
|
||||
|
||||
// CarpStatus represents information about the status of a carp. Status may trail the actual
|
||||
// state of a system.
|
||||
type CarpStatus struct {
|
||||
// Current condition of the carp.
|
||||
// More info: http://kubernetes.io/docs/user-guide/carp-states#carp-phase
|
||||
// +optional
|
||||
Phase CarpPhase `json:"phase,omitempty" protobuf:"bytes,1,opt,name=phase,casttype=CarpPhase"`
|
||||
// Current service state of carp.
|
||||
// More info: http://kubernetes.io/docs/user-guide/carp-states#carp-conditions
|
||||
// +optional
|
||||
Conditions []CarpCondition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type" protobuf:"bytes,2,rep,name=conditions"`
|
||||
// A human readable message indicating details about why the carp is in this condition.
|
||||
// +optional
|
||||
Message string `json:"message,omitempty" protobuf:"bytes,3,opt,name=message"`
|
||||
// A brief CamelCase message indicating details about why the carp is in this state.
|
||||
// e.g. 'OutOfDisk'
|
||||
// +optional
|
||||
Reason string `json:"reason,omitempty" protobuf:"bytes,4,opt,name=reason"`
|
||||
|
||||
// IP address of the host to which the carp is assigned. Empty if not yet scheduled.
|
||||
// +optional
|
||||
HostIP string `json:"hostIP,omitempty" protobuf:"bytes,5,opt,name=hostIP"`
|
||||
// IP address allocated to the carp. Routable at least within the cluster.
|
||||
// Empty if not yet allocated.
|
||||
// +optional
|
||||
CarpIP string `json:"carpIP,omitempty" protobuf:"bytes,6,opt,name=carpIP"`
|
||||
|
||||
// RFC 3339 date and time at which the object was acknowledged by the Kubelet.
|
||||
// This is before the Kubelet pulled the container image(s) for the carp.
|
||||
// +optional
|
||||
StartTime *metav1.Time `json:"startTime,omitempty" protobuf:"bytes,7,opt,name=startTime"`
|
||||
}
|
||||
|
||||
type CarpCondition struct {
|
||||
// Type is the type of the condition.
|
||||
// Currently only Ready.
|
||||
// More info: http://kubernetes.io/docs/user-guide/carp-states#carp-conditions
|
||||
Type CarpConditionType `json:"type" protobuf:"bytes,1,opt,name=type,casttype=CarpConditionType"`
|
||||
// Status is the status of the condition.
|
||||
// Can be True, False, Unknown.
|
||||
// More info: http://kubernetes.io/docs/user-guide/carp-states#carp-conditions
|
||||
Status ConditionStatus `json:"status" protobuf:"bytes,2,opt,name=status,casttype=ConditionStatus"`
|
||||
// Last time we probed the condition.
|
||||
// +optional
|
||||
LastProbeTime metav1.Time `json:"lastProbeTime,omitempty" protobuf:"bytes,3,opt,name=lastProbeTime"`
|
||||
// Last time the condition transitioned from one status to another.
|
||||
// +optional
|
||||
LastTransitionTime metav1.Time `json:"lastTransitionTime,omitempty" protobuf:"bytes,4,opt,name=lastTransitionTime"`
|
||||
// Unique, one-word, CamelCase reason for the condition's last transition.
|
||||
// +optional
|
||||
Reason string `json:"reason,omitempty" protobuf:"bytes,5,opt,name=reason"`
|
||||
// Human-readable message indicating details about last transition.
|
||||
// +optional
|
||||
Message string `json:"message,omitempty" protobuf:"bytes,6,opt,name=message"`
|
||||
}
|
||||
|
||||
// CarpSpec is a description of a carp
|
||||
type CarpSpec struct {
|
||||
// Restart policy for all containers within the carp.
|
||||
// One of Always, OnFailure, Never.
|
||||
// Default to Always.
|
||||
// More info: http://kubernetes.io/docs/user-guide/carp-states#restartpolicy
|
||||
// +optional
|
||||
RestartPolicy RestartPolicy `json:"restartPolicy,omitempty" protobuf:"bytes,3,opt,name=restartPolicy,casttype=RestartPolicy"`
|
||||
// Optional duration in seconds the carp needs to terminate gracefully. May be decreased in delete request.
|
||||
// Value must be non-negative integer. The value zero indicates delete immediately.
|
||||
// If this value is nil, the default grace period will be used instead.
|
||||
// The grace period is the duration in seconds after the processes running in the carp are sent
|
||||
// a termination signal and the time when the processes are forcibly halted with a kill signal.
|
||||
// Set this value longer than the expected cleanup time for your process.
|
||||
// Defaults to 30 seconds.
|
||||
// +optional
|
||||
TerminationGracePeriodSeconds *int64 `json:"terminationGracePeriodSeconds,omitempty" protobuf:"varint,4,opt,name=terminationGracePeriodSeconds"`
|
||||
// Optional duration in seconds the carp may be active on the node relative to
|
||||
// StartTime before the system will actively try to mark it failed and kill associated containers.
|
||||
// Value must be a positive integer.
|
||||
// +optional
|
||||
ActiveDeadlineSeconds *int64 `json:"activeDeadlineSeconds,omitempty" protobuf:"varint,5,opt,name=activeDeadlineSeconds"`
|
||||
// NodeSelector is a selector which must be true for the carp to fit on a node.
|
||||
// Selector which must match a node's labels for the carp to be scheduled on that node.
|
||||
// More info: http://kubernetes.io/docs/user-guide/node-selection/README
|
||||
// +optional
|
||||
NodeSelector map[string]string `json:"nodeSelector,omitempty" protobuf:"bytes,7,rep,name=nodeSelector"`
|
||||
|
||||
// ServiceAccountName is the name of the ServiceAccount to use to run this carp.
|
||||
// More info: https://git.k8s.io/community/contributors/design-proposals/auth/service_accounts.md
|
||||
// +optional
|
||||
ServiceAccountName string `json:"serviceAccountName,omitempty" protobuf:"bytes,8,opt,name=serviceAccountName"`
|
||||
// DeprecatedServiceAccount is a depreciated alias for ServiceAccountName.
|
||||
// Deprecated: Use serviceAccountName instead.
|
||||
// +k8s:conversion-gen=false
|
||||
// +optional
|
||||
DeprecatedServiceAccount string `json:"serviceAccount,omitempty" protobuf:"bytes,9,opt,name=serviceAccount"`
|
||||
|
||||
// NodeName is a request to schedule this carp onto a specific node. If it is non-empty,
|
||||
// the scheduler simply schedules this carp onto that node, assuming that it fits resource
|
||||
// requirements.
|
||||
// +optional
|
||||
NodeName string `json:"nodeName,omitempty" protobuf:"bytes,10,opt,name=nodeName"`
|
||||
// Host networking requested for this carp. Use the host's network namespace.
|
||||
// If this option is set, the ports that will be used must be specified.
|
||||
// Default to false.
|
||||
// +k8s:conversion-gen=false
|
||||
// +optional
|
||||
HostNetwork bool `json:"hostNetwork,omitempty" protobuf:"varint,11,opt,name=hostNetwork"`
|
||||
// Use the host's pid namespace.
|
||||
// Optional: Default to false.
|
||||
// +k8s:conversion-gen=false
|
||||
// +optional
|
||||
HostPID bool `json:"hostPID,omitempty" protobuf:"varint,12,opt,name=hostPID"`
|
||||
// Use the host's ipc namespace.
|
||||
// Optional: Default to false.
|
||||
// +k8s:conversion-gen=false
|
||||
// +optional
|
||||
HostIPC bool `json:"hostIPC,omitempty" protobuf:"varint,13,opt,name=hostIPC"`
|
||||
// Specifies the hostname of the Carp
|
||||
// If not specified, the carp's hostname will be set to a system-defined value.
|
||||
// +optional
|
||||
Hostname string `json:"hostname,omitempty" protobuf:"bytes,16,opt,name=hostname"`
|
||||
// If specified, the fully qualified Carp hostname will be "<hostname>.<subdomain>.<carp namespace>.svc.<cluster domain>".
|
||||
// If not specified, the carp will not have a domainname at all.
|
||||
// +optional
|
||||
Subdomain string `json:"subdomain,omitempty" protobuf:"bytes,17,opt,name=subdomain"`
|
||||
// If specified, the carp will be dispatched by specified scheduler.
|
||||
// If not specified, the carp will be dispatched by default scheduler.
|
||||
// +optional
|
||||
SchedulerName string `json:"schedulername,omitempty" protobuf:"bytes,19,opt,name=schedulername"`
|
||||
}
|
||||
|
||||
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
|
||||
|
||||
// CarpList is a list of Carps.
|
||||
type CarpList struct {
|
||||
metav1.TypeMeta `json:",inline"`
|
||||
// Standard list metadata.
|
||||
// More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
|
||||
// +optional
|
||||
metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
|
||||
|
||||
// List of carps.
|
||||
// More info: http://kubernetes.io/docs/user-guide/carps
|
||||
Items []Carp `json:"items" protobuf:"bytes,2,rep,name=items"`
|
||||
}
|
266
vendor/k8s.io/apimachinery/pkg/apis/testapigroup/v1/zz_generated.conversion.go
generated
vendored
266
vendor/k8s.io/apimachinery/pkg/apis/testapigroup/v1/zz_generated.conversion.go
generated
vendored
@ -1,266 +0,0 @@
|
||||
// +build !ignore_autogenerated
|
||||
|
||||
/*
|
||||
Copyright 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.
|
||||
*/
|
||||
|
||||
// Code generated by conversion-gen. DO NOT EDIT.
|
||||
|
||||
package v1
|
||||
|
||||
import (
|
||||
unsafe "unsafe"
|
||||
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
testapigroup "k8s.io/apimachinery/pkg/apis/testapigroup"
|
||||
conversion "k8s.io/apimachinery/pkg/conversion"
|
||||
runtime "k8s.io/apimachinery/pkg/runtime"
|
||||
)
|
||||
|
||||
func init() {
|
||||
localSchemeBuilder.Register(RegisterConversions)
|
||||
}
|
||||
|
||||
// RegisterConversions adds conversion functions to the given scheme.
|
||||
// Public to allow building arbitrary schemes.
|
||||
func RegisterConversions(s *runtime.Scheme) error {
|
||||
if err := s.AddGeneratedConversionFunc((*Carp)(nil), (*testapigroup.Carp)(nil), func(a, b interface{}, scope conversion.Scope) error {
|
||||
return Convert_v1_Carp_To_testapigroup_Carp(a.(*Carp), b.(*testapigroup.Carp), scope)
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.AddGeneratedConversionFunc((*testapigroup.Carp)(nil), (*Carp)(nil), func(a, b interface{}, scope conversion.Scope) error {
|
||||
return Convert_testapigroup_Carp_To_v1_Carp(a.(*testapigroup.Carp), b.(*Carp), scope)
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.AddGeneratedConversionFunc((*CarpCondition)(nil), (*testapigroup.CarpCondition)(nil), func(a, b interface{}, scope conversion.Scope) error {
|
||||
return Convert_v1_CarpCondition_To_testapigroup_CarpCondition(a.(*CarpCondition), b.(*testapigroup.CarpCondition), scope)
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.AddGeneratedConversionFunc((*testapigroup.CarpCondition)(nil), (*CarpCondition)(nil), func(a, b interface{}, scope conversion.Scope) error {
|
||||
return Convert_testapigroup_CarpCondition_To_v1_CarpCondition(a.(*testapigroup.CarpCondition), b.(*CarpCondition), scope)
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.AddGeneratedConversionFunc((*CarpList)(nil), (*testapigroup.CarpList)(nil), func(a, b interface{}, scope conversion.Scope) error {
|
||||
return Convert_v1_CarpList_To_testapigroup_CarpList(a.(*CarpList), b.(*testapigroup.CarpList), scope)
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.AddGeneratedConversionFunc((*testapigroup.CarpList)(nil), (*CarpList)(nil), func(a, b interface{}, scope conversion.Scope) error {
|
||||
return Convert_testapigroup_CarpList_To_v1_CarpList(a.(*testapigroup.CarpList), b.(*CarpList), scope)
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.AddGeneratedConversionFunc((*CarpSpec)(nil), (*testapigroup.CarpSpec)(nil), func(a, b interface{}, scope conversion.Scope) error {
|
||||
return Convert_v1_CarpSpec_To_testapigroup_CarpSpec(a.(*CarpSpec), b.(*testapigroup.CarpSpec), scope)
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.AddGeneratedConversionFunc((*testapigroup.CarpSpec)(nil), (*CarpSpec)(nil), func(a, b interface{}, scope conversion.Scope) error {
|
||||
return Convert_testapigroup_CarpSpec_To_v1_CarpSpec(a.(*testapigroup.CarpSpec), b.(*CarpSpec), scope)
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.AddGeneratedConversionFunc((*CarpStatus)(nil), (*testapigroup.CarpStatus)(nil), func(a, b interface{}, scope conversion.Scope) error {
|
||||
return Convert_v1_CarpStatus_To_testapigroup_CarpStatus(a.(*CarpStatus), b.(*testapigroup.CarpStatus), scope)
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.AddGeneratedConversionFunc((*testapigroup.CarpStatus)(nil), (*CarpStatus)(nil), func(a, b interface{}, scope conversion.Scope) error {
|
||||
return Convert_testapigroup_CarpStatus_To_v1_CarpStatus(a.(*testapigroup.CarpStatus), b.(*CarpStatus), scope)
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func autoConvert_v1_Carp_To_testapigroup_Carp(in *Carp, out *testapigroup.Carp, s conversion.Scope) error {
|
||||
out.ObjectMeta = in.ObjectMeta
|
||||
if err := Convert_v1_CarpSpec_To_testapigroup_CarpSpec(&in.Spec, &out.Spec, s); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := Convert_v1_CarpStatus_To_testapigroup_CarpStatus(&in.Status, &out.Status, s); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Convert_v1_Carp_To_testapigroup_Carp is an autogenerated conversion function.
|
||||
func Convert_v1_Carp_To_testapigroup_Carp(in *Carp, out *testapigroup.Carp, s conversion.Scope) error {
|
||||
return autoConvert_v1_Carp_To_testapigroup_Carp(in, out, s)
|
||||
}
|
||||
|
||||
func autoConvert_testapigroup_Carp_To_v1_Carp(in *testapigroup.Carp, out *Carp, s conversion.Scope) error {
|
||||
out.ObjectMeta = in.ObjectMeta
|
||||
if err := Convert_testapigroup_CarpSpec_To_v1_CarpSpec(&in.Spec, &out.Spec, s); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := Convert_testapigroup_CarpStatus_To_v1_CarpStatus(&in.Status, &out.Status, s); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Convert_testapigroup_Carp_To_v1_Carp is an autogenerated conversion function.
|
||||
func Convert_testapigroup_Carp_To_v1_Carp(in *testapigroup.Carp, out *Carp, s conversion.Scope) error {
|
||||
return autoConvert_testapigroup_Carp_To_v1_Carp(in, out, s)
|
||||
}
|
||||
|
||||
func autoConvert_v1_CarpCondition_To_testapigroup_CarpCondition(in *CarpCondition, out *testapigroup.CarpCondition, s conversion.Scope) error {
|
||||
out.Type = testapigroup.CarpConditionType(in.Type)
|
||||
out.Status = testapigroup.ConditionStatus(in.Status)
|
||||
out.LastProbeTime = in.LastProbeTime
|
||||
out.LastTransitionTime = in.LastTransitionTime
|
||||
out.Reason = in.Reason
|
||||
out.Message = in.Message
|
||||
return nil
|
||||
}
|
||||
|
||||
// Convert_v1_CarpCondition_To_testapigroup_CarpCondition is an autogenerated conversion function.
|
||||
func Convert_v1_CarpCondition_To_testapigroup_CarpCondition(in *CarpCondition, out *testapigroup.CarpCondition, s conversion.Scope) error {
|
||||
return autoConvert_v1_CarpCondition_To_testapigroup_CarpCondition(in, out, s)
|
||||
}
|
||||
|
||||
func autoConvert_testapigroup_CarpCondition_To_v1_CarpCondition(in *testapigroup.CarpCondition, out *CarpCondition, s conversion.Scope) error {
|
||||
out.Type = CarpConditionType(in.Type)
|
||||
out.Status = ConditionStatus(in.Status)
|
||||
out.LastProbeTime = in.LastProbeTime
|
||||
out.LastTransitionTime = in.LastTransitionTime
|
||||
out.Reason = in.Reason
|
||||
out.Message = in.Message
|
||||
return nil
|
||||
}
|
||||
|
||||
// Convert_testapigroup_CarpCondition_To_v1_CarpCondition is an autogenerated conversion function.
|
||||
func Convert_testapigroup_CarpCondition_To_v1_CarpCondition(in *testapigroup.CarpCondition, out *CarpCondition, s conversion.Scope) error {
|
||||
return autoConvert_testapigroup_CarpCondition_To_v1_CarpCondition(in, out, s)
|
||||
}
|
||||
|
||||
func autoConvert_v1_CarpList_To_testapigroup_CarpList(in *CarpList, out *testapigroup.CarpList, s conversion.Scope) error {
|
||||
out.ListMeta = in.ListMeta
|
||||
if in.Items != nil {
|
||||
in, out := &in.Items, &out.Items
|
||||
*out = make([]testapigroup.Carp, len(*in))
|
||||
for i := range *in {
|
||||
if err := Convert_v1_Carp_To_testapigroup_Carp(&(*in)[i], &(*out)[i], s); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
} else {
|
||||
out.Items = nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Convert_v1_CarpList_To_testapigroup_CarpList is an autogenerated conversion function.
|
||||
func Convert_v1_CarpList_To_testapigroup_CarpList(in *CarpList, out *testapigroup.CarpList, s conversion.Scope) error {
|
||||
return autoConvert_v1_CarpList_To_testapigroup_CarpList(in, out, s)
|
||||
}
|
||||
|
||||
func autoConvert_testapigroup_CarpList_To_v1_CarpList(in *testapigroup.CarpList, out *CarpList, s conversion.Scope) error {
|
||||
out.ListMeta = in.ListMeta
|
||||
if in.Items != nil {
|
||||
in, out := &in.Items, &out.Items
|
||||
*out = make([]Carp, len(*in))
|
||||
for i := range *in {
|
||||
if err := Convert_testapigroup_Carp_To_v1_Carp(&(*in)[i], &(*out)[i], s); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
} else {
|
||||
out.Items = nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Convert_testapigroup_CarpList_To_v1_CarpList is an autogenerated conversion function.
|
||||
func Convert_testapigroup_CarpList_To_v1_CarpList(in *testapigroup.CarpList, out *CarpList, s conversion.Scope) error {
|
||||
return autoConvert_testapigroup_CarpList_To_v1_CarpList(in, out, s)
|
||||
}
|
||||
|
||||
func autoConvert_v1_CarpSpec_To_testapigroup_CarpSpec(in *CarpSpec, out *testapigroup.CarpSpec, s conversion.Scope) error {
|
||||
out.RestartPolicy = testapigroup.RestartPolicy(in.RestartPolicy)
|
||||
out.TerminationGracePeriodSeconds = (*int64)(unsafe.Pointer(in.TerminationGracePeriodSeconds))
|
||||
out.ActiveDeadlineSeconds = (*int64)(unsafe.Pointer(in.ActiveDeadlineSeconds))
|
||||
out.NodeSelector = *(*map[string]string)(unsafe.Pointer(&in.NodeSelector))
|
||||
out.ServiceAccountName = in.ServiceAccountName
|
||||
// INFO: in.DeprecatedServiceAccount opted out of conversion generation
|
||||
out.NodeName = in.NodeName
|
||||
// INFO: in.HostNetwork opted out of conversion generation
|
||||
// INFO: in.HostPID opted out of conversion generation
|
||||
// INFO: in.HostIPC opted out of conversion generation
|
||||
out.Hostname = in.Hostname
|
||||
out.Subdomain = in.Subdomain
|
||||
out.SchedulerName = in.SchedulerName
|
||||
return nil
|
||||
}
|
||||
|
||||
// Convert_v1_CarpSpec_To_testapigroup_CarpSpec is an autogenerated conversion function.
|
||||
func Convert_v1_CarpSpec_To_testapigroup_CarpSpec(in *CarpSpec, out *testapigroup.CarpSpec, s conversion.Scope) error {
|
||||
return autoConvert_v1_CarpSpec_To_testapigroup_CarpSpec(in, out, s)
|
||||
}
|
||||
|
||||
func autoConvert_testapigroup_CarpSpec_To_v1_CarpSpec(in *testapigroup.CarpSpec, out *CarpSpec, s conversion.Scope) error {
|
||||
out.RestartPolicy = RestartPolicy(in.RestartPolicy)
|
||||
out.TerminationGracePeriodSeconds = (*int64)(unsafe.Pointer(in.TerminationGracePeriodSeconds))
|
||||
out.ActiveDeadlineSeconds = (*int64)(unsafe.Pointer(in.ActiveDeadlineSeconds))
|
||||
out.NodeSelector = *(*map[string]string)(unsafe.Pointer(&in.NodeSelector))
|
||||
out.ServiceAccountName = in.ServiceAccountName
|
||||
out.NodeName = in.NodeName
|
||||
out.Hostname = in.Hostname
|
||||
out.Subdomain = in.Subdomain
|
||||
out.SchedulerName = in.SchedulerName
|
||||
return nil
|
||||
}
|
||||
|
||||
// Convert_testapigroup_CarpSpec_To_v1_CarpSpec is an autogenerated conversion function.
|
||||
func Convert_testapigroup_CarpSpec_To_v1_CarpSpec(in *testapigroup.CarpSpec, out *CarpSpec, s conversion.Scope) error {
|
||||
return autoConvert_testapigroup_CarpSpec_To_v1_CarpSpec(in, out, s)
|
||||
}
|
||||
|
||||
func autoConvert_v1_CarpStatus_To_testapigroup_CarpStatus(in *CarpStatus, out *testapigroup.CarpStatus, s conversion.Scope) error {
|
||||
out.Phase = testapigroup.CarpPhase(in.Phase)
|
||||
out.Conditions = *(*[]testapigroup.CarpCondition)(unsafe.Pointer(&in.Conditions))
|
||||
out.Message = in.Message
|
||||
out.Reason = in.Reason
|
||||
out.HostIP = in.HostIP
|
||||
out.CarpIP = in.CarpIP
|
||||
out.StartTime = (*metav1.Time)(unsafe.Pointer(in.StartTime))
|
||||
return nil
|
||||
}
|
||||
|
||||
// Convert_v1_CarpStatus_To_testapigroup_CarpStatus is an autogenerated conversion function.
|
||||
func Convert_v1_CarpStatus_To_testapigroup_CarpStatus(in *CarpStatus, out *testapigroup.CarpStatus, s conversion.Scope) error {
|
||||
return autoConvert_v1_CarpStatus_To_testapigroup_CarpStatus(in, out, s)
|
||||
}
|
||||
|
||||
func autoConvert_testapigroup_CarpStatus_To_v1_CarpStatus(in *testapigroup.CarpStatus, out *CarpStatus, s conversion.Scope) error {
|
||||
out.Phase = CarpPhase(in.Phase)
|
||||
out.Conditions = *(*[]CarpCondition)(unsafe.Pointer(&in.Conditions))
|
||||
out.Message = in.Message
|
||||
out.Reason = in.Reason
|
||||
out.HostIP = in.HostIP
|
||||
out.CarpIP = in.CarpIP
|
||||
out.StartTime = (*metav1.Time)(unsafe.Pointer(in.StartTime))
|
||||
return nil
|
||||
}
|
||||
|
||||
// Convert_testapigroup_CarpStatus_To_v1_CarpStatus is an autogenerated conversion function.
|
||||
func Convert_testapigroup_CarpStatus_To_v1_CarpStatus(in *testapigroup.CarpStatus, out *CarpStatus, s conversion.Scope) error {
|
||||
return autoConvert_testapigroup_CarpStatus_To_v1_CarpStatus(in, out, s)
|
||||
}
|
164
vendor/k8s.io/apimachinery/pkg/apis/testapigroup/v1/zz_generated.deepcopy.go
generated
vendored
164
vendor/k8s.io/apimachinery/pkg/apis/testapigroup/v1/zz_generated.deepcopy.go
generated
vendored
@ -1,164 +0,0 @@
|
||||
// +build !ignore_autogenerated
|
||||
|
||||
/*
|
||||
Copyright 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.
|
||||
*/
|
||||
|
||||
// Code generated by deepcopy-gen. DO NOT EDIT.
|
||||
|
||||
package v1
|
||||
|
||||
import (
|
||||
runtime "k8s.io/apimachinery/pkg/runtime"
|
||||
)
|
||||
|
||||
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
|
||||
func (in *Carp) DeepCopyInto(out *Carp) {
|
||||
*out = *in
|
||||
out.TypeMeta = in.TypeMeta
|
||||
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
|
||||
in.Spec.DeepCopyInto(&out.Spec)
|
||||
in.Status.DeepCopyInto(&out.Status)
|
||||
return
|
||||
}
|
||||
|
||||
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Carp.
|
||||
func (in *Carp) DeepCopy() *Carp {
|
||||
if in == nil {
|
||||
return nil
|
||||
}
|
||||
out := new(Carp)
|
||||
in.DeepCopyInto(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
|
||||
func (in *Carp) DeepCopyObject() runtime.Object {
|
||||
if c := in.DeepCopy(); c != nil {
|
||||
return c
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
|
||||
func (in *CarpCondition) DeepCopyInto(out *CarpCondition) {
|
||||
*out = *in
|
||||
in.LastProbeTime.DeepCopyInto(&out.LastProbeTime)
|
||||
in.LastTransitionTime.DeepCopyInto(&out.LastTransitionTime)
|
||||
return
|
||||
}
|
||||
|
||||
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CarpCondition.
|
||||
func (in *CarpCondition) DeepCopy() *CarpCondition {
|
||||
if in == nil {
|
||||
return nil
|
||||
}
|
||||
out := new(CarpCondition)
|
||||
in.DeepCopyInto(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
|
||||
func (in *CarpList) DeepCopyInto(out *CarpList) {
|
||||
*out = *in
|
||||
out.TypeMeta = in.TypeMeta
|
||||
out.ListMeta = in.ListMeta
|
||||
if in.Items != nil {
|
||||
in, out := &in.Items, &out.Items
|
||||
*out = make([]Carp, len(*in))
|
||||
for i := range *in {
|
||||
(*in)[i].DeepCopyInto(&(*out)[i])
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CarpList.
|
||||
func (in *CarpList) DeepCopy() *CarpList {
|
||||
if in == nil {
|
||||
return nil
|
||||
}
|
||||
out := new(CarpList)
|
||||
in.DeepCopyInto(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
|
||||
func (in *CarpList) DeepCopyObject() runtime.Object {
|
||||
if c := in.DeepCopy(); c != nil {
|
||||
return c
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
|
||||
func (in *CarpSpec) DeepCopyInto(out *CarpSpec) {
|
||||
*out = *in
|
||||
if in.TerminationGracePeriodSeconds != nil {
|
||||
in, out := &in.TerminationGracePeriodSeconds, &out.TerminationGracePeriodSeconds
|
||||
*out = new(int64)
|
||||
**out = **in
|
||||
}
|
||||
if in.ActiveDeadlineSeconds != nil {
|
||||
in, out := &in.ActiveDeadlineSeconds, &out.ActiveDeadlineSeconds
|
||||
*out = new(int64)
|
||||
**out = **in
|
||||
}
|
||||
if in.NodeSelector != nil {
|
||||
in, out := &in.NodeSelector, &out.NodeSelector
|
||||
*out = make(map[string]string, len(*in))
|
||||
for key, val := range *in {
|
||||
(*out)[key] = val
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CarpSpec.
|
||||
func (in *CarpSpec) DeepCopy() *CarpSpec {
|
||||
if in == nil {
|
||||
return nil
|
||||
}
|
||||
out := new(CarpSpec)
|
||||
in.DeepCopyInto(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
|
||||
func (in *CarpStatus) DeepCopyInto(out *CarpStatus) {
|
||||
*out = *in
|
||||
if in.Conditions != nil {
|
||||
in, out := &in.Conditions, &out.Conditions
|
||||
*out = make([]CarpCondition, len(*in))
|
||||
for i := range *in {
|
||||
(*in)[i].DeepCopyInto(&(*out)[i])
|
||||
}
|
||||
}
|
||||
if in.StartTime != nil {
|
||||
in, out := &in.StartTime, &out.StartTime
|
||||
*out = (*in).DeepCopy()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CarpStatus.
|
||||
func (in *CarpStatus) DeepCopy() *CarpStatus {
|
||||
if in == nil {
|
||||
return nil
|
||||
}
|
||||
out := new(CarpStatus)
|
||||
in.DeepCopyInto(out)
|
||||
return out
|
||||
}
|
32
vendor/k8s.io/apimachinery/pkg/apis/testapigroup/v1/zz_generated.defaults.go
generated
vendored
32
vendor/k8s.io/apimachinery/pkg/apis/testapigroup/v1/zz_generated.defaults.go
generated
vendored
@ -1,32 +0,0 @@
|
||||
// +build !ignore_autogenerated
|
||||
|
||||
/*
|
||||
Copyright 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.
|
||||
*/
|
||||
|
||||
// Code generated by defaulter-gen. DO NOT EDIT.
|
||||
|
||||
package v1
|
||||
|
||||
import (
|
||||
runtime "k8s.io/apimachinery/pkg/runtime"
|
||||
)
|
||||
|
||||
// RegisterDefaults adds defaulters functions to the given scheme.
|
||||
// Public to allow building arbitrary schemes.
|
||||
// All generated defaulters are covering - they call all nested defaulters.
|
||||
func RegisterDefaults(scheme *runtime.Scheme) error {
|
||||
return nil
|
||||
}
|
164
vendor/k8s.io/apimachinery/pkg/apis/testapigroup/zz_generated.deepcopy.go
generated
vendored
164
vendor/k8s.io/apimachinery/pkg/apis/testapigroup/zz_generated.deepcopy.go
generated
vendored
@ -1,164 +0,0 @@
|
||||
// +build !ignore_autogenerated
|
||||
|
||||
/*
|
||||
Copyright 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.
|
||||
*/
|
||||
|
||||
// Code generated by deepcopy-gen. DO NOT EDIT.
|
||||
|
||||
package testapigroup
|
||||
|
||||
import (
|
||||
runtime "k8s.io/apimachinery/pkg/runtime"
|
||||
)
|
||||
|
||||
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
|
||||
func (in *Carp) DeepCopyInto(out *Carp) {
|
||||
*out = *in
|
||||
out.TypeMeta = in.TypeMeta
|
||||
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
|
||||
in.Spec.DeepCopyInto(&out.Spec)
|
||||
in.Status.DeepCopyInto(&out.Status)
|
||||
return
|
||||
}
|
||||
|
||||
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Carp.
|
||||
func (in *Carp) DeepCopy() *Carp {
|
||||
if in == nil {
|
||||
return nil
|
||||
}
|
||||
out := new(Carp)
|
||||
in.DeepCopyInto(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
|
||||
func (in *Carp) DeepCopyObject() runtime.Object {
|
||||
if c := in.DeepCopy(); c != nil {
|
||||
return c
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
|
||||
func (in *CarpCondition) DeepCopyInto(out *CarpCondition) {
|
||||
*out = *in
|
||||
in.LastProbeTime.DeepCopyInto(&out.LastProbeTime)
|
||||
in.LastTransitionTime.DeepCopyInto(&out.LastTransitionTime)
|
||||
return
|
||||
}
|
||||
|
||||
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CarpCondition.
|
||||
func (in *CarpCondition) DeepCopy() *CarpCondition {
|
||||
if in == nil {
|
||||
return nil
|
||||
}
|
||||
out := new(CarpCondition)
|
||||
in.DeepCopyInto(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
|
||||
func (in *CarpList) DeepCopyInto(out *CarpList) {
|
||||
*out = *in
|
||||
out.TypeMeta = in.TypeMeta
|
||||
out.ListMeta = in.ListMeta
|
||||
if in.Items != nil {
|
||||
in, out := &in.Items, &out.Items
|
||||
*out = make([]Carp, len(*in))
|
||||
for i := range *in {
|
||||
(*in)[i].DeepCopyInto(&(*out)[i])
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CarpList.
|
||||
func (in *CarpList) DeepCopy() *CarpList {
|
||||
if in == nil {
|
||||
return nil
|
||||
}
|
||||
out := new(CarpList)
|
||||
in.DeepCopyInto(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
|
||||
func (in *CarpList) DeepCopyObject() runtime.Object {
|
||||
if c := in.DeepCopy(); c != nil {
|
||||
return c
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
|
||||
func (in *CarpSpec) DeepCopyInto(out *CarpSpec) {
|
||||
*out = *in
|
||||
if in.TerminationGracePeriodSeconds != nil {
|
||||
in, out := &in.TerminationGracePeriodSeconds, &out.TerminationGracePeriodSeconds
|
||||
*out = new(int64)
|
||||
**out = **in
|
||||
}
|
||||
if in.ActiveDeadlineSeconds != nil {
|
||||
in, out := &in.ActiveDeadlineSeconds, &out.ActiveDeadlineSeconds
|
||||
*out = new(int64)
|
||||
**out = **in
|
||||
}
|
||||
if in.NodeSelector != nil {
|
||||
in, out := &in.NodeSelector, &out.NodeSelector
|
||||
*out = make(map[string]string, len(*in))
|
||||
for key, val := range *in {
|
||||
(*out)[key] = val
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CarpSpec.
|
||||
func (in *CarpSpec) DeepCopy() *CarpSpec {
|
||||
if in == nil {
|
||||
return nil
|
||||
}
|
||||
out := new(CarpSpec)
|
||||
in.DeepCopyInto(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
|
||||
func (in *CarpStatus) DeepCopyInto(out *CarpStatus) {
|
||||
*out = *in
|
||||
if in.Conditions != nil {
|
||||
in, out := &in.Conditions, &out.Conditions
|
||||
*out = make([]CarpCondition, len(*in))
|
||||
for i := range *in {
|
||||
(*in)[i].DeepCopyInto(&(*out)[i])
|
||||
}
|
||||
}
|
||||
if in.StartTime != nil {
|
||||
in, out := &in.StartTime, &out.StartTime
|
||||
*out = (*in).DeepCopy()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CarpStatus.
|
||||
func (in *CarpStatus) DeepCopy() *CarpStatus {
|
||||
if in == nil {
|
||||
return nil
|
||||
}
|
||||
out := new(CarpStatus)
|
||||
in.DeepCopyInto(out)
|
||||
return out
|
||||
}
|
734
vendor/k8s.io/apimachinery/pkg/conversion/converter_test.go
generated
vendored
734
vendor/k8s.io/apimachinery/pkg/conversion/converter_test.go
generated
vendored
@ -1,734 +0,0 @@
|
||||
/*
|
||||
Copyright 2014 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 conversion
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/gofuzz"
|
||||
flag "github.com/spf13/pflag"
|
||||
|
||||
"k8s.io/apimachinery/pkg/util/diff"
|
||||
)
|
||||
|
||||
var fuzzIters = flag.Int("fuzz-iters", 50, "How many fuzzing iterations to do.")
|
||||
|
||||
// Test a weird version/kind embedding format.
|
||||
type MyWeirdCustomEmbeddedVersionKindField struct {
|
||||
ID string `json:"ID,omitempty"`
|
||||
APIVersion string `json:"myVersionKey,omitempty"`
|
||||
ObjectKind string `json:"myKindKey,omitempty"`
|
||||
Z string `json:"Z,omitempty"`
|
||||
Y uint64 `json:"Y,omitempty"`
|
||||
}
|
||||
|
||||
type TestType1 struct {
|
||||
MyWeirdCustomEmbeddedVersionKindField `json:",inline"`
|
||||
A string `json:"A,omitempty"`
|
||||
B int `json:"B,omitempty"`
|
||||
C int8 `json:"C,omitempty"`
|
||||
D int16 `json:"D,omitempty"`
|
||||
E int32 `json:"E,omitempty"`
|
||||
F int64 `json:"F,omitempty"`
|
||||
G uint `json:"G,omitempty"`
|
||||
H uint8 `json:"H,omitempty"`
|
||||
I uint16 `json:"I,omitempty"`
|
||||
J uint32 `json:"J,omitempty"`
|
||||
K uint64 `json:"K,omitempty"`
|
||||
L bool `json:"L,omitempty"`
|
||||
M map[string]int `json:"M,omitempty"`
|
||||
N map[string]TestType2 `json:"N,omitempty"`
|
||||
O *TestType2 `json:"O,omitempty"`
|
||||
P []TestType2 `json:"Q,omitempty"`
|
||||
}
|
||||
|
||||
type TestType2 struct {
|
||||
A string `json:"A,omitempty"`
|
||||
B int `json:"B,omitempty"`
|
||||
}
|
||||
|
||||
type ExternalTestType2 struct {
|
||||
A string `json:"A,omitempty"`
|
||||
B int `json:"B,omitempty"`
|
||||
}
|
||||
type ExternalTestType1 struct {
|
||||
MyWeirdCustomEmbeddedVersionKindField `json:",inline"`
|
||||
A string `json:"A,omitempty"`
|
||||
B int `json:"B,omitempty"`
|
||||
C int8 `json:"C,omitempty"`
|
||||
D int16 `json:"D,omitempty"`
|
||||
E int32 `json:"E,omitempty"`
|
||||
F int64 `json:"F,omitempty"`
|
||||
G uint `json:"G,omitempty"`
|
||||
H uint8 `json:"H,omitempty"`
|
||||
I uint16 `json:"I,omitempty"`
|
||||
J uint32 `json:"J,omitempty"`
|
||||
K uint64 `json:"K,omitempty"`
|
||||
L bool `json:"L,omitempty"`
|
||||
M map[string]int `json:"M,omitempty"`
|
||||
N map[string]ExternalTestType2 `json:"N,omitempty"`
|
||||
O *ExternalTestType2 `json:"O,omitempty"`
|
||||
P []ExternalTestType2 `json:"Q,omitempty"`
|
||||
}
|
||||
|
||||
func testLogger(t *testing.T) DebugLogger {
|
||||
// We don't set logger to eliminate rubbish logs in tests.
|
||||
// If you want to switch it, simply switch it to: "return t"
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestConverter_byteSlice(t *testing.T) {
|
||||
c := NewConverter(DefaultNameFunc)
|
||||
src := []byte{1, 2, 3}
|
||||
dest := []byte{}
|
||||
err := c.Convert(&src, &dest, 0, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("expected no error")
|
||||
}
|
||||
if e, a := src, dest; !reflect.DeepEqual(e, a) {
|
||||
t.Errorf("expected %#v, got %#v", e, a)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConverter_MismatchedTypes(t *testing.T) {
|
||||
c := NewConverter(DefaultNameFunc)
|
||||
|
||||
err := c.RegisterConversionFunc(
|
||||
func(in *[]string, out *int, s Scope) error {
|
||||
if str, err := strconv.Atoi((*in)[0]); err != nil {
|
||||
return err
|
||||
} else {
|
||||
*out = str
|
||||
return nil
|
||||
}
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error: %v", err)
|
||||
}
|
||||
|
||||
src := []string{"5"}
|
||||
var dest *int
|
||||
err = c.Convert(&src, &dest, 0, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if e, a := 5, *dest; e != a {
|
||||
t.Errorf("expected %#v, got %#v", e, a)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConverter_DefaultConvert(t *testing.T) {
|
||||
type A struct {
|
||||
Foo string
|
||||
Baz int
|
||||
}
|
||||
type B struct {
|
||||
Bar string
|
||||
Baz int
|
||||
}
|
||||
c := NewConverter(DefaultNameFunc)
|
||||
c.Debug = testLogger(t)
|
||||
c.nameFunc = func(t reflect.Type) string { return "MyType" }
|
||||
|
||||
// Ensure conversion funcs can call DefaultConvert to get default behavior,
|
||||
// then fixup remaining fields manually
|
||||
err := c.RegisterConversionFunc(func(in *A, out *B, s Scope) error {
|
||||
if err := s.DefaultConvert(in, out, IgnoreMissingFields); err != nil {
|
||||
return err
|
||||
}
|
||||
out.Bar = in.Foo
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error %v", err)
|
||||
}
|
||||
|
||||
x := A{"hello, intrepid test reader!", 3}
|
||||
y := B{}
|
||||
|
||||
err = c.Convert(&x, &y, 0, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error %v", err)
|
||||
}
|
||||
if e, a := x.Foo, y.Bar; e != a {
|
||||
t.Errorf("expected %v, got %v", e, a)
|
||||
}
|
||||
if e, a := x.Baz, y.Baz; e != a {
|
||||
t.Errorf("expected %v, got %v", e, a)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConverter_DeepCopy(t *testing.T) {
|
||||
type A struct {
|
||||
Foo *string
|
||||
Bar []string
|
||||
Baz interface{}
|
||||
Qux map[string]string
|
||||
}
|
||||
c := NewConverter(DefaultNameFunc)
|
||||
c.Debug = testLogger(t)
|
||||
|
||||
foo, baz := "foo", "baz"
|
||||
x := A{
|
||||
Foo: &foo,
|
||||
Bar: []string{"bar"},
|
||||
Baz: &baz,
|
||||
Qux: map[string]string{"qux": "qux"},
|
||||
}
|
||||
y := A{}
|
||||
|
||||
if err := c.Convert(&x, &y, 0, nil); err != nil {
|
||||
t.Fatalf("unexpected error %v", err)
|
||||
}
|
||||
*x.Foo = "foo2"
|
||||
x.Bar[0] = "bar2"
|
||||
*x.Baz.(*string) = "baz2"
|
||||
x.Qux["qux"] = "qux2"
|
||||
if e, a := *x.Foo, *y.Foo; e == a {
|
||||
t.Errorf("expected difference between %v and %v", e, a)
|
||||
}
|
||||
if e, a := x.Bar, y.Bar; reflect.DeepEqual(e, a) {
|
||||
t.Errorf("expected difference between %v and %v", e, a)
|
||||
}
|
||||
if e, a := *x.Baz.(*string), *y.Baz.(*string); e == a {
|
||||
t.Errorf("expected difference between %v and %v", e, a)
|
||||
}
|
||||
if e, a := x.Qux, y.Qux; reflect.DeepEqual(e, a) {
|
||||
t.Errorf("expected difference between %v and %v", e, a)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConverter_CallsRegisteredFunctions(t *testing.T) {
|
||||
type A struct {
|
||||
Foo string
|
||||
Baz int
|
||||
}
|
||||
type B struct {
|
||||
Bar string
|
||||
Baz int
|
||||
}
|
||||
type C struct{}
|
||||
c := NewConverter(DefaultNameFunc)
|
||||
c.Debug = testLogger(t)
|
||||
err := c.RegisterConversionFunc(func(in *A, out *B, s Scope) error {
|
||||
out.Bar = in.Foo
|
||||
return s.Convert(&in.Baz, &out.Baz, 0)
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error %v", err)
|
||||
}
|
||||
err = c.RegisterConversionFunc(func(in *B, out *A, s Scope) error {
|
||||
out.Foo = in.Bar
|
||||
return s.Convert(&in.Baz, &out.Baz, 0)
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error %v", err)
|
||||
}
|
||||
|
||||
x := A{"hello, intrepid test reader!", 3}
|
||||
y := B{}
|
||||
|
||||
err = c.Convert(&x, &y, 0, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error %v", err)
|
||||
}
|
||||
if e, a := x.Foo, y.Bar; e != a {
|
||||
t.Errorf("expected %v, got %v", e, a)
|
||||
}
|
||||
if e, a := x.Baz, y.Baz; e != a {
|
||||
t.Errorf("expected %v, got %v", e, a)
|
||||
}
|
||||
|
||||
z := B{"all your test are belong to us", 42}
|
||||
w := A{}
|
||||
|
||||
err = c.Convert(&z, &w, 0, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error %v", err)
|
||||
}
|
||||
if e, a := z.Bar, w.Foo; e != a {
|
||||
t.Errorf("expected %v, got %v", e, a)
|
||||
}
|
||||
if e, a := z.Baz, w.Baz; e != a {
|
||||
t.Errorf("expected %v, got %v", e, a)
|
||||
}
|
||||
|
||||
err = c.RegisterConversionFunc(func(in *A, out *C, s Scope) error {
|
||||
return fmt.Errorf("C can't store an A, silly")
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error %v", err)
|
||||
}
|
||||
err = c.Convert(&A{}, &C{}, 0, nil)
|
||||
if err == nil {
|
||||
t.Errorf("unexpected non-error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConverter_IgnoredConversion(t *testing.T) {
|
||||
type A struct{}
|
||||
type B struct{}
|
||||
|
||||
count := 0
|
||||
c := NewConverter(DefaultNameFunc)
|
||||
if err := c.RegisterConversionFunc(func(in *A, out *B, s Scope) error {
|
||||
count++
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatalf("unexpected error %v", err)
|
||||
}
|
||||
if err := c.RegisterIgnoredConversion(&A{}, &B{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
a := A{}
|
||||
b := B{}
|
||||
if err := c.Convert(&a, &b, 0, nil); err != nil {
|
||||
t.Errorf("%v", err)
|
||||
}
|
||||
if count != 0 {
|
||||
t.Errorf("unexpected number of conversion invocations")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConverter_IgnoredConversionNested(t *testing.T) {
|
||||
type C string
|
||||
type A struct {
|
||||
C C
|
||||
}
|
||||
type B struct {
|
||||
C C
|
||||
}
|
||||
|
||||
c := NewConverter(DefaultNameFunc)
|
||||
typed := C("")
|
||||
if err := c.RegisterIgnoredConversion(&typed, &typed); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
a := A{C: C("test")}
|
||||
b := B{C: C("other")}
|
||||
if err := c.Convert(&a, &b, AllowDifferentFieldTypeNames, nil); err != nil {
|
||||
t.Errorf("%v", err)
|
||||
}
|
||||
if b.C != C("other") {
|
||||
t.Errorf("expected no conversion of field C: %#v", b)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConverter_GeneratedConversionOverridden(t *testing.T) {
|
||||
type A struct{}
|
||||
type B struct{}
|
||||
c := NewConverter(DefaultNameFunc)
|
||||
if err := c.RegisterConversionFunc(func(in *A, out *B, s Scope) error {
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatalf("unexpected error %v", err)
|
||||
}
|
||||
if err := c.RegisterGeneratedConversionFunc(func(in *A, out *B, s Scope) error {
|
||||
return fmt.Errorf("generated function should be overridden")
|
||||
}); err != nil {
|
||||
t.Fatalf("unexpected error %v", err)
|
||||
}
|
||||
|
||||
a := A{}
|
||||
b := B{}
|
||||
if err := c.Convert(&a, &b, 0, nil); err != nil {
|
||||
t.Errorf("%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConverter_WithConversionOverridden(t *testing.T) {
|
||||
type A struct{}
|
||||
type B struct{}
|
||||
c := NewConverter(DefaultNameFunc)
|
||||
if err := c.RegisterConversionFunc(func(in *A, out *B, s Scope) error {
|
||||
return fmt.Errorf("conversion function should be overridden")
|
||||
}); err != nil {
|
||||
t.Fatalf("unexpected error %v", err)
|
||||
}
|
||||
if err := c.RegisterGeneratedConversionFunc(func(in *A, out *B, s Scope) error {
|
||||
return fmt.Errorf("generated function should be overridden")
|
||||
}); err != nil {
|
||||
t.Fatalf("unexpected error %v", err)
|
||||
}
|
||||
|
||||
ext := NewConversionFuncs()
|
||||
ext.Add(func(in *A, out *B, s Scope) error {
|
||||
return nil
|
||||
})
|
||||
newc := c.WithConversions(ext)
|
||||
|
||||
a := A{}
|
||||
b := B{}
|
||||
if err := c.Convert(&a, &b, 0, nil); err == nil || err.Error() != "conversion function should be overridden" {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
if err := newc.Convert(&a, &b, 0, nil); err != nil {
|
||||
t.Errorf("%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConverter_MapsStringArrays(t *testing.T) {
|
||||
type A struct {
|
||||
Foo string
|
||||
Baz int
|
||||
Other string
|
||||
}
|
||||
c := NewConverter(DefaultNameFunc)
|
||||
c.Debug = testLogger(t)
|
||||
if err := c.RegisterConversionFunc(func(input *[]string, out *string, s Scope) error {
|
||||
if len(*input) == 0 {
|
||||
*out = ""
|
||||
}
|
||||
*out = (*input)[0]
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatalf("unexpected error %v", err)
|
||||
}
|
||||
|
||||
x := map[string][]string{
|
||||
"Foo": {"bar"},
|
||||
"Baz": {"1"},
|
||||
"Other": {"", "test"},
|
||||
"other": {"wrong"},
|
||||
}
|
||||
y := A{"test", 2, "something"}
|
||||
|
||||
if err := c.Convert(&x, &y, AllowDifferentFieldTypeNames, nil); err == nil {
|
||||
t.Error("unexpected non-error")
|
||||
}
|
||||
|
||||
if err := c.RegisterConversionFunc(func(input *[]string, out *int, s Scope) error {
|
||||
if len(*input) == 0 {
|
||||
*out = 0
|
||||
}
|
||||
str := (*input)[0]
|
||||
i, err := strconv.Atoi(str)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*out = i
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatalf("unexpected error %v", err)
|
||||
}
|
||||
|
||||
if err := c.Convert(&x, &y, AllowDifferentFieldTypeNames, nil); err != nil {
|
||||
t.Fatalf("unexpected error %v", err)
|
||||
}
|
||||
if !reflect.DeepEqual(y, A{"bar", 1, ""}) {
|
||||
t.Errorf("unexpected result: %#v", y)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConverter_MapsStringArraysWithMappingKey(t *testing.T) {
|
||||
type A struct {
|
||||
Foo string `json:"test"`
|
||||
Baz int
|
||||
Other string
|
||||
}
|
||||
c := NewConverter(DefaultNameFunc)
|
||||
c.Debug = testLogger(t)
|
||||
if err := c.RegisterConversionFunc(func(input *[]string, out *string, s Scope) error {
|
||||
if len(*input) == 0 {
|
||||
*out = ""
|
||||
}
|
||||
*out = (*input)[0]
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatalf("unexpected error %v", err)
|
||||
}
|
||||
|
||||
x := map[string][]string{
|
||||
"Foo": {"bar"},
|
||||
"test": {"baz"},
|
||||
}
|
||||
y := A{"", 0, ""}
|
||||
|
||||
if err := c.Convert(&x, &y, AllowDifferentFieldTypeNames|IgnoreMissingFields, &Meta{}); err != nil {
|
||||
t.Fatalf("unexpected error %v", err)
|
||||
}
|
||||
if !reflect.DeepEqual(y, A{"bar", 0, ""}) {
|
||||
t.Errorf("unexpected result: %#v", y)
|
||||
}
|
||||
|
||||
mapping := func(key string, sourceTag, destTag reflect.StructTag) (source string, dest string) {
|
||||
if s := destTag.Get("json"); len(s) > 0 {
|
||||
return strings.SplitN(s, ",", 2)[0], key
|
||||
}
|
||||
return key, key
|
||||
}
|
||||
|
||||
if err := c.Convert(&x, &y, AllowDifferentFieldTypeNames|IgnoreMissingFields, &Meta{KeyNameMapping: mapping}); err != nil {
|
||||
t.Fatalf("unexpected error %v", err)
|
||||
}
|
||||
if !reflect.DeepEqual(y, A{"baz", 0, ""}) {
|
||||
t.Errorf("unexpected result: %#v", y)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConverter_fuzz(t *testing.T) {
|
||||
// Use the same types from the scheme test.
|
||||
table := []struct {
|
||||
from, to, check interface{}
|
||||
}{
|
||||
{&TestType1{}, &ExternalTestType1{}, &TestType1{}},
|
||||
{&ExternalTestType1{}, &TestType1{}, &ExternalTestType1{}},
|
||||
}
|
||||
|
||||
f := fuzz.New().NilChance(.5).NumElements(0, 100)
|
||||
c := NewConverter(DefaultNameFunc)
|
||||
c.nameFunc = func(t reflect.Type) string {
|
||||
// Hide the fact that we don't have separate packages for these things.
|
||||
return map[reflect.Type]string{
|
||||
reflect.TypeOf(TestType1{}): "TestType1",
|
||||
reflect.TypeOf(ExternalTestType1{}): "TestType1",
|
||||
reflect.TypeOf(TestType2{}): "TestType2",
|
||||
reflect.TypeOf(ExternalTestType2{}): "TestType2",
|
||||
}[t]
|
||||
}
|
||||
c.Debug = testLogger(t)
|
||||
|
||||
for i, item := range table {
|
||||
for j := 0; j < *fuzzIters; j++ {
|
||||
f.Fuzz(item.from)
|
||||
err := c.Convert(item.from, item.to, 0, nil)
|
||||
if err != nil {
|
||||
t.Errorf("(%v, %v): unexpected error: %v", i, j, err)
|
||||
continue
|
||||
}
|
||||
err = c.Convert(item.to, item.check, 0, nil)
|
||||
if err != nil {
|
||||
t.Errorf("(%v, %v): unexpected error: %v", i, j, err)
|
||||
continue
|
||||
}
|
||||
if e, a := item.from, item.check; !reflect.DeepEqual(e, a) {
|
||||
t.Errorf("(%v, %v): unexpected diff: %v", i, j, diff.ObjectDiff(e, a))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestConverter_MapElemAddr(t *testing.T) {
|
||||
type Foo struct {
|
||||
A map[int]int
|
||||
}
|
||||
type Bar struct {
|
||||
A map[string]string
|
||||
}
|
||||
c := NewConverter(DefaultNameFunc)
|
||||
c.Debug = testLogger(t)
|
||||
err := c.RegisterConversionFunc(
|
||||
func(in *int, out *string, s Scope) error {
|
||||
*out = fmt.Sprintf("%v", *in)
|
||||
return nil
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error: %v", err)
|
||||
}
|
||||
err = c.RegisterConversionFunc(
|
||||
func(in *string, out *int, s Scope) error {
|
||||
if str, err := strconv.Atoi(*in); err != nil {
|
||||
return err
|
||||
} else {
|
||||
*out = str
|
||||
return nil
|
||||
}
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error: %v", err)
|
||||
}
|
||||
f := fuzz.New().NilChance(0).NumElements(3, 3)
|
||||
first := Foo{}
|
||||
second := Bar{}
|
||||
f.Fuzz(&first)
|
||||
err = c.Convert(&first, &second, AllowDifferentFieldTypeNames, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error: %v", err)
|
||||
}
|
||||
third := Foo{}
|
||||
err = c.Convert(&second, &third, AllowDifferentFieldTypeNames, nil)
|
||||
if e, a := first, third; !reflect.DeepEqual(e, a) {
|
||||
t.Errorf("Unexpected diff: %v", diff.ObjectDiff(e, a))
|
||||
}
|
||||
}
|
||||
|
||||
func TestConverter_tags(t *testing.T) {
|
||||
type Foo struct {
|
||||
A string `test:"foo"`
|
||||
}
|
||||
type Bar struct {
|
||||
A string `test:"bar"`
|
||||
}
|
||||
c := NewConverter(DefaultNameFunc)
|
||||
c.Debug = testLogger(t)
|
||||
err := c.RegisterConversionFunc(
|
||||
func(in *string, out *string, s Scope) error {
|
||||
if e, a := "foo", s.SrcTag().Get("test"); e != a {
|
||||
t.Errorf("expected %v, got %v", e, a)
|
||||
}
|
||||
if e, a := "bar", s.DestTag().Get("test"); e != a {
|
||||
t.Errorf("expected %v, got %v", e, a)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error: %v", err)
|
||||
}
|
||||
err = c.Convert(&Foo{}, &Bar{}, AllowDifferentFieldTypeNames, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConverter_meta(t *testing.T) {
|
||||
type Foo struct{ A string }
|
||||
type Bar struct{ A string }
|
||||
c := NewConverter(DefaultNameFunc)
|
||||
c.Debug = testLogger(t)
|
||||
checks := 0
|
||||
err := c.RegisterConversionFunc(
|
||||
func(in *Foo, out *Bar, s Scope) error {
|
||||
if s.Meta() == nil {
|
||||
t.Errorf("Meta did not get passed!")
|
||||
}
|
||||
checks++
|
||||
s.Convert(&in.A, &out.A, 0)
|
||||
return nil
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error: %v", err)
|
||||
}
|
||||
err = c.RegisterConversionFunc(
|
||||
func(in *string, out *string, s Scope) error {
|
||||
if s.Meta() == nil {
|
||||
t.Errorf("Meta did not get passed a second time!")
|
||||
}
|
||||
checks++
|
||||
return nil
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error: %v", err)
|
||||
}
|
||||
err = c.Convert(&Foo{}, &Bar{}, 0, &Meta{})
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error: %v", err)
|
||||
}
|
||||
if checks != 2 {
|
||||
t.Errorf("Registered functions did not get called.")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConverter_flags(t *testing.T) {
|
||||
type Foo struct{ A string }
|
||||
type Bar struct{ A string }
|
||||
table := []struct {
|
||||
from, to interface{}
|
||||
flags FieldMatchingFlags
|
||||
shouldSucceed bool
|
||||
}{
|
||||
// Check that DestFromSource allows extra fields only in source.
|
||||
{
|
||||
from: &struct{ A string }{},
|
||||
to: &struct{ A, B string }{},
|
||||
flags: DestFromSource,
|
||||
shouldSucceed: false,
|
||||
}, {
|
||||
from: &struct{ A, B string }{},
|
||||
to: &struct{ A string }{},
|
||||
flags: DestFromSource,
|
||||
shouldSucceed: true,
|
||||
},
|
||||
|
||||
// Check that SourceToDest allows for extra fields only in dest.
|
||||
{
|
||||
from: &struct{ A string }{},
|
||||
to: &struct{ A, B string }{},
|
||||
flags: SourceToDest,
|
||||
shouldSucceed: true,
|
||||
}, {
|
||||
from: &struct{ A, B string }{},
|
||||
to: &struct{ A string }{},
|
||||
flags: SourceToDest,
|
||||
shouldSucceed: false,
|
||||
},
|
||||
|
||||
// Check that IgnoreMissingFields makes the above failure cases pass.
|
||||
{
|
||||
from: &struct{ A string }{},
|
||||
to: &struct{ A, B string }{},
|
||||
flags: DestFromSource | IgnoreMissingFields,
|
||||
shouldSucceed: true,
|
||||
}, {
|
||||
from: &struct{ A, B string }{},
|
||||
to: &struct{ A string }{},
|
||||
flags: SourceToDest | IgnoreMissingFields,
|
||||
shouldSucceed: true,
|
||||
},
|
||||
|
||||
// Check that the field type name must match unless
|
||||
// AllowDifferentFieldTypeNames is specified.
|
||||
{
|
||||
from: &struct{ A, B Foo }{},
|
||||
to: &struct{ A Bar }{},
|
||||
flags: DestFromSource,
|
||||
shouldSucceed: false,
|
||||
}, {
|
||||
from: &struct{ A Foo }{},
|
||||
to: &struct{ A, B Bar }{},
|
||||
flags: SourceToDest,
|
||||
shouldSucceed: false,
|
||||
}, {
|
||||
from: &struct{ A, B Foo }{},
|
||||
to: &struct{ A Bar }{},
|
||||
flags: DestFromSource | AllowDifferentFieldTypeNames,
|
||||
shouldSucceed: true,
|
||||
}, {
|
||||
from: &struct{ A Foo }{},
|
||||
to: &struct{ A, B Bar }{},
|
||||
flags: SourceToDest | AllowDifferentFieldTypeNames,
|
||||
shouldSucceed: true,
|
||||
},
|
||||
}
|
||||
f := fuzz.New().NilChance(.5).NumElements(0, 100)
|
||||
c := NewConverter(DefaultNameFunc)
|
||||
c.Debug = testLogger(t)
|
||||
|
||||
for i, item := range table {
|
||||
for j := 0; j < *fuzzIters; j++ {
|
||||
f.Fuzz(item.from)
|
||||
err := c.Convert(item.from, item.to, item.flags, nil)
|
||||
if item.shouldSucceed && err != nil {
|
||||
t.Errorf("(%v, %v): unexpected error: %v", i, j, err)
|
||||
continue
|
||||
}
|
||||
if !item.shouldSucceed && err == nil {
|
||||
t.Errorf("(%v, %v): unexpected non-error", i, j)
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
38
vendor/k8s.io/apimachinery/pkg/conversion/helper_test.go
generated
vendored
38
vendor/k8s.io/apimachinery/pkg/conversion/helper_test.go
generated
vendored
@ -1,38 +0,0 @@
|
||||
/*
|
||||
Copyright 2014 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 conversion
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestInvalidPtrValueKind(t *testing.T) {
|
||||
var simple interface{}
|
||||
switch obj := simple.(type) {
|
||||
default:
|
||||
_, err := EnforcePtr(obj)
|
||||
if err == nil {
|
||||
t.Errorf("Expected error on invalid kind")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnforceNilPtr(t *testing.T) {
|
||||
var nilPtr *struct{}
|
||||
_, err := EnforcePtr(nilPtr)
|
||||
if err == nil {
|
||||
t.Errorf("Expected error on nil pointer")
|
||||
}
|
||||
}
|
219
vendor/k8s.io/apimachinery/pkg/conversion/queryparams/convert_test.go
generated
vendored
219
vendor/k8s.io/apimachinery/pkg/conversion/queryparams/convert_test.go
generated
vendored
@ -1,219 +0,0 @@
|
||||
/*
|
||||
Copyright 2014 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 queryparams_test
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/conversion/queryparams"
|
||||
"k8s.io/apimachinery/pkg/runtime/schema"
|
||||
)
|
||||
|
||||
type namedString string
|
||||
type namedBool bool
|
||||
|
||||
type bar struct {
|
||||
Float1 float32 `json:"float1"`
|
||||
Float2 float64 `json:"float2"`
|
||||
Int1 int64 `json:"int1,omitempty"`
|
||||
Int2 int32 `json:"int2,omitempty"`
|
||||
Int3 int16 `json:"int3,omitempty"`
|
||||
Str1 string `json:"str1,omitempty"`
|
||||
Ignored int
|
||||
Ignored2 string
|
||||
}
|
||||
|
||||
func (obj *bar) GetObjectKind() schema.ObjectKind { return schema.EmptyObjectKind }
|
||||
|
||||
type foo struct {
|
||||
Str string `json:"str"`
|
||||
Integer int `json:"integer,omitempty"`
|
||||
Slice []string `json:"slice,omitempty"`
|
||||
Boolean bool `json:"boolean,omitempty"`
|
||||
NamedStr namedString `json:"namedStr,omitempty"`
|
||||
NamedBool namedBool `json:"namedBool,omitempty"`
|
||||
Foobar bar `json:"foobar,omitempty"`
|
||||
Testmap map[string]string `json:"testmap,omitempty"`
|
||||
}
|
||||
|
||||
func (obj *foo) GetObjectKind() schema.ObjectKind { return schema.EmptyObjectKind }
|
||||
|
||||
type baz struct {
|
||||
Ptr *int `json:"ptr"`
|
||||
Bptr *bool `json:"bptr,omitempty"`
|
||||
}
|
||||
|
||||
func (obj *baz) GetObjectKind() schema.ObjectKind { return schema.EmptyObjectKind }
|
||||
|
||||
// childStructs tests some of the types we serialize to query params for log API calls
|
||||
// notably, the nested time struct
|
||||
type childStructs struct {
|
||||
Container string `json:"container,omitempty"`
|
||||
Follow bool `json:"follow,omitempty"`
|
||||
Previous bool `json:"previous,omitempty"`
|
||||
SinceSeconds *int64 `json:"sinceSeconds,omitempty"`
|
||||
TailLines *int64 `json:"tailLines,omitempty"`
|
||||
SinceTime *metav1.Time `json:"sinceTime,omitempty"`
|
||||
EmptyTime *metav1.Time `json:"emptyTime"`
|
||||
NonPointerTime metav1.Time `json:"nonPointerTime"`
|
||||
}
|
||||
|
||||
func (obj *childStructs) GetObjectKind() schema.ObjectKind { return schema.EmptyObjectKind }
|
||||
|
||||
func validateResult(t *testing.T, input interface{}, actual, expected url.Values) {
|
||||
local := url.Values{}
|
||||
for k, v := range expected {
|
||||
local[k] = v
|
||||
}
|
||||
for k, v := range actual {
|
||||
if ev, ok := local[k]; !ok || !reflect.DeepEqual(ev, v) {
|
||||
if !ok {
|
||||
t.Errorf("%#v: actual value key %s not found in expected map", input, k)
|
||||
} else {
|
||||
t.Errorf("%#v: values don't match: actual: %#v, expected: %#v", input, v, ev)
|
||||
}
|
||||
}
|
||||
delete(local, k)
|
||||
}
|
||||
if len(local) > 0 {
|
||||
t.Errorf("%#v: expected map has keys that were not found in actual map: %#v", input, local)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConvert(t *testing.T) {
|
||||
sinceSeconds := int64(123)
|
||||
tailLines := int64(0)
|
||||
sinceTime := metav1.Date(2000, 1, 1, 12, 34, 56, 0, time.UTC)
|
||||
|
||||
tests := []struct {
|
||||
input interface{}
|
||||
expected url.Values
|
||||
}{
|
||||
{
|
||||
input: &foo{
|
||||
Str: "hello",
|
||||
},
|
||||
expected: url.Values{"str": {"hello"}},
|
||||
},
|
||||
{
|
||||
input: &foo{
|
||||
Str: "test string",
|
||||
Slice: []string{"one", "two", "three"},
|
||||
Integer: 234,
|
||||
Boolean: true,
|
||||
},
|
||||
expected: url.Values{"str": {"test string"}, "slice": {"one", "two", "three"}, "integer": {"234"}, "boolean": {"true"}},
|
||||
},
|
||||
{
|
||||
input: &foo{
|
||||
Str: "named types",
|
||||
NamedStr: "value1",
|
||||
NamedBool: true,
|
||||
},
|
||||
expected: url.Values{"str": {"named types"}, "namedStr": {"value1"}, "namedBool": {"true"}},
|
||||
},
|
||||
{
|
||||
input: &foo{
|
||||
Str: "don't ignore embedded struct",
|
||||
Foobar: bar{
|
||||
Float1: 5.0,
|
||||
},
|
||||
},
|
||||
expected: url.Values{"str": {"don't ignore embedded struct"}, "float1": {"5"}, "float2": {"0"}},
|
||||
},
|
||||
{
|
||||
// Ignore untagged fields
|
||||
input: &bar{
|
||||
Float1: 23.5,
|
||||
Float2: 100.7,
|
||||
Int1: 1,
|
||||
Int2: 2,
|
||||
Int3: 3,
|
||||
Ignored: 1,
|
||||
Ignored2: "ignored",
|
||||
},
|
||||
expected: url.Values{"float1": {"23.5"}, "float2": {"100.7"}, "int1": {"1"}, "int2": {"2"}, "int3": {"3"}},
|
||||
},
|
||||
{
|
||||
// include fields that are not tagged omitempty
|
||||
input: &foo{
|
||||
NamedStr: "named str",
|
||||
},
|
||||
expected: url.Values{"str": {""}, "namedStr": {"named str"}},
|
||||
},
|
||||
{
|
||||
input: &baz{
|
||||
Ptr: intp(5),
|
||||
Bptr: boolp(true),
|
||||
},
|
||||
expected: url.Values{"ptr": {"5"}, "bptr": {"true"}},
|
||||
},
|
||||
{
|
||||
input: &baz{
|
||||
Bptr: boolp(true),
|
||||
},
|
||||
expected: url.Values{"ptr": {""}, "bptr": {"true"}},
|
||||
},
|
||||
{
|
||||
input: &baz{
|
||||
Ptr: intp(5),
|
||||
},
|
||||
expected: url.Values{"ptr": {"5"}},
|
||||
},
|
||||
{
|
||||
input: &childStructs{
|
||||
Container: "mycontainer",
|
||||
Follow: true,
|
||||
Previous: true,
|
||||
SinceSeconds: &sinceSeconds,
|
||||
TailLines: nil,
|
||||
SinceTime: &sinceTime, // test a custom marshaller
|
||||
EmptyTime: nil, // test a nil custom marshaller without omitempty
|
||||
NonPointerTime: sinceTime,
|
||||
},
|
||||
expected: url.Values{"container": {"mycontainer"}, "follow": {"true"}, "previous": {"true"}, "sinceSeconds": {"123"}, "sinceTime": {"2000-01-01T12:34:56Z"}, "emptyTime": {""}, "nonPointerTime": {"2000-01-01T12:34:56Z"}},
|
||||
},
|
||||
{
|
||||
input: &childStructs{
|
||||
Container: "mycontainer",
|
||||
Follow: true,
|
||||
Previous: true,
|
||||
SinceSeconds: &sinceSeconds,
|
||||
TailLines: &tailLines,
|
||||
SinceTime: nil, // test a nil custom marshaller with omitempty
|
||||
NonPointerTime: sinceTime,
|
||||
},
|
||||
expected: url.Values{"container": {"mycontainer"}, "follow": {"true"}, "previous": {"true"}, "sinceSeconds": {"123"}, "tailLines": {"0"}, "emptyTime": {""}, "nonPointerTime": {"2000-01-01T12:34:56Z"}},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
result, err := queryparams.Convert(test.input)
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error while converting %#v: %v", test.input, err)
|
||||
}
|
||||
validateResult(t, test.input, result, test.expected)
|
||||
}
|
||||
}
|
||||
|
||||
func intp(n int) *int { return &n }
|
||||
|
||||
func boolp(b bool) *bool { return &b }
|
57
vendor/k8s.io/apimachinery/pkg/fields/fields_test.go
generated
vendored
57
vendor/k8s.io/apimachinery/pkg/fields/fields_test.go
generated
vendored
@ -1,57 +0,0 @@
|
||||
/*
|
||||
Copyright 2015 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 fields
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func matches(t *testing.T, ls Set, want string) {
|
||||
if ls.String() != want {
|
||||
t.Errorf("Expected '%s', but got '%s'", want, ls.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetString(t *testing.T) {
|
||||
matches(t, Set{"x": "y"}, "x=y")
|
||||
matches(t, Set{"foo": "bar"}, "foo=bar")
|
||||
matches(t, Set{"foo": "bar", "baz": "qup"}, "baz=qup,foo=bar")
|
||||
}
|
||||
|
||||
func TestFieldHas(t *testing.T) {
|
||||
fieldHasTests := []struct {
|
||||
Ls Fields
|
||||
Key string
|
||||
Has bool
|
||||
}{
|
||||
{Set{"x": "y"}, "x", true},
|
||||
{Set{"x": ""}, "x", true},
|
||||
{Set{"x": "y"}, "foo", false},
|
||||
}
|
||||
for _, lh := range fieldHasTests {
|
||||
if has := lh.Ls.Has(lh.Key); has != lh.Has {
|
||||
t.Errorf("%#v.Has(%#v) => %v, expected %v", lh.Ls, lh.Key, has, lh.Has)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFieldGet(t *testing.T) {
|
||||
ls := Set{"x": "y"}
|
||||
if ls.Get("x") != "y" {
|
||||
t.Errorf("Set.Get is broken")
|
||||
}
|
||||
}
|
397
vendor/k8s.io/apimachinery/pkg/fields/selector_test.go
generated
vendored
397
vendor/k8s.io/apimachinery/pkg/fields/selector_test.go
generated
vendored
@ -1,397 +0,0 @@
|
||||
/*
|
||||
Copyright 2015 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 fields
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSplitTerms(t *testing.T) {
|
||||
testcases := map[string][]string{
|
||||
// Simple selectors
|
||||
`a`: {`a`},
|
||||
`a=avalue`: {`a=avalue`},
|
||||
`a=avalue,b=bvalue`: {`a=avalue`, `b=bvalue`},
|
||||
`a=avalue,b==bvalue,c!=cvalue`: {`a=avalue`, `b==bvalue`, `c!=cvalue`},
|
||||
|
||||
// Empty terms
|
||||
``: nil,
|
||||
`a=a,`: {`a=a`, ``},
|
||||
`,a=a`: {``, `a=a`},
|
||||
|
||||
// Escaped values
|
||||
`k=\,,k2=v2`: {`k=\,`, `k2=v2`}, // escaped comma in value
|
||||
`k=\\,k2=v2`: {`k=\\`, `k2=v2`}, // escaped backslash, unescaped comma
|
||||
`k=\\\,,k2=v2`: {`k=\\\,`, `k2=v2`}, // escaped backslash and comma
|
||||
`k=\a\b\`: {`k=\a\b\`}, // non-escape sequences
|
||||
`k=\`: {`k=\`}, // orphan backslash
|
||||
|
||||
// Multi-byte
|
||||
`함=수,목=록`: {`함=수`, `목=록`},
|
||||
}
|
||||
|
||||
for selector, expectedTerms := range testcases {
|
||||
if terms := splitTerms(selector); !reflect.DeepEqual(terms, expectedTerms) {
|
||||
t.Errorf("splitSelectors(`%s`): Expected\n%#v\ngot\n%#v", selector, expectedTerms, terms)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitTerm(t *testing.T) {
|
||||
testcases := map[string]struct {
|
||||
lhs string
|
||||
op string
|
||||
rhs string
|
||||
ok bool
|
||||
}{
|
||||
// Simple terms
|
||||
`a=value`: {lhs: `a`, op: `=`, rhs: `value`, ok: true},
|
||||
`b==value`: {lhs: `b`, op: `==`, rhs: `value`, ok: true},
|
||||
`c!=value`: {lhs: `c`, op: `!=`, rhs: `value`, ok: true},
|
||||
|
||||
// Empty or invalid terms
|
||||
``: {lhs: ``, op: ``, rhs: ``, ok: false},
|
||||
`a`: {lhs: ``, op: ``, rhs: ``, ok: false},
|
||||
|
||||
// Escaped values
|
||||
`k=\,`: {lhs: `k`, op: `=`, rhs: `\,`, ok: true},
|
||||
`k=\=`: {lhs: `k`, op: `=`, rhs: `\=`, ok: true},
|
||||
`k=\\\a\b\=\,\`: {lhs: `k`, op: `=`, rhs: `\\\a\b\=\,\`, ok: true},
|
||||
|
||||
// Multi-byte
|
||||
`함=수`: {lhs: `함`, op: `=`, rhs: `수`, ok: true},
|
||||
}
|
||||
|
||||
for term, expected := range testcases {
|
||||
lhs, op, rhs, ok := splitTerm(term)
|
||||
if lhs != expected.lhs || op != expected.op || rhs != expected.rhs || ok != expected.ok {
|
||||
t.Errorf(
|
||||
"splitTerm(`%s`): Expected\n%s,%s,%s,%v\nGot\n%s,%s,%s,%v",
|
||||
term,
|
||||
expected.lhs, expected.op, expected.rhs, expected.ok,
|
||||
lhs, op, rhs, ok,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEscapeValue(t *testing.T) {
|
||||
// map values to their normalized escaped values
|
||||
testcases := map[string]string{
|
||||
``: ``,
|
||||
`a`: `a`,
|
||||
`=`: `\=`,
|
||||
`,`: `\,`,
|
||||
`\`: `\\`,
|
||||
`\=\,\`: `\\\=\\\,\\`,
|
||||
}
|
||||
|
||||
for unescapedValue, escapedValue := range testcases {
|
||||
actualEscaped := EscapeValue(unescapedValue)
|
||||
if actualEscaped != escapedValue {
|
||||
t.Errorf("EscapeValue(%s): expected %s, got %s", unescapedValue, escapedValue, actualEscaped)
|
||||
}
|
||||
|
||||
actualUnescaped, err := UnescapeValue(escapedValue)
|
||||
if err != nil {
|
||||
t.Errorf("UnescapeValue(%s): unexpected error %v", escapedValue, err)
|
||||
}
|
||||
if actualUnescaped != unescapedValue {
|
||||
t.Errorf("UnescapeValue(%s): expected %s, got %s", escapedValue, unescapedValue, actualUnescaped)
|
||||
}
|
||||
}
|
||||
|
||||
// test invalid escape sequences
|
||||
invalidTestcases := []string{
|
||||
`\`, // orphan slash is invalid
|
||||
`\\\`, // orphan slash is invalid
|
||||
`\a`, // unrecognized escape sequence is invalid
|
||||
}
|
||||
for _, invalidValue := range invalidTestcases {
|
||||
_, err := UnescapeValue(invalidValue)
|
||||
if _, ok := err.(InvalidEscapeSequence); !ok || err == nil {
|
||||
t.Errorf("UnescapeValue(%s): expected invalid escape sequence error, got %#v", invalidValue, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelectorParse(t *testing.T) {
|
||||
testGoodStrings := []string{
|
||||
"x=a,y=b,z=c",
|
||||
"",
|
||||
"x!=a,y=b",
|
||||
`x=a||y\=b`,
|
||||
`x=a\=\=b`,
|
||||
}
|
||||
testBadStrings := []string{
|
||||
"x=a||y=b",
|
||||
"x==a==b",
|
||||
"x=a,b",
|
||||
"x in (a)",
|
||||
"x in (a,b,c)",
|
||||
"x",
|
||||
}
|
||||
for _, test := range testGoodStrings {
|
||||
lq, err := ParseSelector(test)
|
||||
if err != nil {
|
||||
t.Errorf("%v: error %v (%#v)\n", test, err, err)
|
||||
}
|
||||
if test != lq.String() {
|
||||
t.Errorf("%v restring gave: %v\n", test, lq.String())
|
||||
}
|
||||
}
|
||||
for _, test := range testBadStrings {
|
||||
_, err := ParseSelector(test)
|
||||
if err == nil {
|
||||
t.Errorf("%v: did not get expected error\n", test)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeterministicParse(t *testing.T) {
|
||||
s1, err := ParseSelector("x=a,a=x")
|
||||
s2, err2 := ParseSelector("a=x,x=a")
|
||||
if err != nil || err2 != nil {
|
||||
t.Errorf("Unexpected parse error")
|
||||
}
|
||||
if s1.String() != s2.String() {
|
||||
t.Errorf("Non-deterministic parse")
|
||||
}
|
||||
}
|
||||
|
||||
func expectMatch(t *testing.T, selector string, ls Set) {
|
||||
lq, err := ParseSelector(selector)
|
||||
if err != nil {
|
||||
t.Errorf("Unable to parse %v as a selector\n", selector)
|
||||
return
|
||||
}
|
||||
if !lq.Matches(ls) {
|
||||
t.Errorf("Wanted %s to match '%s', but it did not.\n", selector, ls)
|
||||
}
|
||||
}
|
||||
|
||||
func expectNoMatch(t *testing.T, selector string, ls Set) {
|
||||
lq, err := ParseSelector(selector)
|
||||
if err != nil {
|
||||
t.Errorf("Unable to parse %v as a selector\n", selector)
|
||||
return
|
||||
}
|
||||
if lq.Matches(ls) {
|
||||
t.Errorf("Wanted '%s' to not match '%s', but it did.", selector, ls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEverything(t *testing.T) {
|
||||
if !Everything().Matches(Set{"x": "y"}) {
|
||||
t.Errorf("Nil selector didn't match")
|
||||
}
|
||||
if !Everything().Empty() {
|
||||
t.Errorf("Everything was not empty")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelectorMatches(t *testing.T) {
|
||||
expectMatch(t, "", Set{"x": "y"})
|
||||
expectMatch(t, "x=y", Set{"x": "y"})
|
||||
expectMatch(t, "x=y,z=w", Set{"x": "y", "z": "w"})
|
||||
expectMatch(t, "x!=y,z!=w", Set{"x": "z", "z": "a"})
|
||||
expectMatch(t, "notin=in", Set{"notin": "in"}) // in and notin in exactMatch
|
||||
expectNoMatch(t, "x=y", Set{"x": "z"})
|
||||
expectNoMatch(t, "x=y,z=w", Set{"x": "w", "z": "w"})
|
||||
expectNoMatch(t, "x!=y,z!=w", Set{"x": "z", "z": "w"})
|
||||
|
||||
fieldset := Set{
|
||||
"foo": "bar",
|
||||
"baz": "blah",
|
||||
"complex": `=value\,\`,
|
||||
}
|
||||
expectMatch(t, "foo=bar", fieldset)
|
||||
expectMatch(t, "baz=blah", fieldset)
|
||||
expectMatch(t, "foo=bar,baz=blah", fieldset)
|
||||
expectMatch(t, `foo=bar,baz=blah,complex=\=value\\\,\\`, fieldset)
|
||||
expectNoMatch(t, "foo=blah", fieldset)
|
||||
expectNoMatch(t, "baz=bar", fieldset)
|
||||
expectNoMatch(t, "foo=bar,foobar=bar,baz=blah", fieldset)
|
||||
}
|
||||
|
||||
func TestOneTermEqualSelector(t *testing.T) {
|
||||
if !OneTermEqualSelector("x", "y").Matches(Set{"x": "y"}) {
|
||||
t.Errorf("No match when match expected.")
|
||||
}
|
||||
if OneTermEqualSelector("x", "y").Matches(Set{"x": "z"}) {
|
||||
t.Errorf("Match when none expected.")
|
||||
}
|
||||
}
|
||||
|
||||
func expectMatchDirect(t *testing.T, selector, ls Set) {
|
||||
if !SelectorFromSet(selector).Matches(ls) {
|
||||
t.Errorf("Wanted %s to match '%s', but it did not.\n", selector, ls)
|
||||
}
|
||||
}
|
||||
|
||||
func expectNoMatchDirect(t *testing.T, selector, ls Set) {
|
||||
if SelectorFromSet(selector).Matches(ls) {
|
||||
t.Errorf("Wanted '%s' to not match '%s', but it did.", selector, ls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetMatches(t *testing.T) {
|
||||
labelset := Set{
|
||||
"foo": "bar",
|
||||
"baz": "blah",
|
||||
}
|
||||
expectMatchDirect(t, Set{}, labelset)
|
||||
expectMatchDirect(t, Set{"foo": "bar"}, labelset)
|
||||
expectMatchDirect(t, Set{"baz": "blah"}, labelset)
|
||||
expectMatchDirect(t, Set{"foo": "bar", "baz": "blah"}, labelset)
|
||||
expectNoMatchDirect(t, Set{"foo": "=blah"}, labelset)
|
||||
expectNoMatchDirect(t, Set{"baz": "=bar"}, labelset)
|
||||
expectNoMatchDirect(t, Set{"foo": "=bar", "foobar": "bar", "baz": "blah"}, labelset)
|
||||
}
|
||||
|
||||
func TestNilMapIsValid(t *testing.T) {
|
||||
selector := Set(nil).AsSelector()
|
||||
if selector == nil {
|
||||
t.Errorf("Selector for nil set should be Everything")
|
||||
}
|
||||
if !selector.Empty() {
|
||||
t.Errorf("Selector for nil set should be Empty")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetIsEmpty(t *testing.T) {
|
||||
if !(Set{}).AsSelector().Empty() {
|
||||
t.Errorf("Empty set should be empty")
|
||||
}
|
||||
if !(andTerm(nil)).Empty() {
|
||||
t.Errorf("Nil andTerm should be empty")
|
||||
}
|
||||
if (&hasTerm{}).Empty() {
|
||||
t.Errorf("hasTerm should not be empty")
|
||||
}
|
||||
if (¬HasTerm{}).Empty() {
|
||||
t.Errorf("notHasTerm should not be empty")
|
||||
}
|
||||
if !(andTerm{andTerm{}}).Empty() {
|
||||
t.Errorf("Nested andTerm should be empty")
|
||||
}
|
||||
if (andTerm{&hasTerm{"a", "b"}}).Empty() {
|
||||
t.Errorf("Nested andTerm should not be empty")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequiresExactMatch(t *testing.T) {
|
||||
testCases := map[string]struct {
|
||||
S Selector
|
||||
Label string
|
||||
Value string
|
||||
Found bool
|
||||
}{
|
||||
"empty set": {Set{}.AsSelector(), "test", "", false},
|
||||
"empty hasTerm": {&hasTerm{}, "test", "", false},
|
||||
"skipped hasTerm": {&hasTerm{"a", "b"}, "test", "", false},
|
||||
"valid hasTerm": {&hasTerm{"test", "b"}, "test", "b", true},
|
||||
"valid hasTerm no value": {&hasTerm{"test", ""}, "test", "", true},
|
||||
"valid notHasTerm": {¬HasTerm{"test", "b"}, "test", "", false},
|
||||
"valid notHasTerm no value": {¬HasTerm{"test", ""}, "test", "", false},
|
||||
"nil andTerm": {andTerm(nil), "test", "", false},
|
||||
"empty andTerm": {andTerm{}, "test", "", false},
|
||||
"nested andTerm": {andTerm{andTerm{}}, "test", "", false},
|
||||
"nested andTerm matches": {andTerm{&hasTerm{"test", "b"}}, "test", "b", true},
|
||||
"andTerm with non-match": {andTerm{&hasTerm{}, &hasTerm{"test", "b"}}, "test", "b", true},
|
||||
}
|
||||
for k, v := range testCases {
|
||||
value, found := v.S.RequiresExactMatch(v.Label)
|
||||
if value != v.Value {
|
||||
t.Errorf("%s: expected value %s, got %s", k, v.Value, value)
|
||||
}
|
||||
if found != v.Found {
|
||||
t.Errorf("%s: expected found %t, got %t", k, v.Found, found)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTransform(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
selector string
|
||||
transform func(field, value string) (string, string, error)
|
||||
result string
|
||||
isEmpty bool
|
||||
}{
|
||||
{
|
||||
name: "empty selector",
|
||||
selector: "",
|
||||
transform: func(field, value string) (string, string, error) { return field, value, nil },
|
||||
result: "",
|
||||
isEmpty: true,
|
||||
},
|
||||
{
|
||||
name: "no-op transform",
|
||||
selector: "a=b,c=d",
|
||||
transform: func(field, value string) (string, string, error) { return field, value, nil },
|
||||
result: "a=b,c=d",
|
||||
isEmpty: false,
|
||||
},
|
||||
{
|
||||
name: "transform one field",
|
||||
selector: "a=b,c=d",
|
||||
transform: func(field, value string) (string, string, error) {
|
||||
if field == "a" {
|
||||
return "e", "f", nil
|
||||
}
|
||||
return field, value, nil
|
||||
},
|
||||
result: "e=f,c=d",
|
||||
isEmpty: false,
|
||||
},
|
||||
{
|
||||
name: "remove field to make empty",
|
||||
selector: "a=b",
|
||||
transform: func(field, value string) (string, string, error) { return "", "", nil },
|
||||
result: "",
|
||||
isEmpty: true,
|
||||
},
|
||||
{
|
||||
name: "remove only one field",
|
||||
selector: "a=b,c=d,e=f",
|
||||
transform: func(field, value string) (string, string, error) {
|
||||
if field == "c" {
|
||||
return "", "", nil
|
||||
}
|
||||
return field, value, nil
|
||||
},
|
||||
result: "a=b,e=f",
|
||||
isEmpty: false,
|
||||
},
|
||||
}
|
||||
|
||||
for i, tc := range testCases {
|
||||
result, err := ParseAndTransformSelector(tc.selector, tc.transform)
|
||||
if err != nil {
|
||||
t.Errorf("[%d] unexpected error during Transform: %v", i, err)
|
||||
}
|
||||
if result.Empty() != tc.isEmpty {
|
||||
t.Errorf("[%d] expected empty: %t, got: %t", i, tc.isEmpty, result.Empty())
|
||||
}
|
||||
if result.String() != tc.result {
|
||||
t.Errorf("[%d] unexpected result: %s", i, result.String())
|
||||
}
|
||||
}
|
||||
|
||||
}
|
231
vendor/k8s.io/apimachinery/pkg/labels/labels_test.go
generated
vendored
231
vendor/k8s.io/apimachinery/pkg/labels/labels_test.go
generated
vendored
@ -1,231 +0,0 @@
|
||||
/*
|
||||
Copyright 2014 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 labels
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func matches(t *testing.T, ls Set, want string) {
|
||||
if ls.String() != want {
|
||||
t.Errorf("Expected '%s', but got '%s'", want, ls.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetString(t *testing.T) {
|
||||
matches(t, Set{"x": "y"}, "x=y")
|
||||
matches(t, Set{"foo": "bar"}, "foo=bar")
|
||||
matches(t, Set{"foo": "bar", "baz": "qup"}, "baz=qup,foo=bar")
|
||||
|
||||
// TODO: Make our label representation robust enough to handle labels
|
||||
// with ",=!" characters in their names.
|
||||
}
|
||||
|
||||
func TestLabelHas(t *testing.T) {
|
||||
labelHasTests := []struct {
|
||||
Ls Labels
|
||||
Key string
|
||||
Has bool
|
||||
}{
|
||||
{Set{"x": "y"}, "x", true},
|
||||
{Set{"x": ""}, "x", true},
|
||||
{Set{"x": "y"}, "foo", false},
|
||||
}
|
||||
for _, lh := range labelHasTests {
|
||||
if has := lh.Ls.Has(lh.Key); has != lh.Has {
|
||||
t.Errorf("%#v.Has(%#v) => %v, expected %v", lh.Ls, lh.Key, has, lh.Has)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLabelGet(t *testing.T) {
|
||||
ls := Set{"x": "y"}
|
||||
if ls.Get("x") != "y" {
|
||||
t.Errorf("Set.Get is broken")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLabelConflict(t *testing.T) {
|
||||
tests := []struct {
|
||||
labels1 map[string]string
|
||||
labels2 map[string]string
|
||||
conflict bool
|
||||
}{
|
||||
{
|
||||
labels1: map[string]string{},
|
||||
labels2: map[string]string{},
|
||||
conflict: false,
|
||||
},
|
||||
{
|
||||
labels1: map[string]string{"env": "test"},
|
||||
labels2: map[string]string{"infra": "true"},
|
||||
conflict: false,
|
||||
},
|
||||
{
|
||||
labels1: map[string]string{"env": "test"},
|
||||
labels2: map[string]string{"infra": "true", "env": "test"},
|
||||
conflict: false,
|
||||
},
|
||||
{
|
||||
labels1: map[string]string{"env": "test"},
|
||||
labels2: map[string]string{"env": "dev"},
|
||||
conflict: true,
|
||||
},
|
||||
{
|
||||
labels1: map[string]string{"env": "test", "infra": "false"},
|
||||
labels2: map[string]string{"infra": "true", "color": "blue"},
|
||||
conflict: true,
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
conflict := Conflicts(Set(test.labels1), Set(test.labels2))
|
||||
if conflict != test.conflict {
|
||||
t.Errorf("expected: %v but got: %v", test.conflict, conflict)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLabelMerge(t *testing.T) {
|
||||
tests := []struct {
|
||||
labels1 map[string]string
|
||||
labels2 map[string]string
|
||||
mergedLabels map[string]string
|
||||
}{
|
||||
{
|
||||
labels1: map[string]string{},
|
||||
labels2: map[string]string{},
|
||||
mergedLabels: map[string]string{},
|
||||
},
|
||||
{
|
||||
labels1: map[string]string{"infra": "true"},
|
||||
labels2: map[string]string{},
|
||||
mergedLabels: map[string]string{"infra": "true"},
|
||||
},
|
||||
{
|
||||
labels1: map[string]string{"infra": "true"},
|
||||
labels2: map[string]string{"env": "test", "color": "blue"},
|
||||
mergedLabels: map[string]string{"infra": "true", "env": "test", "color": "blue"},
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
mergedLabels := Merge(Set(test.labels1), Set(test.labels2))
|
||||
if !Equals(mergedLabels, test.mergedLabels) {
|
||||
t.Errorf("expected: %v but got: %v", test.mergedLabels, mergedLabels)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLabelSelectorParse(t *testing.T) {
|
||||
tests := []struct {
|
||||
selector string
|
||||
labels map[string]string
|
||||
valid bool
|
||||
}{
|
||||
{
|
||||
selector: "",
|
||||
labels: map[string]string{},
|
||||
valid: true,
|
||||
},
|
||||
{
|
||||
selector: "x=a",
|
||||
labels: map[string]string{"x": "a"},
|
||||
valid: true,
|
||||
},
|
||||
{
|
||||
selector: "x=a,y=b,z=c",
|
||||
labels: map[string]string{"x": "a", "y": "b", "z": "c"},
|
||||
valid: true,
|
||||
},
|
||||
{
|
||||
selector: " x = a , y = b , z = c ",
|
||||
labels: map[string]string{"x": "a", "y": "b", "z": "c"},
|
||||
valid: true,
|
||||
},
|
||||
{
|
||||
selector: "color=green,env=test,service=front",
|
||||
labels: map[string]string{"color": "green", "env": "test", "service": "front"},
|
||||
valid: true,
|
||||
},
|
||||
{
|
||||
selector: "color=green, env=test, service=front",
|
||||
labels: map[string]string{"color": "green", "env": "test", "service": "front"},
|
||||
valid: true,
|
||||
},
|
||||
{
|
||||
selector: ",",
|
||||
labels: map[string]string{},
|
||||
valid: false,
|
||||
},
|
||||
{
|
||||
selector: "x",
|
||||
labels: map[string]string{},
|
||||
valid: false,
|
||||
},
|
||||
{
|
||||
selector: "x,y",
|
||||
labels: map[string]string{},
|
||||
valid: false,
|
||||
},
|
||||
{
|
||||
selector: "x=$y",
|
||||
labels: map[string]string{},
|
||||
valid: false,
|
||||
},
|
||||
{
|
||||
selector: "x!=y",
|
||||
labels: map[string]string{},
|
||||
valid: false,
|
||||
},
|
||||
{
|
||||
selector: "x==y",
|
||||
labels: map[string]string{},
|
||||
valid: false,
|
||||
},
|
||||
{
|
||||
selector: "x=a||y=b",
|
||||
labels: map[string]string{},
|
||||
valid: false,
|
||||
},
|
||||
{
|
||||
selector: "x in (y)",
|
||||
labels: map[string]string{},
|
||||
valid: false,
|
||||
},
|
||||
{
|
||||
selector: "x notin (y)",
|
||||
labels: map[string]string{},
|
||||
valid: false,
|
||||
},
|
||||
{
|
||||
selector: "x y",
|
||||
labels: map[string]string{},
|
||||
valid: false,
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
labels, err := ConvertSelectorToLabelsMap(test.selector)
|
||||
if test.valid && err != nil {
|
||||
t.Errorf("selector: %s, expected no error but got: %s", test.selector, err)
|
||||
} else if !test.valid && err == nil {
|
||||
t.Errorf("selector: %s, expected an error", test.selector)
|
||||
}
|
||||
|
||||
if !Equals(Set(labels), test.labels) {
|
||||
t.Errorf("expected: %s but got: %s", test.labels, labels)
|
||||
}
|
||||
}
|
||||
}
|
619
vendor/k8s.io/apimachinery/pkg/labels/selector_test.go
generated
vendored
619
vendor/k8s.io/apimachinery/pkg/labels/selector_test.go
generated
vendored
@ -1,619 +0,0 @@
|
||||
/*
|
||||
Copyright 2014 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 labels
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"k8s.io/apimachinery/pkg/selection"
|
||||
"k8s.io/apimachinery/pkg/util/sets"
|
||||
)
|
||||
|
||||
func TestSelectorParse(t *testing.T) {
|
||||
testGoodStrings := []string{
|
||||
"x=a,y=b,z=c",
|
||||
"",
|
||||
"x!=a,y=b",
|
||||
"x=",
|
||||
"x= ",
|
||||
"x=,z= ",
|
||||
"x= ,z= ",
|
||||
"!x",
|
||||
"x>1",
|
||||
"x>1,z<5",
|
||||
}
|
||||
testBadStrings := []string{
|
||||
"x=a||y=b",
|
||||
"x==a==b",
|
||||
"!x=a",
|
||||
"x<a",
|
||||
}
|
||||
for _, test := range testGoodStrings {
|
||||
lq, err := Parse(test)
|
||||
if err != nil {
|
||||
t.Errorf("%v: error %v (%#v)\n", test, err, err)
|
||||
}
|
||||
if strings.Replace(test, " ", "", -1) != lq.String() {
|
||||
t.Errorf("%v restring gave: %v\n", test, lq.String())
|
||||
}
|
||||
}
|
||||
for _, test := range testBadStrings {
|
||||
_, err := Parse(test)
|
||||
if err == nil {
|
||||
t.Errorf("%v: did not get expected error\n", test)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeterministicParse(t *testing.T) {
|
||||
s1, err := Parse("x=a,a=x")
|
||||
s2, err2 := Parse("a=x,x=a")
|
||||
if err != nil || err2 != nil {
|
||||
t.Errorf("Unexpected parse error")
|
||||
}
|
||||
if s1.String() != s2.String() {
|
||||
t.Errorf("Non-deterministic parse")
|
||||
}
|
||||
}
|
||||
|
||||
func expectMatch(t *testing.T, selector string, ls Set) {
|
||||
lq, err := Parse(selector)
|
||||
if err != nil {
|
||||
t.Errorf("Unable to parse %v as a selector\n", selector)
|
||||
return
|
||||
}
|
||||
if !lq.Matches(ls) {
|
||||
t.Errorf("Wanted %s to match '%s', but it did not.\n", selector, ls)
|
||||
}
|
||||
}
|
||||
|
||||
func expectNoMatch(t *testing.T, selector string, ls Set) {
|
||||
lq, err := Parse(selector)
|
||||
if err != nil {
|
||||
t.Errorf("Unable to parse %v as a selector\n", selector)
|
||||
return
|
||||
}
|
||||
if lq.Matches(ls) {
|
||||
t.Errorf("Wanted '%s' to not match '%s', but it did.", selector, ls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEverything(t *testing.T) {
|
||||
if !Everything().Matches(Set{"x": "y"}) {
|
||||
t.Errorf("Nil selector didn't match")
|
||||
}
|
||||
if !Everything().Empty() {
|
||||
t.Errorf("Everything was not empty")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelectorMatches(t *testing.T) {
|
||||
expectMatch(t, "", Set{"x": "y"})
|
||||
expectMatch(t, "x=y", Set{"x": "y"})
|
||||
expectMatch(t, "x=y,z=w", Set{"x": "y", "z": "w"})
|
||||
expectMatch(t, "x!=y,z!=w", Set{"x": "z", "z": "a"})
|
||||
expectMatch(t, "notin=in", Set{"notin": "in"}) // in and notin in exactMatch
|
||||
expectMatch(t, "x", Set{"x": "z"})
|
||||
expectMatch(t, "!x", Set{"y": "z"})
|
||||
expectMatch(t, "x>1", Set{"x": "2"})
|
||||
expectMatch(t, "x<1", Set{"x": "0"})
|
||||
expectNoMatch(t, "x=z", Set{})
|
||||
expectNoMatch(t, "x=y", Set{"x": "z"})
|
||||
expectNoMatch(t, "x=y,z=w", Set{"x": "w", "z": "w"})
|
||||
expectNoMatch(t, "x!=y,z!=w", Set{"x": "z", "z": "w"})
|
||||
expectNoMatch(t, "x", Set{"y": "z"})
|
||||
expectNoMatch(t, "!x", Set{"x": "z"})
|
||||
expectNoMatch(t, "x>1", Set{"x": "0"})
|
||||
expectNoMatch(t, "x<1", Set{"x": "2"})
|
||||
|
||||
labelset := Set{
|
||||
"foo": "bar",
|
||||
"baz": "blah",
|
||||
}
|
||||
expectMatch(t, "foo=bar", labelset)
|
||||
expectMatch(t, "baz=blah", labelset)
|
||||
expectMatch(t, "foo=bar,baz=blah", labelset)
|
||||
expectNoMatch(t, "foo=blah", labelset)
|
||||
expectNoMatch(t, "baz=bar", labelset)
|
||||
expectNoMatch(t, "foo=bar,foobar=bar,baz=blah", labelset)
|
||||
}
|
||||
|
||||
func expectMatchDirect(t *testing.T, selector, ls Set) {
|
||||
if !SelectorFromSet(selector).Matches(ls) {
|
||||
t.Errorf("Wanted %s to match '%s', but it did not.\n", selector, ls)
|
||||
}
|
||||
}
|
||||
|
||||
func expectNoMatchDirect(t *testing.T, selector, ls Set) {
|
||||
if SelectorFromSet(selector).Matches(ls) {
|
||||
t.Errorf("Wanted '%s' to not match '%s', but it did.", selector, ls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetMatches(t *testing.T) {
|
||||
labelset := Set{
|
||||
"foo": "bar",
|
||||
"baz": "blah",
|
||||
}
|
||||
expectMatchDirect(t, Set{}, labelset)
|
||||
expectMatchDirect(t, Set{"foo": "bar"}, labelset)
|
||||
expectMatchDirect(t, Set{"baz": "blah"}, labelset)
|
||||
expectMatchDirect(t, Set{"foo": "bar", "baz": "blah"}, labelset)
|
||||
|
||||
//TODO: bad values not handled for the moment in SelectorFromSet
|
||||
//expectNoMatchDirect(t, Set{"foo": "=blah"}, labelset)
|
||||
//expectNoMatchDirect(t, Set{"baz": "=bar"}, labelset)
|
||||
//expectNoMatchDirect(t, Set{"foo": "=bar", "foobar": "bar", "baz": "blah"}, labelset)
|
||||
}
|
||||
|
||||
func TestNilMapIsValid(t *testing.T) {
|
||||
selector := Set(nil).AsSelector()
|
||||
if selector == nil {
|
||||
t.Errorf("Selector for nil set should be Everything")
|
||||
}
|
||||
if !selector.Empty() {
|
||||
t.Errorf("Selector for nil set should be Empty")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetIsEmpty(t *testing.T) {
|
||||
if !(Set{}).AsSelector().Empty() {
|
||||
t.Errorf("Empty set should be empty")
|
||||
}
|
||||
if !(NewSelector()).Empty() {
|
||||
t.Errorf("Nil Selector should be empty")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLexer(t *testing.T) {
|
||||
testcases := []struct {
|
||||
s string
|
||||
t Token
|
||||
}{
|
||||
{"", EndOfStringToken},
|
||||
{",", CommaToken},
|
||||
{"notin", NotInToken},
|
||||
{"in", InToken},
|
||||
{"=", EqualsToken},
|
||||
{"==", DoubleEqualsToken},
|
||||
{">", GreaterThanToken},
|
||||
{"<", LessThanToken},
|
||||
//Note that Lex returns the longest valid token found
|
||||
{"!", DoesNotExistToken},
|
||||
{"!=", NotEqualsToken},
|
||||
{"(", OpenParToken},
|
||||
{")", ClosedParToken},
|
||||
//Non-"special" characters are considered part of an identifier
|
||||
{"~", IdentifierToken},
|
||||
{"||", IdentifierToken},
|
||||
}
|
||||
for _, v := range testcases {
|
||||
l := &Lexer{s: v.s, pos: 0}
|
||||
token, lit := l.Lex()
|
||||
if token != v.t {
|
||||
t.Errorf("Got %d it should be %d for '%s'", token, v.t, v.s)
|
||||
}
|
||||
if v.t != ErrorToken && lit != v.s {
|
||||
t.Errorf("Got '%s' it should be '%s'", lit, v.s)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func min(l, r int) (m int) {
|
||||
m = r
|
||||
if l < r {
|
||||
m = l
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func TestLexerSequence(t *testing.T) {
|
||||
testcases := []struct {
|
||||
s string
|
||||
t []Token
|
||||
}{
|
||||
{"key in ( value )", []Token{IdentifierToken, InToken, OpenParToken, IdentifierToken, ClosedParToken}},
|
||||
{"key notin ( value )", []Token{IdentifierToken, NotInToken, OpenParToken, IdentifierToken, ClosedParToken}},
|
||||
{"key in ( value1, value2 )", []Token{IdentifierToken, InToken, OpenParToken, IdentifierToken, CommaToken, IdentifierToken, ClosedParToken}},
|
||||
{"key", []Token{IdentifierToken}},
|
||||
{"!key", []Token{DoesNotExistToken, IdentifierToken}},
|
||||
{"()", []Token{OpenParToken, ClosedParToken}},
|
||||
{"x in (),y", []Token{IdentifierToken, InToken, OpenParToken, ClosedParToken, CommaToken, IdentifierToken}},
|
||||
{"== != (), = notin", []Token{DoubleEqualsToken, NotEqualsToken, OpenParToken, ClosedParToken, CommaToken, EqualsToken, NotInToken}},
|
||||
{"key>2", []Token{IdentifierToken, GreaterThanToken, IdentifierToken}},
|
||||
{"key<1", []Token{IdentifierToken, LessThanToken, IdentifierToken}},
|
||||
}
|
||||
for _, v := range testcases {
|
||||
var literals []string
|
||||
var tokens []Token
|
||||
l := &Lexer{s: v.s, pos: 0}
|
||||
for {
|
||||
token, lit := l.Lex()
|
||||
if token == EndOfStringToken {
|
||||
break
|
||||
}
|
||||
tokens = append(tokens, token)
|
||||
literals = append(literals, lit)
|
||||
}
|
||||
if len(tokens) != len(v.t) {
|
||||
t.Errorf("Bad number of tokens for '%s %d, %d", v.s, len(tokens), len(v.t))
|
||||
}
|
||||
for i := 0; i < min(len(tokens), len(v.t)); i++ {
|
||||
if tokens[i] != v.t[i] {
|
||||
t.Errorf("Test '%s': Mismatching in token type found '%v' it should be '%v'", v.s, tokens[i], v.t[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestParserLookahead(t *testing.T) {
|
||||
testcases := []struct {
|
||||
s string
|
||||
t []Token
|
||||
}{
|
||||
{"key in ( value )", []Token{IdentifierToken, InToken, OpenParToken, IdentifierToken, ClosedParToken, EndOfStringToken}},
|
||||
{"key notin ( value )", []Token{IdentifierToken, NotInToken, OpenParToken, IdentifierToken, ClosedParToken, EndOfStringToken}},
|
||||
{"key in ( value1, value2 )", []Token{IdentifierToken, InToken, OpenParToken, IdentifierToken, CommaToken, IdentifierToken, ClosedParToken, EndOfStringToken}},
|
||||
{"key", []Token{IdentifierToken, EndOfStringToken}},
|
||||
{"!key", []Token{DoesNotExistToken, IdentifierToken, EndOfStringToken}},
|
||||
{"()", []Token{OpenParToken, ClosedParToken, EndOfStringToken}},
|
||||
{"", []Token{EndOfStringToken}},
|
||||
{"x in (),y", []Token{IdentifierToken, InToken, OpenParToken, ClosedParToken, CommaToken, IdentifierToken, EndOfStringToken}},
|
||||
{"== != (), = notin", []Token{DoubleEqualsToken, NotEqualsToken, OpenParToken, ClosedParToken, CommaToken, EqualsToken, NotInToken, EndOfStringToken}},
|
||||
{"key>2", []Token{IdentifierToken, GreaterThanToken, IdentifierToken, EndOfStringToken}},
|
||||
{"key<1", []Token{IdentifierToken, LessThanToken, IdentifierToken, EndOfStringToken}},
|
||||
}
|
||||
for _, v := range testcases {
|
||||
p := &Parser{l: &Lexer{s: v.s, pos: 0}, position: 0}
|
||||
p.scan()
|
||||
if len(p.scannedItems) != len(v.t) {
|
||||
t.Errorf("Expected %d items found %d", len(v.t), len(p.scannedItems))
|
||||
}
|
||||
for {
|
||||
token, lit := p.lookahead(KeyAndOperator)
|
||||
|
||||
token2, lit2 := p.consume(KeyAndOperator)
|
||||
if token == EndOfStringToken {
|
||||
break
|
||||
}
|
||||
if token != token2 || lit != lit2 {
|
||||
t.Errorf("Bad values")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequirementConstructor(t *testing.T) {
|
||||
requirementConstructorTests := []struct {
|
||||
Key string
|
||||
Op selection.Operator
|
||||
Vals sets.String
|
||||
Success bool
|
||||
}{
|
||||
{"x", selection.In, nil, false},
|
||||
{"x", selection.NotIn, sets.NewString(), false},
|
||||
{"x", selection.In, sets.NewString("foo"), true},
|
||||
{"x", selection.NotIn, sets.NewString("foo"), true},
|
||||
{"x", selection.Exists, nil, true},
|
||||
{"x", selection.DoesNotExist, nil, true},
|
||||
{"1foo", selection.In, sets.NewString("bar"), true},
|
||||
{"1234", selection.In, sets.NewString("bar"), true},
|
||||
{"y", selection.GreaterThan, sets.NewString("1"), true},
|
||||
{"z", selection.LessThan, sets.NewString("6"), true},
|
||||
{"foo", selection.GreaterThan, sets.NewString("bar"), false},
|
||||
{"barz", selection.LessThan, sets.NewString("blah"), false},
|
||||
{strings.Repeat("a", 254), selection.Exists, nil, false}, //breaks DNS rule that len(key) <= 253
|
||||
}
|
||||
for _, rc := range requirementConstructorTests {
|
||||
if _, err := NewRequirement(rc.Key, rc.Op, rc.Vals.List()); err == nil && !rc.Success {
|
||||
t.Errorf("expected error with key:%#v op:%v vals:%v, got no error", rc.Key, rc.Op, rc.Vals)
|
||||
} else if err != nil && rc.Success {
|
||||
t.Errorf("expected no error with key:%#v op:%v vals:%v, got:%v", rc.Key, rc.Op, rc.Vals, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestToString(t *testing.T) {
|
||||
var req Requirement
|
||||
toStringTests := []struct {
|
||||
In *internalSelector
|
||||
Out string
|
||||
Valid bool
|
||||
}{
|
||||
|
||||
{&internalSelector{
|
||||
getRequirement("x", selection.In, sets.NewString("abc", "def"), t),
|
||||
getRequirement("y", selection.NotIn, sets.NewString("jkl"), t),
|
||||
getRequirement("z", selection.Exists, nil, t)},
|
||||
"x in (abc,def),y notin (jkl),z", true},
|
||||
{&internalSelector{
|
||||
getRequirement("x", selection.NotIn, sets.NewString("abc", "def"), t),
|
||||
getRequirement("y", selection.NotEquals, sets.NewString("jkl"), t),
|
||||
getRequirement("z", selection.DoesNotExist, nil, t)},
|
||||
"x notin (abc,def),y!=jkl,!z", true},
|
||||
{&internalSelector{
|
||||
getRequirement("x", selection.In, sets.NewString("abc", "def"), t),
|
||||
req}, // adding empty req for the trailing ','
|
||||
"x in (abc,def),", false},
|
||||
{&internalSelector{
|
||||
getRequirement("x", selection.NotIn, sets.NewString("abc"), t),
|
||||
getRequirement("y", selection.In, sets.NewString("jkl", "mno"), t),
|
||||
getRequirement("z", selection.NotIn, sets.NewString(""), t)},
|
||||
"x notin (abc),y in (jkl,mno),z notin ()", true},
|
||||
{&internalSelector{
|
||||
getRequirement("x", selection.Equals, sets.NewString("abc"), t),
|
||||
getRequirement("y", selection.DoubleEquals, sets.NewString("jkl"), t),
|
||||
getRequirement("z", selection.NotEquals, sets.NewString("a"), t),
|
||||
getRequirement("z", selection.Exists, nil, t)},
|
||||
"x=abc,y==jkl,z!=a,z", true},
|
||||
{&internalSelector{
|
||||
getRequirement("x", selection.GreaterThan, sets.NewString("2"), t),
|
||||
getRequirement("y", selection.LessThan, sets.NewString("8"), t),
|
||||
getRequirement("z", selection.Exists, nil, t)},
|
||||
"x>2,y<8,z", true},
|
||||
}
|
||||
for _, ts := range toStringTests {
|
||||
if out := ts.In.String(); out == "" && ts.Valid {
|
||||
t.Errorf("%#v.String() => '%v' expected no error", ts.In, out)
|
||||
} else if out != ts.Out {
|
||||
t.Errorf("%#v.String() => '%v' want '%v'", ts.In, out, ts.Out)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequirementSelectorMatching(t *testing.T) {
|
||||
var req Requirement
|
||||
labelSelectorMatchingTests := []struct {
|
||||
Set Set
|
||||
Sel Selector
|
||||
Match bool
|
||||
}{
|
||||
{Set{"x": "foo", "y": "baz"}, &internalSelector{
|
||||
req,
|
||||
}, false},
|
||||
{Set{"x": "foo", "y": "baz"}, &internalSelector{
|
||||
getRequirement("x", selection.In, sets.NewString("foo"), t),
|
||||
getRequirement("y", selection.NotIn, sets.NewString("alpha"), t),
|
||||
}, true},
|
||||
{Set{"x": "foo", "y": "baz"}, &internalSelector{
|
||||
getRequirement("x", selection.In, sets.NewString("foo"), t),
|
||||
getRequirement("y", selection.In, sets.NewString("alpha"), t),
|
||||
}, false},
|
||||
{Set{"y": ""}, &internalSelector{
|
||||
getRequirement("x", selection.NotIn, sets.NewString(""), t),
|
||||
getRequirement("y", selection.Exists, nil, t),
|
||||
}, true},
|
||||
{Set{"y": ""}, &internalSelector{
|
||||
getRequirement("x", selection.DoesNotExist, nil, t),
|
||||
getRequirement("y", selection.Exists, nil, t),
|
||||
}, true},
|
||||
{Set{"y": ""}, &internalSelector{
|
||||
getRequirement("x", selection.NotIn, sets.NewString(""), t),
|
||||
getRequirement("y", selection.DoesNotExist, nil, t),
|
||||
}, false},
|
||||
{Set{"y": "baz"}, &internalSelector{
|
||||
getRequirement("x", selection.In, sets.NewString(""), t),
|
||||
}, false},
|
||||
{Set{"z": "2"}, &internalSelector{
|
||||
getRequirement("z", selection.GreaterThan, sets.NewString("1"), t),
|
||||
}, true},
|
||||
{Set{"z": "v2"}, &internalSelector{
|
||||
getRequirement("z", selection.GreaterThan, sets.NewString("1"), t),
|
||||
}, false},
|
||||
}
|
||||
for _, lsm := range labelSelectorMatchingTests {
|
||||
if match := lsm.Sel.Matches(lsm.Set); match != lsm.Match {
|
||||
t.Errorf("%+v.Matches(%#v) => %v, want %v", lsm.Sel, lsm.Set, match, lsm.Match)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetSelectorParser(t *testing.T) {
|
||||
setSelectorParserTests := []struct {
|
||||
In string
|
||||
Out Selector
|
||||
Match bool
|
||||
Valid bool
|
||||
}{
|
||||
{"", NewSelector(), true, true},
|
||||
{"\rx", internalSelector{
|
||||
getRequirement("x", selection.Exists, nil, t),
|
||||
}, true, true},
|
||||
{"this-is-a-dns.domain.com/key-with-dash", internalSelector{
|
||||
getRequirement("this-is-a-dns.domain.com/key-with-dash", selection.Exists, nil, t),
|
||||
}, true, true},
|
||||
{"this-is-another-dns.domain.com/key-with-dash in (so,what)", internalSelector{
|
||||
getRequirement("this-is-another-dns.domain.com/key-with-dash", selection.In, sets.NewString("so", "what"), t),
|
||||
}, true, true},
|
||||
{"0.1.2.domain/99 notin (10.10.100.1, tick.tack.clock)", internalSelector{
|
||||
getRequirement("0.1.2.domain/99", selection.NotIn, sets.NewString("10.10.100.1", "tick.tack.clock"), t),
|
||||
}, true, true},
|
||||
{"foo in (abc)", internalSelector{
|
||||
getRequirement("foo", selection.In, sets.NewString("abc"), t),
|
||||
}, true, true},
|
||||
{"x notin\n (abc)", internalSelector{
|
||||
getRequirement("x", selection.NotIn, sets.NewString("abc"), t),
|
||||
}, true, true},
|
||||
{"x notin \t (abc,def)", internalSelector{
|
||||
getRequirement("x", selection.NotIn, sets.NewString("abc", "def"), t),
|
||||
}, true, true},
|
||||
{"x in (abc,def)", internalSelector{
|
||||
getRequirement("x", selection.In, sets.NewString("abc", "def"), t),
|
||||
}, true, true},
|
||||
{"x in (abc,)", internalSelector{
|
||||
getRequirement("x", selection.In, sets.NewString("abc", ""), t),
|
||||
}, true, true},
|
||||
{"x in ()", internalSelector{
|
||||
getRequirement("x", selection.In, sets.NewString(""), t),
|
||||
}, true, true},
|
||||
{"x notin (abc,,def),bar,z in (),w", internalSelector{
|
||||
getRequirement("bar", selection.Exists, nil, t),
|
||||
getRequirement("w", selection.Exists, nil, t),
|
||||
getRequirement("x", selection.NotIn, sets.NewString("abc", "", "def"), t),
|
||||
getRequirement("z", selection.In, sets.NewString(""), t),
|
||||
}, true, true},
|
||||
{"x,y in (a)", internalSelector{
|
||||
getRequirement("y", selection.In, sets.NewString("a"), t),
|
||||
getRequirement("x", selection.Exists, nil, t),
|
||||
}, false, true},
|
||||
{"x=a", internalSelector{
|
||||
getRequirement("x", selection.Equals, sets.NewString("a"), t),
|
||||
}, true, true},
|
||||
{"x>1", internalSelector{
|
||||
getRequirement("x", selection.GreaterThan, sets.NewString("1"), t),
|
||||
}, true, true},
|
||||
{"x<7", internalSelector{
|
||||
getRequirement("x", selection.LessThan, sets.NewString("7"), t),
|
||||
}, true, true},
|
||||
{"x=a,y!=b", internalSelector{
|
||||
getRequirement("x", selection.Equals, sets.NewString("a"), t),
|
||||
getRequirement("y", selection.NotEquals, sets.NewString("b"), t),
|
||||
}, true, true},
|
||||
{"x=a,y!=b,z in (h,i,j)", internalSelector{
|
||||
getRequirement("x", selection.Equals, sets.NewString("a"), t),
|
||||
getRequirement("y", selection.NotEquals, sets.NewString("b"), t),
|
||||
getRequirement("z", selection.In, sets.NewString("h", "i", "j"), t),
|
||||
}, true, true},
|
||||
{"x=a||y=b", internalSelector{}, false, false},
|
||||
{"x,,y", nil, true, false},
|
||||
{",x,y", nil, true, false},
|
||||
{"x nott in (y)", nil, true, false},
|
||||
{"x notin ( )", internalSelector{
|
||||
getRequirement("x", selection.NotIn, sets.NewString(""), t),
|
||||
}, true, true},
|
||||
{"x notin (, a)", internalSelector{
|
||||
getRequirement("x", selection.NotIn, sets.NewString("", "a"), t),
|
||||
}, true, true},
|
||||
{"a in (xyz),", nil, true, false},
|
||||
{"a in (xyz)b notin ()", nil, true, false},
|
||||
{"a ", internalSelector{
|
||||
getRequirement("a", selection.Exists, nil, t),
|
||||
}, true, true},
|
||||
{"a in (x,y,notin, z,in)", internalSelector{
|
||||
getRequirement("a", selection.In, sets.NewString("in", "notin", "x", "y", "z"), t),
|
||||
}, true, true}, // operator 'in' inside list of identifiers
|
||||
{"a in (xyz abc)", nil, false, false}, // no comma
|
||||
{"a notin(", nil, true, false}, // bad formed
|
||||
{"a (", nil, false, false}, // cpar
|
||||
{"(", nil, false, false}, // opar
|
||||
}
|
||||
|
||||
for _, ssp := range setSelectorParserTests {
|
||||
if sel, err := Parse(ssp.In); err != nil && ssp.Valid {
|
||||
t.Errorf("Parse(%s) => %v expected no error", ssp.In, err)
|
||||
} else if err == nil && !ssp.Valid {
|
||||
t.Errorf("Parse(%s) => %+v expected error", ssp.In, sel)
|
||||
} else if ssp.Match && !reflect.DeepEqual(sel, ssp.Out) {
|
||||
t.Errorf("Parse(%s) => parse output '%#v' doesn't match '%#v' expected match", ssp.In, sel, ssp.Out)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func getRequirement(key string, op selection.Operator, vals sets.String, t *testing.T) Requirement {
|
||||
req, err := NewRequirement(key, op, vals.List())
|
||||
if err != nil {
|
||||
t.Errorf("NewRequirement(%v, %v, %v) resulted in error:%v", key, op, vals, err)
|
||||
return Requirement{}
|
||||
}
|
||||
return *req
|
||||
}
|
||||
|
||||
func TestAdd(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
sel Selector
|
||||
key string
|
||||
operator selection.Operator
|
||||
values []string
|
||||
refSelector Selector
|
||||
}{
|
||||
{
|
||||
"keyInOperator",
|
||||
internalSelector{},
|
||||
"key",
|
||||
selection.In,
|
||||
[]string{"value"},
|
||||
internalSelector{Requirement{"key", selection.In, []string{"value"}}},
|
||||
},
|
||||
{
|
||||
"keyEqualsOperator",
|
||||
internalSelector{Requirement{"key", selection.In, []string{"value"}}},
|
||||
"key2",
|
||||
selection.Equals,
|
||||
[]string{"value2"},
|
||||
internalSelector{
|
||||
Requirement{"key", selection.In, []string{"value"}},
|
||||
Requirement{"key2", selection.Equals, []string{"value2"}},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, ts := range testCases {
|
||||
req, err := NewRequirement(ts.key, ts.operator, ts.values)
|
||||
if err != nil {
|
||||
t.Errorf("%s - Unable to create labels.Requirement", ts.name)
|
||||
}
|
||||
ts.sel = ts.sel.Add(*req)
|
||||
if !reflect.DeepEqual(ts.sel, ts.refSelector) {
|
||||
t.Errorf("%s - Expected %v found %v", ts.name, ts.refSelector, ts.sel)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSafeSort(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
in []string
|
||||
inCopy []string
|
||||
want []string
|
||||
}{
|
||||
{
|
||||
name: "nil strings",
|
||||
in: nil,
|
||||
inCopy: nil,
|
||||
want: nil,
|
||||
},
|
||||
{
|
||||
name: "ordered strings",
|
||||
in: []string{"bar", "foo"},
|
||||
inCopy: []string{"bar", "foo"},
|
||||
want: []string{"bar", "foo"},
|
||||
},
|
||||
{
|
||||
name: "unordered strings",
|
||||
in: []string{"foo", "bar"},
|
||||
inCopy: []string{"foo", "bar"},
|
||||
want: []string{"bar", "foo"},
|
||||
},
|
||||
{
|
||||
name: "duplicated strings",
|
||||
in: []string{"foo", "bar", "foo", "bar"},
|
||||
inCopy: []string{"foo", "bar", "foo", "bar"},
|
||||
want: []string{"bar", "bar", "foo", "foo"},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := safeSort(tt.in); !reflect.DeepEqual(got, tt.want) {
|
||||
t.Errorf("safeSort() = %v, want %v", got, tt.want)
|
||||
}
|
||||
if !reflect.DeepEqual(tt.in, tt.inCopy) {
|
||||
t.Errorf("after safeSort(), input = %v, want %v", tt.in, tt.inCopy)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
115
vendor/k8s.io/apimachinery/pkg/runtime/conversion_test.go
generated
vendored
115
vendor/k8s.io/apimachinery/pkg/runtime/conversion_test.go
generated
vendored
@ -1,115 +0,0 @@
|
||||
/*
|
||||
Copyright 2014 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 runtime_test
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
"k8s.io/apimachinery/pkg/runtime/schema"
|
||||
runtimetesting "k8s.io/apimachinery/pkg/runtime/testing"
|
||||
)
|
||||
|
||||
func TestStringMapConversion(t *testing.T) {
|
||||
internalGV := schema.GroupVersion{Group: "test.group", Version: runtime.APIVersionInternal}
|
||||
externalGV := schema.GroupVersion{Group: "test.group", Version: "external"}
|
||||
|
||||
scheme := runtime.NewScheme()
|
||||
scheme.Log(t)
|
||||
scheme.AddKnownTypeWithName(internalGV.WithKind("Complex"), &runtimetesting.InternalComplex{})
|
||||
scheme.AddKnownTypeWithName(externalGV.WithKind("Complex"), &runtimetesting.ExternalComplex{})
|
||||
|
||||
testCases := map[string]struct {
|
||||
input map[string][]string
|
||||
errFn func(error) bool
|
||||
expected runtime.Object
|
||||
}{
|
||||
"ignores omitempty": {
|
||||
input: map[string][]string{
|
||||
"String": {"not_used"},
|
||||
"string": {"value"},
|
||||
"int": {"1"},
|
||||
"Integer64": {"2"},
|
||||
},
|
||||
expected: &runtimetesting.ExternalComplex{String: "value", Integer: 1},
|
||||
},
|
||||
"returns error on bad int": {
|
||||
input: map[string][]string{
|
||||
"int": {"a"},
|
||||
},
|
||||
errFn: func(err error) bool { return err != nil },
|
||||
expected: &runtimetesting.ExternalComplex{},
|
||||
},
|
||||
"parses int64": {
|
||||
input: map[string][]string{
|
||||
"Int64": {"-1"},
|
||||
},
|
||||
expected: &runtimetesting.ExternalComplex{Int64: -1},
|
||||
},
|
||||
"returns error on bad int64": {
|
||||
input: map[string][]string{
|
||||
"Int64": {"a"},
|
||||
},
|
||||
errFn: func(err error) bool { return err != nil },
|
||||
expected: &runtimetesting.ExternalComplex{},
|
||||
},
|
||||
"parses boolean true": {
|
||||
input: map[string][]string{
|
||||
"bool": {"true"},
|
||||
},
|
||||
expected: &runtimetesting.ExternalComplex{Bool: true},
|
||||
},
|
||||
"parses boolean any value": {
|
||||
input: map[string][]string{
|
||||
"bool": {"foo"},
|
||||
},
|
||||
expected: &runtimetesting.ExternalComplex{Bool: true},
|
||||
},
|
||||
"parses boolean false": {
|
||||
input: map[string][]string{
|
||||
"bool": {"false"},
|
||||
},
|
||||
expected: &runtimetesting.ExternalComplex{Bool: false},
|
||||
},
|
||||
"parses boolean empty value": {
|
||||
input: map[string][]string{
|
||||
"bool": {""},
|
||||
},
|
||||
expected: &runtimetesting.ExternalComplex{Bool: true},
|
||||
},
|
||||
"parses boolean no value": {
|
||||
input: map[string][]string{
|
||||
"bool": {},
|
||||
},
|
||||
expected: &runtimetesting.ExternalComplex{Bool: false},
|
||||
},
|
||||
}
|
||||
|
||||
for k, tc := range testCases {
|
||||
out := &runtimetesting.ExternalComplex{}
|
||||
if err := scheme.Convert(&tc.input, out, nil); (tc.errFn == nil && err != nil) || (tc.errFn != nil && !tc.errFn(err)) {
|
||||
t.Errorf("%s: unexpected error: %v", k, err)
|
||||
continue
|
||||
} else if err != nil {
|
||||
continue
|
||||
}
|
||||
if !reflect.DeepEqual(out, tc.expected) {
|
||||
t.Errorf("%s: unexpected output: %#v", k, out)
|
||||
}
|
||||
}
|
||||
}
|
597
vendor/k8s.io/apimachinery/pkg/runtime/converter_test.go
generated
vendored
597
vendor/k8s.io/apimachinery/pkg/runtime/converter_test.go
generated
vendored
@ -1,597 +0,0 @@
|
||||
/*
|
||||
Copyright 2015 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.
|
||||
*/
|
||||
|
||||
// These tests are in a separate package to break cyclic dependency in tests.
|
||||
// Unstructured type depends on unstructured converter package but we want to test how the converter handles
|
||||
// the Unstructured type so we need to import both.
|
||||
|
||||
package runtime_test
|
||||
|
||||
import (
|
||||
encodingjson "encoding/json"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
||||
"k8s.io/apimachinery/pkg/conversion"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
"k8s.io/apimachinery/pkg/util/diff"
|
||||
"k8s.io/apimachinery/pkg/util/json"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
var simpleEquality = conversion.EqualitiesOrDie(
|
||||
func(a, b time.Time) bool {
|
||||
return a.UTC() == b.UTC()
|
||||
},
|
||||
)
|
||||
|
||||
// Definte a number of test types.
|
||||
type A struct {
|
||||
A int `json:"aa,omitempty"`
|
||||
B string `json:"ab,omitempty"`
|
||||
C bool `json:"ac,omitempty"`
|
||||
}
|
||||
|
||||
type B struct {
|
||||
A A `json:"ba"`
|
||||
B string `json:"bb"`
|
||||
C map[string]string `json:"bc"`
|
||||
D []string `json:"bd"`
|
||||
}
|
||||
|
||||
type C struct {
|
||||
A []A `json:"ca"`
|
||||
B `json:",inline"`
|
||||
C string `json:"cc"`
|
||||
D *int64 `json:"cd"`
|
||||
E map[string]int `json:"ce"`
|
||||
F []bool `json:"cf"`
|
||||
G []int `json:"cg"`
|
||||
H float32 `json:"ch"`
|
||||
I []interface{} `json:"ci"`
|
||||
}
|
||||
|
||||
type D struct {
|
||||
A []interface{} `json:"da"`
|
||||
}
|
||||
|
||||
type E struct {
|
||||
A interface{} `json:"ea"`
|
||||
}
|
||||
|
||||
type F struct {
|
||||
A string `json:"fa"`
|
||||
B map[string]string `json:"fb"`
|
||||
C []A `json:"fc"`
|
||||
D int `json:"fd"`
|
||||
E float32 `json:"fe"`
|
||||
F []string `json:"ff"`
|
||||
G []int `json:"fg"`
|
||||
H []bool `json:"fh"`
|
||||
I []float32 `json:"fi"`
|
||||
}
|
||||
|
||||
type G struct {
|
||||
CustomValue1 CustomValue `json:"customValue1"`
|
||||
CustomValue2 *CustomValue `json:"customValue2"`
|
||||
CustomPointer1 CustomPointer `json:"customPointer1"`
|
||||
CustomPointer2 *CustomPointer `json:"customPointer2"`
|
||||
}
|
||||
|
||||
type CustomValue struct {
|
||||
data []byte
|
||||
}
|
||||
|
||||
// MarshalJSON has a value receiver on this type.
|
||||
func (c CustomValue) MarshalJSON() ([]byte, error) {
|
||||
return c.data, nil
|
||||
}
|
||||
|
||||
type CustomPointer struct {
|
||||
data []byte
|
||||
}
|
||||
|
||||
// MarshalJSON has a pointer receiver on this type.
|
||||
func (c *CustomPointer) MarshalJSON() ([]byte, error) {
|
||||
return c.data, nil
|
||||
}
|
||||
|
||||
func doRoundTrip(t *testing.T, item interface{}) {
|
||||
data, err := json.Marshal(item)
|
||||
if err != nil {
|
||||
t.Errorf("Error when marshaling object: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
unstr := make(map[string]interface{})
|
||||
err = json.Unmarshal(data, &unstr)
|
||||
if err != nil {
|
||||
t.Errorf("Error when unmarshaling to unstructured: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
data, err = json.Marshal(unstr)
|
||||
if err != nil {
|
||||
t.Errorf("Error when marshaling unstructured: %v", err)
|
||||
return
|
||||
}
|
||||
unmarshalledObj := reflect.New(reflect.TypeOf(item).Elem()).Interface()
|
||||
err = json.Unmarshal(data, unmarshalledObj)
|
||||
if err != nil {
|
||||
t.Errorf("Error when unmarshaling to object: %v", err)
|
||||
return
|
||||
}
|
||||
if !reflect.DeepEqual(item, unmarshalledObj) {
|
||||
t.Errorf("Object changed during JSON operations, diff: %v", diff.ObjectReflectDiff(item, unmarshalledObj))
|
||||
return
|
||||
}
|
||||
|
||||
// TODO: should be using mismatch detection but fails due to another error
|
||||
newUnstr, err := runtime.DefaultUnstructuredConverter.ToUnstructured(item)
|
||||
if err != nil {
|
||||
t.Errorf("ToUnstructured failed: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
newObj := reflect.New(reflect.TypeOf(item).Elem()).Interface()
|
||||
err = runtime.NewTestUnstructuredConverter(simpleEquality).FromUnstructured(newUnstr, newObj)
|
||||
if err != nil {
|
||||
t.Errorf("FromUnstructured failed: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
if !reflect.DeepEqual(item, newObj) {
|
||||
t.Errorf("Object changed, diff: %v", diff.ObjectReflectDiff(item, newObj))
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoundTrip(t *testing.T) {
|
||||
intVal := int64(42)
|
||||
testCases := []struct {
|
||||
obj interface{}
|
||||
}{
|
||||
{
|
||||
obj: &unstructured.UnstructuredList{
|
||||
Object: map[string]interface{}{
|
||||
"kind": "List",
|
||||
},
|
||||
// Not testing a list with nil Items because items is a non-optional field and hence
|
||||
// is always marshaled into an empty array which is not equal to nil when unmarshalled and will fail.
|
||||
// That is expected.
|
||||
Items: []unstructured.Unstructured{},
|
||||
},
|
||||
},
|
||||
{
|
||||
obj: &unstructured.UnstructuredList{
|
||||
Object: map[string]interface{}{
|
||||
"kind": "List",
|
||||
},
|
||||
Items: []unstructured.Unstructured{
|
||||
{
|
||||
Object: map[string]interface{}{
|
||||
"kind": "Pod",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
obj: &unstructured.Unstructured{
|
||||
Object: map[string]interface{}{
|
||||
"kind": "Pod",
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
obj: &unstructured.Unstructured{
|
||||
Object: map[string]interface{}{
|
||||
"apiVersion": "v1",
|
||||
"kind": "Foo",
|
||||
"metadata": map[string]interface{}{
|
||||
"name": "foo1",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
// This (among others) tests nil map, slice and pointer.
|
||||
obj: &C{
|
||||
C: "ccc",
|
||||
},
|
||||
},
|
||||
{
|
||||
// This (among others) tests empty map and slice.
|
||||
obj: &C{
|
||||
A: []A{},
|
||||
C: "ccc",
|
||||
E: map[string]int{},
|
||||
I: []interface{}{},
|
||||
},
|
||||
},
|
||||
{
|
||||
obj: &C{
|
||||
A: []A{
|
||||
{
|
||||
A: 1,
|
||||
B: "11",
|
||||
C: true,
|
||||
},
|
||||
{
|
||||
A: 2,
|
||||
B: "22",
|
||||
C: false,
|
||||
},
|
||||
},
|
||||
B: B{
|
||||
A: A{
|
||||
A: 3,
|
||||
B: "33",
|
||||
},
|
||||
B: "bbb",
|
||||
C: map[string]string{
|
||||
"k1": "v1",
|
||||
"k2": "v2",
|
||||
},
|
||||
D: []string{"s1", "s2"},
|
||||
},
|
||||
C: "ccc",
|
||||
D: &intVal,
|
||||
E: map[string]int{
|
||||
"k1": 1,
|
||||
"k2": 2,
|
||||
},
|
||||
F: []bool{true, false, false},
|
||||
G: []int{1, 2, 5},
|
||||
H: 3.3,
|
||||
I: []interface{}{nil, nil, nil},
|
||||
},
|
||||
},
|
||||
{
|
||||
// Test slice of interface{} with empty slices.
|
||||
obj: &D{
|
||||
A: []interface{}{[]interface{}{}, []interface{}{}},
|
||||
},
|
||||
},
|
||||
{
|
||||
// Test slice of interface{} with different values.
|
||||
obj: &D{
|
||||
A: []interface{}{3.0, "3.0", nil},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for i := range testCases {
|
||||
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
|
||||
doRoundTrip(t, testCases[i].obj)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Verifies that:
|
||||
// 1) serialized json -> object
|
||||
// 2) serialized json -> map[string]interface{} -> object
|
||||
// produces the same object.
|
||||
func doUnrecognized(t *testing.T, jsonData string, item interface{}, expectedErr error) {
|
||||
unmarshalledObj := reflect.New(reflect.TypeOf(item).Elem()).Interface()
|
||||
err := json.Unmarshal([]byte(jsonData), unmarshalledObj)
|
||||
if (err != nil) != (expectedErr != nil) {
|
||||
t.Errorf("Unexpected error when unmarshaling to object: %v, expected: %v", err, expectedErr)
|
||||
return
|
||||
}
|
||||
|
||||
unstr := make(map[string]interface{})
|
||||
err = json.Unmarshal([]byte(jsonData), &unstr)
|
||||
if err != nil {
|
||||
t.Errorf("Error when unmarshaling to unstructured: %v", err)
|
||||
return
|
||||
}
|
||||
newObj := reflect.New(reflect.TypeOf(item).Elem()).Interface()
|
||||
err = runtime.NewTestUnstructuredConverter(simpleEquality).FromUnstructured(unstr, newObj)
|
||||
if (err != nil) != (expectedErr != nil) {
|
||||
t.Errorf("Unexpected error in FromUnstructured: %v, expected: %v", err, expectedErr)
|
||||
}
|
||||
|
||||
if expectedErr == nil && !reflect.DeepEqual(unmarshalledObj, newObj) {
|
||||
t.Errorf("Object changed, diff: %v", diff.ObjectReflectDiff(unmarshalledObj, newObj))
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnrecognized(t *testing.T) {
|
||||
testCases := []struct {
|
||||
data string
|
||||
obj interface{}
|
||||
err error
|
||||
}{
|
||||
{
|
||||
data: "{\"da\":[3.0,\"3.0\",null]}",
|
||||
obj: &D{},
|
||||
},
|
||||
{
|
||||
data: "{\"ea\":[3.0,\"3.0\",null]}",
|
||||
obj: &E{},
|
||||
},
|
||||
{
|
||||
data: "{\"ea\":[null,null,null]}",
|
||||
obj: &E{},
|
||||
},
|
||||
{
|
||||
data: "{\"ea\":[[],[null]]}",
|
||||
obj: &E{},
|
||||
},
|
||||
{
|
||||
data: "{\"ea\":{\"a\":[],\"b\":null}}",
|
||||
obj: &E{},
|
||||
},
|
||||
{
|
||||
data: "{\"fa\":\"fa\",\"fb\":{\"a\":\"a\"}}",
|
||||
obj: &F{},
|
||||
},
|
||||
{
|
||||
data: "{\"fa\":\"fa\",\"fb\":{\"a\":null}}",
|
||||
obj: &F{},
|
||||
},
|
||||
{
|
||||
data: "{\"fc\":[null]}",
|
||||
obj: &F{},
|
||||
},
|
||||
{
|
||||
data: "{\"fc\":[{\"aa\":123,\"ab\":\"bbb\"}]}",
|
||||
obj: &F{},
|
||||
},
|
||||
{
|
||||
// Only unknown fields
|
||||
data: "{\"fx\":[{\"aa\":123,\"ab\":\"bbb\"}],\"fz\":123}",
|
||||
obj: &F{},
|
||||
},
|
||||
{
|
||||
data: "{\"fc\":[{\"aa\":\"aaa\",\"ab\":\"bbb\"}]}",
|
||||
obj: &F{},
|
||||
err: fmt.Errorf("json: cannot unmarshal string into Go value of type int"),
|
||||
},
|
||||
{
|
||||
data: "{\"fd\":123,\"fe\":3.5}",
|
||||
obj: &F{},
|
||||
},
|
||||
{
|
||||
data: "{\"ff\":[\"abc\"],\"fg\":[123],\"fh\":[true,false]}",
|
||||
obj: &F{},
|
||||
},
|
||||
{
|
||||
// Invalid string data
|
||||
data: "{\"fa\":123}",
|
||||
obj: &F{},
|
||||
err: fmt.Errorf("json: cannot unmarshal number into Go value of type string"),
|
||||
},
|
||||
{
|
||||
// Invalid string data
|
||||
data: "{\"fa\":13.5}",
|
||||
obj: &F{},
|
||||
err: fmt.Errorf("json: cannot unmarshal number into Go value of type string"),
|
||||
},
|
||||
{
|
||||
// Invalid string data
|
||||
data: "{\"fa\":true}",
|
||||
obj: &F{},
|
||||
err: fmt.Errorf("json: cannot unmarshal bool into Go value of type string"),
|
||||
},
|
||||
{
|
||||
// Invalid []string data
|
||||
data: "{\"ff\":123}",
|
||||
obj: &F{},
|
||||
err: fmt.Errorf("json: cannot unmarshal number into Go value of type []string"),
|
||||
},
|
||||
{
|
||||
// Invalid []string data
|
||||
data: "{\"ff\":3.5}",
|
||||
obj: &F{},
|
||||
err: fmt.Errorf("json: cannot unmarshal number into Go value of type []string"),
|
||||
},
|
||||
{
|
||||
// Invalid []string data
|
||||
data: "{\"ff\":[123,345]}",
|
||||
obj: &F{},
|
||||
err: fmt.Errorf("json: cannot unmarshal number into Go value of type string"),
|
||||
},
|
||||
{
|
||||
// Invalid []int data
|
||||
data: "{\"fg\":123}",
|
||||
obj: &F{},
|
||||
err: fmt.Errorf("json: cannot unmarshal number into Go value of type []int"),
|
||||
},
|
||||
{
|
||||
// Invalid []int data
|
||||
data: "{\"fg\":\"abc\"}",
|
||||
obj: &F{},
|
||||
err: fmt.Errorf("json: cannot unmarshal string into Go value of type []int"),
|
||||
},
|
||||
{
|
||||
// Invalid []int data
|
||||
data: "{\"fg\":[\"abc\"]}",
|
||||
obj: &F{},
|
||||
err: fmt.Errorf("json: cannot unmarshal string into Go value of type int"),
|
||||
},
|
||||
{
|
||||
// Invalid []int data
|
||||
data: "{\"fg\":[3.5]}",
|
||||
obj: &F{},
|
||||
err: fmt.Errorf("json: cannot unmarshal number 3.5 into Go value of type int"),
|
||||
},
|
||||
{
|
||||
// Invalid []int data
|
||||
data: "{\"fg\":[true,false]}",
|
||||
obj: &F{},
|
||||
err: fmt.Errorf("json: cannot unmarshal number 3.5 into Go value of type int"),
|
||||
},
|
||||
{
|
||||
// Invalid []bool data
|
||||
data: "{\"fh\":123}",
|
||||
obj: &F{},
|
||||
err: fmt.Errorf("json: cannot unmarshal number into Go value of type []bool"),
|
||||
},
|
||||
{
|
||||
// Invalid []bool data
|
||||
data: "{\"fh\":\"abc\"}",
|
||||
obj: &F{},
|
||||
err: fmt.Errorf("json: cannot unmarshal string into Go value of type []bool"),
|
||||
},
|
||||
{
|
||||
// Invalid []bool data
|
||||
data: "{\"fh\":[\"abc\"]}",
|
||||
obj: &F{},
|
||||
err: fmt.Errorf("json: cannot unmarshal string into Go value of type bool"),
|
||||
},
|
||||
{
|
||||
// Invalid []bool data
|
||||
data: "{\"fh\":[3.5]}",
|
||||
obj: &F{},
|
||||
err: fmt.Errorf("json: cannot unmarshal number into Go value of type bool"),
|
||||
},
|
||||
{
|
||||
// Invalid []bool data
|
||||
data: "{\"fh\":[123]}",
|
||||
obj: &F{},
|
||||
err: fmt.Errorf("json: cannot unmarshal number into Go value of type bool"),
|
||||
},
|
||||
{
|
||||
// Invalid []float data
|
||||
data: "{\"fi\":123}",
|
||||
obj: &F{},
|
||||
err: fmt.Errorf("json: cannot unmarshal number into Go value of type []float32"),
|
||||
},
|
||||
{
|
||||
// Invalid []float data
|
||||
data: "{\"fi\":\"abc\"}",
|
||||
obj: &F{},
|
||||
err: fmt.Errorf("json: cannot unmarshal string into Go value of type []float32"),
|
||||
},
|
||||
{
|
||||
// Invalid []float data
|
||||
data: "{\"fi\":[\"abc\"]}",
|
||||
obj: &F{},
|
||||
err: fmt.Errorf("json: cannot unmarshal string into Go value of type float32"),
|
||||
},
|
||||
{
|
||||
// Invalid []float data
|
||||
data: "{\"fi\":[true]}",
|
||||
obj: &F{},
|
||||
err: fmt.Errorf("json: cannot unmarshal bool into Go value of type float32"),
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.data, func(t *testing.T) {
|
||||
doUnrecognized(t, tc.data, tc.obj, tc.err)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeepCopyJSON(t *testing.T) {
|
||||
src := map[string]interface{}{
|
||||
"a": nil,
|
||||
"b": int64(123),
|
||||
"c": map[string]interface{}{
|
||||
"a": "b",
|
||||
},
|
||||
"d": []interface{}{
|
||||
int64(1), int64(2),
|
||||
},
|
||||
"e": "estr",
|
||||
"f": true,
|
||||
"g": encodingjson.Number("123"),
|
||||
}
|
||||
deepCopy := runtime.DeepCopyJSON(src)
|
||||
assert.Equal(t, src, deepCopy)
|
||||
}
|
||||
|
||||
func TestFloatIntConversion(t *testing.T) {
|
||||
unstr := map[string]interface{}{"fd": float64(3)}
|
||||
|
||||
var obj F
|
||||
if err := runtime.NewTestUnstructuredConverter(simpleEquality).FromUnstructured(unstr, &obj); err != nil {
|
||||
t.Errorf("Unexpected error in FromUnstructured: %v", err)
|
||||
}
|
||||
|
||||
data, err := json.Marshal(unstr)
|
||||
if err != nil {
|
||||
t.Fatalf("Error when marshaling unstructured: %v", err)
|
||||
}
|
||||
var unmarshalled F
|
||||
if err := json.Unmarshal(data, &unmarshalled); err != nil {
|
||||
t.Fatalf("Error when unmarshaling to object: %v", err)
|
||||
}
|
||||
|
||||
if !reflect.DeepEqual(obj, unmarshalled) {
|
||||
t.Errorf("Incorrect conversion, diff: %v", diff.ObjectReflectDiff(obj, unmarshalled))
|
||||
}
|
||||
}
|
||||
|
||||
func TestCustomToUnstructured(t *testing.T) {
|
||||
testcases := []struct {
|
||||
Data string
|
||||
Expected interface{}
|
||||
}{
|
||||
{Data: `null`, Expected: nil},
|
||||
{Data: `true`, Expected: true},
|
||||
{Data: `false`, Expected: false},
|
||||
{Data: `[]`, Expected: []interface{}{}},
|
||||
{Data: `[1]`, Expected: []interface{}{int64(1)}},
|
||||
{Data: `{}`, Expected: map[string]interface{}{}},
|
||||
{Data: `{"a":1}`, Expected: map[string]interface{}{"a": int64(1)}},
|
||||
{Data: `0`, Expected: int64(0)},
|
||||
{Data: `0.0`, Expected: float64(0)},
|
||||
}
|
||||
|
||||
for _, tc := range testcases {
|
||||
tc := tc
|
||||
t.Run(tc.Data, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
result, err := runtime.NewTestUnstructuredConverter(simpleEquality).ToUnstructured(&G{
|
||||
CustomValue1: CustomValue{data: []byte(tc.Data)},
|
||||
CustomValue2: &CustomValue{data: []byte(tc.Data)},
|
||||
CustomPointer1: CustomPointer{data: []byte(tc.Data)},
|
||||
CustomPointer2: &CustomPointer{data: []byte(tc.Data)},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
for field, fieldResult := range result {
|
||||
assert.Equal(t, tc.Expected, fieldResult, field)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCustomToUnstructuredTopLevel(t *testing.T) {
|
||||
// Only objects are supported at the top level
|
||||
topLevelCases := []interface{}{
|
||||
&CustomValue{data: []byte(`{"a":1}`)},
|
||||
&CustomPointer{data: []byte(`{"a":1}`)},
|
||||
}
|
||||
expected := map[string]interface{}{"a": int64(1)}
|
||||
for i, obj := range topLevelCases {
|
||||
obj := obj
|
||||
t.Run(strconv.Itoa(i), func(t *testing.T) {
|
||||
t.Parallel()
|
||||
result, err := runtime.NewTestUnstructuredConverter(simpleEquality).ToUnstructured(obj)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, expected, result)
|
||||
})
|
||||
}
|
||||
}
|
256
vendor/k8s.io/apimachinery/pkg/runtime/embedded_test.go
generated
vendored
256
vendor/k8s.io/apimachinery/pkg/runtime/embedded_test.go
generated
vendored
@ -1,256 +0,0 @@
|
||||
/*
|
||||
Copyright 2014 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 runtime_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"k8s.io/apimachinery/pkg/api/meta"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
"k8s.io/apimachinery/pkg/runtime/schema"
|
||||
"k8s.io/apimachinery/pkg/runtime/serializer"
|
||||
runtimetesting "k8s.io/apimachinery/pkg/runtime/testing"
|
||||
"k8s.io/apimachinery/pkg/util/diff"
|
||||
)
|
||||
|
||||
func TestDecodeEmptyRawExtensionAsObject(t *testing.T) {
|
||||
internalGV := schema.GroupVersion{Group: "test.group", Version: runtime.APIVersionInternal}
|
||||
externalGV := schema.GroupVersion{Group: "test.group", Version: "v1test"}
|
||||
externalGVK := externalGV.WithKind("ObjectTest")
|
||||
|
||||
s := runtime.NewScheme()
|
||||
s.AddKnownTypes(internalGV, &runtimetesting.ObjectTest{})
|
||||
s.AddKnownTypeWithName(externalGVK, &runtimetesting.ObjectTestExternal{})
|
||||
|
||||
codec := serializer.NewCodecFactory(s).LegacyCodec(externalGV)
|
||||
|
||||
obj, gvk, err := codec.Decode([]byte(`{"kind":"`+externalGVK.Kind+`","apiVersion":"`+externalGV.String()+`","items":[{}]}`), nil, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
test := obj.(*runtimetesting.ObjectTest)
|
||||
if unk, ok := test.Items[0].(*runtime.Unknown); !ok || unk.Kind != "" || unk.APIVersion != "" || string(unk.Raw) != "{}" || unk.ContentType != runtime.ContentTypeJSON {
|
||||
t.Fatalf("unexpected object: %#v", test.Items[0])
|
||||
}
|
||||
if *gvk != externalGVK {
|
||||
t.Fatalf("unexpected kind: %#v", gvk)
|
||||
}
|
||||
|
||||
obj, gvk, err = codec.Decode([]byte(`{"kind":"`+externalGVK.Kind+`","apiVersion":"`+externalGV.String()+`","items":[{"kind":"Other","apiVersion":"v1"}]}`), nil, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
test = obj.(*runtimetesting.ObjectTest)
|
||||
if unk, ok := test.Items[0].(*runtime.Unknown); !ok || unk.Kind != "" || unk.APIVersion != "" || string(unk.Raw) != `{"kind":"Other","apiVersion":"v1"}` || unk.ContentType != runtime.ContentTypeJSON {
|
||||
t.Fatalf("unexpected object: %#v", test.Items[0])
|
||||
}
|
||||
if *gvk != externalGVK {
|
||||
t.Fatalf("unexpected kind: %#v", gvk)
|
||||
}
|
||||
}
|
||||
|
||||
func TestArrayOfRuntimeObject(t *testing.T) {
|
||||
internalGV := schema.GroupVersion{Group: "test.group", Version: runtime.APIVersionInternal}
|
||||
externalGV := schema.GroupVersion{Group: "test.group", Version: "v1test"}
|
||||
|
||||
s := runtime.NewScheme()
|
||||
s.AddKnownTypes(internalGV, &runtimetesting.EmbeddedTest{})
|
||||
s.AddKnownTypeWithName(externalGV.WithKind("EmbeddedTest"), &runtimetesting.EmbeddedTestExternal{})
|
||||
s.AddKnownTypes(internalGV, &runtimetesting.ObjectTest{})
|
||||
s.AddKnownTypeWithName(externalGV.WithKind("ObjectTest"), &runtimetesting.ObjectTestExternal{})
|
||||
|
||||
codec := serializer.NewCodecFactory(s).LegacyCodec(externalGV)
|
||||
|
||||
innerItems := []runtime.Object{
|
||||
&runtimetesting.EmbeddedTest{ID: "baz"},
|
||||
}
|
||||
items := []runtime.Object{
|
||||
&runtimetesting.EmbeddedTest{ID: "foo"},
|
||||
&runtimetesting.EmbeddedTest{ID: "bar"},
|
||||
// TODO: until YAML is removed, this JSON must be in ascending key order to ensure consistent roundtrip serialization
|
||||
&runtime.Unknown{
|
||||
Raw: []byte(`{"apiVersion":"unknown.group/unknown","foo":"bar","kind":"OtherTest"}`),
|
||||
ContentType: runtime.ContentTypeJSON,
|
||||
},
|
||||
&runtimetesting.ObjectTest{
|
||||
Items: runtime.NewEncodableList(codec, innerItems),
|
||||
},
|
||||
}
|
||||
internal := &runtimetesting.ObjectTest{
|
||||
Items: runtime.NewEncodableList(codec, items),
|
||||
}
|
||||
wire, err := runtime.Encode(codec, internal)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
t.Logf("Wire format is:\n%s\n", string(wire))
|
||||
|
||||
obj := &runtimetesting.ObjectTestExternal{}
|
||||
if err := json.Unmarshal(wire, obj); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
t.Logf("exact wire is: %s", string(obj.Items[0].Raw))
|
||||
|
||||
items[3] = &runtimetesting.ObjectTest{Items: innerItems}
|
||||
internal.Items = items
|
||||
|
||||
decoded, err := runtime.Decode(codec, wire)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
list, err := meta.ExtractList(decoded)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if errs := runtime.DecodeList(list, codec); len(errs) > 0 {
|
||||
t.Fatalf("unexpected error: %v", errs)
|
||||
}
|
||||
|
||||
list2, err := meta.ExtractList(list[3])
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if errs := runtime.DecodeList(list2, codec); len(errs) > 0 {
|
||||
t.Fatalf("unexpected error: %v", errs)
|
||||
}
|
||||
if err := meta.SetList(list[3], list2); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
// we want DecodeList to set type meta if possible, even on runtime.Unknown objects
|
||||
internal.Items[2].(*runtime.Unknown).TypeMeta = runtime.TypeMeta{Kind: "OtherTest", APIVersion: "unknown.group/unknown"}
|
||||
if e, a := internal.Items, list; !reflect.DeepEqual(e, a) {
|
||||
t.Errorf("mismatched decoded: %s", diff.ObjectGoPrintSideBySide(e, a))
|
||||
}
|
||||
}
|
||||
|
||||
func TestNestedObject(t *testing.T) {
|
||||
internalGV := schema.GroupVersion{Group: "test.group", Version: runtime.APIVersionInternal}
|
||||
externalGV := schema.GroupVersion{Group: "test.group", Version: "v1test"}
|
||||
embeddedTestExternalGVK := externalGV.WithKind("EmbeddedTest")
|
||||
|
||||
s := runtime.NewScheme()
|
||||
s.AddKnownTypes(internalGV, &runtimetesting.EmbeddedTest{})
|
||||
s.AddKnownTypeWithName(embeddedTestExternalGVK, &runtimetesting.EmbeddedTestExternal{})
|
||||
|
||||
codec := serializer.NewCodecFactory(s).LegacyCodec(externalGV)
|
||||
|
||||
inner := &runtimetesting.EmbeddedTest{
|
||||
ID: "inner",
|
||||
}
|
||||
outer := &runtimetesting.EmbeddedTest{
|
||||
ID: "outer",
|
||||
Object: runtime.NewEncodable(codec, inner),
|
||||
}
|
||||
|
||||
wire, err := runtime.Encode(codec, outer)
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected encode error '%v'", err)
|
||||
}
|
||||
|
||||
t.Logf("Wire format is:\n%v\n", string(wire))
|
||||
|
||||
decoded, err := runtime.Decode(codec, wire)
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected decode error %v", err)
|
||||
}
|
||||
|
||||
// for later tests
|
||||
outer.Object = inner
|
||||
|
||||
if e, a := outer, decoded; reflect.DeepEqual(e, a) {
|
||||
t.Errorf("Expected unequal %#v %#v", e, a)
|
||||
}
|
||||
|
||||
obj, err := runtime.Decode(codec, decoded.(*runtimetesting.EmbeddedTest).Object.(*runtime.Unknown).Raw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
decoded.(*runtimetesting.EmbeddedTest).Object = obj
|
||||
if e, a := outer, decoded; !reflect.DeepEqual(e, a) {
|
||||
t.Errorf("Expected equal %#v %#v", e, a)
|
||||
}
|
||||
|
||||
// test JSON decoding of the external object, which should preserve
|
||||
// raw bytes
|
||||
var externalViaJSON runtimetesting.EmbeddedTestExternal
|
||||
err = json.Unmarshal(wire, &externalViaJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected decode error %v", err)
|
||||
}
|
||||
if externalViaJSON.Kind == "" || externalViaJSON.APIVersion == "" || externalViaJSON.ID != "outer" {
|
||||
t.Errorf("Expected objects to have type info set, got %#v", externalViaJSON)
|
||||
}
|
||||
if len(externalViaJSON.EmptyObject.Raw) > 0 {
|
||||
t.Errorf("Expected deserialization of empty nested objects into empty bytes, got %#v", externalViaJSON)
|
||||
}
|
||||
|
||||
// test JSON decoding, too, since Decode uses yaml unmarshalling.
|
||||
// Generic Unmarshalling of JSON cannot load the nested objects because there is
|
||||
// no default schema set. Consumers wishing to get direct JSON decoding must use
|
||||
// the external representation
|
||||
var decodedViaJSON runtimetesting.EmbeddedTest
|
||||
err = json.Unmarshal(wire, &decodedViaJSON)
|
||||
if err == nil {
|
||||
t.Fatal("Expeceted decode error")
|
||||
}
|
||||
if _, ok := err.(*json.UnmarshalTypeError); !ok {
|
||||
t.Fatalf("Unexpected decode error: %v", err)
|
||||
}
|
||||
if a := decodedViaJSON; a.Object != nil || a.EmptyObject != nil {
|
||||
t.Errorf("Expected embedded objects to be nil: %#v", a)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeepCopyOfRuntimeObject checks to make sure that runtime.Objects's can be passed through DeepCopy with fidelity
|
||||
func TestDeepCopyOfRuntimeObject(t *testing.T) {
|
||||
internalGV := schema.GroupVersion{Group: "test.group", Version: runtime.APIVersionInternal}
|
||||
externalGV := schema.GroupVersion{Group: "test.group", Version: "v1test"}
|
||||
embeddedTestExternalGVK := externalGV.WithKind("EmbeddedTest")
|
||||
|
||||
s := runtime.NewScheme()
|
||||
s.AddKnownTypes(internalGV, &runtimetesting.EmbeddedTest{})
|
||||
s.AddKnownTypeWithName(embeddedTestExternalGVK, &runtimetesting.EmbeddedTestExternal{})
|
||||
|
||||
original := &runtimetesting.EmbeddedTest{
|
||||
ID: "outer",
|
||||
Object: &runtimetesting.EmbeddedTest{
|
||||
ID: "inner",
|
||||
},
|
||||
}
|
||||
|
||||
codec := serializer.NewCodecFactory(s).LegacyCodec(externalGV)
|
||||
|
||||
originalData, err := runtime.Encode(codec, original)
|
||||
if err != nil {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
t.Logf("originalRole = %v\n", string(originalData))
|
||||
|
||||
copyOfOriginal := original.DeepCopy()
|
||||
copiedData, err := runtime.Encode(codec, copyOfOriginal)
|
||||
if err != nil {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
t.Logf("copyOfRole = %v\n", string(copiedData))
|
||||
|
||||
if !reflect.DeepEqual(original, copyOfOriginal) {
|
||||
t.Errorf("expected \n%v\n, got \n%v", string(originalData), string(copiedData))
|
||||
}
|
||||
}
|
113
vendor/k8s.io/apimachinery/pkg/runtime/extension_test.go
generated
vendored
113
vendor/k8s.io/apimachinery/pkg/runtime/extension_test.go
generated
vendored
@ -1,113 +0,0 @@
|
||||
/*
|
||||
Copyright 2014 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 runtime_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
)
|
||||
|
||||
func TestEmbeddedRawExtensionMarshal(t *testing.T) {
|
||||
type test struct {
|
||||
Ext runtime.RawExtension
|
||||
}
|
||||
|
||||
extension := test{Ext: runtime.RawExtension{Raw: []byte(`{"foo":"bar"}`)}}
|
||||
data, err := json.Marshal(extension)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if string(data) != `{"Ext":{"foo":"bar"}}` {
|
||||
t.Errorf("unexpected data: %s", string(data))
|
||||
}
|
||||
}
|
||||
func TestEmbeddedRawExtensionUnmarshal(t *testing.T) {
|
||||
type test struct {
|
||||
Ext runtime.RawExtension
|
||||
}
|
||||
|
||||
testCases := map[string]struct {
|
||||
orig test
|
||||
}{
|
||||
"non-empty object": {
|
||||
orig: test{Ext: runtime.RawExtension{Raw: []byte(`{"foo":"bar"}`)}},
|
||||
},
|
||||
"empty object": {
|
||||
orig: test{Ext: runtime.RawExtension{}},
|
||||
},
|
||||
}
|
||||
|
||||
for k, tc := range testCases {
|
||||
new := test{}
|
||||
data, _ := json.Marshal(tc.orig)
|
||||
if err := json.Unmarshal(data, &new); err != nil {
|
||||
t.Errorf("%s: umarshal error: %v", k, err)
|
||||
}
|
||||
if !reflect.DeepEqual(tc.orig, new) {
|
||||
t.Errorf("%s: unmarshaled struct differs from original: %v %v", k, tc.orig, new)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmbeddedRawExtensionRoundTrip(t *testing.T) {
|
||||
type test struct {
|
||||
Ext runtime.RawExtension
|
||||
}
|
||||
|
||||
testCases := map[string]struct {
|
||||
orig test
|
||||
}{
|
||||
"non-empty object": {
|
||||
orig: test{Ext: runtime.RawExtension{Raw: []byte(`{"foo":"bar"}`)}},
|
||||
},
|
||||
"empty object": {
|
||||
orig: test{Ext: runtime.RawExtension{}},
|
||||
},
|
||||
}
|
||||
|
||||
for k, tc := range testCases {
|
||||
new1 := test{}
|
||||
new2 := test{}
|
||||
data, err := json.Marshal(tc.orig)
|
||||
if err != nil {
|
||||
t.Errorf("1st marshal error: %v", err)
|
||||
}
|
||||
if err = json.Unmarshal(data, &new1); err != nil {
|
||||
t.Errorf("1st unmarshal error: %v", err)
|
||||
}
|
||||
newData, err := json.Marshal(new1)
|
||||
if err != nil {
|
||||
t.Errorf("2st marshal error: %v", err)
|
||||
}
|
||||
if err = json.Unmarshal(newData, &new2); err != nil {
|
||||
t.Errorf("2nd unmarshal error: %v", err)
|
||||
}
|
||||
if !bytes.Equal(data, newData) {
|
||||
t.Errorf("%s: re-marshaled data differs from original: %v %v", k, data, newData)
|
||||
}
|
||||
if !reflect.DeepEqual(tc.orig, new1) {
|
||||
t.Errorf("%s: unmarshaled struct differs from original: %v %v", k, tc.orig, new1)
|
||||
}
|
||||
if !reflect.DeepEqual(new1, new2) {
|
||||
t.Errorf("%s: re-unmarshaled struct differs from original: %v %v", k, new1, new2)
|
||||
}
|
||||
}
|
||||
}
|
127
vendor/k8s.io/apimachinery/pkg/runtime/generated.proto
generated
vendored
127
vendor/k8s.io/apimachinery/pkg/runtime/generated.proto
generated
vendored
@ -1,127 +0,0 @@
|
||||
/*
|
||||
Copyright 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.
|
||||
*/
|
||||
|
||||
|
||||
// This file was autogenerated by go-to-protobuf. Do not edit it manually!
|
||||
|
||||
syntax = 'proto2';
|
||||
|
||||
package k8s.io.apimachinery.pkg.runtime;
|
||||
|
||||
// Package-wide variables from generator "generated".
|
||||
option go_package = "runtime";
|
||||
|
||||
// RawExtension is used to hold extensions in external versions.
|
||||
//
|
||||
// To use this, make a field which has RawExtension as its type in your external, versioned
|
||||
// struct, and Object in your internal struct. You also need to register your
|
||||
// various plugin types.
|
||||
//
|
||||
// // Internal package:
|
||||
// type MyAPIObject struct {
|
||||
// runtime.TypeMeta `json:",inline"`
|
||||
// MyPlugin runtime.Object `json:"myPlugin"`
|
||||
// }
|
||||
// type PluginA struct {
|
||||
// AOption string `json:"aOption"`
|
||||
// }
|
||||
//
|
||||
// // External package:
|
||||
// type MyAPIObject struct {
|
||||
// runtime.TypeMeta `json:",inline"`
|
||||
// MyPlugin runtime.RawExtension `json:"myPlugin"`
|
||||
// }
|
||||
// type PluginA struct {
|
||||
// AOption string `json:"aOption"`
|
||||
// }
|
||||
//
|
||||
// // On the wire, the JSON will look something like this:
|
||||
// {
|
||||
// "kind":"MyAPIObject",
|
||||
// "apiVersion":"v1",
|
||||
// "myPlugin": {
|
||||
// "kind":"PluginA",
|
||||
// "aOption":"foo",
|
||||
// },
|
||||
// }
|
||||
//
|
||||
// So what happens? Decode first uses json or yaml to unmarshal the serialized data into
|
||||
// your external MyAPIObject. That causes the raw JSON to be stored, but not unpacked.
|
||||
// The next step is to copy (using pkg/conversion) into the internal struct. The runtime
|
||||
// package's DefaultScheme has conversion functions installed which will unpack the
|
||||
// JSON stored in RawExtension, turning it into the correct object type, and storing it
|
||||
// in the Object. (TODO: In the case where the object is of an unknown type, a
|
||||
// runtime.Unknown object will be created and stored.)
|
||||
//
|
||||
// +k8s:deepcopy-gen=true
|
||||
// +protobuf=true
|
||||
// +k8s:openapi-gen=true
|
||||
message RawExtension {
|
||||
// Raw is the underlying serialization of this object.
|
||||
//
|
||||
// TODO: Determine how to detect ContentType and ContentEncoding of 'Raw' data.
|
||||
optional bytes raw = 1;
|
||||
}
|
||||
|
||||
// TypeMeta is shared by all top level objects. The proper way to use it is to inline it in your type,
|
||||
// like this:
|
||||
// type MyAwesomeAPIObject struct {
|
||||
// runtime.TypeMeta `json:",inline"`
|
||||
// ... // other fields
|
||||
// }
|
||||
// func (obj *MyAwesomeAPIObject) SetGroupVersionKind(gvk *metav1.GroupVersionKind) { metav1.UpdateTypeMeta(obj,gvk) }; GroupVersionKind() *GroupVersionKind
|
||||
//
|
||||
// TypeMeta is provided here for convenience. You may use it directly from this package or define
|
||||
// your own with the same fields.
|
||||
//
|
||||
// +k8s:deepcopy-gen=false
|
||||
// +protobuf=true
|
||||
// +k8s:openapi-gen=true
|
||||
message TypeMeta {
|
||||
// +optional
|
||||
optional string apiVersion = 1;
|
||||
|
||||
// +optional
|
||||
optional string kind = 2;
|
||||
}
|
||||
|
||||
// Unknown allows api objects with unknown types to be passed-through. This can be used
|
||||
// to deal with the API objects from a plug-in. Unknown objects still have functioning
|
||||
// TypeMeta features-- kind, version, etc.
|
||||
// TODO: Make this object have easy access to field based accessors and settors for
|
||||
// metadata and field mutatation.
|
||||
//
|
||||
// +k8s:deepcopy-gen=true
|
||||
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
|
||||
// +protobuf=true
|
||||
// +k8s:openapi-gen=true
|
||||
message Unknown {
|
||||
optional TypeMeta typeMeta = 1;
|
||||
|
||||
// Raw will hold the complete serialized object which couldn't be matched
|
||||
// with a registered type. Most likely, nothing should be done with this
|
||||
// except for passing it through the system.
|
||||
optional bytes raw = 2;
|
||||
|
||||
// ContentEncoding is encoding used to encode 'Raw' data.
|
||||
// Unspecified means no encoding.
|
||||
optional string contentEncoding = 3;
|
||||
|
||||
// ContentType is serialization method used to serialize 'Raw'.
|
||||
// Unspecified means ContentTypeJSON.
|
||||
optional string contentType = 4;
|
||||
}
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user