本文整理汇总了Golang中k8s/io/kubernetes/pkg/util/diff.ObjectReflectDiff函数的典型用法代码示例。如果您正苦于以下问题:Golang ObjectReflectDiff函数的具体用法?Golang ObjectReflectDiff怎么用?Golang ObjectReflectDiff使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ObjectReflectDiff函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: roundTrip
func roundTrip(t *testing.T, codec runtime.Codec, item runtime.Object) {
printer := spew.ConfigState{DisableMethods: true}
original := item
copied, err := api.Scheme.DeepCopy(item)
if err != nil {
panic(fmt.Sprintf("unable to copy: %v", err))
}
item = copied.(runtime.Object)
name := reflect.TypeOf(item).Elem().Name()
data, err := runtime.Encode(codec, item)
if err != nil {
if runtime.IsNotRegisteredError(err) {
t.Logf("%v: not registered: %v (%s)", name, err, printer.Sprintf("%#v", item))
} else {
t.Errorf("%v: %v (%s)", name, err, printer.Sprintf("%#v", item))
}
return
}
if !api.Semantic.DeepEqual(original, item) {
t.Errorf("0: %v: encode altered the object, diff: %v", name, diff.ObjectReflectDiff(original, item))
return
}
obj2, err := runtime.Decode(codec, data)
if err != nil {
t.Errorf("0: %v: %v\nCodec: %#v\nData: %s\nSource: %#v", name, err, codec, dataAsString(data), printer.Sprintf("%#v", item))
panic("failed")
}
if !api.Semantic.DeepEqual(original, obj2) {
t.Errorf("\n1: %v: diff: %v\nCodec: %#v\nSource:\n\n%#v\n\nEncoded:\n\n%s\n\nFinal:\n\n%#v", name, diff.ObjectReflectDiff(item, obj2), codec, printer.Sprintf("%#v", item), dataAsString(data), printer.Sprintf("%#v", obj2))
return
}
obj3 := reflect.New(reflect.TypeOf(item).Elem()).Interface().(runtime.Object)
if err := runtime.DecodeInto(codec, data, obj3); err != nil {
t.Errorf("2: %v: %v", name, err)
return
}
if !api.Semantic.DeepEqual(item, obj3) {
t.Errorf("3: %v: diff: %v\nCodec: %#v", name, diff.ObjectReflectDiff(item, obj3), codec)
return
}
}
示例2: roundTrip
func roundTrip(t *testing.T, codec runtime.Codec, originalItem runtime.Object) {
// Make a copy of the originalItem to give to conversion functions
// This lets us know if conversion messed with the input object
deepCopy, err := kapi.Scheme.DeepCopy(originalItem)
if err != nil {
t.Errorf("Could not copy object: %v", err)
return
}
item := deepCopy.(runtime.Object)
name := reflect.TypeOf(item).Elem().Name()
data, err := runtime.Encode(codec, item)
if err != nil {
if runtime.IsNotRegisteredError(err) {
t.Logf("%v skipped: not registered: %v", name, err)
return
}
t.Errorf("%v: %v (%#v)", name, err, item)
return
}
obj2, err := runtime.Decode(codec, data)
if err != nil {
t.Errorf("0: %v: %v\nCodec: %v\nData: %s\nSource: %#v", name, err, codec, string(data), originalItem)
return
}
if reflect.TypeOf(item) != reflect.TypeOf(obj2) {
obj2conv := reflect.New(reflect.TypeOf(item).Elem()).Interface().(runtime.Object)
if err := kapi.Scheme.Convert(obj2, obj2conv, nil); err != nil {
t.Errorf("0X: no conversion from %v to %v: %v", reflect.TypeOf(item), reflect.TypeOf(obj2), err)
return
}
obj2 = obj2conv
}
if !kapi.Semantic.DeepEqual(originalItem, obj2) {
t.Errorf("1: %v: diff: %v\nCodec: %v\nData: %s", name, diff.ObjectReflectDiff(originalItem, obj2), codec, dataToString(data))
return
}
obj3 := reflect.New(reflect.TypeOf(item).Elem()).Interface().(runtime.Object)
if err := runtime.DecodeInto(codec, data, obj3); err != nil {
t.Errorf("2: %v: %v", name, err)
return
}
if !kapi.Semantic.DeepEqual(originalItem, obj3) {
t.Errorf("3: %v: diff: %v\nCodec: %v", name, diff.ObjectReflectDiff(originalItem, obj3), codec)
return
}
}
示例3: TestDoRequestFailed
func TestDoRequestFailed(t *testing.T) {
status := &unversioned.Status{
Code: http.StatusNotFound,
Status: unversioned.StatusFailure,
Reason: unversioned.StatusReasonNotFound,
Message: " \"\" not found",
Details: &unversioned.StatusDetails{},
}
expectedBody, _ := runtime.Encode(testapi.Default.Codec(), status)
fakeHandler := utiltesting.FakeHandler{
StatusCode: 404,
ResponseBody: string(expectedBody),
T: t,
}
testServer := httptest.NewServer(&fakeHandler)
defer testServer.Close()
c, err := restClient(testServer)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
err = c.Get().Do().Error()
if err == nil {
t.Errorf("unexpected non-error")
}
ss, ok := err.(errors.APIStatus)
if !ok {
t.Errorf("unexpected error type %v", err)
}
actual := ss.Status()
if !reflect.DeepEqual(status, &actual) {
t.Errorf("Unexpected mis-match: %s", diff.ObjectReflectDiff(status, &actual))
}
}
示例4: TestAPIServerDefaults
func TestAPIServerDefaults(t *testing.T) {
defaults := apiserveroptions.NewServerRunOptions()
// This is a snapshot of the default config
// If the default changes (new fields are added, or default values change), we want to know
// Once we've reacted to the changes appropriately in BuildKubernetesMasterConfig(), update this expected default to match the new upstream defaults
expectedDefaults := &apiserveroptions.ServerRunOptions{
GenericServerRunOptions: &genericapiserveroptions.ServerRunOptions{
AnonymousAuth: true,
BindAddress: net.ParseIP("0.0.0.0"),
CertDirectory: "/var/run/kubernetes",
InsecureBindAddress: net.ParseIP("127.0.0.1"),
InsecurePort: 8080,
LongRunningRequestRE: "(/|^)((watch|proxy)(/|$)|(logs?|portforward|exec|attach)/?$)",
MaxRequestsInFlight: 400,
SecurePort: 6443,
EnableProfiling: true,
EnableGarbageCollection: true,
EnableWatchCache: true,
MinRequestTimeout: 1800,
ServiceNodePortRange: genericapiserveroptions.DefaultServiceNodePortRange,
RuntimeConfig: utilconfig.ConfigurationMap{},
StorageVersions: registered.AllPreferredGroupVersions(),
MasterCount: 1,
DefaultStorageVersions: registered.AllPreferredGroupVersions(),
StorageConfig: storagebackend.Config{
ServerList: nil,
Prefix: "/registry",
DeserializationCacheSize: 0,
},
DefaultStorageMediaType: "application/json",
AdmissionControl: "AlwaysAdmit",
AuthorizationMode: "AlwaysAllow",
DeleteCollectionWorkers: 1,
MasterServiceNamespace: "default",
AuthorizationWebhookCacheAuthorizedTTL: 5 * time.Minute,
AuthorizationWebhookCacheUnauthorizedTTL: 30 * time.Second,
},
EventTTL: 1 * time.Hour,
KubeletConfig: kubeletclient.KubeletClientConfig{
Port: 10250,
PreferredAddressTypes: []string{
string(apiv1.NodeHostName),
string(apiv1.NodeInternalIP),
string(apiv1.NodeExternalIP),
string(apiv1.NodeLegacyHostIP),
},
EnableHttps: true,
HTTPTimeout: time.Duration(5) * time.Second,
},
WebhookTokenAuthnCacheTTL: 2 * time.Minute,
}
if !reflect.DeepEqual(defaults, expectedDefaults) {
t.Logf("expected defaults, actual defaults: \n%s", diff.ObjectReflectDiff(expectedDefaults, defaults))
t.Errorf("Got different defaults than expected, adjust in BuildKubernetesMasterConfig and update expectedDefaults")
}
}
示例5: doDeepCopyTest
func doDeepCopyTest(t *testing.T, kind unversioned.GroupVersionKind, f *fuzz.Fuzzer) {
item, err := api.Scheme.New(kind)
if err != nil {
t.Fatalf("Could not create a %v: %s", kind, err)
}
f.Fuzz(item)
itemCopy, err := api.Scheme.DeepCopy(item)
if err != nil {
t.Errorf("Could not deep copy a %v: %s", kind, err)
return
}
if !reflect.DeepEqual(item, itemCopy) {
t.Errorf("\nexpected: %#v\n\ngot: %#v\n\ndiff: %v", item, itemCopy, diff.ObjectReflectDiff(item, itemCopy))
}
}
示例6: TestSetKubernetesDefaults
func TestSetKubernetesDefaults(t *testing.T) {
testCases := []struct {
Config restclient.Config
After restclient.Config
Err bool
}{
{
restclient.Config{},
restclient.Config{
APIPath: "/api",
ContentConfig: restclient.ContentConfig{
GroupVersion: testapi.Default.GroupVersion(),
NegotiatedSerializer: testapi.Default.NegotiatedSerializer(),
},
QPS: 5,
Burst: 10,
},
false,
},
// Add this test back when we fixed config and SetKubernetesDefaults
// {
// restclient.Config{
// GroupVersion: &unversioned.GroupVersion{Group: "not.a.group", Version: "not_an_api"},
// },
// restclient.Config{},
// true,
// },
}
for _, testCase := range testCases {
val := &testCase.Config
err := SetKubernetesDefaults(val)
val.UserAgent = ""
switch {
case err == nil && testCase.Err:
t.Errorf("expected error but was nil")
continue
case err != nil && !testCase.Err:
t.Errorf("unexpected error %v", err)
continue
case err != nil:
continue
}
if !reflect.DeepEqual(*val, testCase.After) {
t.Errorf("unexpected result object: %s", diff.ObjectReflectDiff(*val, testCase.After))
}
}
}
示例7: TestUnconditionalUpdate
func TestUnconditionalUpdate(t *testing.T) {
storage := makeLocalTestStorage()
ctx := kapi.WithUser(kapi.WithNamespace(kapi.NewContext(), "unittest"), &user.DefaultInfo{Name: "system:admin"})
realizedRoleObj, err := storage.Create(ctx, &authorizationapi.Role{
ObjectMeta: kapi.ObjectMeta{Name: "my-role"},
Rules: []authorizationapi.PolicyRule{
{Verbs: sets.NewString(authorizationapi.VerbAll)},
},
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
realizedRole := realizedRoleObj.(*authorizationapi.Role)
role := &authorizationapi.Role{
ObjectMeta: realizedRole.ObjectMeta,
Rules: []authorizationapi.PolicyRule{
{Verbs: sets.NewString("list", "update")},
},
}
role.ResourceVersion = ""
obj, created, err := storage.Update(ctx, role.Name, rest.DefaultUpdatedObjectInfo(role, kapi.Scheme))
if err != nil || created {
t.Errorf("Unexpected error %v", err)
}
switch actual := obj.(type) {
case *unversioned.Status:
t.Errorf("Unexpected operation error: %v", obj)
case *authorizationapi.Role:
if realizedRole.ResourceVersion == actual.ResourceVersion {
t.Errorf("Expected change to role binding. Expected: %s, Got: %s", realizedRole.ResourceVersion, actual.ResourceVersion)
}
role.ResourceVersion = actual.ResourceVersion
if !reflect.DeepEqual(role, obj) {
t.Errorf("Updated role does not match input role. %s", diff.ObjectReflectDiff(role, obj))
}
default:
t.Errorf("Unexpected result type: %v", obj)
}
}
示例8: TestUnconditionalUpdate
func TestUnconditionalUpdate(t *testing.T) {
ctx := kapi.WithUser(kapi.WithNamespace(kapi.NewContext(), "unittest"), &user.DefaultInfo{Name: "system:admin"})
storage := makeTestStorage()
obj, err := storage.Create(ctx, &authorizationapi.RoleBinding{
ObjectMeta: kapi.ObjectMeta{Name: "my-roleBinding"},
RoleRef: kapi.ObjectReference{Name: "admin"},
})
if err != nil {
t.Errorf("unexpected error: %v", err)
return
}
original := obj.(*authorizationapi.RoleBinding)
roleBinding := &authorizationapi.RoleBinding{
ObjectMeta: original.ObjectMeta,
RoleRef: kapi.ObjectReference{Name: "admin"},
Subjects: []kapi.ObjectReference{{Name: "bob", Kind: "User"}},
}
roleBinding.ResourceVersion = ""
obj, created, err := storage.Update(ctx, roleBinding.Name, rest.DefaultUpdatedObjectInfo(roleBinding, kapi.Scheme))
if err != nil || created {
t.Errorf("Unexpected error %v", err)
}
switch actual := obj.(type) {
case *unversioned.Status:
t.Errorf("Unexpected operation error: %v", obj)
case *authorizationapi.RoleBinding:
if original.ResourceVersion == actual.ResourceVersion {
t.Errorf("Expected change to role binding. Expected: %s, Got: %s", original.ResourceVersion, actual.ResourceVersion)
}
roleBinding.ResourceVersion = actual.ResourceVersion
if !reflect.DeepEqual(roleBinding, obj) {
t.Errorf("Updated roleBinding does not match input roleBinding. %s", diff.ObjectReflectDiff(roleBinding, obj))
}
default:
t.Errorf("Unexpected result type: %v", obj)
}
}
示例9: TestDoRawRequestFailed
func TestDoRawRequestFailed(t *testing.T) {
status := &unversioned.Status{
Code: http.StatusNotFound,
Status: unversioned.StatusFailure,
Reason: unversioned.StatusReasonNotFound,
Message: "the server could not find the requested resource",
Details: &unversioned.StatusDetails{
Causes: []unversioned.StatusCause{
{Type: unversioned.CauseTypeUnexpectedServerResponse, Message: "unknown"},
},
},
}
expectedBody, _ := runtime.Encode(testapi.Default.Codec(), status)
fakeHandler := utiltesting.FakeHandler{
StatusCode: 404,
ResponseBody: string(expectedBody),
T: t,
}
testServer := httptest.NewServer(&fakeHandler)
defer testServer.Close()
c, err := restClient(testServer)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
body, err := c.Get().Do().Raw()
if err == nil || body == nil {
t.Errorf("unexpected non-error: %#v", body)
}
ss, ok := err.(errors.APIStatus)
if !ok {
t.Errorf("unexpected error type %v", err)
}
actual := ss.Status()
if !reflect.DeepEqual(status, &actual) {
t.Errorf("Unexpected mis-match: %s", diff.ObjectReflectDiff(status, &actual))
}
}
示例10: TestSchedulerServerDefaults
func TestSchedulerServerDefaults(t *testing.T) {
defaults := scheduleroptions.NewSchedulerServer()
// This is a snapshot of the default config
// If the default changes (new fields are added, or default values change), we want to know
// Once we've reacted to the changes appropriately in BuildKubernetesMasterConfig(), update this expected default to match the new upstream defaults
expectedDefaults := &scheduleroptions.SchedulerServer{
KubeSchedulerConfiguration: componentconfig.KubeSchedulerConfiguration{
Port: 10251, // disabled
Address: "0.0.0.0",
AlgorithmProvider: "DefaultProvider",
ContentType: "application/vnd.kubernetes.protobuf",
KubeAPIQPS: 50,
KubeAPIBurst: 100,
SchedulerName: "default-scheduler",
HardPodAffinitySymmetricWeight: 1,
FailureDomains: "kubernetes.io/hostname,failure-domain.beta.kubernetes.io/zone,failure-domain.beta.kubernetes.io/region",
LeaderElection: componentconfig.LeaderElectionConfiguration{
LeaderElect: true,
LeaseDuration: unversioned.Duration{
Duration: 15 * time.Second,
},
RenewDeadline: unversioned.Duration{
Duration: 10 * time.Second,
},
RetryPeriod: unversioned.Duration{
Duration: 2 * time.Second,
},
},
},
}
if !reflect.DeepEqual(defaults, expectedDefaults) {
t.Logf("expected defaults, actual defaults: \n%s", diff.ObjectReflectDiff(expectedDefaults, defaults))
t.Errorf("Got different defaults than expected, adjust in BuildKubernetesMasterConfig and update expectedDefaults")
}
}
示例11: doDeepCopyTest
func doDeepCopyTest(t *testing.T, kind unversioned.GroupVersionKind, f *fuzz.Fuzzer) {
item, err := api.Scheme.New(kind)
if err != nil {
t.Fatalf("Could not create a %v: %s", kind, err)
}
f.Fuzz(item)
itemCopy, err := api.Scheme.DeepCopy(item)
if err != nil {
t.Errorf("Could not deep copy a %v: %s", kind, err)
return
}
if !reflect.DeepEqual(item, itemCopy) {
t.Errorf("\nexpected: %#v\n\ngot: %#v\n\ndiff: %v", item, itemCopy, diff.ObjectReflectDiff(item, itemCopy))
}
prefuzzData := &bytes.Buffer{}
if err := api.Codecs.LegacyCodec(kind.GroupVersion()).Encode(item, prefuzzData); err != nil {
t.Errorf("Could not encode a %v: %s", kind, err)
return
}
// Refuzz the copy, which should have no effect on the original
f.Fuzz(itemCopy)
postfuzzData := &bytes.Buffer{}
if err := api.Codecs.LegacyCodec(kind.GroupVersion()).Encode(item, postfuzzData); err != nil {
t.Errorf("Could not encode a %v: %s", kind, err)
return
}
if bytes.Compare(prefuzzData.Bytes(), postfuzzData.Bytes()) != 0 {
t.Log(diff.StringDiff(prefuzzData.String(), postfuzzData.String()))
t.Errorf("Fuzzing copy modified original of %#v", kind)
return
}
}
示例12: TestProxyConfig
func TestProxyConfig(t *testing.T) {
// This is a snapshot of the default config
// If the default changes (new fields are added, or default values change), we want to know
// Once we've reacted to the changes appropriately in buildKubeProxyConfig(), update this expected default to match the new upstream defaults
oomScoreAdj := int32(-999)
ipTablesMasqueratebit := int32(14)
expectedDefaultConfig := &proxyoptions.ProxyServerConfig{
KubeProxyConfiguration: componentconfig.KubeProxyConfiguration{
BindAddress: "0.0.0.0",
ClusterCIDR: "",
HealthzPort: 10249, // disabled
HealthzBindAddress: "127.0.0.1", // disabled
OOMScoreAdj: &oomScoreAdj, // disabled
ResourceContainer: "/kube-proxy", // disabled
IPTablesSyncPeriod: unversioned.Duration{Duration: 30 * time.Second},
// from k8s.io/kubernetes/cmd/kube-proxy/app/options/options.go
// defaults to 14.
IPTablesMasqueradeBit: &ipTablesMasqueratebit,
UDPIdleTimeout: unversioned.Duration{Duration: 250 * time.Millisecond},
ConntrackMaxPerCore: 32 * 1024,
ConntrackTCPEstablishedTimeout: unversioned.Duration{Duration: 86400 * time.Second}, // 1 day (1/5 default)
},
ConfigSyncPeriod: 15 * time.Minute,
KubeAPIQPS: 5.0,
KubeAPIBurst: 10,
ContentType: "application/vnd.kubernetes.protobuf",
}
actualDefaultConfig := proxyoptions.NewProxyConfig()
if !reflect.DeepEqual(expectedDefaultConfig, actualDefaultConfig) {
t.Errorf("Default kube proxy config has changed. Adjust buildKubeProxyConfig() as needed to disable or make use of additions.")
t.Logf("Difference %s", diff.ObjectReflectDiff(expectedDefaultConfig, actualDefaultConfig))
}
}
示例13: TestSpecificRoundTrips
func TestSpecificRoundTrips(t *testing.T) {
boolFalse := false
testCases := []struct {
mediaType string
in, out runtime.Object
to, from unversioned.GroupVersion
}{
{
in: &configapi.MasterConfig{
AdmissionConfig: configapi.AdmissionConfig{
PluginConfig: map[string]configapi.AdmissionPluginConfig{
"test1": {Configuration: &configapi.LDAPSyncConfig{BindDN: "first"}},
"test2": {Configuration: &runtime.Unknown{Raw: []byte(`{"kind":"LDAPSyncConfig","apiVersion":"v1","bindDN":"second"}`)}},
"test3": {Configuration: &runtime.Unknown{Raw: []byte(`{"kind":"Unknown","apiVersion":"some/version"}`)}},
"test4": {Configuration: nil},
},
},
},
to: configapiv1.SchemeGroupVersion,
out: &configapiv1.MasterConfig{
TypeMeta: unversioned.TypeMeta{Kind: "MasterConfig", APIVersion: "v1"},
AdmissionConfig: configapiv1.AdmissionConfig{
PluginConfig: map[string]configapiv1.AdmissionPluginConfig{
"test1": {Configuration: runtime.RawExtension{
Object: &configapiv1.LDAPSyncConfig{BindDN: "first"},
Raw: []byte(`{"kind":"LDAPSyncConfig","apiVersion":"v1","url":"","bindDN":"first","bindPassword":"","insecure":false,"ca":"","groupUIDNameMapping":null}`),
}},
"test2": {Configuration: runtime.RawExtension{
Object: &configapiv1.LDAPSyncConfig{BindDN: "second"},
Raw: []byte(`{"kind":"LDAPSyncConfig","apiVersion":"v1","bindDN":"second"}`),
}},
"test3": {Configuration: runtime.RawExtension{
Object: &runtime.Unknown{TypeMeta: runtime.TypeMeta{Kind: "Unknown", APIVersion: "some/version"}, ContentType: "application/json", Raw: []byte(`{"kind":"Unknown","apiVersion":"some/version"}`)},
Raw: []byte(`{"kind":"Unknown","apiVersion":"some/version"}`),
}},
"test4": {},
},
},
VolumeConfig: configapiv1.MasterVolumeConfig{DynamicProvisioningEnabled: &boolFalse},
},
from: configapiv1.SchemeGroupVersion,
},
}
f := serializer.NewCodecFactory(configapi.Scheme)
for i, test := range testCases {
var s runtime.Serializer
if len(test.mediaType) != 0 {
info, _ := f.SerializerForMediaType(test.mediaType, nil)
s = info.Serializer
} else {
info, _ := f.SerializerForMediaType(f.SupportedMediaTypes()[0], nil)
s = info.Serializer
}
data, err := runtime.Encode(f.LegacyCodec(test.to), test.in)
if err != nil {
t.Errorf("%d: unable to encode: %v", i, err)
continue
}
result, err := runtime.Decode(f.DecoderToVersion(s, test.from), data)
if err != nil {
t.Errorf("%d: unable to decode: %v", i, err)
continue
}
if !reflect.DeepEqual(test.out, result) {
t.Errorf("%d: result did not match: %s", i, diff.ObjectReflectDiff(test.out, result))
continue
}
}
}
示例14: TestLimitVerifier
//.........这里部分代码省略.........
Items: []api.TagEvent{
{
DockerImageReference: testutil.MakeDockerImageReference("test", "is", testutil.BaseImageWith2LayersDigest),
Image: testutil.BaseImageWith2LayersDigest,
},
},
},
},
},
},
isEvaluator: makeISEvaluator(1, 0),
expected: makeISForbiddenError("is", []kapi.ResourceName{api.ResourceImageStreamImages}),
},
{
name: "exceed tags",
is: api.ImageStream{
ObjectMeta: kapi.ObjectMeta{
Namespace: "test",
Name: "is",
},
Spec: api.ImageStreamSpec{
Tags: map[string]api.TagReference{
"new": {
Name: "new",
From: &kapi.ObjectReference{
Kind: "DockerImage",
Name: testutil.MakeDockerImageReference("test", "is", testutil.ChildImageWith2LayersDigest),
},
},
},
},
},
isEvaluator: makeISEvaluator(0, 0),
expected: makeISForbiddenError("is", []kapi.ResourceName{api.ResourceImageStreamTags}),
},
{
name: "exceed images and tags",
is: api.ImageStream{
ObjectMeta: kapi.ObjectMeta{
Namespace: "test",
Name: "is",
},
Spec: api.ImageStreamSpec{
Tags: map[string]api.TagReference{
"new": {
Name: "new",
From: &kapi.ObjectReference{
Kind: "DockerImage",
Name: testutil.MakeDockerImageReference("test", "other", testutil.BaseImageWith1LayerDigest),
},
},
},
},
Status: api.ImageStreamStatus{
Tags: map[string]api.TagEventList{
"latest": {
Items: []api.TagEvent{
{
DockerImageReference: testutil.MakeDockerImageReference("test", "other", testutil.BaseImageWith1LayerDigest),
Image: testutil.BaseImageWith1LayerDigest,
},
},
},
},
},
},
isEvaluator: makeISEvaluator(0, 0),
expected: makeISForbiddenError("is", []kapi.ResourceName{api.ResourceImageStreamImages, api.ResourceImageStreamTags}),
},
}
for _, tc := range tests {
sar := &fakeSubjectAccessReviewRegistry{
allow: true,
}
tagVerifier := &TagVerifier{sar}
s := &Strategy{
tagVerifier: tagVerifier,
limitVerifier: &testutil.FakeImageStreamLimitVerifier{
ImageStreamEvaluator: tc.isEvaluator,
},
defaultRegistry: &fakeDefaultRegistry{},
}
ctx := kapi.WithUser(kapi.NewDefaultContext(), &fakeUser{})
err := s.BeforeCreate(ctx, &tc.is)
if e, a := tc.expected, err; !reflect.DeepEqual(e, a) {
t.Errorf("%s: unexpected validation errors: %s", tc.name, diff.ObjectReflectDiff(e, a))
}
// Update must fail the exact same way
err = s.BeforeUpdate(ctx, &tc.is, &api.ImageStream{})
if e, a := tc.expected, err; !reflect.DeepEqual(e, a) {
t.Errorf("%s: unexpected validation errors: %s", tc.name, diff.ObjectReflectDiff(e, a))
}
}
}
示例15: TestAdmissionResolveImages
//.........这里部分代码省略.........
Spec: buildapi.BuildSpec{
CommonSpec: buildapi.CommonSpec{
Strategy: buildapi.BuildStrategy{
CustomStrategy: &buildapi.CustomBuildStrategy{
From: kapi.ObjectReference{Kind: "ImageStreamTag", Name: "test:other"},
},
},
},
},
}, nil, unversioned.GroupVersionKind{Version: "v1", Kind: "Build"},
"default", "build1", unversioned.GroupVersionResource{Version: "v1", Resource: "builds"},
"", admission.Create, nil,
),
admit: true,
expect: &buildapi.Build{
Spec: buildapi.BuildSpec{
CommonSpec: buildapi.CommonSpec{
Strategy: buildapi.BuildStrategy{
CustomStrategy: &buildapi.CustomBuildStrategy{
From: kapi.ObjectReference{Kind: "DockerImage", Name: "integrated.registry/image1/[email protected]:0000000000000000000000000000000000000000000000000000000000000001"},
},
},
},
},
},
},
// resolves builds with image stream images
{
client: testclient.NewSimpleFake(
&imageapi.ImageStreamImage{
ObjectMeta: kapi.ObjectMeta{Name: "[email protected]:0000000000000000000000000000000000000000000000000000000000000001", Namespace: "default"},
Image: *image1,
},
),
attrs: admission.NewAttributesRecord(
&buildapi.Build{
Spec: buildapi.BuildSpec{
CommonSpec: buildapi.CommonSpec{
Strategy: buildapi.BuildStrategy{
DockerStrategy: &buildapi.DockerBuildStrategy{
From: &kapi.ObjectReference{Kind: "ImageStreamImage", Name: "[email protected]:0000000000000000000000000000000000000000000000000000000000000001"},
},
},
},
},
}, nil, unversioned.GroupVersionKind{Version: "v1", Kind: "Build"},
"default", "build1", unversioned.GroupVersionResource{Version: "v1", Resource: "builds"},
"", admission.Create, nil,
),
admit: true,
expect: &buildapi.Build{
Spec: buildapi.BuildSpec{
CommonSpec: buildapi.CommonSpec{
Strategy: buildapi.BuildStrategy{
DockerStrategy: &buildapi.DockerBuildStrategy{
From: &kapi.ObjectReference{Kind: "DockerImage", Name: "integrated.registry/image1/image1:latest"},
},
},
},
},
},
},
}
for i, test := range testCases {
onResources := []unversioned.GroupResource{{Resource: "builds"}, {Resource: "pods"}}
p, err := newImagePolicyPlugin(nil, &api.ImagePolicyConfig{
ResolveImages: api.RequiredRewrite,
ExecutionRules: []api.ImageExecutionPolicyRule{
{ImageCondition: api.ImageCondition{OnResources: onResources}},
},
})
if err != nil {
t.Fatal(err)
}
setDefaultCache(p)
p.SetOpenshiftClient(test.client)
p.SetDefaultRegistryFunc(func() (string, bool) {
return "integrated.registry", true
})
if err := p.Validate(); err != nil {
t.Fatal(err)
}
if err := p.Admit(test.attrs); err != nil {
if test.admit {
t.Errorf("%d: should admit: %v", i, err)
}
continue
}
if !test.admit {
t.Errorf("%d: should not admit", i)
continue
}
if !reflect.DeepEqual(test.expect, test.attrs.GetObject()) {
t.Errorf("%d: unequal: %s", i, diff.ObjectReflectDiff(test.expect, test.attrs.GetObject()))
}
}
}