| 1 |
/* |
| 2 |
Copyright 2014 The Kubernetes Authors. |
| 3 |
|
| 4 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
you may not use this file except in compliance with the License. |
| 6 |
You may obtain a copy of the License at |
| 7 |
|
| 8 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
|
| 10 |
Unless required by applicable law or agreed to in writing, software |
| 11 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
See the License for the specific language governing permissions and |
| 14 |
limitations under the License. |
| 15 |
*/ |
| 16 |
|
| 17 |
package endpoints |
| 18 |
|
| 19 |
import ( |
| 20 |
"bytes" |
| 21 |
"compress/gzip" |
| 22 |
"context" |
| 23 |
"encoding/json" |
| 24 |
"errors" |
| 25 |
"fmt" |
| 26 |
"io" |
| 27 |
"io/ioutil" |
| 28 |
"math/rand" |
| 29 |
"net/http" |
| 30 |
"net/http/httptest" |
| 31 |
"net/http/httputil" |
| 32 |
"net/url" |
| 33 |
"reflect" |
| 34 |
"strconv" |
| 35 |
"strings" |
| 36 |
"sync" |
| 37 |
"testing" |
| 38 |
"time" |
| 39 |
|
| 40 |
"github.com/emicklei/go-restful/v3" |
| 41 |
"github.com/google/go-cmp/cmp" |
| 42 |
|
| 43 |
"k8s.io/apimachinery/pkg/api/apitesting/fuzzer" |
| 44 |
apiequality "k8s.io/apimachinery/pkg/api/equality" |
| 45 |
apierrors "k8s.io/apimachinery/pkg/api/errors" |
| 46 |
"k8s.io/apimachinery/pkg/api/meta" |
| 47 |
metainternalversion "k8s.io/apimachinery/pkg/apis/meta/internalversion" |
| 48 |
metainternalversionscheme "k8s.io/apimachinery/pkg/apis/meta/internalversion/scheme" |
| 49 |
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 50 |
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" |
| 51 |
metav1beta1 "k8s.io/apimachinery/pkg/apis/meta/v1beta1" |
| 52 |
"k8s.io/apimachinery/pkg/fields" |
| 53 |
"k8s.io/apimachinery/pkg/labels" |
| 54 |
"k8s.io/apimachinery/pkg/runtime" |
| 55 |
"k8s.io/apimachinery/pkg/runtime/schema" |
| 56 |
"k8s.io/apimachinery/pkg/runtime/serializer" |
| 57 |
"k8s.io/apimachinery/pkg/runtime/serializer/streaming" |
| 58 |
"k8s.io/apimachinery/pkg/types" |
| 59 |
"k8s.io/apimachinery/pkg/util/managedfields" |
| 60 |
"k8s.io/apimachinery/pkg/util/net" |
| 61 |
utilruntime "k8s.io/apimachinery/pkg/util/runtime" |
| 62 |
"k8s.io/apimachinery/pkg/util/sets" |
| 63 |
"k8s.io/apimachinery/pkg/watch" |
| 64 |
"k8s.io/apiserver/pkg/admission" |
| 65 |
auditinternal "k8s.io/apiserver/pkg/apis/audit" |
| 66 |
"k8s.io/apiserver/pkg/apis/example" |
| 67 |
examplefuzzer "k8s.io/apiserver/pkg/apis/example/fuzzer" |
| 68 |
examplev1 "k8s.io/apiserver/pkg/apis/example/v1" |
| 69 |
"k8s.io/apiserver/pkg/audit" |
| 70 |
auditpolicy "k8s.io/apiserver/pkg/audit/policy" |
| 71 |
genericapifilters "k8s.io/apiserver/pkg/endpoints/filters" |
| 72 |
"k8s.io/apiserver/pkg/endpoints/handlers/negotiation" |
| 73 |
"k8s.io/apiserver/pkg/endpoints/handlers/responsewriters" |
| 74 |
"k8s.io/apiserver/pkg/endpoints/request" |
| 75 |
genericapitesting "k8s.io/apiserver/pkg/endpoints/testing" |
| 76 |
"k8s.io/apiserver/pkg/registry/rest" |
| 77 |
) |
| 78 |
|
| 79 |
type alwaysMutatingDeny struct{} |
| 80 |
|
| 81 |
func (alwaysMutatingDeny) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) { |
| 82 |
return admission.NewForbidden(a, errors.New("Mutating admission control is denying all modifications")) |
| 83 |
} |
| 84 |
|
| 85 |
func (alwaysMutatingDeny) Handles(operation admission.Operation) bool { |
| 86 |
return true |
| 87 |
} |
| 88 |
|
| 89 |
var _ admission.MutationInterface = &alwaysMutatingDeny{} |
| 90 |
|
| 91 |
type alwaysValidatingDeny struct{} |
| 92 |
|
| 93 |
func (alwaysValidatingDeny) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) { |
| 94 |
return admission.NewForbidden(a, errors.New("Validating admission control is denying all modifications")) |
| 95 |
} |
| 96 |
|
| 97 |
func (alwaysValidatingDeny) Handles(operation admission.Operation) bool { |
| 98 |
return true |
| 99 |
} |
| 100 |
|
| 101 |
var _ admission.ValidationInterface = &alwaysValidatingDeny{} |
| 102 |
|
| 103 |
// This creates fake API versions, similar to api/latest.go. |
| 104 |
var testAPIGroup = "test.group" |
| 105 |
var testAPIGroup2 = "test.group2" |
| 106 |
var testInternalGroupVersion = schema.GroupVersion{Group: testAPIGroup, Version: runtime.APIVersionInternal} |
| 107 |
var testGroupVersion = schema.GroupVersion{Group: testAPIGroup, Version: "version"} |
| 108 |
var newGroupVersion = schema.GroupVersion{Group: testAPIGroup, Version: "version2"} |
| 109 |
var testGroup2Version = schema.GroupVersion{Group: testAPIGroup2, Version: "version"} |
| 110 |
var testInternalGroup2Version = schema.GroupVersion{Group: testAPIGroup2, Version: runtime.APIVersionInternal} |
| 111 |
var prefix = "apis" |
| 112 |
|
| 113 |
var grouplessGroupVersion = schema.GroupVersion{Group: "", Version: "v1"} |
| 114 |
var grouplessInternalGroupVersion = schema.GroupVersion{Group: "", Version: runtime.APIVersionInternal} |
| 115 |
var grouplessPrefix = "api" |
| 116 |
|
| 117 |
var groupVersions = []schema.GroupVersion{grouplessGroupVersion, testGroupVersion, newGroupVersion} |
| 118 |
|
| 119 |
var scheme = runtime.NewScheme() |
| 120 |
var codecs = serializer.NewCodecFactory(scheme) |
| 121 |
|
| 122 |
var codec = codecs.LegacyCodec(groupVersions...) |
| 123 |
var testCodec = codecs.LegacyCodec(testGroupVersion) |
| 124 |
var newCodec = codecs.LegacyCodec(newGroupVersion) |
| 125 |
var parameterCodec = runtime.NewParameterCodec(scheme) |
| 126 |
|
| 127 |
var accessor = meta.NewAccessor() |
| 128 |
var namer runtime.Namer = accessor |
| 129 |
var admissionControl admission.Interface |
| 130 |
|
| 131 |
func init() { |
| 132 |
metav1.AddToGroupVersion(scheme, metav1.SchemeGroupVersion) |
| 133 |
|
| 134 |
// unnamed core group |
| 135 |
scheme.AddUnversionedTypes(grouplessGroupVersion, &metav1.Status{}) |
| 136 |
metav1.AddToGroupVersion(scheme, grouplessGroupVersion) |
| 137 |
|
| 138 |
utilruntime.Must(example.AddToScheme(scheme)) |
| 139 |
utilruntime.Must(examplev1.AddToScheme(scheme)) |
| 140 |
} |
| 141 |
|
| 142 |
func addGrouplessTypes() { |
| 143 |
scheme.AddKnownTypes(grouplessGroupVersion, |
| 144 |
&genericapitesting.Simple{}, &genericapitesting.SimpleList{}, &metav1.ListOptions{}, |
| 145 |
&metav1.DeleteOptions{}, &genericapitesting.SimpleGetOptions{}, &genericapitesting.SimpleRoot{}) |
| 146 |
scheme.AddKnownTypes(grouplessInternalGroupVersion, |
| 147 |
&genericapitesting.Simple{}, &genericapitesting.SimpleList{}, |
| 148 |
&genericapitesting.SimpleGetOptions{}, &genericapitesting.SimpleRoot{}) |
| 149 |
|
| 150 |
utilruntime.Must(genericapitesting.RegisterConversions(scheme)) |
| 151 |
} |
| 152 |
|
| 153 |
func addTestTypes() { |
| 154 |
scheme.AddKnownTypes(testGroupVersion, |
| 155 |
&genericapitesting.Simple{}, &genericapitesting.SimpleList{}, |
| 156 |
&metav1.DeleteOptions{}, &genericapitesting.SimpleGetOptions{}, &genericapitesting.SimpleRoot{}, |
| 157 |
&genericapitesting.SimpleXGSubresource{}) |
| 158 |
scheme.AddKnownTypes(testGroupVersion, &examplev1.Pod{}) |
| 159 |
scheme.AddKnownTypes(testInternalGroupVersion, |
| 160 |
&genericapitesting.Simple{}, &genericapitesting.SimpleList{}, |
| 161 |
&genericapitesting.SimpleGetOptions{}, &genericapitesting.SimpleRoot{}, |
| 162 |
&genericapitesting.SimpleXGSubresource{}) |
| 163 |
scheme.AddKnownTypes(testInternalGroupVersion, &example.Pod{}) |
| 164 |
// Register SimpleXGSubresource in both testGroupVersion and testGroup2Version, and also their |
| 165 |
// their corresponding internal versions, to verify that the desired group version object is |
| 166 |
// served in the tests. |
| 167 |
scheme.AddKnownTypes(testGroup2Version, &genericapitesting.SimpleXGSubresource{}) |
| 168 |
scheme.AddKnownTypes(testInternalGroup2Version, &genericapitesting.SimpleXGSubresource{}) |
| 169 |
metav1.AddToGroupVersion(scheme, testGroupVersion) |
| 170 |
|
| 171 |
utilruntime.Must(genericapitesting.RegisterConversions(scheme)) |
| 172 |
} |
| 173 |
|
| 174 |
func addNewTestTypes() { |
| 175 |
scheme.AddKnownTypes(newGroupVersion, |
| 176 |
&genericapitesting.Simple{}, &genericapitesting.SimpleList{}, |
| 177 |
&metav1.DeleteOptions{}, &genericapitesting.SimpleGetOptions{}, &genericapitesting.SimpleRoot{}, |
| 178 |
&examplev1.Pod{}, |
| 179 |
) |
| 180 |
metav1.AddToGroupVersion(scheme, newGroupVersion) |
| 181 |
|
| 182 |
utilruntime.Must(genericapitesting.RegisterConversions(scheme)) |
| 183 |
} |
| 184 |
|
| 185 |
func init() { |
| 186 |
// Certain API objects are returned regardless of the contents of storage: |
| 187 |
// api.Status is returned in errors |
| 188 |
|
| 189 |
addGrouplessTypes() |
| 190 |
addTestTypes() |
| 191 |
addNewTestTypes() |
| 192 |
|
| 193 |
scheme.AddFieldLabelConversionFunc(grouplessGroupVersion.WithKind("Simple"), |
| 194 |
func(label, value string) (string, string, error) { |
| 195 |
return label, value, nil |
| 196 |
}, |
| 197 |
) |
| 198 |
scheme.AddFieldLabelConversionFunc(testGroupVersion.WithKind("Simple"), |
| 199 |
func(label, value string) (string, string, error) { |
| 200 |
return label, value, nil |
| 201 |
}, |
| 202 |
) |
| 203 |
scheme.AddFieldLabelConversionFunc(newGroupVersion.WithKind("Simple"), |
| 204 |
func(label, value string) (string, string, error) { |
| 205 |
return label, value, nil |
| 206 |
}, |
| 207 |
) |
| 208 |
} |
| 209 |
|
| 210 |
// defaultAPIServer exposes nested objects for testability. |
| 211 |
type defaultAPIServer struct { |
| 212 |
http.Handler |
| 213 |
container *restful.Container |
| 214 |
} |
| 215 |
|
| 216 |
func handleWithWarnings(storage map[string]rest.Storage) http.Handler { |
| 217 |
return genericapifilters.WithWarningRecorder(handle(storage)) |
| 218 |
} |
| 219 |
|
| 220 |
// uses the default settings |
| 221 |
func handle(storage map[string]rest.Storage) http.Handler { |
| 222 |
return handleInternal(storage, admissionControl, nil) |
| 223 |
} |
| 224 |
|
| 225 |
func handleInternal(storage map[string]rest.Storage, admissionControl admission.Interface, auditSink audit.Sink) http.Handler { |
| 226 |
container := restful.NewContainer() |
| 227 |
container.Router(restful.CurlyRouter{}) |
| 228 |
mux := container.ServeMux |
| 229 |
|
| 230 |
template := APIGroupVersion{ |
| 231 |
Storage: storage, |
| 232 |
|
| 233 |
Creater: scheme, |
| 234 |
Convertor: scheme, |
| 235 |
TypeConverter: managedfields.NewDeducedTypeConverter(), |
| 236 |
UnsafeConvertor: runtime.UnsafeObjectConvertor(scheme), |
| 237 |
Defaulter: scheme, |
| 238 |
Typer: scheme, |
| 239 |
Namer: namer, |
| 240 |
|
| 241 |
EquivalentResourceRegistry: runtime.NewEquivalentResourceRegistry(), |
| 242 |
|
| 243 |
ParameterCodec: parameterCodec, |
| 244 |
|
| 245 |
Admit: admissionControl, |
| 246 |
} |
| 247 |
|
| 248 |
// groupless v1 version |
| 249 |
{ |
| 250 |
group := template |
| 251 |
group.Root = "/" + grouplessPrefix |
| 252 |
group.GroupVersion = grouplessGroupVersion |
| 253 |
group.OptionsExternalVersion = &grouplessGroupVersion |
| 254 |
group.Serializer = codecs |
| 255 |
if _, _, err := (&group).InstallREST(container); err != nil { |
| 256 |
panic(fmt.Sprintf("unable to install container %s: %v", group.GroupVersion, err)) |
| 257 |
} |
| 258 |
} |
| 259 |
|
| 260 |
// group version 1 |
| 261 |
{ |
| 262 |
group := template |
| 263 |
group.Root = "/" + prefix |
| 264 |
group.GroupVersion = testGroupVersion |
| 265 |
group.OptionsExternalVersion = &testGroupVersion |
| 266 |
group.Serializer = codecs |
| 267 |
if _, _, err := (&group).InstallREST(container); err != nil { |
| 268 |
panic(fmt.Sprintf("unable to install container %s: %v", group.GroupVersion, err)) |
| 269 |
} |
| 270 |
} |
| 271 |
|
| 272 |
// group version 2 |
| 273 |
{ |
| 274 |
group := template |
| 275 |
group.Root = "/" + prefix |
| 276 |
group.GroupVersion = newGroupVersion |
| 277 |
group.OptionsExternalVersion = &newGroupVersion |
| 278 |
group.Serializer = codecs |
| 279 |
if _, _, err := (&group).InstallREST(container); err != nil { |
| 280 |
panic(fmt.Sprintf("unable to install container %s: %v", group.GroupVersion, err)) |
| 281 |
} |
| 282 |
} |
| 283 |
longRunningCheck := func(r *http.Request, requestInfo *request.RequestInfo) bool { |
| 284 |
// simplified long-running check |
| 285 |
return requestInfo.Verb == "watch" || requestInfo.Verb == "proxy" |
| 286 |
} |
| 287 |
fakeRuleEvaluator := auditpolicy.NewFakePolicyRuleEvaluator(auditinternal.LevelRequestResponse, nil) |
| 288 |
handler := genericapifilters.WithAudit(mux, auditSink, fakeRuleEvaluator, longRunningCheck) |
| 289 |
handler = genericapifilters.WithRequestDeadline(handler, auditSink, fakeRuleEvaluator, longRunningCheck, codecs, 60*time.Second) |
| 290 |
handler = genericapifilters.WithRequestInfo(handler, testRequestInfoResolver()) |
| 291 |
handler = genericapifilters.WithAuditInit(handler) |
| 292 |
|
| 293 |
return &defaultAPIServer{handler, container} |
| 294 |
} |
| 295 |
|
| 296 |
func testRequestInfoResolver() *request.RequestInfoFactory { |
| 297 |
return &request.RequestInfoFactory{ |
| 298 |
APIPrefixes: sets.NewString("api", "apis"), |
| 299 |
GrouplessAPIPrefixes: sets.NewString("api"), |
| 300 |
} |
| 301 |
} |
| 302 |
|
| 303 |
func TestSimpleSetupRight(t *testing.T) { |
| 304 |
s := &genericapitesting.Simple{ObjectMeta: metav1.ObjectMeta{Name: "aName"}} |
| 305 |
wire, err := runtime.Encode(codec, s) |
| 306 |
if err != nil { |
| 307 |
t.Fatal(err) |
| 308 |
} |
| 309 |
s2, err := runtime.Decode(codec, wire) |
| 310 |
if err != nil { |
| 311 |
t.Fatal(err) |
| 312 |
} |
| 313 |
if !reflect.DeepEqual(s, s2) { |
| 314 |
t.Fatalf("encode/decode broken:\n%#v\n%#v\n", s, s2) |
| 315 |
} |
| 316 |
} |
| 317 |
|
| 318 |
func TestSimpleOptionsSetupRight(t *testing.T) { |
| 319 |
s := &genericapitesting.SimpleGetOptions{} |
| 320 |
wire, err := runtime.Encode(codec, s) |
| 321 |
if err != nil { |
| 322 |
t.Fatal(err) |
| 323 |
} |
| 324 |
s2, err := runtime.Decode(codec, wire) |
| 325 |
if err != nil { |
| 326 |
t.Fatal(err) |
| 327 |
} |
| 328 |
if !reflect.DeepEqual(s, s2) { |
| 329 |
t.Fatalf("encode/decode broken:\n%#v\n%#v\n", s, s2) |
| 330 |
} |
| 331 |
} |
| 332 |
|
| 333 |
type SimpleRESTStorage struct { |
| 334 |
lock sync.Mutex |
| 335 |
|
| 336 |
errors map[string]error |
| 337 |
list []genericapitesting.Simple |
| 338 |
item genericapitesting.Simple |
| 339 |
|
| 340 |
updated *genericapitesting.Simple |
| 341 |
created *genericapitesting.Simple |
| 342 |
|
| 343 |
stream *SimpleStream |
| 344 |
|
| 345 |
deleted string |
| 346 |
deleteOptions *metav1.DeleteOptions |
| 347 |
|
| 348 |
actualNamespace string |
| 349 |
namespacePresent bool |
| 350 |
|
| 351 |
// These are set when Watch is called |
| 352 |
fakeWatch *watch.FakeWatcher |
| 353 |
requestedLabelSelector labels.Selector |
| 354 |
requestedFieldSelector fields.Selector |
| 355 |
requestedResourceVersion string |
| 356 |
requestedResourceNamespace string |
| 357 |
|
| 358 |
expectedResourceNamespace string |
| 359 |
|
| 360 |
// If non-nil, called inside the WorkFunc when answering update, delete, create. |
| 361 |
// obj receives the original input to the update, delete, or create call. |
| 362 |
injectedFunction func(obj runtime.Object) (returnObj runtime.Object, err error) |
| 363 |
} |
| 364 |
|
| 365 |
func (storage *SimpleRESTStorage) NamespaceScoped() bool { |
| 366 |
return true |
| 367 |
} |
| 368 |
|
| 369 |
func (storage *SimpleRESTStorage) ConvertToTable(ctx context.Context, obj runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) { |
| 370 |
return rest.NewDefaultTableConvertor(schema.GroupResource{Resource: "simple"}).ConvertToTable(ctx, obj, tableOptions) |
| 371 |
} |
| 372 |
|
| 373 |
func (storate *SimpleRESTStorage) GetSingularName() string { |
| 374 |
return "simple" |
| 375 |
} |
| 376 |
|
| 377 |
func (storage *SimpleRESTStorage) List(ctx context.Context, options *metainternalversion.ListOptions) (runtime.Object, error) { |
| 378 |
storage.checkContext(ctx) |
| 379 |
result := &genericapitesting.SimpleList{ |
| 380 |
ListMeta: metav1.ListMeta{ |
| 381 |
ResourceVersion: "10", |
| 382 |
}, |
| 383 |
Items: storage.list, |
| 384 |
} |
| 385 |
storage.requestedLabelSelector = labels.Everything() |
| 386 |
if options != nil && options.LabelSelector != nil { |
| 387 |
storage.requestedLabelSelector = options.LabelSelector |
| 388 |
} |
| 389 |
storage.requestedFieldSelector = fields.Everything() |
| 390 |
if options != nil && options.FieldSelector != nil { |
| 391 |
storage.requestedFieldSelector = options.FieldSelector |
| 392 |
} |
| 393 |
return result, storage.errors["list"] |
| 394 |
} |
| 395 |
|
| 396 |
type SimpleStream struct { |
| 397 |
version string |
| 398 |
accept string |
| 399 |
contentType string |
| 400 |
err error |
| 401 |
|
| 402 |
io.Reader |
| 403 |
closed bool |
| 404 |
} |
| 405 |
|
| 406 |
func (s *SimpleStream) Close() error { |
| 407 |
s.closed = true |
| 408 |
return nil |
| 409 |
} |
| 410 |
|
| 411 |
func (s *SimpleStream) GetObjectKind() schema.ObjectKind { return schema.EmptyObjectKind } |
| 412 |
func (s *SimpleStream) DeepCopyObject() runtime.Object { |
| 413 |
panic("SimpleStream does not support DeepCopy") |
| 414 |
} |
| 415 |
|
| 416 |
func (s *SimpleStream) InputStream(_ context.Context, version, accept string) (io.ReadCloser, bool, string, error) { |
| 417 |
s.version = version |
| 418 |
s.accept = accept |
| 419 |
return s, false, s.contentType, s.err |
| 420 |
} |
| 421 |
|
| 422 |
type OutputConnect struct { |
| 423 |
response string |
| 424 |
} |
| 425 |
|
| 426 |
func (h *OutputConnect) ServeHTTP(w http.ResponseWriter, req *http.Request) { |
| 427 |
w.Write([]byte(h.response)) |
| 428 |
} |
| 429 |
|
| 430 |
func (storage *SimpleRESTStorage) Get(ctx context.Context, id string, options *metav1.GetOptions) (runtime.Object, error) { |
| 431 |
storage.checkContext(ctx) |
| 432 |
if id == "binary" { |
| 433 |
return storage.stream, storage.errors["get"] |
| 434 |
} |
| 435 |
return storage.item.DeepCopy(), storage.errors["get"] |
| 436 |
} |
| 437 |
|
| 438 |
func (storage *SimpleRESTStorage) checkContext(ctx context.Context) { |
| 439 |
storage.actualNamespace, storage.namespacePresent = request.NamespaceFrom(ctx) |
| 440 |
} |
| 441 |
|
| 442 |
func (storage *SimpleRESTStorage) Delete(ctx context.Context, id string, deleteValidation rest.ValidateObjectFunc, options *metav1.DeleteOptions) (runtime.Object, bool, error) { |
| 443 |
storage.checkContext(ctx) |
| 444 |
storage.deleted = id |
| 445 |
storage.deleteOptions = options |
| 446 |
if err := storage.errors["delete"]; err != nil { |
| 447 |
return nil, false, err |
| 448 |
} |
| 449 |
if err := deleteValidation(ctx, &storage.item); err != nil { |
| 450 |
return nil, false, err |
| 451 |
} |
| 452 |
var obj runtime.Object = &metav1.Status{Status: metav1.StatusSuccess} |
| 453 |
var err error |
| 454 |
if storage.injectedFunction != nil { |
| 455 |
obj, err = storage.injectedFunction(&genericapitesting.Simple{ObjectMeta: metav1.ObjectMeta{Name: id}}) |
| 456 |
} |
| 457 |
return obj, true, err |
| 458 |
} |
| 459 |
|
| 460 |
func (storage *SimpleRESTStorage) New() runtime.Object { |
| 461 |
return &genericapitesting.Simple{} |
| 462 |
} |
| 463 |
|
| 464 |
func (storage *SimpleRESTStorage) NewList() runtime.Object { |
| 465 |
return &genericapitesting.SimpleList{} |
| 466 |
} |
| 467 |
|
| 468 |
func (storage *SimpleRESTStorage) Destroy() { |
| 469 |
} |
| 470 |
|
| 471 |
func (storage *SimpleRESTStorage) Create(ctx context.Context, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error) { |
| 472 |
storage.checkContext(ctx) |
| 473 |
storage.created = obj.(*genericapitesting.Simple) |
| 474 |
if err := storage.errors["create"]; err != nil { |
| 475 |
return nil, err |
| 476 |
} |
| 477 |
var err error |
| 478 |
if storage.injectedFunction != nil { |
| 479 |
obj, err = storage.injectedFunction(obj) |
| 480 |
} |
| 481 |
if err := createValidation(ctx, obj); err != nil { |
| 482 |
return nil, err |
| 483 |
} |
| 484 |
return obj, err |
| 485 |
} |
| 486 |
|
| 487 |
func (storage *SimpleRESTStorage) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) { |
| 488 |
storage.checkContext(ctx) |
| 489 |
obj, err := objInfo.UpdatedObject(ctx, &storage.item) |
| 490 |
if err != nil { |
| 491 |
return nil, false, err |
| 492 |
} |
| 493 |
storage.updated = obj.(*genericapitesting.Simple) |
| 494 |
if err := storage.errors["update"]; err != nil { |
| 495 |
return nil, false, err |
| 496 |
} |
| 497 |
if storage.injectedFunction != nil { |
| 498 |
obj, err = storage.injectedFunction(obj) |
| 499 |
} |
| 500 |
if err := updateValidation(ctx, &storage.item, obj); err != nil { |
| 501 |
return nil, false, err |
| 502 |
} |
| 503 |
return obj, false, err |
| 504 |
} |
| 505 |
|
| 506 |
// Implement ResourceWatcher. |
| 507 |
func (storage *SimpleRESTStorage) Watch(ctx context.Context, options *metainternalversion.ListOptions) (watch.Interface, error) { |
| 508 |
storage.lock.Lock() |
| 509 |
defer storage.lock.Unlock() |
| 510 |
storage.checkContext(ctx) |
| 511 |
storage.requestedLabelSelector = labels.Everything() |
| 512 |
if options != nil && options.LabelSelector != nil { |
| 513 |
storage.requestedLabelSelector = options.LabelSelector |
| 514 |
} |
| 515 |
storage.requestedFieldSelector = fields.Everything() |
| 516 |
if options != nil && options.FieldSelector != nil { |
| 517 |
storage.requestedFieldSelector = options.FieldSelector |
| 518 |
} |
| 519 |
storage.requestedResourceVersion = "" |
| 520 |
if options != nil { |
| 521 |
storage.requestedResourceVersion = options.ResourceVersion |
| 522 |
} |
| 523 |
storage.requestedResourceNamespace = request.NamespaceValue(ctx) |
| 524 |
if err := storage.errors["watch"]; err != nil { |
| 525 |
return nil, err |
| 526 |
} |
| 527 |
storage.fakeWatch = watch.NewFake() |
| 528 |
return storage.fakeWatch, nil |
| 529 |
} |
| 530 |
|
| 531 |
func (storage *SimpleRESTStorage) Watcher() *watch.FakeWatcher { |
| 532 |
storage.lock.Lock() |
| 533 |
defer storage.lock.Unlock() |
| 534 |
return storage.fakeWatch |
| 535 |
} |
| 536 |
|
| 537 |
// Implement Connecter |
| 538 |
type ConnecterRESTStorage struct { |
| 539 |
connectHandler http.Handler |
| 540 |
handlerFunc func() http.Handler |
| 541 |
|
| 542 |
emptyConnectOptions runtime.Object |
| 543 |
receivedConnectOptions runtime.Object |
| 544 |
receivedID string |
| 545 |
receivedResponder rest.Responder |
| 546 |
takesPath string |
| 547 |
} |
| 548 |
|
| 549 |
// Implement Connecter |
| 550 |
var _ = rest.Connecter(&ConnecterRESTStorage{}) |
| 551 |
|
| 552 |
func (s *ConnecterRESTStorage) New() runtime.Object { |
| 553 |
return &genericapitesting.Simple{} |
| 554 |
} |
| 555 |
|
| 556 |
func (s *ConnecterRESTStorage) Destroy() { |
| 557 |
} |
| 558 |
|
| 559 |
func (s *ConnecterRESTStorage) Connect(ctx context.Context, id string, options runtime.Object, responder rest.Responder) (http.Handler, error) { |
| 560 |
s.receivedConnectOptions = options |
| 561 |
s.receivedID = id |
| 562 |
s.receivedResponder = responder |
| 563 |
if s.handlerFunc != nil { |
| 564 |
return s.handlerFunc(), nil |
| 565 |
} |
| 566 |
return s.connectHandler, nil |
| 567 |
} |
| 568 |
|
| 569 |
func (s *ConnecterRESTStorage) ConnectMethods() []string { |
| 570 |
return []string{"GET", "POST", "PUT", "DELETE"} |
| 571 |
} |
| 572 |
|
| 573 |
func (s *ConnecterRESTStorage) NewConnectOptions() (runtime.Object, bool, string) { |
| 574 |
if len(s.takesPath) > 0 { |
| 575 |
return s.emptyConnectOptions, true, s.takesPath |
| 576 |
} |
| 577 |
return s.emptyConnectOptions, false, "" |
| 578 |
} |
| 579 |
|
| 580 |
func (s *ConnecterRESTStorage) GetSingularName() string { |
| 581 |
return "simple" |
| 582 |
} |
| 583 |
|
| 584 |
type MetadataRESTStorage struct { |
| 585 |
*SimpleRESTStorage |
| 586 |
types []string |
| 587 |
} |
| 588 |
|
| 589 |
func (m *MetadataRESTStorage) ProducesMIMETypes(method string) []string { |
| 590 |
return m.types |
| 591 |
} |
| 592 |
|
| 593 |
func (m *MetadataRESTStorage) ProducesObject(verb string) interface{} { |
| 594 |
return nil |
| 595 |
} |
| 596 |
|
| 597 |
var _ rest.StorageMetadata = &MetadataRESTStorage{} |
| 598 |
|
| 599 |
type GetWithOptionsRESTStorage struct { |
| 600 |
*SimpleRESTStorage |
| 601 |
optionsReceived runtime.Object |
| 602 |
takesPath string |
| 603 |
} |
| 604 |
|
| 605 |
func (r *GetWithOptionsRESTStorage) Get(ctx context.Context, name string, options runtime.Object) (runtime.Object, error) { |
| 606 |
if _, ok := options.(*genericapitesting.SimpleGetOptions); !ok { |
| 607 |
return nil, fmt.Errorf("Unexpected options object: %#v", options) |
| 608 |
} |
| 609 |
r.optionsReceived = options |
| 610 |
return r.SimpleRESTStorage.Get(ctx, name, &metav1.GetOptions{}) |
| 611 |
} |
| 612 |
|
| 613 |
func (r *GetWithOptionsRESTStorage) NewGetOptions() (runtime.Object, bool, string) { |
| 614 |
if len(r.takesPath) > 0 { |
| 615 |
return &genericapitesting.SimpleGetOptions{}, true, r.takesPath |
| 616 |
} |
| 617 |
return &genericapitesting.SimpleGetOptions{}, false, "" |
| 618 |
} |
| 619 |
|
| 620 |
var _ rest.GetterWithOptions = &GetWithOptionsRESTStorage{} |
| 621 |
|
| 622 |
type GetWithOptionsRootRESTStorage struct { |
| 623 |
*SimpleTypedStorage |
| 624 |
optionsReceived runtime.Object |
| 625 |
takesPath string |
| 626 |
} |
| 627 |
|
| 628 |
func (r *GetWithOptionsRootRESTStorage) GetSingularName() string { |
| 629 |
return "simple" |
| 630 |
} |
| 631 |
|
| 632 |
func (r *GetWithOptionsRootRESTStorage) NamespaceScoped() bool { |
| 633 |
return false |
| 634 |
} |
| 635 |
|
| 636 |
func (r *GetWithOptionsRootRESTStorage) Get(ctx context.Context, name string, options runtime.Object) (runtime.Object, error) { |
| 637 |
if _, ok := options.(*genericapitesting.SimpleGetOptions); !ok { |
| 638 |
return nil, fmt.Errorf("Unexpected options object: %#v", options) |
| 639 |
} |
| 640 |
r.optionsReceived = options |
| 641 |
return r.SimpleTypedStorage.Get(ctx, name, &metav1.GetOptions{}) |
| 642 |
} |
| 643 |
|
| 644 |
func (r *GetWithOptionsRootRESTStorage) NewGetOptions() (runtime.Object, bool, string) { |
| 645 |
if len(r.takesPath) > 0 { |
| 646 |
return &genericapitesting.SimpleGetOptions{}, true, r.takesPath |
| 647 |
} |
| 648 |
return &genericapitesting.SimpleGetOptions{}, false, "" |
| 649 |
} |
| 650 |
|
| 651 |
var _ rest.GetterWithOptions = &GetWithOptionsRootRESTStorage{} |
| 652 |
|
| 653 |
type NamedCreaterRESTStorage struct { |
| 654 |
*SimpleRESTStorage |
| 655 |
createdName string |
| 656 |
} |
| 657 |
|
| 658 |
func (storage *NamedCreaterRESTStorage) Create(ctx context.Context, name string, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error) { |
| 659 |
storage.checkContext(ctx) |
| 660 |
storage.created = obj.(*genericapitesting.Simple) |
| 661 |
storage.createdName = name |
| 662 |
if err := storage.errors["create"]; err != nil { |
| 663 |
return nil, err |
| 664 |
} |
| 665 |
var err error |
| 666 |
if storage.injectedFunction != nil { |
| 667 |
obj, err = storage.injectedFunction(obj) |
| 668 |
} |
| 669 |
if err := createValidation(ctx, obj); err != nil { |
| 670 |
return nil, err |
| 671 |
} |
| 672 |
return obj, err |
| 673 |
} |
| 674 |
|
| 675 |
type SimpleTypedStorage struct { |
| 676 |
errors map[string]error |
| 677 |
item runtime.Object |
| 678 |
baseType runtime.Object |
| 679 |
|
| 680 |
actualNamespace string |
| 681 |
namespacePresent bool |
| 682 |
} |
| 683 |
|
| 684 |
func (storage *SimpleTypedStorage) New() runtime.Object { |
| 685 |
return storage.baseType |
| 686 |
} |
| 687 |
|
| 688 |
func (storage *SimpleTypedStorage) Destroy() { |
| 689 |
} |
| 690 |
|
| 691 |
func (storage *SimpleTypedStorage) Get(ctx context.Context, id string, options *metav1.GetOptions) (runtime.Object, error) { |
| 692 |
storage.checkContext(ctx) |
| 693 |
return storage.item.DeepCopyObject(), storage.errors["get"] |
| 694 |
} |
| 695 |
|
| 696 |
func (storage *SimpleTypedStorage) checkContext(ctx context.Context) { |
| 697 |
storage.actualNamespace, storage.namespacePresent = request.NamespaceFrom(ctx) |
| 698 |
} |
| 699 |
|
| 700 |
func (storage *SimpleTypedStorage) GetSingularName() string { |
| 701 |
return "simple" |
| 702 |
} |
| 703 |
|
| 704 |
func bodyOrDie(response *http.Response) string { |
| 705 |
defer response.Body.Close() |
| 706 |
body, err := ioutil.ReadAll(response.Body) |
| 707 |
if err != nil { |
| 708 |
panic(err) |
| 709 |
} |
| 710 |
return string(body) |
| 711 |
} |
| 712 |
|
| 713 |
func extractBody(response *http.Response, object runtime.Object) (string, error) { |
| 714 |
return extractBodyDecoder(response, object, codec) |
| 715 |
} |
| 716 |
|
| 717 |
func extractBodyDecoder(response *http.Response, object runtime.Object, decoder runtime.Decoder) (string, error) { |
| 718 |
defer response.Body.Close() |
| 719 |
body, err := ioutil.ReadAll(response.Body) |
| 720 |
if err != nil { |
| 721 |
return string(body), err |
| 722 |
} |
| 723 |
return string(body), runtime.DecodeInto(decoder, body, object) |
| 724 |
} |
| 725 |
|
| 726 |
func extractBodyObject(response *http.Response, decoder runtime.Decoder) (runtime.Object, string, error) { |
| 727 |
defer response.Body.Close() |
| 728 |
body, err := ioutil.ReadAll(response.Body) |
| 729 |
if err != nil { |
| 730 |
return nil, string(body), err |
| 731 |
} |
| 732 |
obj, err := runtime.Decode(decoder, body) |
| 733 |
return obj, string(body), err |
| 734 |
} |
| 735 |
|
| 736 |
func TestNotFound(t *testing.T) { |
| 737 |
type T struct { |
| 738 |
Method string |
| 739 |
Path string |
| 740 |
Status int |
| 741 |
} |
| 742 |
cases := map[string]T{ |
| 743 |
// Positive checks to make sure everything is wired correctly |
| 744 |
"groupless GET root": {"GET", "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/simpleroots", http.StatusOK}, |
| 745 |
"groupless GET namespaced": {"GET", "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/namespaces/ns/simples", http.StatusOK}, |
| 746 |
|
| 747 |
"groupless GET long prefix": {"GET", "/" + grouplessPrefix + "/", http.StatusNotFound}, |
| 748 |
|
| 749 |
"groupless root PATCH method": {"PATCH", "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/simpleroots", http.StatusMethodNotAllowed}, |
| 750 |
"groupless root GET missing storage": {"GET", "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/blah", http.StatusNotFound}, |
| 751 |
"groupless root GET with extra segment": {"GET", "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/simpleroots/bar/baz", http.StatusNotFound}, |
| 752 |
"groupless root DELETE without extra segment": {"DELETE", "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/simpleroots", http.StatusMethodNotAllowed}, |
| 753 |
"groupless root DELETE with extra segment": {"DELETE", "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/simpleroots/bar/baz", http.StatusNotFound}, |
| 754 |
"groupless root PUT without extra segment": {"PUT", "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/simpleroots", http.StatusMethodNotAllowed}, |
| 755 |
"groupless root PUT with extra segment": {"PUT", "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/simpleroots/bar/baz", http.StatusNotFound}, |
| 756 |
"groupless root watch missing storage": {"GET", "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/watch/", http.StatusInternalServerError}, |
| 757 |
|
| 758 |
"groupless namespaced PATCH method": {"PATCH", "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/namespaces/ns/simples", http.StatusMethodNotAllowed}, |
| 759 |
"groupless namespaced GET long prefix": {"GET", "/" + grouplessPrefix + "/", http.StatusNotFound}, |
| 760 |
"groupless namespaced GET missing storage": {"GET", "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/blah", http.StatusNotFound}, |
| 761 |
"groupless namespaced GET with extra segment": {"GET", "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/namespaces/ns/simples/bar/baz", http.StatusNotFound}, |
| 762 |
"groupless namespaced POST with extra segment": {"POST", "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/namespaces/ns/simples/bar", http.StatusMethodNotAllowed}, |
| 763 |
"groupless namespaced DELETE without extra segment": {"DELETE", "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/namespaces/ns/simples", http.StatusMethodNotAllowed}, |
| 764 |
"groupless namespaced DELETE with extra segment": {"DELETE", "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/namespaces/ns/simples/bar/baz", http.StatusNotFound}, |
| 765 |
"groupless namespaced PUT without extra segment": {"PUT", "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/namespaces/ns/simples", http.StatusMethodNotAllowed}, |
| 766 |
"groupless namespaced PUT with extra segment": {"PUT", "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/namespaces/ns/simples/bar/baz", http.StatusNotFound}, |
| 767 |
"groupless namespaced watch missing storage": {"GET", "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/watch/", http.StatusInternalServerError}, |
| 768 |
"groupless namespaced watch with bad method": {"POST", "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/watch/namespaces/ns/simples/bar", http.StatusMethodNotAllowed}, |
| 769 |
"groupless namespaced watch param with bad method": {"POST", "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/namespaces/ns/simples/bar?watch=true", http.StatusMethodNotAllowed}, |
| 770 |
|
| 771 |
// Positive checks to make sure everything is wired correctly |
| 772 |
"GET root": {"GET", "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/simpleroots", http.StatusOK}, |
| 773 |
// TODO: JTL: "GET root item": {"GET", "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/simpleroots/bar", http.StatusOK}, |
| 774 |
"GET namespaced": {"GET", "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/namespaces/ns/simples", http.StatusOK}, |
| 775 |
// TODO: JTL: "GET namespaced item": {"GET", "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/namespaces/ns/simples/bar", http.StatusOK}, |
| 776 |
|
| 777 |
"GET long prefix": {"GET", "/" + prefix + "/", http.StatusNotFound}, |
| 778 |
|
| 779 |
"root PATCH method": {"PATCH", "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/simpleroots", http.StatusMethodNotAllowed}, |
| 780 |
"root GET missing storage": {"GET", "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/blah", http.StatusNotFound}, |
| 781 |
"root GET with extra segment": {"GET", "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/simpleroots/bar/baz", http.StatusNotFound}, |
| 782 |
// TODO: JTL: "root POST with extra segment": {"POST", "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/simpleroots/bar", http.StatusMethodNotAllowed}, |
| 783 |
"root DELETE without extra segment": {"DELETE", "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/simpleroots", http.StatusMethodNotAllowed}, |
| 784 |
"root DELETE with extra segment": {"DELETE", "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/simpleroots/bar/baz", http.StatusNotFound}, |
| 785 |
"root PUT without extra segment": {"PUT", "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/simpleroots", http.StatusMethodNotAllowed}, |
| 786 |
"root PUT with extra segment": {"PUT", "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/simpleroots/bar/baz", http.StatusNotFound}, |
| 787 |
"root watch missing storage": {"GET", "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/watch/", http.StatusInternalServerError}, |
| 788 |
// TODO: JTL: "root watch with bad method": {"POST", "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/watch/simpleroot/bar", http.StatusMethodNotAllowed}, |
| 789 |
|
| 790 |
"namespaced PATCH method": {"PATCH", "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/namespaces/ns/simples", http.StatusMethodNotAllowed}, |
| 791 |
"namespaced GET long prefix": {"GET", "/" + prefix + "/", http.StatusNotFound}, |
| 792 |
"namespaced GET missing storage": {"GET", "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/blah", http.StatusNotFound}, |
| 793 |
"namespaced GET with extra segment": {"GET", "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/namespaces/ns/simples/bar/baz", http.StatusNotFound}, |
| 794 |
"namespaced POST with extra segment": {"POST", "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/namespaces/ns/simples/bar", http.StatusMethodNotAllowed}, |
| 795 |
"namespaced DELETE without extra segment": {"DELETE", "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/namespaces/ns/simples", http.StatusMethodNotAllowed}, |
| 796 |
"namespaced DELETE with extra segment": {"DELETE", "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/namespaces/ns/simples/bar/baz", http.StatusNotFound}, |
| 797 |
"namespaced PUT without extra segment": {"PUT", "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/namespaces/ns/simples", http.StatusMethodNotAllowed}, |
| 798 |
"namespaced PUT with extra segment": {"PUT", "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/namespaces/ns/simples/bar/baz", http.StatusNotFound}, |
| 799 |
"namespaced watch missing storage": {"GET", "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/watch/", http.StatusInternalServerError}, |
| 800 |
"namespaced watch with bad method": {"POST", "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/watch/namespaces/ns/simples/bar", http.StatusMethodNotAllowed}, |
| 801 |
"namespaced watch param with bad method": {"POST", "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/namespaces/ns/simples/bar?watch=true", http.StatusMethodNotAllowed}, |
| 802 |
} |
| 803 |
handler := handle(map[string]rest.Storage{ |
| 804 |
"simples": &SimpleRESTStorage{}, |
| 805 |
"simpleroots": &SimpleRESTStorage{}, |
| 806 |
}) |
| 807 |
server := httptest.NewServer(handler) |
| 808 |
defer server.Close() |
| 809 |
client := http.Client{} |
| 810 |
for k, v := range cases { |
| 811 |
request, err := http.NewRequest(v.Method, server.URL+v.Path, nil) |
| 812 |
if err != nil { |
| 813 |
t.Fatalf("unexpected error: %v", err) |
| 814 |
} |
| 815 |
|
| 816 |
response, err := client.Do(request) |
| 817 |
if err != nil { |
| 818 |
t.Errorf("unexpected error: %v", err) |
| 819 |
} |
| 820 |
|
| 821 |
if response.StatusCode != v.Status { |
| 822 |
t.Errorf("Expected %d for %s (%s), Got %#v", v.Status, v.Method, k, response) |
| 823 |
} |
| 824 |
} |
| 825 |
} |
| 826 |
|
| 827 |
type UnimplementedRESTStorage struct{} |
| 828 |
|
| 829 |
func (UnimplementedRESTStorage) NamespaceScoped() bool { |
| 830 |
return true |
| 831 |
} |
| 832 |
|
| 833 |
func (UnimplementedRESTStorage) New() runtime.Object { |
| 834 |
return &genericapitesting.Simple{} |
| 835 |
} |
| 836 |
|
| 837 |
func (UnimplementedRESTStorage) Destroy() { |
| 838 |
} |
| 839 |
|
| 840 |
func (UnimplementedRESTStorage) GetSingularName() string { |
| 841 |
return "" |
| 842 |
} |
| 843 |
|
| 844 |
// TestUnimplementedRESTStorage ensures that if a rest.Storage does not implement a given |
| 845 |
// method, that it is literally not registered with the server. In the past, |
| 846 |
// we registered everything, and returned method not supported if it didn't support |
| 847 |
// a verb. Now we literally do not register a storage if it does not implement anything. |
| 848 |
// TODO: in future, we should update proxy/redirect |
| 849 |
func TestUnimplementedRESTStorage(t *testing.T) { |
| 850 |
type T struct { |
| 851 |
Method string |
| 852 |
Path string |
| 853 |
ErrCode int |
| 854 |
} |
| 855 |
cases := map[string]T{ |
| 856 |
"groupless GET object": {"GET", "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/foo/bar", http.StatusNotFound}, |
| 857 |
"groupless GET list": {"GET", "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/foo", http.StatusNotFound}, |
| 858 |
"groupless POST list": {"POST", "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/foo", http.StatusNotFound}, |
| 859 |
"groupless PUT object": {"PUT", "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/foo/bar", http.StatusNotFound}, |
| 860 |
"groupless DELETE object": {"DELETE", "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/foo/bar", http.StatusNotFound}, |
| 861 |
"groupless watch list": {"GET", "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/watch/foo", http.StatusNotFound}, |
| 862 |
"groupless watch object": {"GET", "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/watch/foo/bar", http.StatusNotFound}, |
| 863 |
"groupless proxy object": {"GET", "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/proxy/foo/bar", http.StatusNotFound}, |
| 864 |
|
| 865 |
"GET object": {"GET", "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/foo/bar", http.StatusNotFound}, |
| 866 |
"GET list": {"GET", "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/foo", http.StatusNotFound}, |
| 867 |
"POST list": {"POST", "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/foo", http.StatusNotFound}, |
| 868 |
"PUT object": {"PUT", "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/foo/bar", http.StatusNotFound}, |
| 869 |
"DELETE object": {"DELETE", "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/foo/bar", http.StatusNotFound}, |
| 870 |
"watch list": {"GET", "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/watch/foo", http.StatusNotFound}, |
| 871 |
"watch object": {"GET", "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/watch/foo/bar", http.StatusNotFound}, |
| 872 |
"proxy object": {"GET", "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/proxy/foo/bar", http.StatusNotFound}, |
| 873 |
} |
| 874 |
handler := handle(map[string]rest.Storage{ |
| 875 |
"foo": UnimplementedRESTStorage{}, |
| 876 |
}) |
| 877 |
server := httptest.NewServer(handler) |
| 878 |
defer server.Close() |
| 879 |
client := http.Client{} |
| 880 |
for k, v := range cases { |
| 881 |
request, err := http.NewRequest(v.Method, server.URL+v.Path, bytes.NewReader([]byte(`{"kind":"Simple","apiVersion":"version"}`))) |
| 882 |
if err != nil { |
| 883 |
t.Fatalf("unexpected error: %v", err) |
| 884 |
} |
| 885 |
|
| 886 |
response, err := client.Do(request) |
| 887 |
if err != nil { |
| 888 |
t.Fatalf("unexpected error: %v", err) |
| 889 |
} |
| 890 |
defer response.Body.Close() |
| 891 |
data, err := ioutil.ReadAll(response.Body) |
| 892 |
if err != nil { |
| 893 |
t.Fatalf("unexpected error: %v", err) |
| 894 |
} |
| 895 |
if response.StatusCode != v.ErrCode { |
| 896 |
t.Errorf("%s: expected %d for %s, Got %s", k, v.ErrCode, v.Method, string(data)) |
| 897 |
continue |
| 898 |
} |
| 899 |
} |
| 900 |
} |
| 901 |
|
| 902 |
type OnlyGetRESTStorage struct { |
| 903 |
UnimplementedRESTStorage |
| 904 |
} |
| 905 |
|
| 906 |
func (OnlyGetRESTStorage) Get(ctx context.Context, id string, options *metav1.GetOptions) (runtime.Object, error) { |
| 907 |
return nil, nil |
| 908 |
} |
| 909 |
|
| 910 |
func (OnlyGetRESTStorage) NewList() runtime.Object { |
| 911 |
return &genericapitesting.SimpleList{} |
| 912 |
} |
| 913 |
|
| 914 |
func (OnlyGetRESTStorage) List(ctx context.Context, options *metainternalversion.ListOptions) (runtime.Object, error) { |
| 915 |
return nil, nil |
| 916 |
} |
| 917 |
|
| 918 |
func (OnlyGetRESTStorage) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) { |
| 919 |
return nil, nil |
| 920 |
} |
| 921 |
|
| 922 |
// TestSomeUnimplementedRESTStorage ensures that if a rest.Storage does |
| 923 |
// not implement a given method, that it is literally not registered |
| 924 |
// with the server. We need to have at least one verb supported inorder |
| 925 |
// to get a MethodNotAllowed rather than NotFound error. |
| 926 |
func TestSomeUnimplementedRESTStorage(t *testing.T) { |
| 927 |
type T struct { |
| 928 |
Method string |
| 929 |
Path string |
| 930 |
ErrCode int |
| 931 |
} |
| 932 |
|
| 933 |
cases := map[string]T{ |
| 934 |
"groupless POST list": {"POST", "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/namespaces/default/foo", http.StatusMethodNotAllowed}, |
| 935 |
"groupless PUT object": {"PUT", "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/namespaces/default/foo/bar", http.StatusMethodNotAllowed}, |
| 936 |
"groupless DELETE object": {"DELETE", "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/namespaces/default/foo/bar", http.StatusMethodNotAllowed}, |
| 937 |
"groupless DELETE collection": {"DELETE", "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/namespaces/default/foo", http.StatusMethodNotAllowed}, |
| 938 |
"POST list": {"POST", "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/namespaces/default/foo", http.StatusMethodNotAllowed}, |
| 939 |
"PUT object": {"PUT", "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/namespaces/default/foo/bar", http.StatusMethodNotAllowed}, |
| 940 |
"DELETE object": {"DELETE", "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/namespaces/default/foo/bar", http.StatusMethodNotAllowed}, |
| 941 |
"DELETE collection": {"DELETE", "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/namespaces/default/foo", http.StatusMethodNotAllowed}, |
| 942 |
} |
| 943 |
handler := handle(map[string]rest.Storage{ |
| 944 |
"foo": OnlyGetRESTStorage{}, |
| 945 |
}) |
| 946 |
server := httptest.NewServer(handler) |
| 947 |
defer server.Close() |
| 948 |
client := http.Client{} |
| 949 |
for k, v := range cases { |
| 950 |
request, err := http.NewRequest(v.Method, server.URL+v.Path, bytes.NewReader([]byte(`{"kind":"Simple","apiVersion":"version"}`))) |
| 951 |
if err != nil { |
| 952 |
t.Fatalf("unexpected error: %v", err) |
| 953 |
} |
| 954 |
|
| 955 |
response, err := client.Do(request) |
| 956 |
if err != nil { |
| 957 |
t.Fatalf("unexpected error: %v", err) |
| 958 |
} |
| 959 |
defer response.Body.Close() |
| 960 |
data, err := ioutil.ReadAll(response.Body) |
| 961 |
if err != nil { |
| 962 |
t.Fatalf("unexpected error: %v", err) |
| 963 |
} |
| 964 |
if response.StatusCode != v.ErrCode { |
| 965 |
t.Errorf("%s: expected %d for %s, Got %s", k, v.ErrCode, v.Method, string(data)) |
| 966 |
continue |
| 967 |
} |
| 968 |
} |
| 969 |
} |
| 970 |
|
| 971 |
func TestList(t *testing.T) { |
| 972 |
testCases := []struct { |
| 973 |
url string |
| 974 |
namespace string |
| 975 |
legacy bool |
| 976 |
label string |
| 977 |
field string |
| 978 |
}{ |
| 979 |
// Groupless API |
| 980 |
|
| 981 |
// legacy namespace param is ignored |
| 982 |
{ |
| 983 |
url: "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/simple?namespace=", |
| 984 |
namespace: "", |
| 985 |
legacy: true, |
| 986 |
}, |
| 987 |
{ |
| 988 |
url: "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/simple?namespace=other", |
| 989 |
namespace: "", |
| 990 |
legacy: true, |
| 991 |
}, |
| 992 |
{ |
| 993 |
url: "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/simple?namespace=other&labelSelector=a%3Db&fieldSelector=c%3Dd", |
| 994 |
namespace: "", |
| 995 |
legacy: true, |
| 996 |
label: "a=b", |
| 997 |
field: "c=d", |
| 998 |
}, |
| 999 |
// legacy api version is honored |
| 1000 |
{ |
| 1001 |
url: "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/simple", |
| 1002 |
namespace: "", |
| 1003 |
legacy: true, |
| 1004 |
}, |
| 1005 |
{ |
| 1006 |
url: "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/namespaces/other/simple", |
| 1007 |
namespace: "other", |
| 1008 |
legacy: true, |
| 1009 |
}, |
| 1010 |
{ |
| 1011 |
url: "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/namespaces/other/simple?labelSelector=a%3Db&fieldSelector=c%3Dd", |
| 1012 |
namespace: "other", |
| 1013 |
legacy: true, |
| 1014 |
label: "a=b", |
| 1015 |
field: "c=d", |
| 1016 |
}, |
| 1017 |
// list items across all namespaces |
| 1018 |
{ |
| 1019 |
url: "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/simple", |
| 1020 |
namespace: "", |
| 1021 |
legacy: true, |
| 1022 |
}, |
| 1023 |
// list items in a namespace in the path |
| 1024 |
{ |
| 1025 |
url: "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/namespaces/default/simple", |
| 1026 |
namespace: "default", |
| 1027 |
}, |
| 1028 |
{ |
| 1029 |
url: "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/namespaces/other/simple", |
| 1030 |
namespace: "other", |
| 1031 |
}, |
| 1032 |
{ |
| 1033 |
url: "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/namespaces/other/simple?labelSelector=a%3Db&fieldSelector=c%3Dd", |
| 1034 |
namespace: "other", |
| 1035 |
label: "a=b", |
| 1036 |
field: "c=d", |
| 1037 |
}, |
| 1038 |
// list items across all namespaces |
| 1039 |
{ |
| 1040 |
url: "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/simple", |
| 1041 |
namespace: "", |
| 1042 |
}, |
| 1043 |
|
| 1044 |
// Group API |
| 1045 |
|
| 1046 |
// legacy namespace param is ignored |
| 1047 |
{ |
| 1048 |
url: "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/simple?namespace=", |
| 1049 |
namespace: "", |
| 1050 |
legacy: true, |
| 1051 |
}, |
| 1052 |
{ |
| 1053 |
url: "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/simple?namespace=other", |
| 1054 |
namespace: "", |
| 1055 |
legacy: true, |
| 1056 |
}, |
| 1057 |
{ |
| 1058 |
url: "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/simple?namespace=other&labelSelector=a%3Db&fieldSelector=c%3Dd", |
| 1059 |
namespace: "", |
| 1060 |
legacy: true, |
| 1061 |
label: "a=b", |
| 1062 |
field: "c=d", |
| 1063 |
}, |
| 1064 |
// legacy api version is honored |
| 1065 |
{ |
| 1066 |
url: "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/simple", |
| 1067 |
namespace: "", |
| 1068 |
legacy: true, |
| 1069 |
}, |
| 1070 |
{ |
| 1071 |
url: "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/namespaces/other/simple", |
| 1072 |
namespace: "other", |
| 1073 |
legacy: true, |
| 1074 |
}, |
| 1075 |
{ |
| 1076 |
url: "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/namespaces/other/simple?labelSelector=a%3Db&fieldSelector=c%3Dd", |
| 1077 |
namespace: "other", |
| 1078 |
legacy: true, |
| 1079 |
label: "a=b", |
| 1080 |
field: "c=d", |
| 1081 |
}, |
| 1082 |
// list items across all namespaces |
| 1083 |
{ |
| 1084 |
url: "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/simple", |
| 1085 |
namespace: "", |
| 1086 |
legacy: true, |
| 1087 |
}, |
| 1088 |
// list items in a namespace in the path |
| 1089 |
{ |
| 1090 |
url: "/" + prefix + "/" + newGroupVersion.Group + "/" + newGroupVersion.Version + "/namespaces/default/simple", |
| 1091 |
namespace: "default", |
| 1092 |
}, |
| 1093 |
{ |
| 1094 |
url: "/" + prefix + "/" + newGroupVersion.Group + "/" + newGroupVersion.Version + "/namespaces/other/simple", |
| 1095 |
namespace: "other", |
| 1096 |
}, |
| 1097 |
{ |
| 1098 |
url: "/" + prefix + "/" + newGroupVersion.Group + "/" + newGroupVersion.Version + "/namespaces/other/simple?labelSelector=a%3Db&fieldSelector=c%3Dd", |
| 1099 |
namespace: "other", |
| 1100 |
label: "a=b", |
| 1101 |
field: "c=d", |
| 1102 |
}, |
| 1103 |
// list items across all namespaces |
| 1104 |
{ |
| 1105 |
url: "/" + prefix + "/" + newGroupVersion.Group + "/" + newGroupVersion.Version + "/simple", |
| 1106 |
namespace: "", |
| 1107 |
}, |
| 1108 |
} |
| 1109 |
for i, testCase := range testCases { |
| 1110 |
storage := map[string]rest.Storage{} |
| 1111 |
simpleStorage := SimpleRESTStorage{expectedResourceNamespace: testCase.namespace} |
| 1112 |
storage["simple"] = &simpleStorage |
| 1113 |
var handler = handleInternal(storage, admissionControl, nil) |
| 1114 |
server := httptest.NewServer(handler) |
| 1115 |
defer server.Close() |
| 1116 |
|
| 1117 |
resp, err := http.Get(server.URL + testCase.url) |
| 1118 |
if err != nil { |
| 1119 |
t.Errorf("%d: unexpected error: %v", i, err) |
| 1120 |
continue |
| 1121 |
} |
| 1122 |
defer resp.Body.Close() |
| 1123 |
if resp.StatusCode != http.StatusOK { |
| 1124 |
t.Errorf("%d: unexpected status: %d from url %s, Expected: %d, %#v", i, resp.StatusCode, testCase.url, http.StatusOK, resp) |
| 1125 |
body, err := ioutil.ReadAll(resp.Body) |
| 1126 |
if err != nil { |
| 1127 |
t.Errorf("%d: unexpected error: %v", i, err) |
| 1128 |
continue |
| 1129 |
} |
| 1130 |
t.Logf("%d: body: %s", i, string(body)) |
| 1131 |
continue |
| 1132 |
} |
| 1133 |
if !simpleStorage.namespacePresent { |
| 1134 |
t.Errorf("%d: namespace not set", i) |
| 1135 |
} else if simpleStorage.actualNamespace != testCase.namespace { |
| 1136 |
t.Errorf("%d: %q unexpected resource namespace: %s", i, testCase.url, simpleStorage.actualNamespace) |
| 1137 |
} |
| 1138 |
if simpleStorage.requestedLabelSelector == nil || simpleStorage.requestedLabelSelector.String() != testCase.label { |
| 1139 |
t.Errorf("%d: unexpected label selector: expected=%v got=%v", i, testCase.label, simpleStorage.requestedLabelSelector) |
| 1140 |
} |
| 1141 |
if simpleStorage.requestedFieldSelector == nil || simpleStorage.requestedFieldSelector.String() != testCase.field { |
| 1142 |
t.Errorf("%d: unexpected field selector: expected=%v got=%v", i, testCase.field, simpleStorage.requestedFieldSelector) |
| 1143 |
} |
| 1144 |
} |
| 1145 |
} |
| 1146 |
|
| 1147 |
func TestRequestsWithInvalidQuery(t *testing.T) { |
| 1148 |
storage := map[string]rest.Storage{} |
| 1149 |
|
| 1150 |
storage["simple"] = &SimpleRESTStorage{expectedResourceNamespace: "default"} |
| 1151 |
storage["withoptions"] = GetWithOptionsRESTStorage{} |
| 1152 |
|
| 1153 |
var handler = handleInternal(storage, admissionControl, nil) |
| 1154 |
server := httptest.NewServer(handler) |
| 1155 |
defer server.Close() |
| 1156 |
|
| 1157 |
for i, test := range []struct { |
| 1158 |
postfix string |
| 1159 |
method string |
| 1160 |
}{ |
| 1161 |
{"/simple?labelSelector=<invalid>", http.MethodGet}, |
| 1162 |
{"/simple/foo?gracePeriodSeconds=<invalid>", http.MethodDelete}, |
| 1163 |
// {"/simple?labelSelector=<value>", http.MethodDelete}, TODO: implement DeleteCollection in SimpleRESTStorage |
| 1164 |
// {"/simple/foo?export=<invalid>", http.MethodGet}, TODO: there is no invalid bool in conversion. Should we be more strict? |
| 1165 |
// {"/simple/foo?resourceVersion=<invalid>", http.MethodGet}, TODO: there is no invalid resourceVersion. Should we be more strict? |
| 1166 |
// {"/withoptions?labelSelector=<invalid>", http.MethodGet}, TODO: SimpleGetOptions is always valid. Add more validation that can fail. |
| 1167 |
} { |
| 1168 |
baseURL := server.URL + "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/namespaces/default" |
| 1169 |
url := baseURL + test.postfix |
| 1170 |
r, err := http.NewRequest(test.method, url, nil) |
| 1171 |
if err != nil { |
| 1172 |
t.Errorf("%d: unexpected error: %v", i, err) |
| 1173 |
continue |
| 1174 |
} |
| 1175 |
resp, err := http.DefaultClient.Do(r) |
| 1176 |
if err != nil { |
| 1177 |
t.Errorf("%d: unexpected error: %v", i, err) |
| 1178 |
continue |
| 1179 |
} |
| 1180 |
defer resp.Body.Close() |
| 1181 |
if resp.StatusCode != http.StatusBadRequest { |
| 1182 |
t.Errorf("%d: unexpected status: %d from url %s, Expected: %d, %#v", i, resp.StatusCode, url, http.StatusBadRequest, resp) |
| 1183 |
body, err := ioutil.ReadAll(resp.Body) |
| 1184 |
if err != nil { |
| 1185 |
t.Errorf("%d: unexpected error: %v", i, err) |
| 1186 |
continue |
| 1187 |
} |
| 1188 |
t.Logf("%d: body: %s", i, string(body)) |
| 1189 |
} |
| 1190 |
} |
| 1191 |
} |
| 1192 |
|
| 1193 |
func TestListCompression(t *testing.T) { |
| 1194 |
testCases := []struct { |
| 1195 |
url string |
| 1196 |
namespace string |
| 1197 |
legacy bool |
| 1198 |
label string |
| 1199 |
field string |
| 1200 |
acceptEncoding string |
| 1201 |
}{ |
| 1202 |
// list items in a namespace in the path |
| 1203 |
{ |
| 1204 |
url: "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/namespaces/default/simple", |
| 1205 |
namespace: "default", |
| 1206 |
acceptEncoding: "", |
| 1207 |
}, |
| 1208 |
{ |
| 1209 |
url: "/" + grouplessPrefix + "/" + grouplessGroupVersion.Version + "/namespaces/default/simple", |
| 1210 |
namespace: "default", |
| 1211 |
acceptEncoding: "gzip", |
| 1212 |
}, |
| 1213 |
} |
| 1214 |
for i, testCase := range testCases { |
| 1215 |
storage := map[string]rest.Storage{} |
| 1216 |
simpleStorage := SimpleRESTStorage{ |
| 1217 |
expectedResourceNamespace: testCase.namespace, |
| 1218 |
list: []genericapitesting.Simple{ |
| 1219 |
{Other: strings.Repeat("0123456789abcdef", (128*1024/16)+1)}, |
| 1220 |
}, |
| 1221 |
} |
| 1222 |
storage["simple"] = &simpleStorage |
| 1223 |
var handler = handleInternal(storage, admissionControl, nil) |
| 1224 |
|
| 1225 |
handler = genericapifilters.WithRequestInfo(handler, newTestRequestInfoResolver()) |
| 1226 |
|
| 1227 |
server := httptest.NewServer(handler) |
| 1228 |
|
| 1229 |
defer server.Close() |
| 1230 |
|
| 1231 |
req, err := http.NewRequest("GET", server.URL+testCase.url, nil) |
| 1232 |
if err != nil { |
| 1233 |
t.Errorf("%d: unexpected error: %v", i, err) |
| 1234 |
continue |
| 1235 |
} |
| 1236 |
// It's necessary to manually set Accept-Encoding here |
| 1237 |
// to prevent http.DefaultClient from automatically |
| 1238 |
// decoding responses |
| 1239 |
req.Header.Set("Accept-Encoding", testCase.acceptEncoding) |
| 1240 |
resp, err := http.DefaultClient.Do(req) |
| 1241 |
if err != nil { |
| 1242 |
t.Errorf("%d: unexpected error: %v", i, err) |
| 1243 |
continue |
| 1244 |
} |
| 1245 |
defer resp.Body.Close() |
| 1246 |
if resp.StatusCode != http.StatusOK { |
| 1247 |
t.Errorf("%d: unexpected status: %d from url %s, Expected: %d, %#v", i, resp.StatusCode, testCase.url, http.StatusOK, resp) |
| 1248 |
body, err := ioutil.ReadAll(resp.Body) |
| 1249 |
if err != nil { |
| 1250 |
t.Errorf("%d: unexpected error: %v", i, err) |
| 1251 |
continue |
| 1252 |
} |
| 1253 |
t.Logf("%d: body: %s", i, string(body)) |
| 1254 |
continue |
| 1255 |
} |
| 1256 |
if !simpleStorage.namespacePresent { |
| 1257 |
t.Errorf("%d: namespace not set", i) |
| 1258 |
} else if simpleStorage.actualNamespace != testCase.namespace { |
| 1259 |
t.Errorf("%d: %q unexpected resource namespace: %s", i, testCase.url, simpleStorage.actualNamespace) |
| 1260 |
} |
| 1261 |
if simpleStorage.requestedLabelSelector == nil || simpleStorage.requestedLabelSelector.String() != testCase.label { |
| 1262 |
t.Errorf("%d: unexpected label selector: %v", i, simpleStorage.requestedLabelSelector) |
| 1263 |
} |
| 1264 |
if simpleStorage.requestedFieldSelector == nil || simpleStorage.requestedFieldSelector.String() != testCase.field { |
| 1265 |
t.Errorf("%d: unexpected field selector: %v", i, simpleStorage.requestedFieldSelector) |
| 1266 |
} |
| 1267 |
|
| 1268 |
var decoder *json.Decoder |
| 1269 |
if testCase.acceptEncoding == "gzip" { |
| 1270 |
gzipReader, err := gzip.NewReader(resp.Body) |
| 1271 |
if err != nil { |
| 1272 |
t.Fatalf("unexpected error creating gzip reader: %v", err) |
| 1273 |
} |
| 1274 |
decoder = json.NewDecoder(gzipReader) |
| 1275 |
} else { |
| 1276 |
decoder = json.NewDecoder(resp.Body) |
| 1277 |
} |
| 1278 |
var itemOut genericapitesting.SimpleList |
| 1279 |
err = decoder.Decode(&itemOut) |
| 1280 |
if err != nil { |
| 1281 |
t.Errorf("failed to read response body as SimpleList: %v", err) |
| 1282 |
} |
| 1283 |
} |
| 1284 |
} |
| 1285 |
|
| 1286 |
func TestLogs(t *testing.T) { |
| 1287 |
handler := handle(map[string]rest.Storage{}) |
| 1288 |
server := httptest.NewServer(handler) |
| 1289 |
defer server.Close() |
| 1290 |
client := http.Client{} |
| 1291 |
|
| 1292 |
request, err := http.NewRequest("GET", server.URL+"/logs", nil) |
| 1293 |
if err != nil { |
| 1294 |
t.Errorf("unexpected error: %v", err) |
| 1295 |
} |
| 1296 |
|
| 1297 |
response, err := client.Do(request) |
| 1298 |
if err != nil { |
| 1299 |
t.Errorf("unexpected error: %v", err) |
| 1300 |
} |
| 1301 |
|
| 1302 |
body, err := ioutil.ReadAll(response.Body) |
| 1303 |
if err != nil { |
| 1304 |
t.Fatalf("unexpected error: %v", err) |
| 1305 |
} |
| 1306 |
t.Logf("Data: %s", string(body)) |
| 1307 |
} |
| 1308 |
|
| 1309 |
func TestErrorList(t *testing.T) { |
| 1310 |
storage := map[string]rest.Storage{} |
| 1311 |
simpleStorage := SimpleRESTStorage{ |
| 1312 |
errors: map[string]error{"list": fmt.Errorf("test Error")}, |
| 1313 |
} |
| 1314 |
storage["simple"] = &simpleStorage |
| 1315 |
handler := handle(storage) |
| 1316 |
server := httptest.NewServer(handler) |
| 1317 |
defer server.Close() |
| 1318 |
|
| 1319 |
resp, err := http.Get(server.URL + "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/simple") |
| 1320 |
if err != nil { |
| 1321 |
t.Fatalf("unexpected error: %v", err) |
| 1322 |
} |
| 1323 |
|
| 1324 |
if resp.StatusCode != http.StatusInternalServerError { |
| 1325 |
t.Errorf("Unexpected status: %d, Expected: %d, %#v", resp.StatusCode, http.StatusInternalServerError, resp) |
| 1326 |
} |
| 1327 |
} |
| 1328 |
|
| 1329 |
func TestNonEmptyList(t *testing.T) { |
| 1330 |
storage := map[string]rest.Storage{} |
| 1331 |
simpleStorage := SimpleRESTStorage{ |
| 1332 |
list: []genericapitesting.Simple{ |
| 1333 |
{ |
| 1334 |
ObjectMeta: metav1.ObjectMeta{Name: "something", Namespace: "other"}, |
| 1335 |
Other: "foo", |
| 1336 |
}, |
| 1337 |
}, |
| 1338 |
} |
| 1339 |
storage["simple"] = &simpleStorage |
| 1340 |
handler := handle(storage) |
| 1341 |
server := httptest.NewServer(handler) |
| 1342 |
defer server.Close() |
| 1343 |
|
| 1344 |
resp, err := http.Get(server.URL + "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/simple") |
| 1345 |
if err != nil { |
| 1346 |
t.Fatalf("unexpected error: %v", err) |
| 1347 |
} |
| 1348 |
|
| 1349 |
if resp.StatusCode != http.StatusOK { |
| 1350 |
t.Errorf("Unexpected status: %d, Expected: %d, %#v", resp.StatusCode, http.StatusOK, resp) |
| 1351 |
body, err := ioutil.ReadAll(resp.Body) |
| 1352 |
if err != nil { |
| 1353 |
t.Fatalf("unexpected error: %v", err) |
| 1354 |
} |
| 1355 |
t.Logf("Data: %s", string(body)) |
| 1356 |
} |
| 1357 |
|
| 1358 |
var listOut genericapitesting.SimpleList |
| 1359 |
body, err := extractBody(resp, &listOut) |
| 1360 |
if err != nil { |
| 1361 |
t.Fatalf("unexpected error: %v", err) |
| 1362 |
} |
| 1363 |
t.Log(body) |
| 1364 |
|
| 1365 |
if len(listOut.Items) != 1 { |
| 1366 |
t.Errorf("Unexpected response: %#v", listOut) |
| 1367 |
return |
| 1368 |
} |
| 1369 |
if listOut.Items[0].Other != simpleStorage.list[0].Other { |
| 1370 |
t.Errorf("Unexpected data: %#v, %s", listOut.Items[0], string(body)) |
| 1371 |
} |
| 1372 |
} |
| 1373 |
|
| 1374 |
func TestMetadata(t *testing.T) { |
| 1375 |
simpleStorage := &MetadataRESTStorage{&SimpleRESTStorage{}, []string{"text/plain"}} |
| 1376 |
h := handle(map[string]rest.Storage{"simple": simpleStorage}) |
| 1377 |
ws := h.(*defaultAPIServer).container.RegisteredWebServices() |
| 1378 |
if len(ws) == 0 { |
| 1379 |
t.Fatal("no web services registered") |
| 1380 |
} |
| 1381 |
matches := map[string]int{} |
| 1382 |
for _, w := range ws { |
| 1383 |
for _, r := range w.Routes() { |
| 1384 |
t.Logf("%v %v %#v", r.Method, r.Path, r.Produces) |
| 1385 |
s := strings.Join(r.Produces, ",") |
| 1386 |
i := matches[s] |
| 1387 |
matches[s] = i + 1 |
| 1388 |
} |
| 1389 |
} |
| 1390 |
cs := []func() bool{ |
| 1391 |
func() bool { |
| 1392 |
return matches["text/plain,application/json,application/yaml,application/vnd.kubernetes.protobuf"] == 0 |
| 1393 |
}, |
| 1394 |
func() bool { |
| 1395 |
return matches["application/json,application/yaml,application/vnd.kubernetes.protobuf,application/json;stream=watch,application/vnd.kubernetes.protobuf;stream=watch"] == 0 |
| 1396 |
}, |
| 1397 |
func() bool { |
| 1398 |
return matches["application/json,application/yaml,application/vnd.kubernetes.protobuf"] == 0 |
| 1399 |
}, |
| 1400 |
func() bool { |
| 1401 |
return len(matches) != 4 |
| 1402 |
}, |
| 1403 |
} |
| 1404 |
for i, c := range cs { |
| 1405 |
if c() { |
| 1406 |
t.Errorf("[%d]unexpected mime types: %#v", i, matches) |
| 1407 |
} |
| 1408 |
} |
| 1409 |
} |
| 1410 |
|
| 1411 |
func TestGet(t *testing.T) { |
| 1412 |
storage := map[string]rest.Storage{} |
| 1413 |
simpleStorage := SimpleRESTStorage{ |
| 1414 |
item: genericapitesting.Simple{ |
| 1415 |
Other: "foo", |
| 1416 |
}, |
| 1417 |
} |
| 1418 |
storage["simple"] = &simpleStorage |
| 1419 |
handler := handle(storage) |
| 1420 |
server := httptest.NewServer(handler) |
| 1421 |
defer server.Close() |
| 1422 |
|
| 1423 |
resp, err := http.Get(server.URL + "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/namespaces/default/simple/id") |
| 1424 |
if err != nil { |
| 1425 |
t.Fatalf("unexpected error: %v", err) |
| 1426 |
} |
| 1427 |
if resp.StatusCode != http.StatusOK { |
| 1428 |
t.Fatalf("unexpected response: %#v", resp) |
| 1429 |
} |
| 1430 |
var itemOut genericapitesting.Simple |
| 1431 |
body, err := extractBody(resp, &itemOut) |
| 1432 |
if err != nil { |
| 1433 |
t.Errorf("unexpected error: %v", err) |
| 1434 |
} |
| 1435 |
|
| 1436 |
if itemOut.Name != simpleStorage.item.Name { |
| 1437 |
t.Errorf("Unexpected data: %#v, expected %#v (%s)", itemOut, simpleStorage.item, string(body)) |
| 1438 |
} |
| 1439 |
} |
| 1440 |
|
| 1441 |
func BenchmarkGet(b *testing.B) { |
| 1442 |
storage := map[string]rest.Storage{} |
| 1443 |
simpleStorage := SimpleRESTStorage{ |
| 1444 |
item: genericapitesting.Simple{ |
| 1445 |
Other: "foo", |
| 1446 |
}, |
| 1447 |
} |
| 1448 |
storage["simple"] = &simpleStorage |
| 1449 |
handler := handle(storage) |
| 1450 |
server := httptest.NewServer(handler) |
| 1451 |
defer server.Close() |
| 1452 |
|
| 1453 |
u := server.URL + "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/namespaces/default/simple/id" |
| 1454 |
|
| 1455 |
b.ResetTimer() |
| 1456 |
for i := 0; i < b.N; i++ { |
| 1457 |
resp, err := http.Get(u) |
| 1458 |
if err != nil { |
| 1459 |
b.Fatalf("unexpected error: %v", err) |
| 1460 |
} |
| 1461 |
if resp.StatusCode != http.StatusOK { |
| 1462 |
b.Fatalf("unexpected response: %#v", resp) |
| 1463 |
} |
| 1464 |
if _, err := io.Copy(ioutil.Discard, resp.Body); err != nil { |
| 1465 |
b.Fatalf("unable to read body") |
| 1466 |
} |
| 1467 |
} |
| 1468 |
b.StopTimer() |
| 1469 |
} |
| 1470 |
|
| 1471 |
func BenchmarkGetNoCompression(b *testing.B) { |
| 1472 |
storage := map[string]rest.Storage{} |
| 1473 |
simpleStorage := SimpleRESTStorage{ |
| 1474 |
item: genericapitesting.Simple{ |
| 1475 |
Other: "foo", |
| 1476 |
}, |
| 1477 |
} |
| 1478 |
storage["simple"] = &simpleStorage |
| 1479 |
handler := handle(storage) |
| 1480 |
server := httptest.NewServer(handler) |
| 1481 |
defer server.Close() |
| 1482 |
|
| 1483 |
client := &http.Client{ |
| 1484 |
Transport: &http.Transport{ |
| 1485 |
DisableCompression: true, |
| 1486 |
}, |
| 1487 |
} |
| 1488 |
|
| 1489 |
u := server.URL + "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/namespaces/default/simple/id" |
| 1490 |
|
| 1491 |
b.ResetTimer() |
| 1492 |
for i := 0; i < b.N; i++ { |
| 1493 |
resp, err := client.Get(u) |
| 1494 |
if err != nil { |
| 1495 |
b.Fatalf("unexpected error: %v", err) |
| 1496 |
} |
| 1497 |
if resp.StatusCode != http.StatusOK { |
| 1498 |
b.Fatalf("unexpected response: %#v", resp) |
| 1499 |
} |
| 1500 |
if _, err := io.Copy(ioutil.Discard, resp.Body); err != nil { |
| 1501 |
b.Fatalf("unable to read body") |
| 1502 |
} |
| 1503 |
} |
| 1504 |
b.StopTimer() |
| 1505 |
} |
| 1506 |
|
| 1507 |
func TestGetCompression(t *testing.T) { |
| 1508 |
storage := map[string]rest.Storage{} |
| 1509 |
simpleStorage := SimpleRESTStorage{ |
| 1510 |
item: genericapitesting.Simple{ |
| 1511 |
Other: strings.Repeat("0123456789abcdef", (128*1024/16)+1), |
| 1512 |
}, |
| 1513 |
} |
| 1514 |
|
| 1515 |
storage["simple"] = &simpleStorage |
| 1516 |
handler := handle(storage) |
| 1517 |
handler = genericapifilters.WithRequestInfo(handler, newTestRequestInfoResolver()) |
| 1518 |
server := httptest.NewServer(handler) |
| 1519 |
defer server.Close() |
| 1520 |
|
| 1521 |
tests := []struct { |
| 1522 |
acceptEncoding string |
| 1523 |
}{ |
| 1524 |
{acceptEncoding: ""}, |
| 1525 |
{acceptEncoding: "gzip"}, |
| 1526 |
} |
| 1527 |
|
| 1528 |
for _, test := range tests { |
| 1529 |
req, err := http.NewRequest("GET", server.URL+"/"+prefix+"/"+testGroupVersion.Group+"/"+testGroupVersion.Version+"/namespaces/default/simple/id", nil) |
| 1530 |
if err != nil { |
| 1531 |
t.Fatalf("unexpected error creating request: %v", err) |
| 1532 |
} |
| 1533 |
// It's necessary to manually set Accept-Encoding here |
| 1534 |
// to prevent http.DefaultClient from automatically |
| 1535 |
// decoding responses |
| 1536 |
req.Header.Set("Accept-Encoding", test.acceptEncoding) |
| 1537 |
resp, err := http.DefaultClient.Do(req) |
| 1538 |
if err != nil { |
| 1539 |
t.Fatalf("unexpected error: %v", err) |
| 1540 |
} |
| 1541 |
if resp.StatusCode != http.StatusOK { |
| 1542 |
t.Fatalf("unexpected response: %#v", resp) |
| 1543 |
} |
| 1544 |
var decoder *json.Decoder |
| 1545 |
if test.acceptEncoding == "gzip" { |
| 1546 |
gzipReader, err := gzip.NewReader(resp.Body) |
| 1547 |
if err != nil { |
| 1548 |
t.Fatalf("unexpected error creating gzip reader: %v", err) |
| 1549 |
} |
| 1550 |
decoder = json.NewDecoder(gzipReader) |
| 1551 |
} else { |
| 1552 |
decoder = json.NewDecoder(resp.Body) |
| 1553 |
} |
| 1554 |
var itemOut genericapitesting.Simple |
| 1555 |
err = decoder.Decode(&itemOut) |
| 1556 |
if err != nil { |
| 1557 |
t.Errorf("unexpected error: %v", err) |
| 1558 |
} |
| 1559 |
body, err := ioutil.ReadAll(resp.Body) |
| 1560 |
if err != nil { |
| 1561 |
t.Errorf("unexpected error reading body: %v", err) |
| 1562 |
} |
| 1563 |
|
| 1564 |
if itemOut.Name != simpleStorage.item.Name { |
| 1565 |
t.Errorf("Unexpected data: %#v, expected %#v (%s)", itemOut, simpleStorage.item, string(body)) |
| 1566 |
} |
| 1567 |
} |
| 1568 |
} |
| 1569 |
|
| 1570 |
func TestGetPretty(t *testing.T) { |
| 1571 |
storage := map[string]rest.Storage{} |
| 1572 |
simpleStorage := SimpleRESTStorage{ |
| 1573 |
item: genericapitesting.Simple{ |
| 1574 |
Other: "foo", |
| 1575 |
}, |
| 1576 |
} |
| 1577 |
storage["simple"] = &simpleStorage |
| 1578 |
handler := handle(storage) |
| 1579 |
server := httptest.NewServer(handler) |
| 1580 |
defer server.Close() |
| 1581 |
|
| 1582 |
tests := []struct { |
| 1583 |
accept string |
| 1584 |
userAgent string |
| 1585 |
params url.Values |
| 1586 |
pretty bool |
| 1587 |
}{ |
| 1588 |
{accept: runtime.ContentTypeJSON}, |
| 1589 |
{accept: "application/json;pretty=0"}, |
| 1590 |
{accept: runtime.ContentTypeJSON, userAgent: "kubectl"}, |
| 1591 |
{accept: runtime.ContentTypeJSON, params: url.Values{"pretty": {"0"}}}, |
| 1592 |
|
| 1593 |
{pretty: true, accept: runtime.ContentTypeJSON, userAgent: "curl"}, |
| 1594 |
{pretty: true, accept: runtime.ContentTypeJSON, userAgent: "Mozilla/5.0"}, |
| 1595 |
{pretty: true, accept: runtime.ContentTypeJSON, userAgent: "Wget"}, |
| 1596 |
{pretty: true, accept: "application/json;pretty=1"}, |
| 1597 |
{pretty: true, accept: runtime.ContentTypeJSON, params: url.Values{"pretty": {"1"}}}, |
| 1598 |
{pretty: true, accept: runtime.ContentTypeJSON, params: url.Values{"pretty": {"true"}}}, |
| 1599 |
} |
| 1600 |
for i, test := range tests { |
| 1601 |
u, err := url.Parse(server.URL + "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/namespaces/default/simple/id") |
| 1602 |
if err != nil { |
| 1603 |
t.Fatal(err) |
| 1604 |
} |
| 1605 |
u.RawQuery = test.params.Encode() |
| 1606 |
req := &http.Request{Method: "GET", URL: u} |
| 1607 |
req.Header = http.Header{} |
| 1608 |
req.Header.Set("Accept", test.accept) |
| 1609 |
req.Header.Set("User-Agent", test.userAgent) |
| 1610 |
resp, err := http.DefaultClient.Do(req) |
| 1611 |
if err != nil { |
| 1612 |
t.Fatal(err) |
| 1613 |
} |
| 1614 |
if resp.StatusCode != http.StatusOK { |
| 1615 |
t.Fatal(err) |
| 1616 |
} |
| 1617 |
var itemOut genericapitesting.Simple |
| 1618 |
body, err := extractBody(resp, &itemOut) |
| 1619 |
if err != nil { |
| 1620 |
t.Fatal(err) |
| 1621 |
} |
| 1622 |
// to get stable ordering we need to use a go type |
| 1623 |
unstructured := genericapitesting.Simple{} |
| 1624 |
if err := json.Unmarshal([]byte(body), &unstructured); err != nil { |
| 1625 |
t.Fatal(err) |
| 1626 |
} |
| 1627 |
var expect string |
| 1628 |
if test.pretty { |
| 1629 |
out, err := json.MarshalIndent(unstructured, "", " ") |
| 1630 |
if err != nil { |
| 1631 |
t.Fatal(err) |
| 1632 |
} |
| 1633 |
expect = string(out) |
| 1634 |
} else { |
| 1635 |
out, err := json.Marshal(unstructured) |
| 1636 |
if err != nil { |
| 1637 |
t.Fatal(err) |
| 1638 |
} |
| 1639 |
expect = string(out) + "\n" |
| 1640 |
} |
| 1641 |
if expect != body { |
| 1642 |
t.Errorf("%d: body did not match expected:\n%s\n%s", i, body, expect) |
| 1643 |
} |
| 1644 |
} |
| 1645 |
} |
| 1646 |
|
| 1647 |
func TestGetTable(t *testing.T) { |
| 1648 |
now := metav1.Now() |
| 1649 |
obj := genericapitesting.Simple{ |
| 1650 |
ObjectMeta: metav1.ObjectMeta{Name: "foo1", Namespace: "ns1", ResourceVersion: "10", CreationTimestamp: now, UID: types.UID("abcdef0123")}, |
| 1651 |
Other: "foo", |
| 1652 |
} |
| 1653 |
|
| 1654 |
m, err := meta.Accessor(&obj) |
| 1655 |
if err != nil { |
| 1656 |
t.Fatal(err) |
| 1657 |
} |
| 1658 |
var encodedV1Beta1Body []byte |
| 1659 |
{ |
| 1660 |
partial := meta.AsPartialObjectMetadata(m) |
| 1661 |
partial.GetObjectKind().SetGroupVersionKind(metav1beta1.SchemeGroupVersion.WithKind("PartialObjectMetadata")) |
| 1662 |
encodedBody, err := runtime.Encode(metainternalversionscheme.Codecs.LegacyCodec(metav1beta1.SchemeGroupVersion), partial) |
| 1663 |
if err != nil { |
| 1664 |
t.Fatal(err) |
| 1665 |
} |
| 1666 |
// the codec includes a trailing newline that is not present during decode |
| 1667 |
encodedV1Beta1Body = bytes.TrimSpace(encodedBody) |
| 1668 |
} |
| 1669 |
var encodedV1Body []byte |
| 1670 |
{ |
| 1671 |
partial := meta.AsPartialObjectMetadata(m) |
| 1672 |
partial.GetObjectKind().SetGroupVersionKind(metav1.SchemeGroupVersion.WithKind("PartialObjectMetadata")) |
| 1673 |
encodedBody, err := runtime.Encode(metainternalversionscheme.Codecs.LegacyCodec(metav1.SchemeGroupVersion), partial) |
| 1674 |
if err != nil { |
| 1675 |
t.Fatal(err) |
| 1676 |
} |
| 1677 |
// the codec includes a trailing newline that is not present during decode |
| 1678 |
encodedV1Body = bytes.TrimSpace(encodedBody) |
| 1679 |
} |
| 1680 |
|
| 1681 |
metaDoc := metav1.ObjectMeta{}.SwaggerDoc() |
| 1682 |
|
| 1683 |
tests := []struct { |
| 1684 |
accept string |
| 1685 |
params url.Values |
| 1686 |
pretty bool |
| 1687 |
expected *metav1.Table |
| 1688 |
statusCode int |
| 1689 |
item bool |
| 1690 |
}{ |
| 1691 |
{ |
| 1692 |
accept: "application/json;as=Table;v=v1alpha1;g=meta.k8s.io", |
| 1693 |
statusCode: http.StatusNotAcceptable, |
| 1694 |
}, |
| 1695 |
{ |
| 1696 |
accept: runtime.ContentTypeProtobuf + ";as=Table;v=v1beta1;g=meta.k8s.io", |
| 1697 |
statusCode: http.StatusNotAcceptable, |
| 1698 |
}, |
| 1699 |
{ |
| 1700 |
accept: runtime.ContentTypeProtobuf + ";as=Table;v=v1;g=meta.k8s.io", |
| 1701 |
statusCode: http.StatusNotAcceptable, |
| 1702 |
}, |
| 1703 |
|
| 1704 |
{ |
| 1705 |
item: true, |
| 1706 |
accept: "application/json;as=Table;v=v1;g=meta.k8s.io", |
| 1707 |
expected: &metav1.Table{ |
| 1708 |
TypeMeta: metav1.TypeMeta{Kind: "Table", APIVersion: "meta.k8s.io/v1"}, |
| 1709 |
ListMeta: metav1.ListMeta{ResourceVersion: "10"}, |
| 1710 |
ColumnDefinitions: []metav1.TableColumnDefinition{ |
| 1711 |
{Name: "Name", Type: "string", Format: "name", Description: metaDoc["name"]}, |
| 1712 |
{Name: "Created At", Type: "date", Description: metaDoc["creationTimestamp"]}, |
| 1713 |
}, |
| 1714 |
Rows: []metav1.TableRow{ |
| 1715 |
{Cells: []interface{}{"foo1", now.Time.UTC().Format(time.RFC3339)}, Object: runtime.RawExtension{Raw: encodedV1Body}}, |
| 1716 |
}, |
| 1717 |
}, |
| 1718 |
}, |
| 1719 |
{ |
| 1720 |
item: true, |
| 1721 |
accept: "application/json;as=Table;v=v1beta1;g=meta.k8s.io", |
| 1722 |
expected: &metav1.Table{ |
| 1723 |
TypeMeta: metav1.TypeMeta{Kind: "Table", APIVersion: "meta.k8s.io/v1beta1"}, |
| 1724 |
ListMeta: metav1.ListMeta{ResourceVersion: "10"}, |
| 1725 |
ColumnDefinitions: []metav1.TableColumnDefinition{ |
| 1726 |
{Name: "Name", Type: "string", Format: "name", Description: metaDoc["name"]}, |
| 1727 |
{Name: "Created At", Type: "date", Description: metaDoc["creationTimestamp"]}, |
| 1728 |
}, |
| 1729 |
Rows: []metav1.TableRow{ |
| 1730 |
{Cells: []interface{}{"foo1", now.Time.UTC().Format(time.RFC3339)}, Object: runtime.RawExtension{Raw: encodedV1Beta1Body}}, |
| 1731 |
}, |
| 1732 |
}, |
| 1733 |
}, |
| 1734 |
{ |
| 1735 |
item: true, |
| 1736 |
accept: strings.Join([]string{ |
| 1737 |
runtime.ContentTypeProtobuf + ";as=Table;v=v1beta1;g=meta.k8s.io", |
| 1738 |
"application/json;as=Table;v=v1beta1;g=meta.k8s.io", |
| 1739 |
}, ","), |
| 1740 |
expected: &metav1.Table{ |
| 1741 |
TypeMeta: metav1.TypeMeta{Kind: "Table", APIVersion: "meta.k8s.io/v1beta1"}, |
| 1742 |
ListMeta: metav1.ListMeta{ResourceVersion: "10"}, |
| 1743 |
ColumnDefinitions: []metav1.TableColumnDefinition{ |
| 1744 |
{Name: "Name", Type: "string", Format: "name", Description: metaDoc["name"]}, |
| 1745 |
{Name: "Created At", Type: "date", Description: metaDoc["creationTimestamp"]}, |
| 1746 |
}, |
| 1747 |
Rows: []metav1.TableRow{ |
| 1748 |
{Cells: []interface{}{"foo1", now.Time.UTC().Format(time.RFC3339)}, Object: runtime.RawExtension{Raw: encodedV1Beta1Body}}, |
| 1749 |
}, |
| 1750 |
}, |
| 1751 |
}, |
| 1752 |
{ |
| 1753 |
item: true, |
| 1754 |
accept: "application/json;as=Table;v=v1beta1;g=meta.k8s.io", |
| 1755 |
params: url.Values{"includeObject": []string{"Metadata"}}, |
| 1756 |
expected: &metav1.Table{ |
| 1757 |
TypeMeta: metav1.TypeMeta{Kind: "Table", APIVersion: "meta.k8s.io/v1beta1"}, |
| 1758 |
ListMeta: metav1.ListMeta{ResourceVersion: "10"}, |
| 1759 |
ColumnDefinitions: []metav1.TableColumnDefinition{ |
| 1760 |
{Name: "Name", Type: "string", Format: "name", Description: metaDoc["name"]}, |
| 1761 |
{Name: "Created At", Type: "date", Description: metaDoc["creationTimestamp"]}, |
| 1762 |
}, |
| 1763 |
Rows: []metav1.TableRow{ |
| 1764 |
{Cells: []interface{}{"foo1", now.Time.UTC().Format(time.RFC3339)}, Object: runtime.RawExtension{Raw: encodedV1Beta1Body}}, |
| 1765 |
}, |
| 1766 |
}, |
| 1767 |
}, |
| 1768 |
{ |
| 1769 |
accept: "application/json;as=Table;v=v1beta1;g=meta.k8s.io", |
| 1770 |
params: url.Values{"includeObject": []string{"Metadata"}}, |
| 1771 |
expected: &metav1.Table{ |
| 1772 |
TypeMeta: metav1.TypeMeta{Kind: "Table", APIVersion: "meta.k8s.io/v1beta1"}, |
| 1773 |
ListMeta: metav1.ListMeta{ResourceVersion: "10"}, |
| 1774 |
ColumnDefinitions: []metav1.TableColumnDefinition{ |
| 1775 |
{Name: "Name", Type: "string", Format: "name", Description: metaDoc["name"]}, |
| 1776 |
{Name: "Created At", Type: "date", Description: metaDoc["creationTimestamp"]}, |
| 1777 |
}, |
| 1778 |
Rows: []metav1.TableRow{ |
| 1779 |
{Cells: []interface{}{"foo1", now.Time.UTC().Format(time.RFC3339)}, Object: runtime.RawExtension{Raw: encodedV1Beta1Body}}, |
| 1780 |
}, |
| 1781 |
}, |
| 1782 |
}, |
| 1783 |
} |
| 1784 |
for i, test := range tests { |
| 1785 |
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { |
| 1786 |
storage := map[string]rest.Storage{} |
| 1787 |
simpleStorage := SimpleRESTStorage{ |
| 1788 |
item: obj, |
| 1789 |
list: []genericapitesting.Simple{obj}, |
| 1790 |
} |
| 1791 |
storage["simple"] = &simpleStorage |
| 1792 |
handler := handle(storage) |
| 1793 |
server := httptest.NewServer(handler) |
| 1794 |
defer server.Close() |
| 1795 |
|
| 1796 |
var id string |
| 1797 |
if test.item { |
| 1798 |
id = "/id" |
| 1799 |
} |
| 1800 |
u, err := url.Parse(server.URL + "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/namespaces/default/simple" + id) |
| 1801 |
if err != nil { |
| 1802 |
t.Fatal(err) |
| 1803 |
} |
| 1804 |
u.RawQuery = test.params.Encode() |
| 1805 |
req := &http.Request{Method: "GET", URL: u} |
| 1806 |
req.Header = http.Header{} |
| 1807 |
req.Header.Set("Accept", test.accept) |
| 1808 |
resp, err := http.DefaultClient.Do(req) |
| 1809 |
if err != nil { |
| 1810 |
t.Fatal(err) |
| 1811 |
} |
| 1812 |
if test.statusCode != 0 { |
| 1813 |
if resp.StatusCode != test.statusCode { |
| 1814 |
t.Errorf("%d: unexpected response: %#v", i, resp) |
| 1815 |
} |
| 1816 |
obj, _, err := extractBodyObject(resp, unstructured.UnstructuredJSONScheme) |
| 1817 |
if err != nil { |
| 1818 |
t.Fatalf("%d: unexpected body read error: %v", i, err) |
| 1819 |
} |
| 1820 |
gvk := schema.GroupVersionKind{Version: "v1", Kind: "Status"} |
| 1821 |
if obj.GetObjectKind().GroupVersionKind() != gvk { |
| 1822 |
t.Fatalf("%d: unexpected error body: %#v", i, obj) |
| 1823 |
} |
| 1824 |
return |
| 1825 |
} |
| 1826 |
if resp.StatusCode != http.StatusOK { |
| 1827 |
t.Errorf("%d: unexpected response: %#v", i, resp) |
| 1828 |
} |
| 1829 |
var itemOut metav1.Table |
| 1830 |
body, err := extractBody(resp, &itemOut) |
| 1831 |
if err != nil { |
| 1832 |
t.Fatal(err) |
| 1833 |
} |
| 1834 |
if !reflect.DeepEqual(test.expected, &itemOut) { |
| 1835 |
t.Log(body) |
| 1836 |
t.Errorf("%d: did not match: %s", i, cmp.Diff(test.expected, &itemOut)) |
| 1837 |
} |
| 1838 |
}) |
| 1839 |
} |
| 1840 |
} |
| 1841 |
|
| 1842 |
func TestWatchTable(t *testing.T) { |
| 1843 |
obj := genericapitesting.Simple{ |
| 1844 |
ObjectMeta: metav1.ObjectMeta{Name: "foo1", Namespace: "ns1", ResourceVersion: "10", CreationTimestamp: metav1.NewTime(time.Unix(1, 0)), UID: types.UID("abcdef0123")}, |
| 1845 |
Other: "foo", |
| 1846 |
} |
| 1847 |
|
| 1848 |
m, err := meta.Accessor(&obj) |
| 1849 |
if err != nil { |
| 1850 |
t.Fatal(err) |
| 1851 |
} |
| 1852 |
partial := meta.AsPartialObjectMetadata(m) |
| 1853 |
partial.GetObjectKind().SetGroupVersionKind(metav1beta1.SchemeGroupVersion.WithKind("PartialObjectMetadata")) |
| 1854 |
encodedBody, err := runtime.Encode(metainternalversionscheme.Codecs.LegacyCodec(metav1beta1.SchemeGroupVersion), partial) |
| 1855 |
if err != nil { |
| 1856 |
t.Fatal(err) |
| 1857 |
} |
| 1858 |
// the codec includes a trailing newline that is not present during decode |
| 1859 |
encodedBody = bytes.TrimSpace(encodedBody) |
| 1860 |
|
| 1861 |
encodedBodyV1, err := runtime.Encode(metainternalversionscheme.Codecs.LegacyCodec(metav1.SchemeGroupVersion), partial) |
| 1862 |
if err != nil { |
| 1863 |
t.Fatal(err) |
| 1864 |
} |
| 1865 |
// the codec includes a trailing newline that is not present during decode |
| 1866 |
encodedBodyV1 = bytes.TrimSpace(encodedBodyV1) |
| 1867 |
|
| 1868 |
metaDoc := metav1.ObjectMeta{}.SwaggerDoc() |
| 1869 |
|
| 1870 |
s := metainternalversionscheme.Codecs.SupportedMediaTypes()[0].Serializer |
| 1871 |
|
| 1872 |
tests := []struct { |
| 1873 |
accept string |
| 1874 |
params url.Values |
| 1875 |
send func(w *watch.FakeWatcher) |
| 1876 |
|
| 1877 |
expected []*metav1.WatchEvent |
| 1878 |
contentType string |
| 1879 |
statusCode int |
| 1880 |
item bool |
| 1881 |
}{ |
| 1882 |
{ |
| 1883 |
accept: "application/json;as=Table;v=v1alpha1;g=meta.k8s.io", |
| 1884 |
statusCode: http.StatusNotAcceptable, |
| 1885 |
}, |
| 1886 |
{ |
| 1887 |
accept: "application/json;as=Table;v=v1beta1;g=meta.k8s.io", |
| 1888 |
send: func(w *watch.FakeWatcher) { |
| 1889 |
w.Add(&obj) |
| 1890 |
}, |
| 1891 |
expected: []*metav1.WatchEvent{ |
| 1892 |
{ |
| 1893 |
Type: "ADDED", |
| 1894 |
Object: runtime.RawExtension{ |
| 1895 |
Raw: []byte(strings.TrimSpace(runtime.EncodeOrDie(s, &metav1.Table{ |
| 1896 |
TypeMeta: metav1.TypeMeta{Kind: "Table", APIVersion: "meta.k8s.io/v1beta1"}, |
| 1897 |
ListMeta: metav1.ListMeta{ResourceVersion: "10"}, |
| 1898 |
ColumnDefinitions: []metav1.TableColumnDefinition{ |
| 1899 |
{Name: "Name", Type: "string", Format: "name", Description: metaDoc["name"]}, |
| 1900 |
{Name: "Created At", Type: "date", Description: metaDoc["creationTimestamp"]}, |
| 1901 |
}, |
| 1902 |
Rows: []metav1.TableRow{ |
| 1903 |
{Cells: []interface{}{"foo1", time.Unix(1, 0).UTC().Format(time.RFC3339)}, Object: runtime.RawExtension{Raw: encodedBody}}, |
| 1904 |
}, |
| 1905 |
}))), |
| 1906 |
}, |
| 1907 |
}, |
| 1908 |
}, |
| 1909 |
}, |
| 1910 |
{ |
| 1911 |
accept: "application/json;as=Table;v=v1beta1;g=meta.k8s.io", |
| 1912 |
send: func(w *watch.FakeWatcher) { |
| 1913 |
w.Add(&obj) |
| 1914 |
w.Modify(&obj) |
| 1915 |
}, |
| 1916 |
expected: []*metav1.WatchEvent{ |
| 1917 |
{ |
| 1918 |
Type: "ADDED", |
| 1919 |
Object: runtime.RawExtension{ |
| 1920 |
Raw: []byte(strings.TrimSpace(runtime.EncodeOrDie(s, &metav1.Table{ |
| 1921 |
TypeMeta: metav1.TypeMeta{Kind: "Table", APIVersion: "meta.k8s.io/v1beta1"}, |
| 1922 |
ListMeta: metav1.ListMeta{ResourceVersion: "10"}, |
| 1923 |
ColumnDefinitions: []metav1.TableColumnDefinition{ |
| 1924 |
{Name: "Name", Type: "string", Format: "name", Description: metaDoc["name"]}, |
| 1925 |
{Name: "Created At", Type: "date", Description: metaDoc["creationTimestamp"]}, |
| 1926 |
}, |
| 1927 |
Rows: []metav1.TableRow{ |
| 1928 |
{Cells: []interface{}{"foo1", time.Unix(1, 0).UTC().Format(time.RFC3339)}, Object: runtime.RawExtension{Raw: encodedBody}}, |
| 1929 |
}, |
| 1930 |
}))), |
| 1931 |
}, |
| 1932 |
}, |
| 1933 |
{ |
| 1934 |
Type: "MODIFIED", |
| 1935 |
Object: runtime.RawExtension{ |
| 1936 |
Raw: []byte(strings.TrimSpace(runtime.EncodeOrDie(s, &metav1.Table{ |
| 1937 |
TypeMeta: metav1.TypeMeta{Kind: "Table", APIVersion: "meta.k8s.io/v1beta1"}, |
| 1938 |
ListMeta: metav1.ListMeta{ResourceVersion: "10"}, |
| 1939 |
Rows: []metav1.TableRow{ |
| 1940 |
{Cells: []interface{}{"foo1", time.Unix(1, 0).UTC().Format(time.RFC3339)}, Object: runtime.RawExtension{Raw: encodedBody}}, |
| 1941 |
}, |
| 1942 |
}))), |
| 1943 |
}, |
| 1944 |
}, |
| 1945 |
}, |
| 1946 |
}, |
| 1947 |
{ |
| 1948 |
accept: "application/json;as=Table;v=v1;g=meta.k8s.io", |
| 1949 |
send: func(w *watch.FakeWatcher) { |
| 1950 |
w.Add(&obj) |
| 1951 |
w.Modify(&obj) |
| 1952 |
}, |
| 1953 |
expected: []*metav1.WatchEvent{ |
| 1954 |
{ |
| 1955 |
Type: "ADDED", |
| 1956 |
Object: runtime.RawExtension{ |
| 1957 |
Raw: []byte(strings.TrimSpace(runtime.EncodeOrDie(s, &metav1.Table{ |
| 1958 |
TypeMeta: metav1.TypeMeta{Kind: "Table", APIVersion: "meta.k8s.io/v1"}, |
| 1959 |
ListMeta: metav1.ListMeta{ResourceVersion: "10"}, |
| 1960 |
ColumnDefinitions: []metav1.TableColumnDefinition{ |
| 1961 |
{Name: "Name", Type: "string", Format: "name", Description: metaDoc["name"]}, |
| 1962 |
{Name: "Created At", Type: "date", Description: metaDoc["creationTimestamp"]}, |
| 1963 |
}, |
| 1964 |
Rows: []metav1.TableRow{ |
| 1965 |
{Cells: []interface{}{"foo1", time.Unix(1, 0).UTC().Format(time.RFC3339)}, Object: runtime.RawExtension{Raw: encodedBodyV1}}, |
| 1966 |
}, |
| 1967 |
}))), |
| 1968 |
}, |
| 1969 |
}, |
| 1970 |
{ |
| 1971 |
Type: "MODIFIED", |
| 1972 |
Object: runtime.RawExtension{ |
| 1973 |
Raw: []byte(strings.TrimSpace(runtime.EncodeOrDie(s, &metav1.Table{ |
| 1974 |
TypeMeta: metav1.TypeMeta{Kind: "Table", APIVersion: "meta.k8s.io/v1"}, |
| 1975 |
ListMeta: metav1.ListMeta{ResourceVersion: "10"}, |
| 1976 |
Rows: []metav1.TableRow{ |
| 1977 |
{Cells: []interface{}{"foo1", time.Unix(1, 0).UTC().Format(time.RFC3339)}, Object: runtime.RawExtension{Raw: encodedBodyV1}}, |
| 1978 |
}, |
| 1979 |
}))), |
| 1980 |
}, |
| 1981 |
}, |
| 1982 |
}, |
| 1983 |
}, |
| 1984 |
} |
| 1985 |
for i, test := range tests { |
| 1986 |
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { |
| 1987 |
storage := map[string]rest.Storage{} |
| 1988 |
simpleStorage := SimpleRESTStorage{ |
| 1989 |
item: obj, |
| 1990 |
list: []genericapitesting.Simple{obj}, |
| 1991 |
} |
| 1992 |
|
| 1993 |
storage["simple"] = &simpleStorage |
| 1994 |
handler := handle(storage) |
| 1995 |
server := httptest.NewServer(handler) |
| 1996 |
defer server.Close() |
| 1997 |
|
| 1998 |
var id string |
| 1999 |
if test.item { |
| 2000 |
id = "/id" |
| 2001 |
} |
| 2002 |
u, err := url.Parse(server.URL + "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/namespaces/default/simple") |
| 2003 |
if err != nil { |
| 2004 |
t.Fatal(err) |
| 2005 |
} |
| 2006 |
if test.params == nil { |
| 2007 |
test.params = url.Values{} |
| 2008 |
} |
| 2009 |
if test.item { |
| 2010 |
test.params["fieldSelector"] = []string{fmt.Sprintf("metadata.name=%s", id)} |
| 2011 |
} |
| 2012 |
test.params["watch"] = []string{"1"} |
| 2013 |
|
| 2014 |
u.RawQuery = test.params.Encode() |
| 2015 |
req := &http.Request{Method: "GET", URL: u} |
| 2016 |
req.Header = http.Header{} |
| 2017 |
req.Header.Set("Accept", test.accept) |
| 2018 |
resp, err := http.DefaultClient.Do(req) |
| 2019 |
if err != nil { |
| 2020 |
t.Fatal(err) |
| 2021 |
} |
| 2022 |
defer resp.Body.Close() |
| 2023 |
if test.statusCode != 0 { |
| 2024 |
if resp.StatusCode != test.statusCode { |
| 2025 |
t.Fatalf("%d: unexpected response: %#v", i, resp) |
| 2026 |
} |
| 2027 |
obj, _, err := extractBodyObject(resp, unstructured.UnstructuredJSONScheme) |
| 2028 |
if err != nil { |
| 2029 |
t.Fatalf("%d: unexpected body read error: %v", i, err) |
| 2030 |
} |
| 2031 |
gvk := schema.GroupVersionKind{Version: "v1", Kind: "Status"} |
| 2032 |
if obj.GetObjectKind().GroupVersionKind() != gvk { |
| 2033 |
t.Fatalf("%d: unexpected error body: %#v", i, obj) |
| 2034 |
} |
| 2035 |
return |
| 2036 |
} |
| 2037 |
if resp.StatusCode != http.StatusOK { |
| 2038 |
t.Fatalf("%d: unexpected response: %#v", i, resp) |
| 2039 |
} |
| 2040 |
|
| 2041 |
go func() { |
| 2042 |
defer simpleStorage.fakeWatch.Stop() |
| 2043 |
test.send(simpleStorage.fakeWatch) |
| 2044 |
}() |
| 2045 |
|
| 2046 |
body, err := ioutil.ReadAll(resp.Body) |
| 2047 |
if err != nil { |
| 2048 |
t.Fatal(err) |
| 2049 |
} |
| 2050 |
t.Logf("Body:\n%s", string(body)) |
| 2051 |
d := watcher(resp.Header.Get("Content-Type"), ioutil.NopCloser(bytes.NewReader(body))) |
| 2052 |
var actual []*metav1.WatchEvent |
| 2053 |
for { |
| 2054 |
var event metav1.WatchEvent |
| 2055 |
_, _, err := d.Decode(nil, &event) |
| 2056 |
if err == io.EOF { |
| 2057 |
break |
| 2058 |
} |
| 2059 |
if err != nil { |
| 2060 |
t.Fatal(err) |
| 2061 |
} |
| 2062 |
actual = append(actual, &event) |
| 2063 |
} |
| 2064 |
if !reflect.DeepEqual(test.expected, actual) { |
| 2065 |
t.Fatalf("unexpected: %s", cmp.Diff(test.expected, actual)) |
| 2066 |
} |
| 2067 |
}) |
| 2068 |
} |
| 2069 |
} |
| 2070 |
|
| 2071 |
func watcher(mediaType string, r io.ReadCloser) streaming.Decoder { |
| 2072 |
info, ok := runtime.SerializerInfoForMediaType(metainternalversionscheme.Codecs.SupportedMediaTypes(), mediaType) |
| 2073 |
if !ok || info.StreamSerializer == nil { |
| 2074 |
panic(info) |
| 2075 |
} |
| 2076 |
streamSerializer := info.StreamSerializer |
| 2077 |
fr := streamSerializer.Framer.NewFrameReader(r) |
| 2078 |
d := streaming.NewDecoder(fr, streamSerializer.Serializer) |
| 2079 |
return d |
| 2080 |
} |
| 2081 |
|
| 2082 |
func TestGetPartialObjectMetadata(t *testing.T) { |
| 2083 |
now := metav1.Time{Time: metav1.Now().Rfc3339Copy().Local()} |
| 2084 |
storage := map[string]rest.Storage{} |
| 2085 |
simpleStorage := SimpleRESTStorage{ |
| 2086 |
item: genericapitesting.Simple{ |
| 2087 |
ObjectMeta: metav1.ObjectMeta{Name: "foo1", Namespace: "ns1", CreationTimestamp: now, UID: types.UID("abcdef0123")}, |
| 2088 |
Other: "foo", |
| 2089 |
}, |
| 2090 |
list: []genericapitesting.Simple{ |
| 2091 |
{ |
| 2092 |
ObjectMeta: metav1.ObjectMeta{Name: "foo1", Namespace: "ns1", CreationTimestamp: now, UID: types.UID("newer")}, |
| 2093 |
Other: "foo", |
| 2094 |
}, |
| 2095 |
{ |
| 2096 |
ObjectMeta: metav1.ObjectMeta{Name: "foo2", Namespace: "ns2", CreationTimestamp: now, UID: types.UID("older")}, |
| 2097 |
Other: "bar", |
| 2098 |
}, |
| 2099 |
}, |
| 2100 |
} |
| 2101 |
storage["simple"] = &simpleStorage |
| 2102 |
handler := handle(storage) |
| 2103 |
server := httptest.NewServer(handler) |
| 2104 |
defer server.Close() |
| 2105 |
|
| 2106 |
tests := []struct { |
| 2107 |
accept string |
| 2108 |
params url.Values |
| 2109 |
pretty bool |
| 2110 |
list bool |
| 2111 |
expected runtime.Object |
| 2112 |
expectKind schema.GroupVersionKind |
| 2113 |
statusCode int |
| 2114 |
}{ |
| 2115 |
{ |
| 2116 |
accept: "application/json;as=PartialObjectMetadata;v=v1alpha1;g=meta.k8s.io", |
| 2117 |
statusCode: http.StatusNotAcceptable, |
| 2118 |
}, |
| 2119 |
{ |
| 2120 |
accept: "application/json;as=PartialObjectMetadata;v=v1alpha1;g=meta.k8s.io, application/json", |
| 2121 |
expectKind: schema.GroupVersionKind{Kind: "Simple", Group: testGroupVersion.Group, Version: testGroupVersion.Version}, |
| 2122 |
}, |
| 2123 |
{ |
| 2124 |
accept: "application/json;as=PartialObjectMetadata;v=v1beta1;g=meta.k8s.io, application/json", |
| 2125 |
expectKind: schema.GroupVersionKind{Kind: "PartialObjectMetadata", Group: "meta.k8s.io", Version: "v1beta1"}, |
| 2126 |
}, |
| 2127 |
{ |
| 2128 |
list: true, |
| 2129 |
accept: "application/json;as=PartialObjectMetadata;v=v1beta1;g=meta.k8s.io", |
| 2130 |
statusCode: http.StatusNotAcceptable, |
| 2131 |
}, |
| 2132 |
|
| 2133 |
// verify preferred version overrides supported version |
| 2134 |
{ |
| 2135 |
accept: "application/json;as=PartialObjectMetadata;v=v1beta1;g=meta.k8s.io, application/json;as=PartialObjectMetadata;v=v1;g=meta.k8s.io, application/json", |
| 2136 |
expectKind: schema.GroupVersionKind{Kind: "PartialObjectMetadata", Group: "meta.k8s.io", Version: "v1beta1"}, |
| 2137 |
}, |
| 2138 |
{ |
| 2139 |
accept: "application/json;as=PartialObjectMetadata;v=v1;g=meta.k8s.io, application/json;as=PartialObjectMetadata;v=v1beta1;g=meta.k8s.io, application/json", |
| 2140 |
expectKind: schema.GroupVersionKind{Kind: "PartialObjectMetadata", Group: "meta.k8s.io", Version: "v1"}, |
| 2141 |
}, |
| 2142 |
{ |
| 2143 |
accept: "application/json;as=PartialObjectMetadata;v=v1beta1;g=meta.k8s.io, application/json;as=PartialObjectMetadata;v=v1;g=meta.k8s.io", |
| 2144 |
expectKind: schema.GroupVersionKind{Kind: "PartialObjectMetadata", Group: "meta.k8s.io", Version: "v1beta1"}, |
| 2145 |
}, |
| 2146 |
{ |
| 2147 |
accept: "application/json;as=PartialObjectMetadata;v=v1;g=meta.k8s.io, application/json;as=PartialObjectMetadata;v=v1beta1;g=meta.k8s.io", |
| 2148 |
expectKind: schema.GroupVersionKind{Kind: "PartialObjectMetadata", Group: "meta.k8s.io", Version: "v1"}, |
| 2149 |
}, |
| 2150 |
|
| 2151 |
{ |
| 2152 |
list: true, |
| 2153 |
accept: "application/json;as=PartialObjectMetadata;v=v1alpha1;g=meta.k8s.io, application/json", |
| 2154 |
expectKind: schema.GroupVersionKind{Kind: "SimpleList", Group: testGroupVersion.Group, Version: testGroupVersion.Version}, |
| 2155 |
}, |
| 2156 |
{ |
| 2157 |
list: true, |
| 2158 |
accept: "application/json;as=PartialObjectMetadataList;v=v1beta1;g=meta.k8s.io, application/json", |
| 2159 |
expectKind: schema.GroupVersionKind{Kind: "PartialObjectMetadataList", Group: "meta.k8s.io", Version: "v1beta1"}, |
| 2160 |
}, |
| 2161 |
{ |
| 2162 |
accept: "application/json;as=PartialObjectMetadataList;v=v1beta1;g=meta.k8s.io", |
| 2163 |
statusCode: http.StatusNotAcceptable, |
| 2164 |
}, |
| 2165 |
{ |
| 2166 |
accept: "application/json;as=PartialObjectMetadata;v=v1beta1;g=meta.k8s.io", |
| 2167 |
expected: &metav1beta1.PartialObjectMetadata{ |
| 2168 |
ObjectMeta: metav1.ObjectMeta{Name: "foo1", Namespace: "ns1", CreationTimestamp: now, UID: types.UID("abcdef0123")}, |
| 2169 |
}, |
| 2170 |
expectKind: schema.GroupVersionKind{Kind: "PartialObjectMetadata", Group: "meta.k8s.io", Version: "v1beta1"}, |
| 2171 |
}, |
| 2172 |
{ |
| 2173 |
accept: "application/json;as=PartialObjectMetadata;v=v1;g=meta.k8s.io", |
| 2174 |
expected: &metav1.PartialObjectMetadata{ |
| 2175 |
ObjectMeta: metav1.ObjectMeta{Name: "foo1", Namespace: "ns1", CreationTimestamp: now, UID: types.UID("abcdef0123")}, |
| 2176 |
}, |
| 2177 |
expectKind: schema.GroupVersionKind{Kind: "PartialObjectMetadata", Group: "meta.k8s.io", Version: "v1"}, |
| 2178 |
}, |
| 2179 |
{ |
| 2180 |
list: true, |
| 2181 |
accept: "application/json;as=PartialObjectMetadataList;v=v1beta1;g=meta.k8s.io", |
| 2182 |
expected: &metav1beta1.PartialObjectMetadataList{ |
| 2183 |
ListMeta: metav1.ListMeta{ |
| 2184 |
ResourceVersion: "10", |
| 2185 |
}, |
| 2186 |
Items: []metav1beta1.PartialObjectMetadata{ |
| 2187 |
{ |
| 2188 |
TypeMeta: metav1.TypeMeta{APIVersion: "meta.k8s.io/v1beta1", Kind: "PartialObjectMetadata"}, |
| 2189 |
ObjectMeta: metav1.ObjectMeta{Name: "foo1", Namespace: "ns1", CreationTimestamp: now, UID: types.UID("newer")}, |
| 2190 |
}, |
| 2191 |
{ |
| 2192 |
TypeMeta: metav1.TypeMeta{APIVersion: "meta.k8s.io/v1beta1", Kind: "PartialObjectMetadata"}, |
| 2193 |
ObjectMeta: metav1.ObjectMeta{Name: "foo2", Namespace: "ns2", CreationTimestamp: now, UID: types.UID("older")}, |
| 2194 |
}, |
| 2195 |
}, |
| 2196 |
}, |
| 2197 |
expectKind: schema.GroupVersionKind{Kind: "PartialObjectMetadataList", Group: "meta.k8s.io", Version: "v1beta1"}, |
| 2198 |
}, |
| 2199 |
} |
| 2200 |
for i, test := range tests { |
| 2201 |
suffix := "/namespaces/default/simple/id" |
| 2202 |
if test.list { |
| 2203 |
suffix = "/namespaces/default/simple" |
| 2204 |
} |
| 2205 |
u, err := url.Parse(server.URL + "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + suffix) |
| 2206 |
if err != nil { |
| 2207 |
t.Fatal(err) |
| 2208 |
} |
| 2209 |
u.RawQuery = test.params.Encode() |
| 2210 |
req := &http.Request{Method: "GET", URL: u} |
| 2211 |
req.Header = http.Header{} |
| 2212 |
req.Header.Set("Accept", test.accept) |
| 2213 |
resp, err := http.DefaultClient.Do(req) |
| 2214 |
if err != nil { |
| 2215 |
t.Fatal(err) |
| 2216 |
} |
| 2217 |
if test.statusCode != 0 { |
| 2218 |
if resp.StatusCode != test.statusCode { |
| 2219 |
t.Errorf("%d: unexpected response: %#v", i, resp) |
| 2220 |
} |
| 2221 |
obj, _, err := extractBodyObject(resp, unstructured.UnstructuredJSONScheme) |
| 2222 |
if err != nil { |
| 2223 |
t.Errorf("%d: unexpected body read error: %v", i, err) |
| 2224 |
continue |
| 2225 |
} |
| 2226 |
gvk := schema.GroupVersionKind{Version: "v1", Kind: "Status"} |
| 2227 |
if obj.GetObjectKind().GroupVersionKind() != gvk { |
| 2228 |
t.Errorf("%d: unexpected error body: %#v", i, obj) |
| 2229 |
} |
| 2230 |
continue |
| 2231 |
} |
| 2232 |
if resp.StatusCode != http.StatusOK { |
| 2233 |
t.Errorf("%d: invalid status: %#v\n%s", i, resp, bodyOrDie(resp)) |
| 2234 |
continue |
| 2235 |
} |
| 2236 |
body := "" |
| 2237 |
if test.expected != nil { |
| 2238 |
itemOut, d, err := extractBodyObject(resp, metainternalversionscheme.Codecs.LegacyCodec(metav1beta1.SchemeGroupVersion)) |
| 2239 |
if err != nil { |
| 2240 |
t.Fatal(err) |
| 2241 |
} |
| 2242 |
if !reflect.DeepEqual(test.expected, itemOut) { |
| 2243 |
t.Errorf("%d: did not match: %s", i, cmp.Diff(test.expected, itemOut)) |
| 2244 |
} |
| 2245 |
body = d |
| 2246 |
} else { |
| 2247 |
d, err := ioutil.ReadAll(resp.Body) |
| 2248 |
if err != nil { |
| 2249 |
t.Fatal(err) |
| 2250 |
} |
| 2251 |
body = string(d) |
| 2252 |
} |
| 2253 |
obj := &unstructured.Unstructured{} |
| 2254 |
if err := json.Unmarshal([]byte(body), obj); err != nil { |
| 2255 |
t.Fatal(err) |
| 2256 |
} |
| 2257 |
if obj.GetObjectKind().GroupVersionKind() != test.expectKind { |
| 2258 |
t.Errorf("%d: unexpected kind: %#v", i, obj.GetObjectKind().GroupVersionKind()) |
| 2259 |
} |
| 2260 |
} |
| 2261 |
} |
| 2262 |
|
| 2263 |
func TestGetBinary(t *testing.T) { |
| 2264 |
simpleStorage := SimpleRESTStorage{ |
| 2265 |
stream: &SimpleStream{ |
| 2266 |
contentType: "text/plain", |
| 2267 |
Reader: bytes.NewBufferString("response data"), |
| 2268 |
}, |
| 2269 |
} |
| 2270 |
stream := simpleStorage.stream |
| 2271 |
server := httptest.NewServer(handle(map[string]rest.Storage{"simple": &simpleStorage})) |
| 2272 |
defer server.Close() |
| 2273 |
|
| 2274 |
req, err := http.NewRequest("GET", server.URL+"/"+prefix+"/"+testGroupVersion.Group+"/"+testGroupVersion.Version+"/namespaces/default/simple/binary", nil) |
| 2275 |
if err != nil { |
| 2276 |
t.Fatalf("unexpected error: %v", err) |
| 2277 |
} |
| 2278 |
req.Header.Add("Accept", "text/other, */*") |
| 2279 |
resp, err := http.DefaultClient.Do(req) |
| 2280 |
if err != nil { |
| 2281 |
t.Fatalf("unexpected error: %v", err) |
| 2282 |
} |
| 2283 |
if resp.StatusCode != http.StatusOK { |
| 2284 |
t.Fatalf("unexpected response: %#v", resp) |
| 2285 |
} |
| 2286 |
body, err := ioutil.ReadAll(resp.Body) |
| 2287 |
if err != nil { |
| 2288 |
t.Errorf("unexpected error: %v", err) |
| 2289 |
} |
| 2290 |
if !stream.closed || stream.version != testGroupVersion.String() || stream.accept != "text/other, */*" || |
| 2291 |
resp.Header.Get("Content-Type") != stream.contentType || string(body) != "response data" { |
| 2292 |
t.Errorf("unexpected stream: %#v", stream) |
| 2293 |
} |
| 2294 |
} |
| 2295 |
|
| 2296 |
func validateSimpleGetOptionsParams(t *testing.T, route *restful.Route) { |
| 2297 |
// Validate name and description |
| 2298 |
expectedParams := map[string]string{ |
| 2299 |
"param1": "description for param1", |
| 2300 |
"param2": "description for param2", |
| 2301 |
"atAPath": "", |
| 2302 |
} |
| 2303 |
for _, p := range route.ParameterDocs { |
| 2304 |
data := p.Data() |
| 2305 |
if desc, exists := expectedParams[data.Name]; exists { |
| 2306 |
if desc != data.Description { |
| 2307 |
t.Errorf("unexpected description for parameter %s: %s\n", data.Name, data.Description) |
| 2308 |
} |
| 2309 |
delete(expectedParams, data.Name) |
| 2310 |
} |
| 2311 |
} |
| 2312 |
if len(expectedParams) > 0 { |
| 2313 |
t.Errorf("did not find all expected parameters: %#v", expectedParams) |
| 2314 |
} |
| 2315 |
} |
| 2316 |
|
| 2317 |
func TestGetWithOptionsRouteParams(t *testing.T) { |
| 2318 |
storage := map[string]rest.Storage{} |
| 2319 |
simpleStorage := GetWithOptionsRESTStorage{ |
| 2320 |
SimpleRESTStorage: &SimpleRESTStorage{}, |
| 2321 |
} |
| 2322 |
storage["simple"] = &simpleStorage |
| 2323 |
handler := handle(storage) |
| 2324 |
ws := handler.(*defaultAPIServer).container.RegisteredWebServices() |
| 2325 |
if len(ws) == 0 { |
| 2326 |
t.Fatal("no web services registered") |
| 2327 |
} |
| 2328 |
routes := ws[0].Routes() |
| 2329 |
for i := range routes { |
| 2330 |
if routes[i].Method == "GET" && routes[i].Operation == "readNamespacedSimple" { |
| 2331 |
validateSimpleGetOptionsParams(t, &routes[i]) |
| 2332 |
break |
| 2333 |
} |
| 2334 |
} |
| 2335 |
} |
| 2336 |
|
| 2337 |
func TestGetWithOptions(t *testing.T) { |
| 2338 |
|
| 2339 |
tests := []struct { |
| 2340 |
name string |
| 2341 |
rootScoped bool |
| 2342 |
requestURL string |
| 2343 |
expectedPath string |
| 2344 |
}{ |
| 2345 |
{ |
| 2346 |
name: "basic", |
| 2347 |
requestURL: "/namespaces/default/simple/id?param1=test1¶m2=test2", |
| 2348 |
expectedPath: "", |
| 2349 |
}, |
| 2350 |
{ |
| 2351 |
name: "with root slash", |
| 2352 |
requestURL: "/namespaces/default/simple/id/?param1=test1¶m2=test2", |
| 2353 |
expectedPath: "/", |
| 2354 |
}, |
| 2355 |
{ |
| 2356 |
name: "with path", |
| 2357 |
requestURL: "/namespaces/default/simple/id/a/different/path?param1=test1¶m2=test2", |
| 2358 |
expectedPath: "/a/different/path", |
| 2359 |
}, |
| 2360 |
{ |
| 2361 |
name: "with path with trailing slash", |
| 2362 |
requestURL: "/namespaces/default/simple/id/a/different/path/?param1=test1¶m2=test2", |
| 2363 |
expectedPath: "/a/different/path/", |
| 2364 |
}, |
| 2365 |
{ |
| 2366 |
name: "as subresource", |
| 2367 |
requestURL: "/namespaces/default/simple/id/subresource/another/different/path?param1=test1¶m2=test2", |
| 2368 |
expectedPath: "/another/different/path", |
| 2369 |
}, |
| 2370 |
{ |
| 2371 |
name: "cluster-scoped basic", |
| 2372 |
rootScoped: true, |
| 2373 |
requestURL: "/simple/id?param1=test1¶m2=test2", |
| 2374 |
expectedPath: "", |
| 2375 |
}, |
| 2376 |
{ |
| 2377 |
name: "cluster-scoped basic with path", |
| 2378 |
rootScoped: true, |
| 2379 |
requestURL: "/simple/id/a/cluster/path?param1=test1¶m2=test2", |
| 2380 |
expectedPath: "/a/cluster/path", |
| 2381 |
}, |
| 2382 |
{ |
| 2383 |
name: "cluster-scoped basic as subresource", |
| 2384 |
rootScoped: true, |
| 2385 |
requestURL: "/simple/id/subresource/another/cluster/path?param1=test1¶m2=test2", |
| 2386 |
expectedPath: "/another/cluster/path", |
| 2387 |
}, |
| 2388 |
} |
| 2389 |
|
| 2390 |
for _, test := range tests { |
| 2391 |
simpleStorage := GetWithOptionsRESTStorage{ |
| 2392 |
SimpleRESTStorage: &SimpleRESTStorage{ |
| 2393 |
item: genericapitesting.Simple{ |
| 2394 |
Other: "foo", |
| 2395 |
}, |
| 2396 |
}, |
| 2397 |
takesPath: "atAPath", |
| 2398 |
} |
| 2399 |
simpleRootStorage := GetWithOptionsRootRESTStorage{ |
| 2400 |
SimpleTypedStorage: &SimpleTypedStorage{ |
| 2401 |
baseType: &genericapitesting.SimpleRoot{}, // a root scoped type |
| 2402 |
item: &genericapitesting.SimpleRoot{ |
| 2403 |
Other: "foo", |
| 2404 |
}, |
| 2405 |
}, |
| 2406 |
takesPath: "atAPath", |
| 2407 |
} |
| 2408 |
|
| 2409 |
storage := map[string]rest.Storage{} |
| 2410 |
if test.rootScoped { |
| 2411 |
storage["simple"] = &simpleRootStorage |
| 2412 |
storage["simple/subresource"] = &simpleRootStorage |
| 2413 |
} else { |
| 2414 |
storage["simple"] = &simpleStorage |
| 2415 |
storage["simple/subresource"] = &simpleStorage |
| 2416 |
} |
| 2417 |
handler := handle(storage) |
| 2418 |
server := httptest.NewServer(handler) |
| 2419 |
defer server.Close() |
| 2420 |
|
| 2421 |
resp, err := http.Get(server.URL + "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + test.requestURL) |
| 2422 |
if err != nil { |
| 2423 |
t.Errorf("%s: %v", test.name, err) |
| 2424 |
continue |
| 2425 |
} |
| 2426 |
if resp.StatusCode != http.StatusOK { |
| 2427 |
t.Errorf("%s: unexpected response: %#v", test.name, resp) |
| 2428 |
continue |
| 2429 |
} |
| 2430 |
|
| 2431 |
var itemOut runtime.Object |
| 2432 |
if test.rootScoped { |
| 2433 |
itemOut = &genericapitesting.SimpleRoot{} |
| 2434 |
} else { |
| 2435 |
itemOut = &genericapitesting.Simple{} |
| 2436 |
} |
| 2437 |
body, err := extractBody(resp, itemOut) |
| 2438 |
if err != nil { |
| 2439 |
t.Errorf("%s: %v", test.name, err) |
| 2440 |
continue |
| 2441 |
} |
| 2442 |
if metadata, err := meta.Accessor(itemOut); err == nil { |
| 2443 |
if metadata.GetName() != simpleStorage.item.Name { |
| 2444 |
t.Errorf("%s: Unexpected data: %#v, expected %#v (%s)", test.name, itemOut, simpleStorage.item, string(body)) |
| 2445 |
continue |
| 2446 |
} |
| 2447 |
} else { |
| 2448 |
t.Errorf("%s: Couldn't get name from %#v: %v", test.name, itemOut, err) |
| 2449 |
} |
| 2450 |
|
| 2451 |
var opts *genericapitesting.SimpleGetOptions |
| 2452 |
var ok bool |
| 2453 |
if test.rootScoped { |
| 2454 |
opts, ok = simpleRootStorage.optionsReceived.(*genericapitesting.SimpleGetOptions) |
| 2455 |
} else { |
| 2456 |
opts, ok = simpleStorage.optionsReceived.(*genericapitesting.SimpleGetOptions) |
| 2457 |
|
| 2458 |
} |
| 2459 |
if !ok { |
| 2460 |
t.Errorf("%s: Unexpected options object received: %#v", test.name, simpleStorage.optionsReceived) |
| 2461 |
continue |
| 2462 |
} |
| 2463 |
if opts.Param1 != "test1" || opts.Param2 != "test2" { |
| 2464 |
t.Errorf("%s: Did not receive expected options: %#v", test.name, opts) |
| 2465 |
continue |
| 2466 |
} |
| 2467 |
if opts.Path != test.expectedPath { |
| 2468 |
t.Errorf("%s: Unexpected path value. Expected: %s. Actual: %s.", test.name, test.expectedPath, opts.Path) |
| 2469 |
continue |
| 2470 |
} |
| 2471 |
} |
| 2472 |
} |
| 2473 |
|
| 2474 |
func TestGetMissing(t *testing.T) { |
| 2475 |
storage := map[string]rest.Storage{} |
| 2476 |
simpleStorage := SimpleRESTStorage{ |
| 2477 |
errors: map[string]error{"get": apierrors.NewNotFound(schema.GroupResource{Resource: "simples"}, "id")}, |
| 2478 |
} |
| 2479 |
storage["simple"] = &simpleStorage |
| 2480 |
handler := handle(storage) |
| 2481 |
server := httptest.NewServer(handler) |
| 2482 |
defer server.Close() |
| 2483 |
|
| 2484 |
resp, err := http.Get(server.URL + "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/namespaces/default/simple/id") |
| 2485 |
if err != nil { |
| 2486 |
t.Errorf("unexpected error: %v", err) |
| 2487 |
} |
| 2488 |
|
| 2489 |
if resp.StatusCode != http.StatusNotFound { |
| 2490 |
t.Errorf("Unexpected response %#v", resp) |
| 2491 |
} |
| 2492 |
} |
| 2493 |
|
| 2494 |
func TestGetRetryAfter(t *testing.T) { |
| 2495 |
storage := map[string]rest.Storage{} |
| 2496 |
simpleStorage := SimpleRESTStorage{ |
| 2497 |
errors: map[string]error{"get": apierrors.NewServerTimeout(schema.GroupResource{Resource: "simples"}, "id", 2)}, |
| 2498 |
} |
| 2499 |
storage["simple"] = &simpleStorage |
| 2500 |
handler := handle(storage) |
| 2501 |
server := httptest.NewServer(handler) |
| 2502 |
defer server.Close() |
| 2503 |
|
| 2504 |
resp, err := http.Get(server.URL + "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/namespaces/default/simple/id") |
| 2505 |
if err != nil { |
| 2506 |
t.Errorf("unexpected error: %v", err) |
| 2507 |
} |
| 2508 |
if resp.StatusCode != http.StatusInternalServerError { |
| 2509 |
t.Errorf("Unexpected response %#v", resp) |
| 2510 |
} |
| 2511 |
if resp.Header.Get("Retry-After") != "2" { |
| 2512 |
t.Errorf("Unexpected Retry-After header: %v", resp.Header) |
| 2513 |
} |
| 2514 |
} |
| 2515 |
|
| 2516 |
func TestConnect(t *testing.T) { |
| 2517 |
responseText := "Hello World" |
| 2518 |
itemID := "theID" |
| 2519 |
connectStorage := &ConnecterRESTStorage{ |
| 2520 |
connectHandler: &OutputConnect{ |
| 2521 |
response: responseText, |
| 2522 |
}, |
| 2523 |
} |
| 2524 |
storage := map[string]rest.Storage{ |
| 2525 |
"simple": &SimpleRESTStorage{}, |
| 2526 |
"simple/connect": connectStorage, |
| 2527 |
} |
| 2528 |
handler := handle(storage) |
| 2529 |
server := httptest.NewServer(handler) |
| 2530 |
defer server.Close() |
| 2531 |
|
| 2532 |
resp, err := http.Get(server.URL + "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/namespaces/default/simple/" + itemID + "/connect") |
| 2533 |
|
| 2534 |
if err != nil { |
| 2535 |
t.Errorf("unexpected error: %v", err) |
| 2536 |
} |
| 2537 |
if resp.StatusCode != http.StatusOK { |
| 2538 |
t.Errorf("unexpected response: %#v", resp) |
| 2539 |
} |
| 2540 |
defer resp.Body.Close() |
| 2541 |
body, err := ioutil.ReadAll(resp.Body) |
| 2542 |
if err != nil { |
| 2543 |
t.Fatalf("Unexpected error: %v", err) |
| 2544 |
} |
| 2545 |
if connectStorage.receivedID != itemID { |
| 2546 |
t.Errorf("Unexpected item id. Expected: %s. Actual: %s.", itemID, connectStorage.receivedID) |
| 2547 |
} |
| 2548 |
if string(body) != responseText { |
| 2549 |
t.Errorf("Unexpected response. Expected: %s. Actual: %s.", responseText, string(body)) |
| 2550 |
} |
| 2551 |
} |
| 2552 |
|
| 2553 |
func TestConnectResponderObject(t *testing.T) { |
| 2554 |
itemID := "theID" |
| 2555 |
simple := &genericapitesting.Simple{Other: "foo"} |
| 2556 |
connectStorage := &ConnecterRESTStorage{} |
| 2557 |
connectStorage.handlerFunc = func() http.Handler { |
| 2558 |
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { |
| 2559 |
connectStorage.receivedResponder.Object(http.StatusCreated, simple) |
| 2560 |
}) |
| 2561 |
} |
| 2562 |
storage := map[string]rest.Storage{ |
| 2563 |
"simple": &SimpleRESTStorage{}, |
| 2564 |
"simple/connect": connectStorage, |
| 2565 |
} |
| 2566 |
handler := handle(storage) |
| 2567 |
server := httptest.NewServer(handler) |
| 2568 |
defer server.Close() |
| 2569 |
|
| 2570 |
resp, err := http.Get(server.URL + "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/namespaces/default/simple/" + itemID + "/connect") |
| 2571 |
|
| 2572 |
if err != nil { |
| 2573 |
t.Errorf("unexpected error: %v", err) |
| 2574 |
} |
| 2575 |
if resp.StatusCode != http.StatusCreated { |
| 2576 |
t.Errorf("unexpected response: %#v", resp) |
| 2577 |
} |
| 2578 |
defer resp.Body.Close() |
| 2579 |
body, err := ioutil.ReadAll(resp.Body) |
| 2580 |
if err != nil { |
| 2581 |
t.Fatalf("Unexpected error: %v", err) |
| 2582 |
} |
| 2583 |
if connectStorage.receivedID != itemID { |
| 2584 |
t.Errorf("Unexpected item id. Expected: %s. Actual: %s.", itemID, connectStorage.receivedID) |
| 2585 |
} |
| 2586 |
obj, err := runtime.Decode(codec, body) |
| 2587 |
if err != nil { |
| 2588 |
t.Fatal(err) |
| 2589 |
} |
| 2590 |
if !apiequality.Semantic.DeepEqual(obj, simple) { |
| 2591 |
t.Errorf("Unexpected response: %#v", obj) |
| 2592 |
} |
| 2593 |
} |
| 2594 |
|
| 2595 |
func TestConnectResponderError(t *testing.T) { |
| 2596 |
itemID := "theID" |
| 2597 |
connectStorage := &ConnecterRESTStorage{} |
| 2598 |
connectStorage.handlerFunc = func() http.Handler { |
| 2599 |
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { |
| 2600 |
connectStorage.receivedResponder.Error(apierrors.NewForbidden(schema.GroupResource{Resource: "simples"}, itemID, errors.New("you are terminated"))) |
| 2601 |
}) |
| 2602 |
} |
| 2603 |
storage := map[string]rest.Storage{ |
| 2604 |
"simple": &SimpleRESTStorage{}, |
| 2605 |
"simple/connect": connectStorage, |
| 2606 |
} |
| 2607 |
handler := handle(storage) |
| 2608 |
server := httptest.NewServer(handler) |
| 2609 |
defer server.Close() |
| 2610 |
|
| 2611 |
resp, err := http.Get(server.URL + "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/namespaces/default/simple/" + itemID + "/connect") |
| 2612 |
|
| 2613 |
if err != nil { |
| 2614 |
t.Errorf("unexpected error: %v", err) |
| 2615 |
} |
| 2616 |
if resp.StatusCode != http.StatusForbidden { |
| 2617 |
t.Errorf("unexpected response: %#v", resp) |
| 2618 |
} |
| 2619 |
defer resp.Body.Close() |
| 2620 |
body, err := ioutil.ReadAll(resp.Body) |
| 2621 |
if err != nil { |
| 2622 |
t.Fatalf("Unexpected error: %v", err) |
| 2623 |
} |
| 2624 |
if connectStorage.receivedID != itemID { |
| 2625 |
t.Errorf("Unexpected item id. Expected: %s. Actual: %s.", itemID, connectStorage.receivedID) |
| 2626 |
} |
| 2627 |
obj, err := runtime.Decode(codec, body) |
| 2628 |
if err != nil { |
| 2629 |
t.Fatal(err) |
| 2630 |
} |
| 2631 |
if obj.(*metav1.Status).Code != http.StatusForbidden { |
| 2632 |
t.Errorf("Unexpected response: %#v", obj) |
| 2633 |
} |
| 2634 |
} |
| 2635 |
|
| 2636 |
func TestConnectWithOptionsRouteParams(t *testing.T) { |
| 2637 |
connectStorage := &ConnecterRESTStorage{ |
| 2638 |
connectHandler: &OutputConnect{}, |
| 2639 |
emptyConnectOptions: &genericapitesting.SimpleGetOptions{}, |
| 2640 |
} |
| 2641 |
storage := map[string]rest.Storage{ |
| 2642 |
"simple": &SimpleRESTStorage{}, |
| 2643 |
"simple/connect": connectStorage, |
| 2644 |
} |
| 2645 |
handler := handle(storage) |
| 2646 |
ws := handler.(*defaultAPIServer).container.RegisteredWebServices() |
| 2647 |
if len(ws) == 0 { |
| 2648 |
t.Fatal("no web services registered") |
| 2649 |
} |
| 2650 |
routes := ws[0].Routes() |
| 2651 |
for i := range routes { |
| 2652 |
switch routes[i].Operation { |
| 2653 |
case "connectGetNamespacedSimpleConnect": |
| 2654 |
case "connectPostNamespacedSimpleConnect": |
| 2655 |
case "connectPutNamespacedSimpleConnect": |
| 2656 |
case "connectDeleteNamespacedSimpleConnect": |
| 2657 |
validateSimpleGetOptionsParams(t, &routes[i]) |
| 2658 |
|
| 2659 |
} |
| 2660 |
} |
| 2661 |
} |
| 2662 |
|
| 2663 |
func TestConnectWithOptions(t *testing.T) { |
| 2664 |
responseText := "Hello World" |
| 2665 |
itemID := "theID" |
| 2666 |
connectStorage := &ConnecterRESTStorage{ |
| 2667 |
connectHandler: &OutputConnect{ |
| 2668 |
response: responseText, |
| 2669 |
}, |
| 2670 |
emptyConnectOptions: &genericapitesting.SimpleGetOptions{}, |
| 2671 |
} |
| 2672 |
storage := map[string]rest.Storage{ |
| 2673 |
"simple": &SimpleRESTStorage{}, |
| 2674 |
"simple/connect": connectStorage, |
| 2675 |
} |
| 2676 |
handler := handle(storage) |
| 2677 |
server := httptest.NewServer(handler) |
| 2678 |
defer server.Close() |
| 2679 |
|
| 2680 |
resp, err := http.Get(server.URL + "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/namespaces/default/simple/" + itemID + "/connect?param1=value1¶m2=value2") |
| 2681 |
|
| 2682 |
if err != nil { |
| 2683 |
t.Errorf("unexpected error: %v", err) |
| 2684 |
} |
| 2685 |
if resp.StatusCode != http.StatusOK { |
| 2686 |
t.Errorf("unexpected response: %#v", resp) |
| 2687 |
} |
| 2688 |
defer resp.Body.Close() |
| 2689 |
body, err := ioutil.ReadAll(resp.Body) |
| 2690 |
if err != nil { |
| 2691 |
t.Fatalf("Unexpected error: %v", err) |
| 2692 |
} |
| 2693 |
if connectStorage.receivedID != itemID { |
| 2694 |
t.Errorf("Unexpected item id. Expected: %s. Actual: %s.", itemID, connectStorage.receivedID) |
| 2695 |
} |
| 2696 |
if string(body) != responseText { |
| 2697 |
t.Errorf("Unexpected response. Expected: %s. Actual: %s.", responseText, string(body)) |
| 2698 |
} |
| 2699 |
if connectStorage.receivedResponder == nil { |
| 2700 |
t.Errorf("Unexpected responder") |
| 2701 |
} |
| 2702 |
opts, ok := connectStorage.receivedConnectOptions.(*genericapitesting.SimpleGetOptions) |
| 2703 |
if !ok { |
| 2704 |
t.Fatalf("Unexpected options type: %#v", connectStorage.receivedConnectOptions) |
| 2705 |
} |
| 2706 |
if opts.Param1 != "value1" && opts.Param2 != "value2" { |
| 2707 |
t.Errorf("Unexpected options value: %#v", opts) |
| 2708 |
} |
| 2709 |
} |
| 2710 |
|
| 2711 |
func TestConnectWithOptionsAndPath(t *testing.T) { |
| 2712 |
responseText := "Hello World" |
| 2713 |
itemID := "theID" |
| 2714 |
testPath := "/a/b/c/def" |
| 2715 |
connectStorage := &ConnecterRESTStorage{ |
| 2716 |
connectHandler: &OutputConnect{ |
| 2717 |
response: responseText, |
| 2718 |
}, |
| 2719 |
emptyConnectOptions: &genericapitesting.SimpleGetOptions{}, |
| 2720 |
takesPath: "atAPath", |
| 2721 |
} |
| 2722 |
storage := map[string]rest.Storage{ |
| 2723 |
"simple": &SimpleRESTStorage{}, |
| 2724 |
"simple/connect": connectStorage, |
| 2725 |
} |
| 2726 |
handler := handle(storage) |
| 2727 |
server := httptest.NewServer(handler) |
| 2728 |
defer server.Close() |
| 2729 |
|
| 2730 |
resp, err := http.Get(server.URL + "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/namespaces/default/simple/" + itemID + "/connect" + testPath + "?param1=value1¶m2=value2") |
| 2731 |
|
| 2732 |
if err != nil { |
| 2733 |
t.Errorf("unexpected error: %v", err) |
| 2734 |
} |
| 2735 |
if resp.StatusCode != http.StatusOK { |
| 2736 |
t.Errorf("unexpected response: %#v", resp) |
| 2737 |
} |
| 2738 |
defer resp.Body.Close() |
| 2739 |
body, err := ioutil.ReadAll(resp.Body) |
| 2740 |
if err != nil { |
| 2741 |
t.Fatalf("Unexpected error: %v", err) |
| 2742 |
} |
| 2743 |
if connectStorage.receivedID != itemID { |
| 2744 |
t.Errorf("Unexpected item id. Expected: %s. Actual: %s.", itemID, connectStorage.receivedID) |
| 2745 |
} |
| 2746 |
if string(body) != responseText { |
| 2747 |
t.Errorf("Unexpected response. Expected: %s. Actual: %s.", responseText, string(body)) |
| 2748 |
} |
| 2749 |
opts, ok := connectStorage.receivedConnectOptions.(*genericapitesting.SimpleGetOptions) |
| 2750 |
if !ok { |
| 2751 |
t.Fatalf("Unexpected options type: %#v", connectStorage.receivedConnectOptions) |
| 2752 |
} |
| 2753 |
if opts.Param1 != "value1" && opts.Param2 != "value2" { |
| 2754 |
t.Errorf("Unexpected options value: %#v", opts) |
| 2755 |
} |
| 2756 |
if opts.Path != testPath { |
| 2757 |
t.Errorf("Unexpected path value. Expected: %s. Actual: %s.", testPath, opts.Path) |
| 2758 |
} |
| 2759 |
} |
| 2760 |
|
| 2761 |
func TestDelete(t *testing.T) { |
| 2762 |
storage := map[string]rest.Storage{} |
| 2763 |
simpleStorage := SimpleRESTStorage{} |
| 2764 |
ID := "id" |
| 2765 |
storage["simple"] = &simpleStorage |
| 2766 |
handler := handle(storage) |
| 2767 |
server := httptest.NewServer(handler) |
| 2768 |
defer server.Close() |
| 2769 |
|
| 2770 |
client := http.Client{} |
| 2771 |
request, err := http.NewRequest("DELETE", server.URL+"/"+prefix+"/"+testGroupVersion.Group+"/"+testGroupVersion.Version+"/namespaces/default/simple/"+ID, nil) |
| 2772 |
if err != nil { |
| 2773 |
t.Errorf("unexpected error: %v", err) |
| 2774 |
} |
| 2775 |
res, err := client.Do(request) |
| 2776 |
if err != nil { |
| 2777 |
t.Fatalf("unexpected error: %v", err) |
| 2778 |
} |
| 2779 |
if res.StatusCode != http.StatusOK { |
| 2780 |
t.Errorf("unexpected response: %#v", res) |
| 2781 |
} |
| 2782 |
if simpleStorage.deleted != ID { |
| 2783 |
t.Errorf("Unexpected delete: %s, expected %s", simpleStorage.deleted, ID) |
| 2784 |
} |
| 2785 |
} |
| 2786 |
|
| 2787 |
func TestDeleteWithOptions(t *testing.T) { |
| 2788 |
storage := map[string]rest.Storage{} |
| 2789 |
simpleStorage := SimpleRESTStorage{} |
| 2790 |
ID := "id" |
| 2791 |
storage["simple"] = &simpleStorage |
| 2792 |
handler := handle(storage) |
| 2793 |
server := httptest.NewServer(handler) |
| 2794 |
defer server.Close() |
| 2795 |
|
| 2796 |
grace := int64(300) |
| 2797 |
item := &metav1.DeleteOptions{ |
| 2798 |
GracePeriodSeconds: &grace, |
| 2799 |
} |
| 2800 |
body, err := runtime.Encode(codec, item) |
| 2801 |
if err != nil { |
| 2802 |
t.Fatalf("unexpected error: %v", err) |
| 2803 |
} |
| 2804 |
|
| 2805 |
client := http.Client{} |
| 2806 |
request, err := http.NewRequest("DELETE", server.URL+"/"+prefix+"/"+testGroupVersion.Group+"/"+testGroupVersion.Version+"/namespaces/default/simple/"+ID, bytes.NewReader(body)) |
| 2807 |
if err != nil { |
| 2808 |
t.Errorf("unexpected error: %v", err) |
| 2809 |
} |
| 2810 |
res, err := client.Do(request) |
| 2811 |
if err != nil { |
| 2812 |
t.Fatalf("unexpected error: %v", err) |
| 2813 |
} |
| 2814 |
if res.StatusCode != http.StatusOK { |
| 2815 |
t.Errorf("unexpected response: %s %#v", request.URL, res) |
| 2816 |
s, err := ioutil.ReadAll(res.Body) |
| 2817 |
if err != nil { |
| 2818 |
t.Fatalf("unexpected error: %v", err) |
| 2819 |
} |
| 2820 |
t.Log(string(s)) |
| 2821 |
} |
| 2822 |
if simpleStorage.deleted != ID { |
| 2823 |
t.Errorf("Unexpected delete: %s, expected %s", simpleStorage.deleted, ID) |
| 2824 |
} |
| 2825 |
simpleStorage.deleteOptions.GetObjectKind().SetGroupVersionKind(schema.GroupVersionKind{}) |
| 2826 |
if !apiequality.Semantic.DeepEqual(simpleStorage.deleteOptions, item) { |
| 2827 |
t.Errorf("unexpected delete options: %s", cmp.Diff(simpleStorage.deleteOptions, item)) |
| 2828 |
} |
| 2829 |
} |
| 2830 |
|
| 2831 |
func TestDeleteWithOptionsQuery(t *testing.T) { |
| 2832 |
storage := map[string]rest.Storage{} |
| 2833 |
simpleStorage := SimpleRESTStorage{} |
| 2834 |
ID := "id" |
| 2835 |
storage["simple"] = &simpleStorage |
| 2836 |
handler := handle(storage) |
| 2837 |
server := httptest.NewServer(handler) |
| 2838 |
defer server.Close() |
| 2839 |
|
| 2840 |
grace := int64(300) |
| 2841 |
item := &metav1.DeleteOptions{ |
| 2842 |
GracePeriodSeconds: &grace, |
| 2843 |
} |
| 2844 |
|
| 2845 |
client := http.Client{} |
| 2846 |
request, err := http.NewRequest("DELETE", server.URL+"/"+prefix+"/"+testGroupVersion.Group+"/"+testGroupVersion.Version+"/namespaces/default/simple/"+ID+"?gracePeriodSeconds="+strconv.FormatInt(grace, 10), nil) |
| 2847 |
if err != nil { |
| 2848 |
t.Errorf("unexpected error: %v", err) |
| 2849 |
} |
| 2850 |
res, err := client.Do(request) |
| 2851 |
if err != nil { |
| 2852 |
t.Fatalf("unexpected error: %v", err) |
| 2853 |
} |
| 2854 |
if res.StatusCode != http.StatusOK { |
| 2855 |
t.Errorf("unexpected response: %s %#v", request.URL, res) |
| 2856 |
s, err := ioutil.ReadAll(res.Body) |
| 2857 |
if err != nil { |
| 2858 |
t.Fatalf("unexpected error: %v", err) |
| 2859 |
} |
| 2860 |
t.Log(string(s)) |
| 2861 |
} |
| 2862 |
if simpleStorage.deleted != ID { |
| 2863 |
t.Fatalf("Unexpected delete: %s, expected %s", simpleStorage.deleted, ID) |
| 2864 |
} |
| 2865 |
simpleStorage.deleteOptions.GetObjectKind().SetGroupVersionKind(schema.GroupVersionKind{}) |
| 2866 |
if !apiequality.Semantic.DeepEqual(simpleStorage.deleteOptions, item) { |
| 2867 |
t.Errorf("unexpected delete options: %s", cmp.Diff(simpleStorage.deleteOptions, item)) |
| 2868 |
} |
| 2869 |
} |
| 2870 |
|
| 2871 |
func TestDeleteWithOptionsQueryAndBody(t *testing.T) { |
| 2872 |
storage := map[string]rest.Storage{} |
| 2873 |
simpleStorage := SimpleRESTStorage{} |
| 2874 |
ID := "id" |
| 2875 |
storage["simple"] = &simpleStorage |
| 2876 |
handler := handle(storage) |
| 2877 |
server := httptest.NewServer(handler) |
| 2878 |
defer server.Close() |
| 2879 |
|
| 2880 |
grace := int64(300) |
| 2881 |
item := &metav1.DeleteOptions{ |
| 2882 |
GracePeriodSeconds: &grace, |
| 2883 |
} |
| 2884 |
body, err := runtime.Encode(codec, item) |
| 2885 |
if err != nil { |
| 2886 |
t.Fatalf("unexpected error: %v", err) |
| 2887 |
} |
| 2888 |
client := http.Client{} |
| 2889 |
request, err := http.NewRequest("DELETE", server.URL+"/"+prefix+"/"+testGroupVersion.Group+"/"+testGroupVersion.Version+"/namespaces/default/simple/"+ID+"?gracePeriodSeconds="+strconv.FormatInt(grace+10, 10), bytes.NewReader(body)) |
| 2890 |
if err != nil { |
| 2891 |
t.Errorf("unexpected error: %v", err) |
| 2892 |
} |
| 2893 |
res, err := client.Do(request) |
| 2894 |
if err != nil { |
| 2895 |
t.Fatalf("unexpected error: %v", err) |
| 2896 |
} |
| 2897 |
if res.StatusCode != http.StatusOK { |
| 2898 |
t.Errorf("unexpected response: %s %#v", request.URL, res) |
| 2899 |
s, err := ioutil.ReadAll(res.Body) |
| 2900 |
if err != nil { |
| 2901 |
t.Fatalf("unexpected error: %v", err) |
| 2902 |
} |
| 2903 |
t.Log(string(s)) |
| 2904 |
} |
| 2905 |
if simpleStorage.deleted != ID { |
| 2906 |
t.Errorf("Unexpected delete: %s, expected %s", simpleStorage.deleted, ID) |
| 2907 |
} |
| 2908 |
simpleStorage.deleteOptions.GetObjectKind().SetGroupVersionKind(schema.GroupVersionKind{}) |
| 2909 |
if !apiequality.Semantic.DeepEqual(simpleStorage.deleteOptions, item) { |
| 2910 |
t.Errorf("unexpected delete options: %s", cmp.Diff(simpleStorage.deleteOptions, item)) |
| 2911 |
} |
| 2912 |
} |
| 2913 |
|
| 2914 |
func TestDeleteInvokesAdmissionControl(t *testing.T) { |
| 2915 |
// TODO: remove mutating deny when we removed it from the endpoint implementation and ported all plugins |
| 2916 |
for _, admit := range []admission.Interface{alwaysMutatingDeny{}, alwaysValidatingDeny{}} { |
| 2917 |
t.Logf("Testing %T", admit) |
| 2918 |
|
| 2919 |
storage := map[string]rest.Storage{} |
| 2920 |
simpleStorage := SimpleRESTStorage{} |
| 2921 |
ID := "id" |
| 2922 |
storage["simple"] = &simpleStorage |
| 2923 |
handler := handleInternal(storage, admit, nil) |
| 2924 |
server := httptest.NewServer(handler) |
| 2925 |
defer server.Close() |
| 2926 |
|
| 2927 |
client := http.Client{} |
| 2928 |
request, err := http.NewRequest("DELETE", server.URL+"/"+prefix+"/"+testGroupVersion.Group+"/"+testGroupVersion.Version+"/namespaces/default/simple/"+ID, nil) |
| 2929 |
if err != nil { |
| 2930 |
t.Errorf("unexpected error: %v", err) |
| 2931 |
} |
| 2932 |
response, err := client.Do(request) |
| 2933 |
if err != nil { |
| 2934 |
t.Errorf("unexpected error: %v", err) |
| 2935 |
} |
| 2936 |
if response.StatusCode != http.StatusForbidden { |
| 2937 |
t.Errorf("Unexpected response %#v", response) |
| 2938 |
} |
| 2939 |
} |
| 2940 |
} |
| 2941 |
|
| 2942 |
func TestDeleteMissing(t *testing.T) { |
| 2943 |
storage := map[string]rest.Storage{} |
| 2944 |
ID := "id" |
| 2945 |
simpleStorage := SimpleRESTStorage{ |
| 2946 |
errors: map[string]error{"delete": apierrors.NewNotFound(schema.GroupResource{Resource: "simples"}, ID)}, |
| 2947 |
} |
| 2948 |
storage["simple"] = &simpleStorage |
| 2949 |
handler := handle(storage) |
| 2950 |
server := httptest.NewServer(handler) |
| 2951 |
defer server.Close() |
| 2952 |
|
| 2953 |
client := http.Client{} |
| 2954 |
request, err := http.NewRequest("DELETE", server.URL+"/"+prefix+"/"+testGroupVersion.Group+"/"+testGroupVersion.Version+"/namespaces/default/simple/"+ID, nil) |
| 2955 |
if err != nil { |
| 2956 |
t.Errorf("unexpected error: %v", err) |
| 2957 |
} |
| 2958 |
response, err := client.Do(request) |
| 2959 |
if err != nil { |
| 2960 |
t.Errorf("unexpected error: %v", err) |
| 2961 |
} |
| 2962 |
|
| 2963 |
if response.StatusCode != http.StatusNotFound { |
| 2964 |
t.Errorf("Unexpected response %#v", response) |
| 2965 |
} |
| 2966 |
} |
| 2967 |
|
| 2968 |
func TestUpdate(t *testing.T) { |
| 2969 |
storage := map[string]rest.Storage{} |
| 2970 |
simpleStorage := SimpleRESTStorage{} |
| 2971 |
ID := "id" |
| 2972 |
storage["simple"] = &simpleStorage |
| 2973 |
handler := handle(storage) |
| 2974 |
server := httptest.NewServer(handler) |
| 2975 |
defer server.Close() |
| 2976 |
|
| 2977 |
item := &genericapitesting.Simple{ |
| 2978 |
ObjectMeta: metav1.ObjectMeta{ |
| 2979 |
Name: ID, |
| 2980 |
Namespace: "", // update should allow the client to send an empty namespace |
| 2981 |
}, |
| 2982 |
Other: "bar", |
| 2983 |
} |
| 2984 |
body, err := runtime.Encode(testCodec, item) |
| 2985 |
if err != nil { |
| 2986 |
// The following cases will fail, so die now |
| 2987 |
t.Fatalf("unexpected error: %v", err) |
| 2988 |
} |
| 2989 |
|
| 2990 |
client := http.Client{} |
| 2991 |
request, err := http.NewRequest("PUT", server.URL+"/"+prefix+"/"+testGroupVersion.Group+"/"+testGroupVersion.Version+"/namespaces/default/simple/"+ID, bytes.NewReader(body)) |
| 2992 |
if err != nil { |
| 2993 |
t.Errorf("unexpected error: %v", err) |
| 2994 |
} |
| 2995 |
response, err := client.Do(request) |
| 2996 |
if err != nil { |
| 2997 |
t.Errorf("unexpected error: %v", err) |
| 2998 |
} |
| 2999 |
dump, _ := httputil.DumpResponse(response, true) |
| 3000 |
t.Log(string(dump)) |
| 3001 |
|
| 3002 |
if simpleStorage.updated == nil || simpleStorage.updated.Name != item.Name { |
| 3003 |
t.Errorf("Unexpected update value %#v, expected %#v.", simpleStorage.updated, item) |
| 3004 |
} |
| 3005 |
} |
| 3006 |
|
| 3007 |
func TestUpdateInvokesAdmissionControl(t *testing.T) { |
| 3008 |
for _, admit := range []admission.Interface{alwaysMutatingDeny{}, alwaysValidatingDeny{}} { |
| 3009 |
t.Logf("Testing %T", admit) |
| 3010 |
|
| 3011 |
storage := map[string]rest.Storage{} |
| 3012 |
simpleStorage := SimpleRESTStorage{} |
| 3013 |
ID := "id" |
| 3014 |
storage["simple"] = &simpleStorage |
| 3015 |
handler := handleInternal(storage, admit, nil) |
| 3016 |
server := httptest.NewServer(handler) |
| 3017 |
defer server.Close() |
| 3018 |
|
| 3019 |
item := &genericapitesting.Simple{ |
| 3020 |
ObjectMeta: metav1.ObjectMeta{ |
| 3021 |
Name: ID, |
| 3022 |
Namespace: metav1.NamespaceDefault, |
| 3023 |
}, |
| 3024 |
Other: "bar", |
| 3025 |
} |
| 3026 |
body, err := runtime.Encode(testCodec, item) |
| 3027 |
if err != nil { |
| 3028 |
// The following cases will fail, so die now |
| 3029 |
t.Fatalf("unexpected error: %v", err) |
| 3030 |
} |
| 3031 |
|
| 3032 |
client := http.Client{} |
| 3033 |
request, err := http.NewRequest("PUT", server.URL+"/"+prefix+"/"+testGroupVersion.Group+"/"+testGroupVersion.Version+"/namespaces/default/simple/"+ID, bytes.NewReader(body)) |
| 3034 |
if err != nil { |
| 3035 |
t.Errorf("unexpected error: %v", err) |
| 3036 |
} |
| 3037 |
response, err := client.Do(request) |
| 3038 |
if err != nil { |
| 3039 |
t.Errorf("unexpected error: %v", err) |
| 3040 |
} |
| 3041 |
dump, _ := httputil.DumpResponse(response, true) |
| 3042 |
t.Log(string(dump)) |
| 3043 |
|
| 3044 |
if response.StatusCode != http.StatusForbidden { |
| 3045 |
t.Errorf("Unexpected response %#v", response) |
| 3046 |
} |
| 3047 |
} |
| 3048 |
} |
| 3049 |
|
| 3050 |
func TestUpdateRequiresMatchingName(t *testing.T) { |
| 3051 |
storage := map[string]rest.Storage{} |
| 3052 |
simpleStorage := SimpleRESTStorage{} |
| 3053 |
ID := "id" |
| 3054 |
storage["simple"] = &simpleStorage |
| 3055 |
handler := handle(storage) |
| 3056 |
server := httptest.NewServer(handler) |
| 3057 |
defer server.Close() |
| 3058 |
|
| 3059 |
item := &genericapitesting.Simple{ |
| 3060 |
Other: "bar", |
| 3061 |
} |
| 3062 |
body, err := runtime.Encode(testCodec, item) |
| 3063 |
if err != nil { |
| 3064 |
// The following cases will fail, so die now |
| 3065 |
t.Fatalf("unexpected error: %v", err) |
| 3066 |
} |
| 3067 |
|
| 3068 |
client := http.Client{} |
| 3069 |
request, err := http.NewRequest("PUT", server.URL+"/"+prefix+"/"+testGroupVersion.Group+"/"+testGroupVersion.Version+"/namespaces/default/simple/"+ID, bytes.NewReader(body)) |
| 3070 |
if err != nil { |
| 3071 |
t.Errorf("unexpected error: %v", err) |
| 3072 |
} |
| 3073 |
response, err := client.Do(request) |
| 3074 |
if err != nil { |
| 3075 |
t.Errorf("unexpected error: %v", err) |
| 3076 |
} |
| 3077 |
if response.StatusCode != http.StatusBadRequest { |
| 3078 |
dump, _ := httputil.DumpResponse(response, true) |
| 3079 |
t.Log(string(dump)) |
| 3080 |
t.Errorf("Unexpected response %#v", response) |
| 3081 |
} |
| 3082 |
} |
| 3083 |
|
| 3084 |
func TestUpdateAllowsMissingNamespace(t *testing.T) { |
| 3085 |
storage := map[string]rest.Storage{} |
| 3086 |
simpleStorage := SimpleRESTStorage{} |
| 3087 |
ID := "id" |
| 3088 |
storage["simple"] = &simpleStorage |
| 3089 |
handler := handle(storage) |
| 3090 |
server := httptest.NewServer(handler) |
| 3091 |
defer server.Close() |
| 3092 |
|
| 3093 |
item := &genericapitesting.Simple{ |
| 3094 |
ObjectMeta: metav1.ObjectMeta{ |
| 3095 |
Name: ID, |
| 3096 |
}, |
| 3097 |
Other: "bar", |
| 3098 |
} |
| 3099 |
body, err := runtime.Encode(testCodec, item) |
| 3100 |
if err != nil { |
| 3101 |
// The following cases will fail, so die now |
| 3102 |
t.Fatalf("unexpected error: %v", err) |
| 3103 |
} |
| 3104 |
|
| 3105 |
client := http.Client{} |
| 3106 |
request, err := http.NewRequest("PUT", server.URL+"/"+prefix+"/"+testGroupVersion.Group+"/"+testGroupVersion.Version+"/namespaces/default/simple/"+ID, bytes.NewReader(body)) |
| 3107 |
if err != nil { |
| 3108 |
t.Errorf("unexpected error: %v", err) |
| 3109 |
} |
| 3110 |
response, err := client.Do(request) |
| 3111 |
if err != nil { |
| 3112 |
t.Errorf("unexpected error: %v", err) |
| 3113 |
} |
| 3114 |
dump, _ := httputil.DumpResponse(response, true) |
| 3115 |
t.Log(string(dump)) |
| 3116 |
|
| 3117 |
if response.StatusCode != http.StatusOK { |
| 3118 |
t.Errorf("Unexpected response %#v", response) |
| 3119 |
} |
| 3120 |
} |
| 3121 |
|
| 3122 |
// when the object name and namespace can't be retrieved, don't update. It isn't safe. |
| 3123 |
func TestUpdateDisallowsMismatchedNamespaceOnError(t *testing.T) { |
| 3124 |
storage := map[string]rest.Storage{} |
| 3125 |
simpleStorage := SimpleRESTStorage{} |
| 3126 |
ID := "id" |
| 3127 |
storage["simple"] = &simpleStorage |
| 3128 |
handler := handle(storage) |
| 3129 |
server := httptest.NewServer(handler) |
| 3130 |
defer server.Close() |
| 3131 |
|
| 3132 |
item := &genericapitesting.Simple{ |
| 3133 |
ObjectMeta: metav1.ObjectMeta{ |
| 3134 |
Name: ID, |
| 3135 |
Namespace: "other", // does not match request |
| 3136 |
}, |
| 3137 |
Other: "bar", |
| 3138 |
} |
| 3139 |
body, err := runtime.Encode(testCodec, item) |
| 3140 |
if err != nil { |
| 3141 |
// The following cases will fail, so die now |
| 3142 |
t.Fatalf("unexpected error: %v", err) |
| 3143 |
} |
| 3144 |
|
| 3145 |
client := http.Client{} |
| 3146 |
request, err := http.NewRequest("PUT", server.URL+"/"+prefix+"/"+testGroupVersion.Group+"/"+testGroupVersion.Version+"/namespaces/default/simple/"+ID, bytes.NewReader(body)) |
| 3147 |
if err != nil { |
| 3148 |
t.Errorf("unexpected error: %v", err) |
| 3149 |
} |
| 3150 |
response, err := client.Do(request) |
| 3151 |
if err != nil { |
| 3152 |
t.Errorf("unexpected error: %v", err) |
| 3153 |
} |
| 3154 |
dump, _ := httputil.DumpResponse(response, true) |
| 3155 |
t.Log(string(dump)) |
| 3156 |
|
| 3157 |
if simpleStorage.updated != nil { |
| 3158 |
t.Errorf("Unexpected update value %#v.", simpleStorage.updated) |
| 3159 |
} |
| 3160 |
} |
| 3161 |
|
| 3162 |
func TestUpdatePreventsMismatchedNamespace(t *testing.T) { |
| 3163 |
storage := map[string]rest.Storage{} |
| 3164 |
simpleStorage := SimpleRESTStorage{} |
| 3165 |
ID := "id" |
| 3166 |
storage["simple"] = &simpleStorage |
| 3167 |
handler := handle(storage) |
| 3168 |
server := httptest.NewServer(handler) |
| 3169 |
defer server.Close() |
| 3170 |
|
| 3171 |
item := &genericapitesting.Simple{ |
| 3172 |
ObjectMeta: metav1.ObjectMeta{ |
| 3173 |
Name: ID, |
| 3174 |
Namespace: "other", |
| 3175 |
}, |
| 3176 |
Other: "bar", |
| 3177 |
} |
| 3178 |
body, err := runtime.Encode(testCodec, item) |
| 3179 |
if err != nil { |
| 3180 |
// The following cases will fail, so die now |
| 3181 |
t.Fatalf("unexpected error: %v", err) |
| 3182 |
} |
| 3183 |
|
| 3184 |
client := http.Client{} |
| 3185 |
request, err := http.NewRequest("PUT", server.URL+"/"+prefix+"/"+testGroupVersion.Group+"/"+testGroupVersion.Version+"/namespaces/default/simple/"+ID, bytes.NewReader(body)) |
| 3186 |
if err != nil { |
| 3187 |
t.Errorf("unexpected error: %v", err) |
| 3188 |
} |
| 3189 |
response, err := client.Do(request) |
| 3190 |
if err != nil { |
| 3191 |
t.Errorf("unexpected error: %v", err) |
| 3192 |
} |
| 3193 |
if response.StatusCode != http.StatusBadRequest { |
| 3194 |
t.Errorf("Unexpected response %#v", response) |
| 3195 |
} |
| 3196 |
} |
| 3197 |
|
| 3198 |
func TestUpdateMissing(t *testing.T) { |
| 3199 |
storage := map[string]rest.Storage{} |
| 3200 |
ID := "id" |
| 3201 |
simpleStorage := SimpleRESTStorage{ |
| 3202 |
errors: map[string]error{"update": apierrors.NewNotFound(schema.GroupResource{Resource: "simples"}, ID)}, |
| 3203 |
} |
| 3204 |
storage["simple"] = &simpleStorage |
| 3205 |
handler := handle(storage) |
| 3206 |
server := httptest.NewServer(handler) |
| 3207 |
defer server.Close() |
| 3208 |
|
| 3209 |
item := &genericapitesting.Simple{ |
| 3210 |
ObjectMeta: metav1.ObjectMeta{ |
| 3211 |
Name: ID, |
| 3212 |
Namespace: metav1.NamespaceDefault, |
| 3213 |
}, |
| 3214 |
Other: "bar", |
| 3215 |
} |
| 3216 |
body, err := runtime.Encode(testCodec, item) |
| 3217 |
if err != nil { |
| 3218 |
t.Errorf("unexpected error: %v", err) |
| 3219 |
} |
| 3220 |
|
| 3221 |
client := http.Client{} |
| 3222 |
request, err := http.NewRequest("PUT", server.URL+"/"+prefix+"/"+testGroupVersion.Group+"/"+testGroupVersion.Version+"/namespaces/default/simple/"+ID, bytes.NewReader(body)) |
| 3223 |
if err != nil { |
| 3224 |
t.Errorf("unexpected error: %v", err) |
| 3225 |
} |
| 3226 |
response, err := client.Do(request) |
| 3227 |
if err != nil { |
| 3228 |
t.Errorf("unexpected error: %v", err) |
| 3229 |
} |
| 3230 |
if response.StatusCode != http.StatusNotFound { |
| 3231 |
t.Errorf("Unexpected response %#v", response) |
| 3232 |
} |
| 3233 |
} |
| 3234 |
|
| 3235 |
func TestCreateNotFound(t *testing.T) { |
| 3236 |
handler := handle(map[string]rest.Storage{ |
| 3237 |
"simple": &SimpleRESTStorage{ |
| 3238 |
// storage.Create can fail with not found error in theory. |
| 3239 |
// See https://pr.k8s.io/486#discussion_r15037092. |
| 3240 |
errors: map[string]error{"create": apierrors.NewNotFound(schema.GroupResource{Resource: "simples"}, "id")}, |
| 3241 |
}, |
| 3242 |
}) |
| 3243 |
server := httptest.NewServer(handler) |
| 3244 |
defer server.Close() |
| 3245 |
client := http.Client{} |
| 3246 |
|
| 3247 |
simple := &genericapitesting.Simple{Other: "foo"} |
| 3248 |
data, err := runtime.Encode(testCodec, simple) |
| 3249 |
if err != nil { |
| 3250 |
t.Errorf("unexpected error: %v", err) |
| 3251 |
} |
| 3252 |
request, err := http.NewRequest("POST", server.URL+"/"+prefix+"/"+testGroupVersion.Group+"/"+testGroupVersion.Version+"/namespaces/default/simple", bytes.NewBuffer(data)) |
| 3253 |
if err != nil { |
| 3254 |
t.Errorf("unexpected error: %v", err) |
| 3255 |
} |
| 3256 |
|
| 3257 |
response, err := client.Do(request) |
| 3258 |
if err != nil { |
| 3259 |
t.Errorf("unexpected error: %v", err) |
| 3260 |
} |
| 3261 |
|
| 3262 |
if response.StatusCode != http.StatusNotFound { |
| 3263 |
t.Errorf("Unexpected response %#v", response) |
| 3264 |
} |
| 3265 |
} |
| 3266 |
|
| 3267 |
func TestCreateChecksDecode(t *testing.T) { |
| 3268 |
handler := handle(map[string]rest.Storage{"simple": &SimpleRESTStorage{}}) |
| 3269 |
server := httptest.NewServer(handler) |
| 3270 |
defer server.Close() |
| 3271 |
client := http.Client{} |
| 3272 |
|
| 3273 |
simple := &example.Pod{} |
| 3274 |
data, err := runtime.Encode(testCodec, simple) |
| 3275 |
if err != nil { |
| 3276 |
t.Errorf("unexpected error: %v", err) |
| 3277 |
} |
| 3278 |
request, err := http.NewRequest("POST", server.URL+"/"+prefix+"/"+testGroupVersion.Group+"/"+testGroupVersion.Version+"/namespaces/default/simple", bytes.NewBuffer(data)) |
| 3279 |
if err != nil { |
| 3280 |
t.Errorf("unexpected error: %v", err) |
| 3281 |
} |
| 3282 |
response, err := client.Do(request) |
| 3283 |
if err != nil { |
| 3284 |
t.Errorf("unexpected error: %v", err) |
| 3285 |
} |
| 3286 |
if response.StatusCode != http.StatusBadRequest { |
| 3287 |
t.Errorf("Unexpected response %#v", response) |
| 3288 |
} |
| 3289 |
b, err := ioutil.ReadAll(response.Body) |
| 3290 |
if err != nil { |
| 3291 |
t.Errorf("unexpected error: %v", err) |
| 3292 |
} else if !strings.Contains(string(b), "cannot be handled as a Simple") { |
| 3293 |
t.Errorf("unexpected response: %s", string(b)) |
| 3294 |
} |
| 3295 |
} |
| 3296 |
|
| 3297 |
func TestParentResourceIsRequired(t *testing.T) { |
| 3298 |
storage := &SimpleTypedStorage{ |
| 3299 |
baseType: &genericapitesting.SimpleRoot{}, // a root scoped type |
| 3300 |
item: &genericapitesting.SimpleRoot{}, |
| 3301 |
} |
| 3302 |
group := &APIGroupVersion{ |
| 3303 |
Storage: map[string]rest.Storage{ |
| 3304 |
"simple/sub": storage, |
| 3305 |
}, |
| 3306 |
Root: "/" + prefix, |
| 3307 |
Creater: scheme, |
| 3308 |
Convertor: scheme, |
| 3309 |
UnsafeConvertor: runtime.UnsafeObjectConvertor(scheme), |
| 3310 |
Defaulter: scheme, |
| 3311 |
Typer: scheme, |
| 3312 |
Namer: namer, |
| 3313 |
|
| 3314 |
EquivalentResourceRegistry: runtime.NewEquivalentResourceRegistry(), |
| 3315 |
|
| 3316 |
Admit: admissionControl, |
| 3317 |
|
| 3318 |
GroupVersion: newGroupVersion, |
| 3319 |
OptionsExternalVersion: &newGroupVersion, |
| 3320 |
|
| 3321 |
Serializer: codecs, |
| 3322 |
ParameterCodec: parameterCodec, |
| 3323 |
} |
| 3324 |
container := restful.NewContainer() |
| 3325 |
if _, _, err := group.InstallREST(container); err == nil { |
| 3326 |
t.Fatal("expected error") |
| 3327 |
} |
| 3328 |
|
| 3329 |
storage = &SimpleTypedStorage{ |
| 3330 |
baseType: &genericapitesting.SimpleRoot{}, // a root scoped type |
| 3331 |
item: &genericapitesting.SimpleRoot{}, |
| 3332 |
} |
| 3333 |
group = &APIGroupVersion{ |
| 3334 |
Storage: map[string]rest.Storage{ |
| 3335 |
"simple": &SimpleRESTStorage{}, |
| 3336 |
"simple/sub": storage, |
| 3337 |
}, |
| 3338 |
Root: "/" + prefix, |
| 3339 |
Creater: scheme, |
| 3340 |
Convertor: scheme, |
| 3341 |
UnsafeConvertor: runtime.UnsafeObjectConvertor(scheme), |
| 3342 |
TypeConverter: managedfields.NewDeducedTypeConverter(), |
| 3343 |
Defaulter: scheme, |
| 3344 |
Typer: scheme, |
| 3345 |
Namer: namer, |
| 3346 |
|
| 3347 |
EquivalentResourceRegistry: runtime.NewEquivalentResourceRegistry(), |
| 3348 |
|
| 3349 |
Admit: admissionControl, |
| 3350 |
|
| 3351 |
GroupVersion: newGroupVersion, |
| 3352 |
OptionsExternalVersion: &newGroupVersion, |
| 3353 |
|
| 3354 |
Serializer: codecs, |
| 3355 |
ParameterCodec: parameterCodec, |
| 3356 |
} |
| 3357 |
container = restful.NewContainer() |
| 3358 |
if _, _, err := group.InstallREST(container); err != nil { |
| 3359 |
t.Fatal(err) |
| 3360 |
} |
| 3361 |
|
| 3362 |
handler := genericapifilters.WithRequestInfo(container, newTestRequestInfoResolver()) |
| 3363 |
|
| 3364 |
// resource is NOT registered in the root scope |
| 3365 |
w := httptest.NewRecorder() |
| 3366 |
handler.ServeHTTP(w, &http.Request{Method: "GET", URL: &url.URL{Path: "/" + prefix + "/simple/test/sub"}}) |
| 3367 |
if w.Code != http.StatusNotFound { |
| 3368 |
t.Errorf("expected not found: %#v", w) |
| 3369 |
} |
| 3370 |
|
| 3371 |
// resource is registered in the namespace scope |
| 3372 |
w = httptest.NewRecorder() |
| 3373 |
handler.ServeHTTP(w, &http.Request{Method: "GET", URL: &url.URL{Path: "/" + prefix + "/" + newGroupVersion.Group + "/" + newGroupVersion.Version + "/namespaces/test/simple/test/sub"}}) |
| 3374 |
if w.Code != http.StatusOK { |
| 3375 |
t.Fatalf("expected OK: %#v", w) |
| 3376 |
} |
| 3377 |
if storage.actualNamespace != "test" { |
| 3378 |
t.Errorf("namespace should be set %#v", storage) |
| 3379 |
} |
| 3380 |
} |
| 3381 |
|
| 3382 |
func TestNamedCreaterWithName(t *testing.T) { |
| 3383 |
pathName := "helloworld" |
| 3384 |
storage := &NamedCreaterRESTStorage{SimpleRESTStorage: &SimpleRESTStorage{}} |
| 3385 |
handler := handle(map[string]rest.Storage{ |
| 3386 |
"simple": &SimpleRESTStorage{}, |
| 3387 |
"simple/sub": storage, |
| 3388 |
}) |
| 3389 |
server := httptest.NewServer(handler) |
| 3390 |
defer server.Close() |
| 3391 |
client := http.Client{} |
| 3392 |
|
| 3393 |
simple := &genericapitesting.Simple{Other: "foo"} |
| 3394 |
data, err := runtime.Encode(testCodec, simple) |
| 3395 |
if err != nil { |
| 3396 |
t.Errorf("unexpected error: %v", err) |
| 3397 |
} |
| 3398 |
request, err := http.NewRequest("POST", server.URL+"/"+prefix+"/"+testGroupVersion.Group+"/"+testGroupVersion.Version+"/namespaces/default/simple/"+pathName+"/sub", bytes.NewBuffer(data)) |
| 3399 |
if err != nil { |
| 3400 |
t.Errorf("unexpected error: %v", err) |
| 3401 |
} |
| 3402 |
response, err := client.Do(request) |
| 3403 |
if err != nil { |
| 3404 |
t.Errorf("unexpected error: %v", err) |
| 3405 |
} |
| 3406 |
if response.StatusCode != http.StatusCreated { |
| 3407 |
t.Errorf("Unexpected response %#v", response) |
| 3408 |
} |
| 3409 |
if storage.createdName != pathName { |
| 3410 |
t.Errorf("Did not get expected name in create context. Got: %s, Expected: %s", storage.createdName, pathName) |
| 3411 |
} |
| 3412 |
} |
| 3413 |
|
| 3414 |
func TestNamedCreaterWithoutName(t *testing.T) { |
| 3415 |
storage := &NamedCreaterRESTStorage{ |
| 3416 |
SimpleRESTStorage: &SimpleRESTStorage{ |
| 3417 |
injectedFunction: func(obj runtime.Object) (runtime.Object, error) { |
| 3418 |
time.Sleep(5 * time.Millisecond) |
| 3419 |
return obj, nil |
| 3420 |
}, |
| 3421 |
}, |
| 3422 |
} |
| 3423 |
|
| 3424 |
handler := handle(map[string]rest.Storage{"foo": storage}) |
| 3425 |
server := httptest.NewServer(handler) |
| 3426 |
defer server.Close() |
| 3427 |
client := http.Client{} |
| 3428 |
|
| 3429 |
simple := &genericapitesting.Simple{ |
| 3430 |
Other: "bar", |
| 3431 |
} |
| 3432 |
data, err := runtime.Encode(testCodec, simple) |
| 3433 |
if err != nil { |
| 3434 |
t.Errorf("unexpected error: %v", err) |
| 3435 |
} |
| 3436 |
request, err := http.NewRequest("POST", server.URL+"/"+prefix+"/"+testGroupVersion.Group+"/"+testGroupVersion.Version+"/namespaces/default/foo", bytes.NewBuffer(data)) |
| 3437 |
if err != nil { |
| 3438 |
t.Errorf("unexpected error: %v", err) |
| 3439 |
} |
| 3440 |
|
| 3441 |
wg := sync.WaitGroup{} |
| 3442 |
wg.Add(1) |
| 3443 |
var response *http.Response |
| 3444 |
go func() { |
| 3445 |
response, err = client.Do(request) |
| 3446 |
wg.Done() |
| 3447 |
}() |
| 3448 |
wg.Wait() |
| 3449 |
if err != nil { |
| 3450 |
t.Errorf("unexpected error: %v", err) |
| 3451 |
} |
| 3452 |
// empty name is not allowed for NamedCreater |
| 3453 |
if response.StatusCode != http.StatusBadRequest { |
| 3454 |
t.Errorf("Unexpected response %#v", response) |
| 3455 |
} |
| 3456 |
} |
| 3457 |
|
| 3458 |
type namePopulatorAdmissionControl struct { |
| 3459 |
t *testing.T |
| 3460 |
populateName string |
| 3461 |
} |
| 3462 |
|
| 3463 |
func (npac *namePopulatorAdmissionControl) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) { |
| 3464 |
if a.GetName() != npac.populateName { |
| 3465 |
npac.t.Errorf("Unexpected name: got %q, expected %q", a.GetName(), npac.populateName) |
| 3466 |
} |
| 3467 |
return nil |
| 3468 |
} |
| 3469 |
|
| 3470 |
func (npac *namePopulatorAdmissionControl) Handles(operation admission.Operation) bool { |
| 3471 |
return true |
| 3472 |
} |
| 3473 |
|
| 3474 |
var _ admission.ValidationInterface = &namePopulatorAdmissionControl{} |
| 3475 |
|
| 3476 |
func TestNamedCreaterWithGenerateName(t *testing.T) { |
| 3477 |
populateName := "bar" |
| 3478 |
storage := &SimpleRESTStorage{ |
| 3479 |
injectedFunction: func(obj runtime.Object) (runtime.Object, error) { |
| 3480 |
time.Sleep(5 * time.Millisecond) |
| 3481 |
if metadata, err := meta.Accessor(obj); err == nil { |
| 3482 |
if len(metadata.GetName()) != 0 { |
| 3483 |
t.Errorf("Unexpected name %q", metadata.GetName()) |
| 3484 |
} |
| 3485 |
metadata.SetName(populateName) |
| 3486 |
} else { |
| 3487 |
return nil, err |
| 3488 |
} |
| 3489 |
return obj, nil |
| 3490 |
}, |
| 3491 |
} |
| 3492 |
|
| 3493 |
ac := &namePopulatorAdmissionControl{ |
| 3494 |
t: t, |
| 3495 |
populateName: populateName, |
| 3496 |
} |
| 3497 |
|
| 3498 |
handler := handleInternal(map[string]rest.Storage{"foo": storage}, ac, nil) |
| 3499 |
server := httptest.NewServer(handler) |
| 3500 |
defer server.Close() |
| 3501 |
client := http.Client{} |
| 3502 |
|
| 3503 |
simple := &genericapitesting.Simple{ |
| 3504 |
Other: "bar", |
| 3505 |
} |
| 3506 |
data, err := runtime.Encode(testCodec, simple) |
| 3507 |
if err != nil { |
| 3508 |
t.Errorf("unexpected error: %v", err) |
| 3509 |
} |
| 3510 |
request, err := http.NewRequest("POST", server.URL+"/"+prefix+"/"+testGroupVersion.Group+"/"+testGroupVersion.Version+"/namespaces/default/foo", bytes.NewBuffer(data)) |
| 3511 |
if err != nil { |
| 3512 |
t.Errorf("unexpected error: %v", err) |
| 3513 |
} |
| 3514 |
|
| 3515 |
wg := sync.WaitGroup{} |
| 3516 |
wg.Add(1) |
| 3517 |
var response *http.Response |
| 3518 |
go func() { |
| 3519 |
response, err = client.Do(request) |
| 3520 |
wg.Done() |
| 3521 |
}() |
| 3522 |
wg.Wait() |
| 3523 |
if err != nil { |
| 3524 |
t.Errorf("unexpected error: %v", err) |
| 3525 |
} |
| 3526 |
if response.StatusCode != http.StatusCreated { |
| 3527 |
t.Errorf("Unexpected status: %d, Expected: %d, %#v", response.StatusCode, http.StatusOK, response) |
| 3528 |
} |
| 3529 |
|
| 3530 |
var itemOut genericapitesting.Simple |
| 3531 |
body, err := extractBody(response, &itemOut) |
| 3532 |
if err != nil { |
| 3533 |
t.Errorf("unexpected error: %v %#v", err, response) |
| 3534 |
} |
| 3535 |
|
| 3536 |
// Avoid comparing managed fields in expected result |
| 3537 |
itemOut.ManagedFields = nil |
| 3538 |
itemOut.GetObjectKind().SetGroupVersionKind(schema.GroupVersionKind{}) |
| 3539 |
simple.Name = populateName |
| 3540 |
simple.Namespace = "default" // populated by create handler to match request URL |
| 3541 |
if !reflect.DeepEqual(&itemOut, simple) { |
| 3542 |
t.Errorf("Unexpected data: %#v, expected %#v (%s)", itemOut, simple, string(body)) |
| 3543 |
} |
| 3544 |
} |
| 3545 |
|
| 3546 |
func TestUpdateChecksDecode(t *testing.T) { |
| 3547 |
handler := handle(map[string]rest.Storage{"simple": &SimpleRESTStorage{}}) |
| 3548 |
server := httptest.NewServer(handler) |
| 3549 |
defer server.Close() |
| 3550 |
client := http.Client{} |
| 3551 |
|
| 3552 |
simple := &example.Pod{} |
| 3553 |
data, err := runtime.Encode(testCodec, simple) |
| 3554 |
if err != nil { |
| 3555 |
t.Errorf("unexpected error: %v", err) |
| 3556 |
} |
| 3557 |
request, err := http.NewRequest("PUT", server.URL+"/"+prefix+"/"+testGroupVersion.Group+"/"+testGroupVersion.Version+"/namespaces/default/simple/bar", bytes.NewBuffer(data)) |
| 3558 |
if err != nil { |
| 3559 |
t.Errorf("unexpected error: %v", err) |
| 3560 |
} |
| 3561 |
response, err := client.Do(request) |
| 3562 |
if err != nil { |
| 3563 |
t.Errorf("unexpected error: %v", err) |
| 3564 |
} |
| 3565 |
if response.StatusCode != http.StatusBadRequest { |
| 3566 |
t.Errorf("Unexpected response %#v\n%s", response, readBodyOrDie(response.Body)) |
| 3567 |
} |
| 3568 |
b, err := ioutil.ReadAll(response.Body) |
| 3569 |
if err != nil { |
| 3570 |
t.Errorf("unexpected error: %v", err) |
| 3571 |
} else if !strings.Contains(string(b), "cannot be handled as a Simple") { |
| 3572 |
t.Errorf("unexpected response: %s", string(b)) |
| 3573 |
} |
| 3574 |
} |
| 3575 |
|
| 3576 |
func TestCreate(t *testing.T) { |
| 3577 |
storage := SimpleRESTStorage{ |
| 3578 |
injectedFunction: func(obj runtime.Object) (runtime.Object, error) { |
| 3579 |
time.Sleep(5 * time.Millisecond) |
| 3580 |
return obj, nil |
| 3581 |
}, |
| 3582 |
} |
| 3583 |
handler := handle(map[string]rest.Storage{"foo": &storage}) |
| 3584 |
server := httptest.NewServer(handler) |
| 3585 |
defer server.Close() |
| 3586 |
client := http.Client{} |
| 3587 |
|
| 3588 |
simple := &genericapitesting.Simple{ |
| 3589 |
Other: "bar", |
| 3590 |
} |
| 3591 |
data, err := runtime.Encode(testCodec, simple) |
| 3592 |
if err != nil { |
| 3593 |
t.Errorf("unexpected error: %v", err) |
| 3594 |
} |
| 3595 |
request, err := http.NewRequest("POST", server.URL+"/"+prefix+"/"+testGroupVersion.Group+"/"+testGroupVersion.Version+"/namespaces/default/foo", bytes.NewBuffer(data)) |
| 3596 |
if err != nil { |
| 3597 |
t.Errorf("unexpected error: %v", err) |
| 3598 |
} |
| 3599 |
|
| 3600 |
wg := sync.WaitGroup{} |
| 3601 |
wg.Add(1) |
| 3602 |
var response *http.Response |
| 3603 |
go func() { |
| 3604 |
response, err = client.Do(request) |
| 3605 |
wg.Done() |
| 3606 |
}() |
| 3607 |
wg.Wait() |
| 3608 |
if err != nil { |
| 3609 |
t.Errorf("unexpected error: %v", err) |
| 3610 |
} |
| 3611 |
|
| 3612 |
var itemOut genericapitesting.Simple |
| 3613 |
body, err := extractBody(response, &itemOut) |
| 3614 |
if err != nil { |
| 3615 |
t.Errorf("unexpected error: %v %#v", err, response) |
| 3616 |
} |
| 3617 |
|
| 3618 |
// Avoid comparing managed fields in expected result |
| 3619 |
itemOut.ManagedFields = nil |
| 3620 |
itemOut.GetObjectKind().SetGroupVersionKind(schema.GroupVersionKind{}) |
| 3621 |
simple.Namespace = "default" // populated by create handler to match request URL |
| 3622 |
if !reflect.DeepEqual(&itemOut, simple) { |
| 3623 |
t.Errorf("Unexpected data: %#v, expected %#v (%s)", itemOut, simple, string(body)) |
| 3624 |
} |
| 3625 |
if response.StatusCode != http.StatusCreated { |
| 3626 |
t.Errorf("Unexpected status: %d, Expected: %d, %#v", response.StatusCode, http.StatusOK, response) |
| 3627 |
} |
| 3628 |
} |
| 3629 |
|
| 3630 |
func TestCreateYAML(t *testing.T) { |
| 3631 |
storage := SimpleRESTStorage{ |
| 3632 |
injectedFunction: func(obj runtime.Object) (runtime.Object, error) { |
| 3633 |
time.Sleep(5 * time.Millisecond) |
| 3634 |
return obj, nil |
| 3635 |
}, |
| 3636 |
} |
| 3637 |
handler := handle(map[string]rest.Storage{"foo": &storage}) |
| 3638 |
server := httptest.NewServer(handler) |
| 3639 |
defer server.Close() |
| 3640 |
client := http.Client{} |
| 3641 |
|
| 3642 |
// yaml encoder |
| 3643 |
simple := &genericapitesting.Simple{ |
| 3644 |
Other: "bar", |
| 3645 |
} |
| 3646 |
info, ok := runtime.SerializerInfoForMediaType(codecs.SupportedMediaTypes(), "application/yaml") |
| 3647 |
if !ok { |
| 3648 |
t.Fatal("No yaml serializer") |
| 3649 |
} |
| 3650 |
encoder := codecs.EncoderForVersion(info.Serializer, testGroupVersion) |
| 3651 |
decoder := codecs.DecoderToVersion(info.Serializer, testInternalGroupVersion) |
| 3652 |
|
| 3653 |
data, err := runtime.Encode(encoder, simple) |
| 3654 |
if err != nil { |
| 3655 |
t.Fatalf("unexpected error: %v", err) |
| 3656 |
} |
| 3657 |
request, err := http.NewRequest("POST", server.URL+"/"+prefix+"/"+testGroupVersion.Group+"/"+testGroupVersion.Version+"/namespaces/default/foo", bytes.NewBuffer(data)) |
| 3658 |
if err != nil { |
| 3659 |
t.Fatalf("unexpected error: %v", err) |
| 3660 |
} |
| 3661 |
request.Header.Set("Accept", "application/yaml, application/json") |
| 3662 |
request.Header.Set("Content-Type", "application/yaml") |
| 3663 |
|
| 3664 |
wg := sync.WaitGroup{} |
| 3665 |
wg.Add(1) |
| 3666 |
var response *http.Response |
| 3667 |
go func() { |
| 3668 |
response, err = client.Do(request) |
| 3669 |
wg.Done() |
| 3670 |
}() |
| 3671 |
wg.Wait() |
| 3672 |
if err != nil { |
| 3673 |
t.Fatalf("unexpected error: %v", err) |
| 3674 |
} |
| 3675 |
|
| 3676 |
var itemOut genericapitesting.Simple |
| 3677 |
body, err := extractBodyDecoder(response, &itemOut, decoder) |
| 3678 |
if err != nil { |
| 3679 |
t.Fatalf("unexpected error: %v %#v", err, response) |
| 3680 |
} |
| 3681 |
|
| 3682 |
// Avoid comparing managed fields in expected result |
| 3683 |
itemOut.ManagedFields = nil |
| 3684 |
itemOut.GetObjectKind().SetGroupVersionKind(schema.GroupVersionKind{}) |
| 3685 |
simple.Namespace = "default" // populated by create handler to match request URL |
| 3686 |
if !reflect.DeepEqual(&itemOut, simple) { |
| 3687 |
t.Errorf("Unexpected data: %#v, expected %#v (%s)", itemOut, simple, string(body)) |
| 3688 |
} |
| 3689 |
if response.StatusCode != http.StatusCreated { |
| 3690 |
t.Errorf("Unexpected status: %d, Expected: %d, %#v", response.StatusCode, http.StatusOK, response) |
| 3691 |
} |
| 3692 |
} |
| 3693 |
|
| 3694 |
func TestCreateInNamespace(t *testing.T) { |
| 3695 |
storage := SimpleRESTStorage{ |
| 3696 |
injectedFunction: func(obj runtime.Object) (runtime.Object, error) { |
| 3697 |
time.Sleep(5 * time.Millisecond) |
| 3698 |
return obj, nil |
| 3699 |
}, |
| 3700 |
} |
| 3701 |
handler := handle(map[string]rest.Storage{"foo": &storage}) |
| 3702 |
server := httptest.NewServer(handler) |
| 3703 |
defer server.Close() |
| 3704 |
client := http.Client{} |
| 3705 |
|
| 3706 |
simple := &genericapitesting.Simple{ |
| 3707 |
Other: "bar", |
| 3708 |
} |
| 3709 |
data, err := runtime.Encode(testCodec, simple) |
| 3710 |
if err != nil { |
| 3711 |
t.Fatalf("unexpected error: %v", err) |
| 3712 |
} |
| 3713 |
request, err := http.NewRequest("POST", server.URL+"/"+prefix+"/"+testGroupVersion.Group+"/"+testGroupVersion.Version+"/namespaces/other/foo", bytes.NewBuffer(data)) |
| 3714 |
if err != nil { |
| 3715 |
t.Fatalf("unexpected error: %v", err) |
| 3716 |
} |
| 3717 |
|
| 3718 |
wg := sync.WaitGroup{} |
| 3719 |
wg.Add(1) |
| 3720 |
var response *http.Response |
| 3721 |
go func() { |
| 3722 |
response, err = client.Do(request) |
| 3723 |
wg.Done() |
| 3724 |
}() |
| 3725 |
wg.Wait() |
| 3726 |
if err != nil { |
| 3727 |
t.Fatalf("unexpected error: %v", err) |
| 3728 |
} |
| 3729 |
|
| 3730 |
var itemOut genericapitesting.Simple |
| 3731 |
body, err := extractBody(response, &itemOut) |
| 3732 |
if err != nil { |
| 3733 |
t.Fatalf("unexpected error: %v\n%s", err, data) |
| 3734 |
} |
| 3735 |
|
| 3736 |
// Avoid comparing managed fields in expected result |
| 3737 |
itemOut.ManagedFields = nil |
| 3738 |
itemOut.GetObjectKind().SetGroupVersionKind(schema.GroupVersionKind{}) |
| 3739 |
simple.Namespace = "other" // populated by create handler to match request URL |
| 3740 |
if !reflect.DeepEqual(&itemOut, simple) { |
| 3741 |
t.Errorf("Unexpected data: %#v, expected %#v (%s)", itemOut, simple, string(body)) |
| 3742 |
} |
| 3743 |
if response.StatusCode != http.StatusCreated { |
| 3744 |
t.Errorf("Unexpected status: %d, Expected: %d, %#v", response.StatusCode, http.StatusOK, response) |
| 3745 |
} |
| 3746 |
} |
| 3747 |
|
| 3748 |
func TestCreateInvokeAdmissionControl(t *testing.T) { |
| 3749 |
for _, admit := range []admission.Interface{alwaysMutatingDeny{}, alwaysValidatingDeny{}} { |
| 3750 |
t.Logf("Testing %T", admit) |
| 3751 |
|
| 3752 |
storage := SimpleRESTStorage{ |
| 3753 |
injectedFunction: func(obj runtime.Object) (runtime.Object, error) { |
| 3754 |
time.Sleep(5 * time.Millisecond) |
| 3755 |
return obj, nil |
| 3756 |
}, |
| 3757 |
} |
| 3758 |
handler := handleInternal(map[string]rest.Storage{"foo": &storage}, admit, nil) |
| 3759 |
server := httptest.NewServer(handler) |
| 3760 |
defer server.Close() |
| 3761 |
client := http.Client{} |
| 3762 |
|
| 3763 |
simple := &genericapitesting.Simple{ |
| 3764 |
Other: "bar", |
| 3765 |
} |
| 3766 |
data, err := runtime.Encode(testCodec, simple) |
| 3767 |
if err != nil { |
| 3768 |
t.Errorf("unexpected error: %v", err) |
| 3769 |
} |
| 3770 |
request, err := http.NewRequest("POST", server.URL+"/"+prefix+"/"+testGroupVersion.Group+"/"+testGroupVersion.Version+"/namespaces/other/foo", bytes.NewBuffer(data)) |
| 3771 |
if err != nil { |
| 3772 |
t.Errorf("unexpected error: %v", err) |
| 3773 |
} |
| 3774 |
|
| 3775 |
var response *http.Response |
| 3776 |
response, err = client.Do(request) |
| 3777 |
if err != nil { |
| 3778 |
t.Errorf("unexpected error: %v", err) |
| 3779 |
} |
| 3780 |
if response.StatusCode != http.StatusForbidden { |
| 3781 |
t.Errorf("Unexpected status: %d, Expected: %d, %#v", response.StatusCode, http.StatusForbidden, response) |
| 3782 |
} |
| 3783 |
} |
| 3784 |
} |
| 3785 |
|
| 3786 |
func expectAPIStatus(t *testing.T, method, url string, data []byte, code int) *metav1.Status { |
| 3787 |
t.Helper() |
| 3788 |
client := http.Client{} |
| 3789 |
request, err := http.NewRequest(method, url, bytes.NewBuffer(data)) |
| 3790 |
if err != nil { |
| 3791 |
t.Fatalf("unexpected error %#v", err) |
| 3792 |
return nil |
| 3793 |
} |
| 3794 |
response, err := client.Do(request) |
| 3795 |
if err != nil { |
| 3796 |
t.Fatalf("unexpected error on %s %s: %v", method, url, err) |
| 3797 |
return nil |
| 3798 |
} |
| 3799 |
var status metav1.Status |
| 3800 |
body, err := extractBody(response, &status) |
| 3801 |
if err != nil { |
| 3802 |
t.Fatalf("unexpected error on %s %s: %v\nbody:\n%s", method, url, err, body) |
| 3803 |
return nil |
| 3804 |
} |
| 3805 |
if code != response.StatusCode { |
| 3806 |
t.Fatalf("Expected %s %s to return %d, Got %d: %v", method, url, code, response.StatusCode, body) |
| 3807 |
} |
| 3808 |
return &status |
| 3809 |
} |
| 3810 |
|
| 3811 |
func TestDelayReturnsError(t *testing.T) { |
| 3812 |
storage := SimpleRESTStorage{ |
| 3813 |
injectedFunction: func(obj runtime.Object) (runtime.Object, error) { |
| 3814 |
return nil, apierrors.NewAlreadyExists(schema.GroupResource{Resource: "foos"}, "bar") |
| 3815 |
}, |
| 3816 |
} |
| 3817 |
handler := handle(map[string]rest.Storage{"foo": &storage}) |
| 3818 |
server := httptest.NewServer(handler) |
| 3819 |
defer server.Close() |
| 3820 |
|
| 3821 |
status := expectAPIStatus(t, "DELETE", fmt.Sprintf("%s/"+prefix+"/"+testGroupVersion.Group+"/"+testGroupVersion.Version+"/namespaces/default/foo/bar", server.URL), nil, http.StatusConflict) |
| 3822 |
if status.Status != metav1.StatusFailure || status.Message == "" || status.Details == nil || status.Reason != metav1.StatusReasonAlreadyExists { |
| 3823 |
t.Errorf("Unexpected status %#v", status) |
| 3824 |
} |
| 3825 |
} |
| 3826 |
|
| 3827 |
type UnregisteredAPIObject struct { |
| 3828 |
Value string |
| 3829 |
} |
| 3830 |
|
| 3831 |
func (obj *UnregisteredAPIObject) GetObjectKind() schema.ObjectKind { |
| 3832 |
return schema.EmptyObjectKind |
| 3833 |
} |
| 3834 |
func (obj *UnregisteredAPIObject) DeepCopyObject() runtime.Object { |
| 3835 |
if obj == nil { |
| 3836 |
return nil |
| 3837 |
} |
| 3838 |
clone := *obj |
| 3839 |
return &clone |
| 3840 |
} |
| 3841 |
|
| 3842 |
func TestWriteJSONDecodeError(t *testing.T) { |
| 3843 |
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { |
| 3844 |
responsewriters.WriteObjectNegotiated(codecs, negotiation.DefaultEndpointRestrictions, newGroupVersion, w, req, http.StatusOK, &UnregisteredAPIObject{"Undecodable"}, false) |
| 3845 |
})) |
| 3846 |
defer server.Close() |
| 3847 |
// Decode error response behavior is dictated by |
| 3848 |
// apiserver/pkg/endpoints/handlers/responsewriters/status.go::ErrorToAPIStatus(). |
| 3849 |
// Unless specific metav1.Status() parameters are implemented for the particular error in question, such that |
| 3850 |
// the status code is defined, metav1 errors where error.status == metav1.StatusFailure |
| 3851 |
// will throw a '500 Internal Server Error'. Non-metav1 type errors will always throw a '500 Internal Server Error'. |
| 3852 |
status := expectAPIStatus(t, "GET", server.URL, nil, http.StatusInternalServerError) |
| 3853 |
if status.Reason != metav1.StatusReasonUnknown { |
| 3854 |
t.Errorf("unexpected reason %#v", status) |
| 3855 |
} |
| 3856 |
if !strings.Contains(status.Message, "no kind is registered for the type endpoints.UnregisteredAPIObject") { |
| 3857 |
t.Errorf("unexpected message %#v", status) |
| 3858 |
} |
| 3859 |
} |
| 3860 |
|
| 3861 |
type marshalError struct { |
| 3862 |
err error |
| 3863 |
} |
| 3864 |
|
| 3865 |
func (m *marshalError) MarshalJSON() ([]byte, error) { |
| 3866 |
return []byte{}, m.err |
| 3867 |
} |
| 3868 |
|
| 3869 |
func TestWriteRAWJSONMarshalError(t *testing.T) { |
| 3870 |
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { |
| 3871 |
responsewriters.WriteRawJSON(http.StatusOK, &marshalError{errors.New("Undecodable")}, w) |
| 3872 |
})) |
| 3873 |
defer server.Close() |
| 3874 |
client := http.Client{} |
| 3875 |
resp, err := client.Get(server.URL) |
| 3876 |
if err != nil { |
| 3877 |
t.Errorf("unexpected error: %v", err) |
| 3878 |
} |
| 3879 |
|
| 3880 |
if resp.StatusCode != http.StatusInternalServerError { |
| 3881 |
t.Errorf("unexpected status code %d", resp.StatusCode) |
| 3882 |
} |
| 3883 |
} |
| 3884 |
|
| 3885 |
func TestCreateTimeout(t *testing.T) { |
| 3886 |
testOver := make(chan struct{}) |
| 3887 |
defer close(testOver) |
| 3888 |
storage := SimpleRESTStorage{ |
| 3889 |
injectedFunction: func(obj runtime.Object) (runtime.Object, error) { |
| 3890 |
// Eliminate flakes by ensuring the create operation takes longer than this test. |
| 3891 |
<-testOver |
| 3892 |
return obj, nil |
| 3893 |
}, |
| 3894 |
} |
| 3895 |
handler := handle(map[string]rest.Storage{ |
| 3896 |
"foo": &storage, |
| 3897 |
}) |
| 3898 |
server := httptest.NewServer(handler) |
| 3899 |
defer server.Close() |
| 3900 |
|
| 3901 |
simple := &genericapitesting.Simple{Other: "foo"} |
| 3902 |
data, err := runtime.Encode(testCodec, simple) |
| 3903 |
if err != nil { |
| 3904 |
t.Errorf("unexpected error: %v", err) |
| 3905 |
} |
| 3906 |
itemOut := expectAPIStatus(t, "POST", server.URL+"/"+prefix+"/"+testGroupVersion.Group+"/"+testGroupVersion.Version+"/namespaces/default/foo?timeout=4ms", data, http.StatusGatewayTimeout) |
| 3907 |
if itemOut.Status != metav1.StatusFailure || itemOut.Reason != metav1.StatusReasonTimeout { |
| 3908 |
t.Errorf("Unexpected status %#v", itemOut) |
| 3909 |
} |
| 3910 |
} |
| 3911 |
|
| 3912 |
func TestCreateChecksAPIVersion(t *testing.T) { |
| 3913 |
handler := handle(map[string]rest.Storage{"simple": &SimpleRESTStorage{}}) |
| 3914 |
server := httptest.NewServer(handler) |
| 3915 |
defer server.Close() |
| 3916 |
client := http.Client{} |
| 3917 |
|
| 3918 |
simple := &genericapitesting.Simple{} |
| 3919 |
//using newCodec and send the request to testVersion URL shall cause a discrepancy in apiVersion |
| 3920 |
data, err := runtime.Encode(newCodec, simple) |
| 3921 |
if err != nil { |
| 3922 |
t.Errorf("unexpected error: %v", err) |
| 3923 |
} |
| 3924 |
request, err := http.NewRequest("POST", server.URL+"/"+prefix+"/"+testGroupVersion.Group+"/"+testGroupVersion.Version+"/namespaces/default/simple", bytes.NewBuffer(data)) |
| 3925 |
if err != nil { |
| 3926 |
t.Errorf("unexpected error: %v", err) |
| 3927 |
} |
| 3928 |
response, err := client.Do(request) |
| 3929 |
if err != nil { |
| 3930 |
t.Errorf("unexpected error: %v", err) |
| 3931 |
} |
| 3932 |
if response.StatusCode != http.StatusBadRequest { |
| 3933 |
t.Errorf("Unexpected response %#v", response) |
| 3934 |
} |
| 3935 |
b, err := ioutil.ReadAll(response.Body) |
| 3936 |
if err != nil { |
| 3937 |
t.Errorf("unexpected error: %v", err) |
| 3938 |
} else if !strings.Contains(string(b), "does not match the expected API version") { |
| 3939 |
t.Errorf("unexpected response: %s", string(b)) |
| 3940 |
} |
| 3941 |
} |
| 3942 |
|
| 3943 |
func TestCreateDefaultsAPIVersion(t *testing.T) { |
| 3944 |
handler := handle(map[string]rest.Storage{"simple": &SimpleRESTStorage{}}) |
| 3945 |
server := httptest.NewServer(handler) |
| 3946 |
defer server.Close() |
| 3947 |
client := http.Client{} |
| 3948 |
|
| 3949 |
simple := &genericapitesting.Simple{} |
| 3950 |
data, err := runtime.Encode(codec, simple) |
| 3951 |
if err != nil { |
| 3952 |
t.Errorf("unexpected error: %v", err) |
| 3953 |
} |
| 3954 |
|
| 3955 |
m := make(map[string]interface{}) |
| 3956 |
if err := json.Unmarshal(data, &m); err != nil { |
| 3957 |
t.Errorf("unexpected error: %v", err) |
| 3958 |
} |
| 3959 |
delete(m, "apiVersion") |
| 3960 |
data, err = json.Marshal(m) |
| 3961 |
if err != nil { |
| 3962 |
t.Errorf("unexpected error: %v", err) |
| 3963 |
} |
| 3964 |
|
| 3965 |
request, err := http.NewRequest("POST", server.URL+"/"+prefix+"/"+testGroupVersion.Group+"/"+testGroupVersion.Version+"/namespaces/default/simple", bytes.NewBuffer(data)) |
| 3966 |
if err != nil { |
| 3967 |
t.Errorf("unexpected error: %v", err) |
| 3968 |
} |
| 3969 |
response, err := client.Do(request) |
| 3970 |
if err != nil { |
| 3971 |
t.Errorf("unexpected error: %v", err) |
| 3972 |
} |
| 3973 |
if response.StatusCode != http.StatusCreated { |
| 3974 |
t.Errorf("unexpected status: %d, Expected: %d, %#v", response.StatusCode, http.StatusCreated, response) |
| 3975 |
} |
| 3976 |
} |
| 3977 |
|
| 3978 |
func TestUpdateChecksAPIVersion(t *testing.T) { |
| 3979 |
handler := handle(map[string]rest.Storage{"simple": &SimpleRESTStorage{}}) |
| 3980 |
server := httptest.NewServer(handler) |
| 3981 |
defer server.Close() |
| 3982 |
client := http.Client{} |
| 3983 |
|
| 3984 |
simple := &genericapitesting.Simple{ObjectMeta: metav1.ObjectMeta{Name: "bar"}} |
| 3985 |
data, err := runtime.Encode(newCodec, simple) |
| 3986 |
if err != nil { |
| 3987 |
t.Fatalf("unexpected error: %v", err) |
| 3988 |
} |
| 3989 |
request, err := http.NewRequest("PUT", server.URL+"/"+prefix+"/"+testGroupVersion.Group+"/"+testGroupVersion.Version+"/namespaces/default/simple/bar", bytes.NewBuffer(data)) |
| 3990 |
if err != nil { |
| 3991 |
t.Fatalf("unexpected error: %v", err) |
| 3992 |
} |
| 3993 |
response, err := client.Do(request) |
| 3994 |
if err != nil { |
| 3995 |
t.Fatalf("unexpected error: %v", err) |
| 3996 |
} |
| 3997 |
if response.StatusCode != http.StatusBadRequest { |
| 3998 |
t.Errorf("Unexpected response %#v", response) |
| 3999 |
} |
| 4000 |
b, err := ioutil.ReadAll(response.Body) |
| 4001 |
if err != nil { |
| 4002 |
t.Errorf("unexpected error: %v", err) |
| 4003 |
} else if !strings.Contains(string(b), "does not match the expected API version") { |
| 4004 |
t.Errorf("unexpected response: %s", string(b)) |
| 4005 |
} |
| 4006 |
} |
| 4007 |
|
| 4008 |
// runRequest is used by TestDryRun since it runs the test twice in a |
| 4009 |
// row with a slightly different URL (one has ?dryRun, one doesn't). |
| 4010 |
func runRequest(t testing.TB, path, verb string, data []byte, contentType string) *http.Response { |
| 4011 |
request, err := http.NewRequest(verb, path, bytes.NewBuffer(data)) |
| 4012 |
if err != nil { |
| 4013 |
t.Fatalf("unexpected error: %v", err) |
| 4014 |
} |
| 4015 |
if contentType != "" { |
| 4016 |
request.Header.Set("Content-Type", contentType) |
| 4017 |
} |
| 4018 |
response, err := http.DefaultClient.Do(request) |
| 4019 |
if err != nil { |
| 4020 |
t.Fatalf("unexpected error: %v", err) |
| 4021 |
} |
| 4022 |
return response |
| 4023 |
} |
| 4024 |
|
| 4025 |
type SimpleRESTStorageWithDeleteCollection struct { |
| 4026 |
SimpleRESTStorage |
| 4027 |
} |
| 4028 |
|
| 4029 |
// Delete collection doesn't do much, but let us test this path. |
| 4030 |
func (storage *SimpleRESTStorageWithDeleteCollection) DeleteCollection(ctx context.Context, deleteValidation rest.ValidateObjectFunc, options *metav1.DeleteOptions, listOptions *metainternalversion.ListOptions) (runtime.Object, error) { |
| 4031 |
storage.checkContext(ctx) |
| 4032 |
return nil, nil |
| 4033 |
} |
| 4034 |
|
| 4035 |
// shared vars used by both TestFieldValidation and BenchmarkFieldValidation |
| 4036 |
var ( |
| 4037 |
strictFieldValidation = "?fieldValidation=Strict" |
| 4038 |
warnFieldValidation = "?fieldValidation=Warn" |
| 4039 |
ignoreFieldValidation = "?fieldValidation=Ignore" |
| 4040 |
) |
| 4041 |
|
| 4042 |
// TestFieldValidation tests the create, update, and patch handlers for correctness when faced with field validation errors. |
| 4043 |
func TestFieldValidation(t *testing.T) { |
| 4044 |
var ( |
| 4045 |
strictDecodingErr = `strict decoding error: duplicate field \"other\", unknown field \"unknown\"` |
| 4046 |
strictDecodingWarns = []string{`duplicate field "other"`, `unknown field "unknown"`} |
| 4047 |
strictDecodingErrYAML = `strict decoding error: yaml: unmarshal errors:\n line 6: key \"other\" already set in map, unknown field \"unknown\"` |
| 4048 |
strictDecodingWarnsYAML = []string{`line 6: key "other" already set in map`, `unknown field "unknown"`} |
| 4049 |
strictDecodingErrYAMLPut = `strict decoding error: yaml: unmarshal errors:\n line 7: key \"other\" already set in map, unknown field \"unknown\"` |
| 4050 |
strictDecodingWarnsYAMLPut = []string{`line 7: key "other" already set in map`, `unknown field "unknown"`} |
| 4051 |
|
| 4052 |
invalidJSONDataPost = []byte(`{"kind":"Simple", "apiVersion":"test.group/version", "metadata":{"creationTimestamp":null}, "other":"foo","other":"bar","unknown":"baz"}`) |
| 4053 |
invalidYAMLDataPost = []byte(`apiVersion: test.group/version |
| 4054 |
kind: Simple |
| 4055 |
metadata: |
| 4056 |
creationTimestamp: null |
| 4057 |
other: foo |
| 4058 |
other: bar |
| 4059 |
unknown: baz`) |
| 4060 |
|
| 4061 |
invalidJSONDataPut = []byte(`{"kind":"Simple", "apiVersion":"test.group/version", "metadata":{"name":"id", "creationTimestamp":null}, "other":"foo","other":"bar","unknown":"baz"}`) |
| 4062 |
invalidYAMLDataPut = []byte(`apiVersion: test.group/version |
| 4063 |
kind: Simple |
| 4064 |
metadata: |
| 4065 |
name: id |
| 4066 |
creationTimestamp: null |
| 4067 |
other: foo |
| 4068 |
other: bar |
| 4069 |
unknown: baz`) |
| 4070 |
|
| 4071 |
invalidMergePatch = []byte(`{"labels":{"foo":"bar"}, "unknown": "foo", "other": "foo", "other": "bar"}`) |
| 4072 |
invalidJSONPatch = []byte(` |
| 4073 |
[ |
| 4074 |
{"op": "add", "path": "/unknown", "value": "foo"}, |
| 4075 |
{"op": "add", "path": "/other", "value": "foo"}, |
| 4076 |
{"op": "add", "path": "/other", "value": "bar"} |
| 4077 |
] |
| 4078 |
`) |
| 4079 |
// note: duplicate fields in the patch itself |
| 4080 |
// are dropped by the |
| 4081 |
// evanphx/json-patch library and is expected. |
| 4082 |
jsonPatchStrictDecodingErr = `strict decoding error: unknown field \"unknown\"` |
| 4083 |
jsonPatchStrictDecodingWarns = []string{`unknown field "unknown"`} |
| 4084 |
|
| 4085 |
invalidSMP = []byte(`{"unknown": "foo", "other":"foo", "other": "bar"}`) |
| 4086 |
|
| 4087 |
fieldValidationTests = []struct { |
| 4088 |
name string |
| 4089 |
path string |
| 4090 |
verb string |
| 4091 |
data []byte |
| 4092 |
queryParams string |
| 4093 |
contentType string |
| 4094 |
expectedErr string |
| 4095 |
expectedWarns []string |
| 4096 |
expectedStatusCode int |
| 4097 |
}{ |
| 4098 |
// Create |
| 4099 |
{name: "post-strict-validation", path: "/namespaces/default/simples", verb: "POST", data: invalidJSONDataPost, queryParams: strictFieldValidation, expectedStatusCode: http.StatusBadRequest, expectedErr: strictDecodingErr}, |
| 4100 |
{name: "post-warn-validation", path: "/namespaces/default/simples", verb: "POST", data: invalidJSONDataPost, queryParams: warnFieldValidation, expectedStatusCode: http.StatusCreated, expectedWarns: strictDecodingWarns}, |
| 4101 |
{name: "post-ignore-validation", path: "/namespaces/default/simples", verb: "POST", data: invalidJSONDataPost, queryParams: ignoreFieldValidation, expectedStatusCode: http.StatusCreated}, |
| 4102 |
|
| 4103 |
{name: "post-strict-validation-yaml", path: "/namespaces/default/simples", verb: "POST", data: invalidYAMLDataPost, queryParams: strictFieldValidation, contentType: "application/yaml", expectedStatusCode: http.StatusBadRequest, expectedErr: strictDecodingErrYAML}, |
| 4104 |
{name: "post-warn-validation-yaml", path: "/namespaces/default/simples", verb: "POST", data: invalidYAMLDataPost, queryParams: warnFieldValidation, contentType: "application/yaml", expectedStatusCode: http.StatusCreated, expectedWarns: strictDecodingWarnsYAML}, |
| 4105 |
{name: "post-ignore-validation-yaml", path: "/namespaces/default/simples", verb: "POST", data: invalidYAMLDataPost, queryParams: ignoreFieldValidation, contentType: "application/yaml", expectedStatusCode: http.StatusCreated}, |
| 4106 |
|
| 4107 |
// Update |
| 4108 |
{name: "put-strict-validation", path: "/namespaces/default/simples/id", verb: "PUT", data: invalidJSONDataPut, queryParams: strictFieldValidation, expectedStatusCode: http.StatusBadRequest, expectedErr: strictDecodingErr}, |
| 4109 |
{name: "put-warn-validation", path: "/namespaces/default/simples/id", verb: "PUT", data: invalidJSONDataPut, queryParams: warnFieldValidation, expectedStatusCode: http.StatusOK, expectedWarns: strictDecodingWarns}, |
| 4110 |
{name: "put-ignore-validation", path: "/namespaces/default/simples/id", verb: "PUT", data: invalidJSONDataPut, queryParams: ignoreFieldValidation, expectedStatusCode: http.StatusOK}, |
| 4111 |
|
| 4112 |
{name: "put-strict-validation-yaml", path: "/namespaces/default/simples/id", verb: "PUT", data: invalidYAMLDataPut, queryParams: strictFieldValidation, contentType: "application/yaml", expectedStatusCode: http.StatusBadRequest, expectedErr: strictDecodingErrYAMLPut}, |
| 4113 |
{name: "put-warn-validation-yaml", path: "/namespaces/default/simples/id", verb: "PUT", data: invalidYAMLDataPut, queryParams: warnFieldValidation, contentType: "application/yaml", expectedStatusCode: http.StatusOK, expectedWarns: strictDecodingWarnsYAMLPut}, |
| 4114 |
{name: "put-ignore-validation-yaml", path: "/namespaces/default/simples/id", verb: "PUT", data: invalidYAMLDataPut, queryParams: ignoreFieldValidation, contentType: "application/yaml", expectedStatusCode: http.StatusOK}, |
| 4115 |
|
| 4116 |
// MergePatch |
| 4117 |
{name: "merge-patch-strict-validation", path: "/namespaces/default/simples/id", verb: "PATCH", data: invalidMergePatch, queryParams: strictFieldValidation, contentType: "application/merge-patch+json; charset=UTF-8", expectedStatusCode: http.StatusUnprocessableEntity, expectedErr: strictDecodingErr}, |
| 4118 |
{name: "merge-patch-warn-validation", path: "/namespaces/default/simples/id", verb: "PATCH", data: invalidMergePatch, queryParams: warnFieldValidation, contentType: "application/merge-patch+json; charset=UTF-8", expectedStatusCode: http.StatusOK, expectedWarns: strictDecodingWarns}, |
| 4119 |
{name: "merge-patch-ignore-validation", path: "/namespaces/default/simples/id", verb: "PATCH", data: invalidMergePatch, queryParams: ignoreFieldValidation, contentType: "application/merge-patch+json; charset=UTF-8", expectedStatusCode: http.StatusOK}, |
| 4120 |
|
| 4121 |
// JSON Patch |
| 4122 |
{name: "json-patch-strict-validation", path: "/namespaces/default/simples/id", verb: "PATCH", data: invalidJSONPatch, queryParams: strictFieldValidation, contentType: "application/json-patch+json; charset=UTF-8", expectedStatusCode: http.StatusUnprocessableEntity, expectedErr: jsonPatchStrictDecodingErr}, |
| 4123 |
{name: "json-patch-warn-validation", path: "/namespaces/default/simples/id", verb: "PATCH", data: invalidJSONPatch, queryParams: warnFieldValidation, contentType: "application/json-patch+json; charset=UTF-8", expectedStatusCode: http.StatusOK, expectedWarns: jsonPatchStrictDecodingWarns}, |
| 4124 |
{name: "json-patch-ignore-validation", path: "/namespaces/default/simples/id", verb: "PATCH", data: invalidJSONPatch, queryParams: ignoreFieldValidation, contentType: "application/json-patch+json; charset=UTF-8", expectedStatusCode: http.StatusOK}, |
| 4125 |
|
| 4126 |
// SMP |
| 4127 |
{name: "strategic-merge-patch-strict-validation", path: "/namespaces/default/simples/id", verb: "PATCH", data: invalidSMP, queryParams: strictFieldValidation, contentType: "application/strategic-merge-patch+json; charset=UTF-8", expectedStatusCode: http.StatusUnprocessableEntity, expectedErr: strictDecodingErr}, |
| 4128 |
{name: "strategic-merge-patch-warn-validation", path: "/namespaces/default/simples/id", verb: "PATCH", data: invalidSMP, queryParams: warnFieldValidation, contentType: "application/strategic-merge-patch+json; charset=UTF-8", expectedStatusCode: http.StatusOK, expectedWarns: strictDecodingWarns}, |
| 4129 |
{name: "strategic-merge-patch-ignore-validation", path: "/namespaces/default/simples/id", verb: "PATCH", data: invalidSMP, queryParams: ignoreFieldValidation, contentType: "application/strategic-merge-patch+json; charset=UTF-8", expectedStatusCode: http.StatusOK}, |
| 4130 |
} |
| 4131 |
) |
| 4132 |
|
| 4133 |
server := httptest.NewServer(handleWithWarnings(map[string]rest.Storage{ |
| 4134 |
"simples": &SimpleRESTStorageWithDeleteCollection{ |
| 4135 |
SimpleRESTStorage{ |
| 4136 |
item: genericapitesting.Simple{ |
| 4137 |
ObjectMeta: metav1.ObjectMeta{ |
| 4138 |
Name: "id", |
| 4139 |
Namespace: "", |
| 4140 |
UID: "uid", |
| 4141 |
}, |
| 4142 |
Other: "baz", |
| 4143 |
}, |
| 4144 |
}, |
| 4145 |
}, |
| 4146 |
"simples/subsimple": &SimpleXGSubresourceRESTStorage{ |
| 4147 |
item: genericapitesting.SimpleXGSubresource{ |
| 4148 |
SubresourceInfo: "foo", |
| 4149 |
}, |
| 4150 |
itemGVK: testGroup2Version.WithKind("SimpleXGSubresource"), |
| 4151 |
}, |
| 4152 |
})) |
| 4153 |
defer server.Close() |
| 4154 |
for _, test := range fieldValidationTests { |
| 4155 |
t.Run(test.name, func(t *testing.T) { |
| 4156 |
baseURL := server.URL + "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version |
| 4157 |
response := runRequest(t, baseURL+test.path+test.queryParams, test.verb, test.data, test.contentType) |
| 4158 |
buf := new(bytes.Buffer) |
| 4159 |
buf.ReadFrom(response.Body) |
| 4160 |
|
| 4161 |
if response.StatusCode != test.expectedStatusCode || !strings.Contains(buf.String(), test.expectedErr) { |
| 4162 |
t.Fatalf("unexpected response: %#v, expected err: %#v", response, test.expectedErr) |
| 4163 |
} |
| 4164 |
|
| 4165 |
warnings, _ := net.ParseWarningHeaders(response.Header["Warning"]) |
| 4166 |
if len(warnings) != len(test.expectedWarns) { |
| 4167 |
t.Fatalf("unexpected number of warnings. Got count %d, expected %d. Got warnings %#v, expected %#v", len(warnings), len(test.expectedWarns), warnings, test.expectedWarns) |
| 4168 |
|
| 4169 |
} |
| 4170 |
for i, warn := range warnings { |
| 4171 |
if warn.Text != test.expectedWarns[i] { |
| 4172 |
t.Fatalf("unexpected warning: %#v, expected warning: %#v", warn.Text, test.expectedWarns[i]) |
| 4173 |
} |
| 4174 |
} |
| 4175 |
}) |
| 4176 |
} |
| 4177 |
} |
| 4178 |
|
| 4179 |
// BenchmarkFieldValidation benchmarks the create, update, and patch handlers for performance distinctions between |
| 4180 |
// strict, warn, and ignore field validation handling. |
| 4181 |
func BenchmarkFieldValidation(b *testing.B) { |
| 4182 |
var ( |
| 4183 |
validJSONDataPost = []byte(`{"kind":"Simple", "apiVersion":"test.group/version", "metadata":{"creationTimestamp":null}, "other":"foo"}`) |
| 4184 |
validYAMLDataPost = []byte(`apiVersion: test.group/version |
| 4185 |
kind: Simple |
| 4186 |
metadata: |
| 4187 |
creationTimestamp: null |
| 4188 |
other: foo`) |
| 4189 |
|
| 4190 |
validJSONDataPut = []byte(`{"kind":"Simple", "apiVersion":"test.group/version", "metadata":{"name":"id", "creationTimestamp":null}, "other":"bar"}`) |
| 4191 |
validYAMLDataPut = []byte(`apiVersion: test.group/version |
| 4192 |
kind: Simple |
| 4193 |
metadata: |
| 4194 |
name: id |
| 4195 |
creationTimestamp: null |
| 4196 |
other: bar`) |
| 4197 |
|
| 4198 |
validMergePatch = []byte(`{"labels":{"foo":"bar"}, "other": "bar"}`) |
| 4199 |
validJSONPatch = []byte(` |
| 4200 |
[ |
| 4201 |
{"op": "add", "path": "/other", "value": "bar"} |
| 4202 |
] |
| 4203 |
`) |
| 4204 |
validSMP = []byte(`{"other": "bar"}`) |
| 4205 |
|
| 4206 |
fieldValidationBenchmarks = []struct { |
| 4207 |
name string |
| 4208 |
path string |
| 4209 |
verb string |
| 4210 |
data []byte |
| 4211 |
queryParams string |
| 4212 |
contentType string |
| 4213 |
expectedStatusCode int |
| 4214 |
}{ |
| 4215 |
// Create |
| 4216 |
{name: "post-strict-validation", path: "/namespaces/default/simples", verb: "POST", data: validJSONDataPost, queryParams: strictFieldValidation, expectedStatusCode: http.StatusCreated}, |
| 4217 |
{name: "post-warn-validation", path: "/namespaces/default/simples", verb: "POST", data: validJSONDataPost, queryParams: warnFieldValidation, expectedStatusCode: http.StatusCreated}, |
| 4218 |
{name: "post-ignore-validation", path: "/namespaces/default/simples", verb: "POST", data: validJSONDataPost, queryParams: ignoreFieldValidation, expectedStatusCode: http.StatusCreated}, |
| 4219 |
|
| 4220 |
{name: "post-strict-validation-yaml", path: "/namespaces/default/simples", verb: "POST", data: validYAMLDataPost, queryParams: strictFieldValidation, contentType: "application/yaml", expectedStatusCode: http.StatusCreated}, |
| 4221 |
{name: "post-warn-validation-yaml", path: "/namespaces/default/simples", verb: "POST", data: validYAMLDataPost, queryParams: warnFieldValidation, contentType: "application/yaml", expectedStatusCode: http.StatusCreated}, |
| 4222 |
{name: "post-ignore-validation-yaml", path: "/namespaces/default/simples", verb: "POST", data: validYAMLDataPost, queryParams: ignoreFieldValidation, contentType: "application/yaml", expectedStatusCode: http.StatusCreated}, |
| 4223 |
|
| 4224 |
// Update |
| 4225 |
{name: "put-strict-validation", path: "/namespaces/default/simples/id", verb: "PUT", data: validJSONDataPut, queryParams: strictFieldValidation, expectedStatusCode: http.StatusOK}, |
| 4226 |
{name: "put-warn-validation", path: "/namespaces/default/simples/id", verb: "PUT", data: validJSONDataPut, queryParams: warnFieldValidation, expectedStatusCode: http.StatusOK}, |
| 4227 |
{name: "put-ignore-validation", path: "/namespaces/default/simples/id", verb: "PUT", data: validJSONDataPut, queryParams: ignoreFieldValidation, expectedStatusCode: http.StatusOK}, |
| 4228 |
|
| 4229 |
{name: "put-strict-validation-yaml", path: "/namespaces/default/simples/id", verb: "PUT", data: validYAMLDataPut, queryParams: strictFieldValidation, contentType: "application/yaml", expectedStatusCode: http.StatusOK}, |
| 4230 |
{name: "put-warn-validation-yaml", path: "/namespaces/default/simples/id", verb: "PUT", data: validYAMLDataPut, queryParams: warnFieldValidation, contentType: "application/yaml", expectedStatusCode: http.StatusOK}, |
| 4231 |
{name: "put-ignore-validation-yaml", path: "/namespaces/default/simples/id", verb: "PUT", data: validYAMLDataPut, queryParams: ignoreFieldValidation, contentType: "application/yaml", expectedStatusCode: http.StatusOK}, |
| 4232 |
|
| 4233 |
// MergePatch |
| 4234 |
{name: "merge-patch-strict-validation", path: "/namespaces/default/simples/id", verb: "PATCH", data: validMergePatch, queryParams: strictFieldValidation, contentType: "application/merge-patch+json; charset=UTF-8", expectedStatusCode: http.StatusOK}, |
| 4235 |
{name: "merge-patch-warn-validation", path: "/namespaces/default/simples/id", verb: "PATCH", data: validMergePatch, queryParams: warnFieldValidation, contentType: "application/merge-patch+json; charset=UTF-8", expectedStatusCode: http.StatusOK}, |
| 4236 |
{name: "merge-patch-ignore-validation", path: "/namespaces/default/simples/id", verb: "PATCH", data: validMergePatch, queryParams: ignoreFieldValidation, contentType: "application/merge-patch+json; charset=UTF-8", expectedStatusCode: http.StatusOK}, |
| 4237 |
|
| 4238 |
// JSON Patch |
| 4239 |
{name: "json-patch-strict-validation", path: "/namespaces/default/simples/id", verb: "PATCH", data: validJSONPatch, queryParams: strictFieldValidation, contentType: "application/json-patch+json; charset=UTF-8", expectedStatusCode: http.StatusOK}, |
| 4240 |
{name: "json-patch-warn-validation", path: "/namespaces/default/simples/id", verb: "PATCH", data: validJSONPatch, queryParams: warnFieldValidation, contentType: "application/json-patch+json; charset=UTF-8", expectedStatusCode: http.StatusOK}, |
| 4241 |
{name: "json-patch-ignore-validation", path: "/namespaces/default/simples/id", verb: "PATCH", data: validJSONPatch, queryParams: ignoreFieldValidation, contentType: "application/json-patch+json; charset=UTF-8", expectedStatusCode: http.StatusOK}, |
| 4242 |
|
| 4243 |
// SMP |
| 4244 |
{name: "strategic-merge-patch-strict-validation", path: "/namespaces/default/simples/id", verb: "PATCH", data: validSMP, queryParams: strictFieldValidation, contentType: "application/strategic-merge-patch+json; charset=UTF-8", expectedStatusCode: http.StatusOK}, |
| 4245 |
{name: "strategic-merge-patch-warn-validation", path: "/namespaces/default/simples/id", verb: "PATCH", data: validSMP, queryParams: warnFieldValidation, contentType: "application/strategic-merge-patch+json; charset=UTF-8", expectedStatusCode: http.StatusOK}, |
| 4246 |
{name: "strategic-merge-patch-ignore-validation", path: "/namespaces/default/simples/id", verb: "PATCH", data: validSMP, queryParams: ignoreFieldValidation, contentType: "application/strategic-merge-patch+json; charset=UTF-8", expectedStatusCode: http.StatusOK}, |
| 4247 |
} |
| 4248 |
) |
| 4249 |
|
| 4250 |
server := httptest.NewServer(handleWithWarnings(map[string]rest.Storage{ |
| 4251 |
"simples": &SimpleRESTStorageWithDeleteCollection{ |
| 4252 |
SimpleRESTStorage{ |
| 4253 |
item: genericapitesting.Simple{ |
| 4254 |
ObjectMeta: metav1.ObjectMeta{ |
| 4255 |
Name: "id", |
| 4256 |
Namespace: "", |
| 4257 |
UID: "uid", |
| 4258 |
}, |
| 4259 |
Other: "bar", |
| 4260 |
}, |
| 4261 |
}, |
| 4262 |
}, |
| 4263 |
"simples/subsimple": &SimpleXGSubresourceRESTStorage{ |
| 4264 |
item: genericapitesting.SimpleXGSubresource{ |
| 4265 |
SubresourceInfo: "foo", |
| 4266 |
}, |
| 4267 |
itemGVK: testGroup2Version.WithKind("SimpleXGSubresource"), |
| 4268 |
}, |
| 4269 |
})) |
| 4270 |
defer server.Close() |
| 4271 |
for _, test := range fieldValidationBenchmarks { |
| 4272 |
b.Run(test.name, func(b *testing.B) { |
| 4273 |
for n := 0; n < b.N; n++ { |
| 4274 |
baseURL := server.URL + "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version |
| 4275 |
response := runRequest(b, baseURL+test.path+test.queryParams, test.verb, test.data, test.contentType) |
| 4276 |
if response.StatusCode != test.expectedStatusCode { |
| 4277 |
b.Fatalf("unexpected status code: %d, expected: %d", response.StatusCode, test.expectedStatusCode) |
| 4278 |
} |
| 4279 |
} |
| 4280 |
}) |
| 4281 |
} |
| 4282 |
} |
| 4283 |
|
| 4284 |
type SimpleXGSubresourceRESTStorage struct { |
| 4285 |
item genericapitesting.SimpleXGSubresource |
| 4286 |
itemGVK schema.GroupVersionKind |
| 4287 |
} |
| 4288 |
|
| 4289 |
var _ = rest.GroupVersionKindProvider(&SimpleXGSubresourceRESTStorage{}) |
| 4290 |
|
| 4291 |
func (storage *SimpleXGSubresourceRESTStorage) New() runtime.Object { |
| 4292 |
return &genericapitesting.SimpleXGSubresource{} |
| 4293 |
} |
| 4294 |
|
| 4295 |
func (storage *SimpleXGSubresourceRESTStorage) Destroy() { |
| 4296 |
} |
| 4297 |
|
| 4298 |
func (storage *SimpleXGSubresourceRESTStorage) Get(ctx context.Context, id string, options *metav1.GetOptions) (runtime.Object, error) { |
| 4299 |
return storage.item.DeepCopyObject(), nil |
| 4300 |
} |
| 4301 |
|
| 4302 |
func (storage *SimpleXGSubresourceRESTStorage) Delete(ctx context.Context, name string, deleteValidation rest.ValidateObjectFunc, options *metav1.DeleteOptions) (runtime.Object, bool, error) { |
| 4303 |
return nil, true, nil |
| 4304 |
} |
| 4305 |
|
| 4306 |
func (storage *SimpleXGSubresourceRESTStorage) GroupVersionKind(containingGV schema.GroupVersion) schema.GroupVersionKind { |
| 4307 |
return storage.itemGVK |
| 4308 |
} |
| 4309 |
|
| 4310 |
func (storage *SimpleXGSubresourceRESTStorage) GetSingularName() string { |
| 4311 |
return "simple" |
| 4312 |
} |
| 4313 |
|
| 4314 |
func TestXGSubresource(t *testing.T) { |
| 4315 |
container := restful.NewContainer() |
| 4316 |
container.Router(restful.CurlyRouter{}) |
| 4317 |
mux := container.ServeMux |
| 4318 |
|
| 4319 |
itemID := "theID" |
| 4320 |
subresourceStorage := &SimpleXGSubresourceRESTStorage{ |
| 4321 |
item: genericapitesting.SimpleXGSubresource{ |
| 4322 |
SubresourceInfo: "foo", |
| 4323 |
}, |
| 4324 |
itemGVK: testGroup2Version.WithKind("SimpleXGSubresource"), |
| 4325 |
} |
| 4326 |
storage := map[string]rest.Storage{ |
| 4327 |
"simple": &SimpleRESTStorage{}, |
| 4328 |
"simple/subsimple": subresourceStorage, |
| 4329 |
} |
| 4330 |
|
| 4331 |
group := APIGroupVersion{ |
| 4332 |
Storage: storage, |
| 4333 |
|
| 4334 |
Creater: scheme, |
| 4335 |
Convertor: scheme, |
| 4336 |
TypeConverter: managedfields.NewDeducedTypeConverter(), |
| 4337 |
UnsafeConvertor: runtime.UnsafeObjectConvertor(scheme), |
| 4338 |
Defaulter: scheme, |
| 4339 |
Typer: scheme, |
| 4340 |
Namer: namer, |
| 4341 |
|
| 4342 |
EquivalentResourceRegistry: runtime.NewEquivalentResourceRegistry(), |
| 4343 |
|
| 4344 |
ParameterCodec: parameterCodec, |
| 4345 |
|
| 4346 |
Admit: admissionControl, |
| 4347 |
|
| 4348 |
Root: "/" + prefix, |
| 4349 |
GroupVersion: testGroupVersion, |
| 4350 |
OptionsExternalVersion: &testGroupVersion, |
| 4351 |
Serializer: codecs, |
| 4352 |
} |
| 4353 |
|
| 4354 |
if _, _, err := (&group).InstallREST(container); err != nil { |
| 4355 |
panic(fmt.Sprintf("unable to install container %s: %v", group.GroupVersion, err)) |
| 4356 |
} |
| 4357 |
|
| 4358 |
server := newTestServer(defaultAPIServer{mux, container}) |
| 4359 |
defer server.Close() |
| 4360 |
|
| 4361 |
resp, err := http.Get(server.URL + "/" + prefix + "/" + testGroupVersion.Group + "/" + testGroupVersion.Version + "/namespaces/default/simple/" + itemID + "/subsimple") |
| 4362 |
if err != nil { |
| 4363 |
t.Fatalf("unexpected error: %v", err) |
| 4364 |
} |
| 4365 |
if resp.StatusCode != http.StatusOK { |
| 4366 |
t.Fatalf("unexpected response: %#v", resp) |
| 4367 |
} |
| 4368 |
var itemOut genericapitesting.SimpleXGSubresource |
| 4369 |
body, err := extractBody(resp, &itemOut) |
| 4370 |
if err != nil { |
| 4371 |
t.Errorf("unexpected error: %v", err) |
| 4372 |
} |
| 4373 |
|
| 4374 |
// Test if the returned object has the expected group, version and kind |
| 4375 |
// We are directly unmarshaling JSON here because TypeMeta cannot be decoded through the |
| 4376 |
// installed decoders. TypeMeta cannot be decoded because it is added to the ignored |
| 4377 |
// conversion type list in API scheme and hence cannot be converted from input type object |
| 4378 |
// to output type object. So it's values don't appear in the decoded output object. |
| 4379 |
decoder := json.NewDecoder(strings.NewReader(body)) |
| 4380 |
var itemFromBody genericapitesting.SimpleXGSubresource |
| 4381 |
err = decoder.Decode(&itemFromBody) |
| 4382 |
if err != nil { |
| 4383 |
t.Errorf("unexpected JSON decoding error: %v", err) |
| 4384 |
} |
| 4385 |
if want := fmt.Sprintf("%s/%s", testGroup2Version.Group, testGroup2Version.Version); itemFromBody.APIVersion != want { |
| 4386 |
t.Errorf("unexpected APIVersion got: %+v want: %+v", itemFromBody.APIVersion, want) |
| 4387 |
} |
| 4388 |
if itemFromBody.Kind != "SimpleXGSubresource" { |
| 4389 |
t.Errorf("unexpected Kind got: %+v want: SimpleXGSubresource", itemFromBody.Kind) |
| 4390 |
} |
| 4391 |
|
| 4392 |
if itemOut.Name != subresourceStorage.item.Name { |
| 4393 |
t.Errorf("Unexpected data: %#v, expected %#v (%s)", itemOut, subresourceStorage.item, string(body)) |
| 4394 |
} |
| 4395 |
} |
| 4396 |
|
| 4397 |
func readBodyOrDie(r io.Reader) []byte { |
| 4398 |
body, err := ioutil.ReadAll(r) |
| 4399 |
if err != nil { |
| 4400 |
panic(err) |
| 4401 |
} |
| 4402 |
return body |
| 4403 |
} |
| 4404 |
|
| 4405 |
// BenchmarkUpdateProtobuf measures the cost of processing an update on the server in proto |
| 4406 |
func BenchmarkUpdateProtobuf(b *testing.B) { |
| 4407 |
items := benchmarkItems(b) |
| 4408 |
|
| 4409 |
simpleStorage := &SimpleRESTStorage{} |
| 4410 |
handler := handle(map[string]rest.Storage{"simples": simpleStorage}) |
| 4411 |
server := httptest.NewServer(handler) |
| 4412 |
defer server.Close() |
| 4413 |
client := http.Client{} |
| 4414 |
|
| 4415 |
dest, _ := url.Parse(server.URL) |
| 4416 |
dest.Path = "/" + prefix + "/" + newGroupVersion.Group + "/" + newGroupVersion.Version + "/namespaces/foo/simples/bar" |
| 4417 |
dest.RawQuery = "" |
| 4418 |
|
| 4419 |
info, _ := runtime.SerializerInfoForMediaType(codecs.SupportedMediaTypes(), "application/vnd.kubernetes.protobuf") |
| 4420 |
e := codecs.EncoderForVersion(info.Serializer, newGroupVersion) |
| 4421 |
data, err := runtime.Encode(e, &items[0]) |
| 4422 |
if err != nil { |
| 4423 |
b.Fatal(err) |
| 4424 |
} |
| 4425 |
|
| 4426 |
b.ResetTimer() |
| 4427 |
for i := 0; i < b.N; i++ { |
| 4428 |
request, err := http.NewRequest("PUT", dest.String(), bytes.NewReader(data)) |
| 4429 |
if err != nil { |
| 4430 |
b.Fatalf("unexpected error: %v", err) |
| 4431 |
} |
| 4432 |
request.Header.Set("Accept", "application/vnd.kubernetes.protobuf") |
| 4433 |
request.Header.Set("Content-Type", "application/vnd.kubernetes.protobuf") |
| 4434 |
response, err := client.Do(request) |
| 4435 |
if err != nil { |
| 4436 |
b.Fatalf("unexpected error: %v", err) |
| 4437 |
} |
| 4438 |
if response.StatusCode != http.StatusBadRequest { |
| 4439 |
body, _ := ioutil.ReadAll(response.Body) |
| 4440 |
b.Fatalf("Unexpected response %#v\n%s", response, body) |
| 4441 |
} |
| 4442 |
_, _ = ioutil.ReadAll(response.Body) |
| 4443 |
response.Body.Close() |
| 4444 |
} |
| 4445 |
b.StopTimer() |
| 4446 |
} |
| 4447 |
|
| 4448 |
func newTestServer(handler http.Handler) *httptest.Server { |
| 4449 |
handler = genericapifilters.WithRequestInfo(handler, newTestRequestInfoResolver()) |
| 4450 |
return httptest.NewServer(handler) |
| 4451 |
} |
| 4452 |
|
| 4453 |
func newTestRequestInfoResolver() *request.RequestInfoFactory { |
| 4454 |
return &request.RequestInfoFactory{ |
| 4455 |
APIPrefixes: sets.NewString("api", "apis"), |
| 4456 |
GrouplessAPIPrefixes: sets.NewString("api"), |
| 4457 |
} |
| 4458 |
} |
| 4459 |
|
| 4460 |
const benchmarkSeed = 100 |
| 4461 |
|
| 4462 |
func benchmarkItems(b *testing.B) []example.Pod { |
| 4463 |
clientapiObjectFuzzer := fuzzer.FuzzerFor(examplefuzzer.Funcs, rand.NewSource(benchmarkSeed), codecs) |
| 4464 |
items := make([]example.Pod, 3) |
| 4465 |
for i := range items { |
| 4466 |
clientapiObjectFuzzer.Fill(&items[i]) |
| 4467 |
} |
| 4468 |
return items |
| 4469 |
} |