Debian Codegraph @

pkg/registry/generic/rest/response_checker_test.go

raw
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 rest
18
19 import (
20 "bytes"
21 "fmt"
22 "io/ioutil"
23 "net/http"
24 "reflect"
25 "strings"
26 "testing"
27
28 "k8s.io/api/core/v1"
29 "k8s.io/apimachinery/pkg/api/errors"
30 )
31
32 func TestGenericHttpResponseChecker(t *testing.T) {
33 responseChecker := NewGenericHttpResponseChecker(v1.Resource("pods"), "foo")
34 tests := []struct {
35 resp *http.Response
36 expectError bool
37 expected error
38 name string
39 }{
40 {
41 resp: &http.Response{
42 Body: ioutil.NopCloser(bytes.NewBufferString("Success")),
43 StatusCode: http.StatusOK,
44 },
45 expectError: false,
46 name: "ok",
47 },
48 {
49 resp: &http.Response{
50 Body: ioutil.NopCloser(bytes.NewBufferString("Invalid request.")),
51 StatusCode: http.StatusBadRequest,
52 },
53 expectError: true,
54 expected: errors.NewBadRequest("Invalid request."),
55 name: "bad request",
56 },
57 {
58 resp: &http.Response{
59 Body: ioutil.NopCloser(bytes.NewBufferString("Pod does not exist.")),
60 StatusCode: http.StatusInternalServerError,
61 },
62 expectError: true,
63 expected: errors.NewInternalError(fmt.Errorf("%s", "Pod does not exist.")),
64 name: "internal server error",
65 },
66 }
67 for _, test := range tests {
68 err := responseChecker.Check(test.resp)
69 if test.expectError && err == nil {
70 t.Error("unexpected non-error")
71 }
72 if !test.expectError && err != nil {
73 t.Errorf("unexpected error: %v", err)
74 }
75 if test.expectError && !reflect.DeepEqual(err, test.expected) {
76 t.Errorf("expected: %s, saw: %s", test.expected, err)
77 }
78 }
79 }
80
81 func TestGenericHttpResponseCheckerLimitReader(t *testing.T) {
82 responseChecker := NewGenericHttpResponseChecker(v1.Resource("pods"), "foo")
83 excessedString := strings.Repeat("a", (maxReadLength + 10000))
84 resp := &http.Response{
85 Body: ioutil.NopCloser(bytes.NewBufferString(excessedString)),
86 StatusCode: http.StatusBadRequest,
87 }
88 err := responseChecker.Check(resp)
89 if err == nil {
90 t.Error("unexpected non-error")
91 }
92 if len(err.Error()) != maxReadLength {
93 t.Errorf("expected length of error message: %d, saw: %d", maxReadLength, len(err.Error()))
94 }
95 }