Debian Codegraph @

runtimevar/runtimevar_test.go

raw
1 // Copyright 2018 The Go Cloud Development Kit Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // Package runtimevar contains tests that exercises the runtimevar APIs. It does not test
16 // driver implementations.
17 package runtimevar
18
19 import (
20 "bytes"
21 "context"
22 "encoding/gob"
23 "encoding/json"
24 "errors"
25 "fmt"
26 "net/url"
27 "reflect"
28 "sync"
29 "testing"
30 "time"
31
32 "github.com/google/go-cmp/cmp"
33 "gocloud.dev/gcerrors"
34 "gocloud.dev/internal/gcerr"
35 "gocloud.dev/runtimevar/driver"
36 "gocloud.dev/secrets/localsecrets"
37 )
38
39 // How long we wait on a call that is expected to block forever before cancelling it.
40 const blockingCheckDelay = 25 * time.Millisecond
41
42 // state implements driver.State.
43 type state struct {
44 val string
45 updateTime time.Time
46 err error
47 }
48
49 func (s *state) Value() (any, error) { return s.val, s.err }
50 func (s *state) UpdateTime() time.Time { return s.updateTime }
51 func (s *state) As(i any) bool { return false }
52
53 // fakeWatcher is a fake implementation of driver.Watcher that returns a set *state.
54 type fakeWatcher struct {
55 driver.Watcher
56
57 mu sync.Mutex
58 state *state
59 newval bool // true iff WatchVariable should return state
60 }
61
62 func (w *fakeWatcher) Set(s *state) {
63 w.mu.Lock()
64 defer w.mu.Unlock()
65 w.state = s
66 w.newval = true
67 }
68
69 func (w *fakeWatcher) WatchVariable(ctx context.Context, prev driver.State) (driver.State, time.Duration) {
70 if err := ctx.Err(); err != nil {
71 w.Set(&state{err: err})
72 }
73 w.mu.Lock()
74 defer w.mu.Unlock()
75 if !w.newval {
76 return nil, 1 * time.Millisecond // to avoid spinning
77 }
78 w.newval = false
79 return w.state, 0
80 }
81
82 func (*fakeWatcher) Close() error { return nil }
83 func (*fakeWatcher) ErrorCode(error) gcerrors.ErrorCode { return gcerrors.Internal }
84
85 func TestVariable_Watch(t *testing.T) {
86 fake := &fakeWatcher{}
87 v := New(fake)
88
89 ctx := context.Background()
90
91 // Watch should block when there's no value yet.
92 ctx2, cancel := context.WithTimeout(ctx, blockingCheckDelay)
93 defer cancel()
94 if _, err := v.Watch(ctx2); err == nil {
95 t.Errorf("Watch with no value yet should block: got nil err, want err")
96 }
97 if ctx2.Err() == nil {
98 t.Error("Watch with no value yet should block")
99 }
100
101 // Setting an error value makes Watch return an error.
102 fake.Set(&state{err: errFake})
103 if _, err := v.Watch(ctx); err == nil {
104 t.Fatal("Watch returned non-nil error, want error")
105 }
106 // But calling Watch again blocks.
107 ctx2, cancel = context.WithTimeout(ctx, blockingCheckDelay)
108 defer cancel()
109 if _, err := v.Watch(ctx2); err == nil {
110 t.Errorf("Watch called again with error value should block: got nil err, want err")
111 }
112 if ctx2.Err() == nil {
113 t.Error("Watch called again with error value should block")
114 }
115
116 // Setting a different error makes Watch return again.
117 fake.Set(&state{err: errors.New("another fake error")})
118 if _, err := v.Watch(ctx); err == nil {
119 t.Fatal("Watch returned non-nil error, want error")
120 }
121
122 // Setting a value makes Watch return again.
123 fake.Set(&state{val: "hello"})
124 if _, err := v.Watch(ctx); err != nil {
125 t.Fatalf("Watch returned error %v, want nil", err)
126 }
127
128 // Make a few updates. Each of these will try to write to the nextWatchCh,
129 // but we should only keep the latest one.
130 fake.Set(&state{val: "hello1"})
131 fake.Set(&state{val: "hello2"})
132 fake.Set(&state{val: "hello3"})
133 fake.Set(&state{val: "hello4"})
134 fake.Set(&state{val: "hello5"})
135 // Wait until we're sure the last one has been received.
136 for {
137 snap, err := v.Latest(ctx)
138 if err != nil {
139 t.Errorf("got unexpected error from Latest: %v", err)
140 }
141 if snap.Value == "hello5" {
142 break
143 }
144 }
145
146 // Watch should get the last one, hello5.
147 if snap, err := v.Watch(ctx); err != nil {
148 t.Fatalf("Watch returned error %v, want nil", err)
149 } else if snap.Value != "hello5" {
150 t.Errorf("Watch got %v, want hello5", snap.Value)
151 }
152
153 // And the next call should block.
154 ctx2, cancel = context.WithTimeout(ctx, blockingCheckDelay)
155 defer cancel()
156 if _, err := v.Watch(ctx2); err == nil {
157 t.Errorf("Watch after no change in good value should block: got nil err, want err")
158 }
159 if ctx2.Err() == nil {
160 t.Error("Watch after no change in good value should block")
161 }
162
163 // Ensure a blocking Watch returns when a new value arrives.
164 // Wait blockingCheckDelay to give some time to be blocking in Watch.
165 // There's no guarantee it will get there, but if Watch doesn't handle
166 // cancelation properly, then the test will fail whenever it does get there,
167 // so at least we'll observe a flaky test.
168 time.AfterFunc(blockingCheckDelay, func() { fake.Set(&state{val: "hello6"}) })
169 if snap, err := v.Watch(ctx); err != nil {
170 t.Errorf("Watch interrupted by new value returned %v, want nil", err)
171 } else if snap.Value != "hello6" {
172 t.Errorf("Watch got %v, want hello6", snap.Value)
173 }
174
175 // Similarly, ensure a blocking Watch is interrupted by Close.
176 time.AfterFunc(blockingCheckDelay, func() {
177 if err := v.Close(); err != nil {
178 t.Error(err)
179 }
180 })
181 if _, err := v.Watch(ctx); err != ErrClosed {
182 t.Errorf("Watch interrupted by Close returned %v, want ErrClosed", err)
183 }
184
185 // Watch should now return ErrClosed.
186 if _, err := v.Watch(ctx); err != ErrClosed {
187 t.Errorf("Watch after Close returned %v, want ErrClosed", err)
188 }
189 }
190
191 func TestVariable_Latest(t *testing.T) {
192 const content1, content2 = "foo", "bar"
193 const numGoroutines = 10
194 ctx := context.Background()
195
196 fake := &fakeWatcher{}
197 v := New(fake)
198
199 // Not healthy at startup.
200 if v.CheckHealth() == nil {
201 t.Error("got nil from CheckHealth, want error")
202 }
203
204 // Latest should block until the context is done, as there's no value.
205 ctx2, cancel := context.WithTimeout(ctx, blockingCheckDelay)
206 defer cancel()
207 if _, err := v.Latest(ctx2); err == nil {
208 t.Errorf("Latest with no value yet should block: got nil err, want err")
209 }
210 if ctx2.Err() == nil {
211 t.Error("Latest with no value yet should block")
212 }
213 // And we're not healthy.
214 if v.CheckHealth() == nil {
215 t.Error("got nil from CheckHealth, want error")
216 }
217
218 // Call Latest concurrently. There's still no value.
219 var wg sync.WaitGroup
220 wg.Add(numGoroutines)
221 for range numGoroutines {
222 go func() {
223 ctx2, cancel := context.WithTimeout(ctx, blockingCheckDelay)
224 cancel()
225 if _, err := v.Latest(ctx2); err == nil {
226 t.Errorf("Latest with no value yet: got nil err, want err")
227 }
228 wg.Done()
229 }()
230 }
231 wg.Wait()
232
233 // Set an error value. Latest should still block.
234 fake.Set(&state{err: errFake})
235 ctx2, cancel = context.WithTimeout(ctx, blockingCheckDelay)
236 defer cancel()
237 if _, err := v.Latest(ctx2); err == nil {
238 t.Errorf("Latest with error value should block: got nil err, want err")
239 }
240 if ctx2.Err() == nil {
241 t.Error("Latest with error value should block")
242 }
243 // And we're still not healthy.
244 if v.CheckHealth() == nil {
245 t.Error("got nil from CheckHealth, want error")
246 }
247
248 // Call Latest concurrently, only exiting each goroutine when they
249 // see the content1 value.
250 wg.Add(numGoroutines)
251 for range numGoroutines {
252 go func() {
253 for {
254 val, err := v.Latest(ctx)
255 if err != nil {
256 continue
257 }
258 if val.Value != content1 {
259 t.Errorf("got %v want %s", val, content1)
260 }
261 wg.Done()
262 return
263 }
264 }()
265 }
266 // Set a good value, after a small delay to give the goroutines a chance
267 // to get into Latest.
268 time.Sleep(blockingCheckDelay)
269 fake.Set(&state{val: content1})
270 wg.Wait()
271 // And now we're healthy.
272 if err := v.CheckHealth(); err != nil {
273 t.Errorf("got %v from CheckHealth, want nil", err)
274 }
275
276 // Set a different value. At some point after this, Latest should start
277 // returning a Snapshot with Value set to content2.
278 fake.Set(&state{val: content2})
279
280 // Call Latest concurrently, only exiting each goroutine when they
281 // see the content2 value.
282 wg.Add(numGoroutines)
283 for range numGoroutines {
284 go func() {
285 for {
286 val, err := v.Latest(ctx)
287 if err != nil {
288 // Errors are unexpected at this point.
289 t.Error(err)
290 }
291 if val.Value == content1 {
292 // Still seeing the old value.
293 continue
294 }
295 if val.Value != content2 {
296 t.Errorf("got %v want %s", val, content2)
297 }
298 wg.Done()
299 return
300 }
301 }()
302 }
303 wg.Wait()
304
305 // Set an error value. Latest should still return content2.
306 fake.Set(&state{err: errFake})
307
308 // Call Latest concurrently. The test will be flaky if some of them
309 // start getting errors.
310 wg.Add(numGoroutines)
311 for range numGoroutines {
312 go func() {
313 val, err := v.Latest(ctx)
314 if err != nil {
315 // Errors are unexpected at this point.
316 t.Error(err)
317 } else if val.Value != content2 {
318 t.Errorf("got %v want %s", val.Value, content2)
319 }
320 wg.Done()
321 return
322 }()
323 }
324 wg.Wait()
325
326 // Still healthy.
327 if err := v.CheckHealth(); err != nil {
328 t.Errorf("got %v from CheckHealth, want nil", err)
329 }
330
331 // Close the variable.
332 if err := v.Close(); err != nil {
333 t.Error(err)
334 }
335
336 // Latest should now return ErrClosed.
337 if _, err := v.Latest(ctx); err != ErrClosed {
338 t.Errorf("Latest after close returned %v, want ErrClosed", err)
339 }
340 // Unhealthy now.
341 if err := v.CheckHealth(); err != ErrClosed {
342 t.Errorf("got %v from CheckHealth, want ErrClosed", err)
343 }
344 }
345
346 // Tests that Latest is interrupted by Close.
347 func TestVariable_LatestBlockedDuringClose(t *testing.T) {
348 fake := &fakeWatcher{}
349 v := New(fake)
350
351 ctx := context.Background()
352
353 // Wait blockingCheckDelay to give some time to be blocking in Latest.
354 // There's no guarantee it will get there, but if Latest doesn't handle
355 // cancelation properly, then the test will fail whenever it does get there,
356 // so at least we'll observe a flaky test.
357 time.AfterFunc(blockingCheckDelay, func() {
358 if err := v.Close(); err != nil {
359 t.Error(err)
360 }
361 })
362 if _, err := v.Latest(ctx); err != ErrClosed {
363 t.Errorf("Latest interrupted by Close got %v, want ErrClosed", err)
364 }
365
366 // Calling Close again should return ErrClosed.
367 if err := v.Close(); err != ErrClosed {
368 t.Errorf("calling Close 2x returned %v, want ErrClosed", err)
369 }
370 }
371
372 var errFake = errors.New("fake")
373
374 // erroringWatcher implements driver.Watcher.
375 // WatchVariable always returns a state with errFake, and Close
376 // always returns errFake.
377 type erroringWatcher struct {
378 driver.Watcher
379 }
380
381 func (b *erroringWatcher) WatchVariable(ctx context.Context, prev driver.State) (driver.State, time.Duration) {
382 return &state{err: errFake}, 0
383 }
384
385 func (b *erroringWatcher) Close() error {
386 return errFake
387 }
388
389 func (b *erroringWatcher) ErrorCode(err error) gcerrors.ErrorCode {
390 return gcerrors.Internal
391 }
392
393 // TestErrorsAreWrapped tests that all errors returned from the driver are
394 // wrapped exactly once by the portable type.
395 func TestErrorsAreWrapped(t *testing.T) {
396 ctx := context.Background()
397 v := New(&erroringWatcher{})
398
399 // verifyWrap ensures that err is wrapped exactly once.
400 verifyWrap := func(description string, err error) {
401 if unwrapped, ok := err.(*gcerr.Error); !ok {
402 t.Errorf("%s: not wrapped: %v", description, err)
403 } else if du, ok := unwrapped.Unwrap().(*gcerr.Error); ok {
404 t.Errorf("%s: double wrapped: %v", description, du)
405 }
406 }
407
408 _, err := v.Watch(ctx)
409 verifyWrap("Watch", err)
410
411 err = v.Close()
412 verifyWrap("Close", err)
413 }
414
415 var (
416 testOpenOnce sync.Once
417 testOpenGot *url.URL
418 )
419
420 func TestURLMux(t *testing.T) {
421 ctx := context.Background()
422
423 mux := new(URLMux)
424 fake := &fakeOpener{}
425 mux.RegisterVariable("foo", fake)
426 mux.RegisterVariable("err", fake)
427
428 if diff := cmp.Diff(mux.VariableSchemes(), []string{"err", "foo"}); diff != "" {
429 t.Errorf("Schemes: %s", diff)
430 }
431 if !mux.ValidVariableScheme("foo") || !mux.ValidVariableScheme("err") {
432 t.Errorf("ValidVariableScheme didn't return true for valid scheme")
433 }
434 if mux.ValidVariableScheme("foo2") || mux.ValidVariableScheme("http") {
435 t.Errorf("ValidVariableScheme didn't return false for invalid scheme")
436 }
437
438 for _, tc := range []struct {
439 name string
440 url string
441 wantErr bool
442 }{
443 {
444 name: "empty URL",
445 wantErr: true,
446 },
447 {
448 name: "invalid URL",
449 url: ":foo",
450 wantErr: true,
451 },
452 {
453 name: "invalid URL no scheme",
454 url: "foo",
455 wantErr: true,
456 },
457 {
458 name: "unregistered scheme",
459 url: "bar://myvar",
460 wantErr: true,
461 },
462 {
463 name: "func returns error",
464 url: "err://myvar",
465 wantErr: true,
466 },
467 {
468 name: "no query options",
469 url: "foo://myvar",
470 },
471 {
472 name: "empty query options",
473 url: "foo://myvar?",
474 },
475 {
476 name: "query options",
477 url: "foo://myvar?aAa=bBb&cCc=dDd",
478 },
479 {
480 name: "multiple query options",
481 url: "foo://myvar?x=a&x=b&x=c",
482 },
483 {
484 name: "fancy var name",
485 url: "foo:///foo/bar/baz",
486 },
487 {
488 name: "using api scheme prefix",
489 url: "runtimevar+foo:///foo/bar/baz",
490 },
491 {
492 name: "using api+type scheme prefix",
493 url: "runtimevar+variable+foo:///foo/bar/baz",
494 },
495 } {
496 t.Run(tc.name, func(t *testing.T) {
497 _, gotErr := mux.OpenVariable(ctx, tc.url)
498 if (gotErr != nil) != tc.wantErr {
499 t.Fatalf("got err %v, want error %v", gotErr, tc.wantErr)
500 }
501 if gotErr != nil {
502 return
503 }
504 if got := fake.u.String(); got != tc.url {
505 t.Errorf("got %q want %q", got, tc.url)
506 }
507 // Repeat with OpenVariableURL.
508 parsed, err := url.Parse(tc.url)
509 if err != nil {
510 t.Fatal(err)
511 }
512 _, gotErr = mux.OpenVariableURL(ctx, parsed)
513 if gotErr != nil {
514 t.Fatalf("got err %v, want nil", gotErr)
515 }
516 if got := fake.u.String(); got != tc.url {
517 t.Errorf("got %q want %q", got, tc.url)
518 }
519 })
520 }
521 }
522
523 type fakeOpener struct {
524 u *url.URL // last url passed to OpenVariableURL
525 }
526
527 func (o *fakeOpener) OpenVariableURL(ctx context.Context, u *url.URL) (*Variable, error) {
528 if u.Scheme == "err" {
529 return nil, errors.New("fail")
530 }
531 o.u = u
532 return nil, nil
533 }
534
535 func TestDecoder(t *testing.T) {
536 type Struct struct {
537 FieldA string
538 FieldB map[string]any
539 }
540
541 num := 4321
542 numptr := &num
543 str := "boring string"
544 strptr := &str
545
546 inputs := []any{
547 str,
548 strptr,
549 num,
550 numptr,
551 100.1,
552 Struct{
553 FieldA: "hello",
554 FieldB: map[string]any{
555 "hello": "world",
556 },
557 },
558 &Struct{
559 FieldA: "world",
560 },
561 map[string]string{
562 "slice": "pizza",
563 },
564 &map[string]any{},
565 []string{"hello", "world"},
566 &[]int{1, 0, 1},
567 [...]float64{3.1415},
568 &[...]int64{4, 5, 6},
569 }
570
571 for _, tc := range []struct {
572 desc string
573 encodeFn func(any) ([]byte, error)
574 decodeFn Decode
575 }{
576 {
577 desc: "JSON",
578 encodeFn: json.Marshal,
579 decodeFn: JSONDecode,
580 },
581 {
582 desc: "Gob",
583 encodeFn: gobMarshal,
584 decodeFn: GobDecode,
585 },
586 } {
587 for i, input := range inputs {
588 t.Run(fmt.Sprintf("%s_%d", tc.desc, i), func(t *testing.T) {
589 decoder := NewDecoder(input, tc.decodeFn)
590 b, err := tc.encodeFn(input)
591 if err != nil {
592 t.Fatalf("marshal error %v", err)
593 }
594 got, err := decoder.Decode(context.Background(), b)
595 if err != nil {
596 t.Fatalf("parse input\n%s\nerror: %v", string(b), err)
597 }
598 if reflect.TypeOf(got) != reflect.TypeOf(input) {
599 t.Errorf("type mismatch got %T, want %T", got, input)
600 }
601 if diff := cmp.Diff(got, input); diff != "" {
602 t.Errorf("value diff:\n%v", diff)
603 }
604 })
605 }
606 }
607 }
608
609 func gobMarshal(v any) ([]byte, error) {
610 var buf bytes.Buffer
611 if err := gob.NewEncoder(&buf).Encode(v); err != nil {
612 return nil, err
613 }
614 return buf.Bytes(), nil
615 }
616
617 func TestStringDecoder(t *testing.T) {
618 input := "hello world"
619 got, err := StringDecoder.Decode(context.Background(), []byte(input))
620 if err != nil {
621 t.Fatalf("error: %v", err)
622 }
623 if input != got.(string) {
624 t.Errorf("output got %v, want %q", got, input)
625 }
626 }
627
628 func TestBytesDecoder(t *testing.T) {
629 input := []byte("hello world")
630 got, err := BytesDecoder.Decode(context.Background(), input)
631 if err != nil {
632 t.Fatalf("error: %v", err)
633 }
634 if diff := cmp.Diff(got, input); diff != "" {
635 t.Errorf("output got %v, want %q", got, input)
636 }
637 }
638
639 func TestDecryptDecoder(t *testing.T) {
640 ctx := context.Background()
641 secretKey, err := localsecrets.NewRandomKey()
642 if err != nil {
643 t.Fatal(err)
644 }
645 keeper := localsecrets.NewKeeper(secretKey)
646
647 tests := []struct {
648 desc string
649 in any
650 encodeFn func(any) ([]byte, error)
651 postDecFn Decode
652 }{
653 {
654 desc: "Bytes",
655 in: []byte("hello world"),
656 encodeFn: func(obj any) ([]byte, error) { return obj.([]byte), nil },
657 },
658 {
659 desc: "String",
660 in: "hello world",
661 encodeFn: func(obj any) ([]byte, error) { return []byte(obj.(string)), nil },
662 postDecFn: StringDecode,
663 },
664 {
665 desc: "JSON",
666 in: map[string]string{
667 "slice": "pizza",
668 },
669 encodeFn: json.Marshal,
670 postDecFn: JSONDecode,
671 },
672 }
673 for _, tc := range tests {
674 t.Run(tc.desc, func(t *testing.T) {
675 decoder := NewDecoder(tc.in, DecryptDecode(keeper, tc.postDecFn))
676
677 b, err := tc.encodeFn(tc.in)
678 if err != nil {
679 t.Fatalf("encode error %v", err)
680 }
681 encrypted, err := keeper.Encrypt(ctx, b)
682 if err != nil {
683 t.Fatalf("encrypt error: %v", err)
684 }
685
686 got, err := decoder.Decode(ctx, encrypted)
687 if err != nil {
688 t.Fatalf("parse input\n%s\nerror: %v", string(b), err)
689 }
690 if reflect.TypeOf(got) != reflect.TypeOf(tc.in) {
691 t.Errorf("type mismatch got %T, want %T", got, tc.in)
692 }
693 if diff := cmp.Diff(got, tc.in); diff != "" {
694 t.Errorf("value diff:\n%v", diff)
695 }
696 })
697 }
698 }