Debian Codegraph @

pkg/endpoints/handlers/finisher/finisher_test.go

raw
1 /*
2 Copyright 2021 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 finisher
18
19 import (
20 "context"
21 "errors"
22 "fmt"
23 "net/http"
24 "reflect"
25 "strings"
26 "testing"
27 "time"
28
29 apiequality "k8s.io/apimachinery/pkg/api/equality"
30 apierrors "k8s.io/apimachinery/pkg/api/errors"
31 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
32 "k8s.io/apimachinery/pkg/runtime"
33 "k8s.io/apiserver/pkg/apis/example"
34
35 "github.com/google/go-cmp/cmp"
36 )
37
38 func TestFinishRequest(t *testing.T) {
39 exampleObj := &example.Pod{}
40 exampleErr := fmt.Errorf("error")
41 successStatusObj := &metav1.Status{Status: metav1.StatusSuccess, Message: "success message"}
42 errorStatusObj := &metav1.Status{Status: metav1.StatusFailure, Message: "error message"}
43 timeoutFunc := func() (context.Context, context.CancelFunc) {
44 return context.WithTimeout(context.TODO(), time.Second)
45 }
46
47 testcases := []struct {
48 name string
49 timeout func() (context.Context, context.CancelFunc)
50 fn ResultFunc
51 expectedObj runtime.Object
52 expectedErr error
53 expectedPanic string
54
55 expectedPanicObj interface{}
56 }{
57 {
58 name: "Expected obj is returned",
59 timeout: timeoutFunc,
60 fn: func() (runtime.Object, error) {
61 return exampleObj, nil
62 },
63 expectedObj: exampleObj,
64 expectedErr: nil,
65 },
66 {
67 name: "Expected error is returned",
68 timeout: timeoutFunc,
69 fn: func() (runtime.Object, error) {
70 return nil, exampleErr
71 },
72 expectedObj: nil,
73 expectedErr: exampleErr,
74 },
75 {
76 name: "No expected error or object or panic",
77 timeout: timeoutFunc,
78 fn: func() (runtime.Object, error) {
79 return nil, nil
80 },
81 },
82 {
83 name: "Successful status object is returned as expected",
84 timeout: timeoutFunc,
85 fn: func() (runtime.Object, error) {
86 return successStatusObj, nil
87 },
88 expectedObj: successStatusObj,
89 expectedErr: nil,
90 },
91 {
92 name: "Error status object is converted to StatusError",
93 timeout: timeoutFunc,
94 fn: func() (runtime.Object, error) {
95 return errorStatusObj, nil
96 },
97 expectedObj: nil,
98 expectedErr: apierrors.FromObject(errorStatusObj),
99 },
100 {
101 name: "Panic is propagated up",
102 timeout: timeoutFunc,
103 fn: func() (runtime.Object, error) {
104 panic("my panic")
105 },
106 expectedObj: nil,
107 expectedErr: nil,
108 expectedPanic: "my panic",
109 },
110 {
111 name: "Panic is propagated with stack",
112 timeout: timeoutFunc,
113 fn: func() (runtime.Object, error) {
114 panic("my panic")
115 },
116 expectedObj: nil,
117 expectedErr: nil,
118 expectedPanic: "finisher_test.go",
119 },
120 {
121 name: "http.ErrAbortHandler panic is propagated without wrapping with stack",
122 timeout: timeoutFunc,
123 fn: func() (runtime.Object, error) {
124 panic(http.ErrAbortHandler)
125 },
126 expectedObj: nil,
127 expectedErr: nil,
128 expectedPanic: http.ErrAbortHandler.Error(),
129 expectedPanicObj: http.ErrAbortHandler,
130 },
131 }
132 for i, tc := range testcases {
133 t.Run(tc.name, func(t *testing.T) {
134 ctx, cancel := tc.timeout()
135 defer func() {
136 cancel()
137
138 r := recover()
139 switch {
140 case r == nil && len(tc.expectedPanic) > 0:
141 t.Errorf("expected panic containing '%s', got none", tc.expectedPanic)
142 case r != nil && len(tc.expectedPanic) == 0:
143 t.Errorf("unexpected panic: %v", r)
144 case r != nil && len(tc.expectedPanic) > 0 && !strings.Contains(fmt.Sprintf("%v", r), tc.expectedPanic):
145 t.Errorf("expected panic containing '%s', got '%v'", tc.expectedPanic, r)
146 }
147
148 if tc.expectedPanicObj != nil && !reflect.DeepEqual(tc.expectedPanicObj, r) {
149 t.Errorf("expected panic obj %#v, got %#v", tc.expectedPanicObj, r)
150 }
151 }()
152 obj, err := FinishRequest(ctx, tc.fn)
153 if (err == nil && tc.expectedErr != nil) || (err != nil && tc.expectedErr == nil) || (err != nil && tc.expectedErr != nil && err.Error() != tc.expectedErr.Error()) {
154 t.Errorf("%d: unexpected err. expected: %v, got: %v", i, tc.expectedErr, err)
155 }
156 if !apiequality.Semantic.DeepEqual(obj, tc.expectedObj) {
157 t.Errorf("%d: unexpected obj. expected %#v, got %#v", i, tc.expectedObj, obj)
158 }
159 })
160 }
161 }
162
163 func TestFinishRequestWithPostTimeoutTracker(t *testing.T) {
164 tests := []struct {
165 name string
166 object runtime.Object
167 postTimeoutWait time.Duration
168 childGoroutineNeverReturns bool
169 err error
170 reason string
171 }{
172 {
173 name: "ResultFunc function returns a result after the request had timed out",
174 object: &example.Pod{},
175 postTimeoutWait: 5 * time.Minute,
176 },
177 {
178 name: "ResultFunc function returns an error after the request had timed out",
179 err: errors.New("my error"),
180 postTimeoutWait: 5 * time.Minute,
181 },
182 {
183 name: "ResultFunc function panics after the request had timed out",
184 reason: "my panic",
185 postTimeoutWait: 5 * time.Minute,
186 },
187 {
188 name: "ResultFunc function never returns, parent gives up after postTimeoutWait",
189 postTimeoutWait: 1 * time.Second,
190 childGoroutineNeverReturns: true,
191 },
192 }
193
194 expectedTimeoutErr := apierrors.NewTimeoutError(fmt.Sprintf("request did not complete within requested timeout - %s",
195 context.DeadlineExceeded), 0)
196
197 for _, test := range tests {
198 t.Run(test.name, func(t *testing.T) {
199 ctx, cancel := context.WithTimeout(context.TODO(), time.Millisecond)
200 defer cancel()
201
202 timeoutAsDesignedCh, resultFuncDoneCh := make(chan struct{}), make(chan struct{})
203 resultFn := func() (runtime.Object, error) {
204 defer func() {
205 if test.childGoroutineNeverReturns {
206 // sleep a bit more than test.postTimeoutWait so the
207 // post-timeout monitor gives up.
208 time.Sleep(test.postTimeoutWait + time.Second)
209 }
210 close(resultFuncDoneCh)
211 }()
212
213 // it will block here
214 <-timeoutAsDesignedCh
215
216 if len(test.reason) > 0 {
217 panic(test.reason)
218 }
219 if test.err != nil && test.object != nil {
220 t.Fatal("both result and err are set, wrong test setup")
221 }
222
223 return test.object, test.err
224 }
225
226 var resultGot *result
227 postTimeoutLoggerCompletedCh := make(chan struct{})
228 decoratedPostTimeoutLogger := func(timedOutAt time.Time, r *result) {
229 defer func() {
230 resultGot = r
231 close(postTimeoutLoggerCompletedCh)
232 }()
233
234 logPostTimeoutResult(timedOutAt, r)
235 }
236
237 _, err := finishRequest(ctx, resultFn, test.postTimeoutWait, decoratedPostTimeoutLogger)
238 if err == nil || err.Error() != expectedTimeoutErr.Error() {
239 t.Errorf("expected timeout error: %v, but got: %v", expectedTimeoutErr, err)
240 }
241
242 // the rest ResultFunc is still running, let's unblock it so it can complete
243 close(timeoutAsDesignedCh)
244
245 t.Log("waiting for the ResultFunc rest function to finish")
246 <-resultFuncDoneCh
247
248 t.Log("waiting for the post-timeout logger to return")
249 <-postTimeoutLoggerCompletedCh
250
251 switch {
252 case test.childGoroutineNeverReturns && resultGot != nil:
253 t.Fatal("expected the result for the post-timeout logger to be nil")
254 case test.childGoroutineNeverReturns:
255 // resultGot is nil, nothing more to verify
256 return
257 case !test.childGoroutineNeverReturns && resultGot == nil:
258 t.Fatal("expected a result for the post-timeout logger, but got nil")
259 }
260
261 if test.object != resultGot.object {
262 t.Errorf("expected object to match, diff: %s", cmp.Diff(test.object, resultGot.object))
263 }
264 if test.err != resultGot.err {
265 t.Errorf("expected err: %v, but got: %v", test.err, resultGot.err)
266 }
267
268 switch {
269 case len(test.reason) == 0:
270 if resultGot.reason != nil {
271 t.Errorf("unexpected panic: %v", resultGot.reason)
272 }
273 case !strings.Contains(fmt.Sprintf("%v", resultGot.reason), test.reason):
274 t.Errorf("expected panic to contain: %q, but got: %v", test.reason, resultGot.reason)
275 }
276 })
277 }
278 }