Debian Codegraph @

runtimevar/drivertest/drivertest.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 drivertest provides a conformance test for implementations of
16 // runtimevar.
17 package drivertest // import "gocloud.dev/runtimevar/drivertest"
18
19 import (
20 "context"
21 "errors"
22 "testing"
23 "time"
24
25 "github.com/google/go-cmp/cmp"
26 "gocloud.dev/gcerrors"
27 "gocloud.dev/internal/testing/setup"
28 "gocloud.dev/runtimevar"
29 "gocloud.dev/runtimevar/driver"
30 )
31
32 // Harness describes the functionality test harnesses must provide to run conformance tests.
33 type Harness interface {
34 // MakeWatcher creates a driver.Watcher to watch the given variable.
35 MakeWatcher(ctx context.Context, name string, decoder *runtimevar.Decoder) (driver.Watcher, error)
36 // CreateVariable creates the variable with the given contents.
37 CreateVariable(ctx context.Context, name string, val []byte) error
38 // UpdateVariable updates an existing variable to have the given contents.
39 UpdateVariable(ctx context.Context, name string, val []byte) error
40 // DeleteVariable deletes an existing variable.
41 DeleteVariable(ctx context.Context, name string) error
42 // Close is called when the test is complete.
43 Close()
44 // Mutable returns true iff the driver supports UpdateVariable/DeleteVariable.
45 // If false, those functions should return errors, and the conformance tests
46 // will skip and/or ignore errors for tests that require them.
47 Mutable() bool
48 }
49
50 // HarnessMaker describes functions that construct a harness for running tests.
51 // It is called exactly once per test; Harness.Close() will be called when the test is complete.
52 type HarnessMaker func(t *testing.T) (Harness, error)
53
54 // AsTest represents a test of As functionality.
55 // The conformance test:
56 // 1. Reads a Snapshot of the variable before it exists.
57 // 2. Calls ErrorCheck.
58 // 3. Creates the variable and reads a Snapshot of it.
59 // 4. Calls SnapshotCheck.
60 type AsTest interface {
61 // Name should return a descriptive name for the test.
62 Name() string
63 // SnapshotCheck will be called to allow verification of Snapshot.As.
64 SnapshotCheck(s *runtimevar.Snapshot) error
65 // ErrorCheck will be called to allow verification of Variable.ErrorAs.
66 // driver is provided so that errors other than err can be checked;
67 // Variable.ErrorAs won't work since it expects driver errors to be wrapped.
68 ErrorCheck(v *runtimevar.Variable, err error) error
69 }
70
71 type verifyAsFailsOnNil struct{}
72
73 func (verifyAsFailsOnNil) Name() string {
74 return "verify As returns false when passed nil"
75 }
76
77 func (verifyAsFailsOnNil) SnapshotCheck(v *runtimevar.Snapshot) error {
78 if v.As(nil) {
79 return errors.New("want Snapshot.As to return false when passed nil")
80 }
81 return nil
82 }
83
84 func (verifyAsFailsOnNil) ErrorCheck(v *runtimevar.Variable, err error) (ret error) {
85 defer func() {
86 if recover() == nil {
87 ret = errors.New("want ErrorAs to panic when passed nil")
88 }
89 }()
90 v.ErrorAs(err, nil)
91 return nil
92 }
93
94 // RunConformanceTests runs conformance tests for driver implementations
95 // of runtimevar.
96 func RunConformanceTests(t *testing.T, newHarness HarnessMaker, asTests []AsTest) {
97 t.Helper()
98
99 t.Run("TestNonExistentVariable", func(t *testing.T) {
100 testNonExistentVariable(t, newHarness)
101 })
102 t.Run("TestString", func(t *testing.T) {
103 testString(t, newHarness)
104 })
105 t.Run("TestJSON", func(t *testing.T) {
106 testJSON(t, newHarness)
107 })
108 t.Run("TestInvalidJSON", func(t *testing.T) {
109 testInvalidJSON(t, newHarness)
110 })
111 t.Run("TestUpdate", func(t *testing.T) {
112 testUpdate(t, newHarness)
113 })
114 t.Run("TestDelete", func(t *testing.T) {
115 testDelete(t, newHarness)
116 })
117 t.Run("TestUpdateWithErrors", func(t *testing.T) {
118 testUpdateWithErrors(t, newHarness)
119 })
120 asTests = append(asTests, verifyAsFailsOnNil{})
121 t.Run("TestAs", func(t *testing.T) {
122 for _, st := range asTests {
123 if st.Name() == "" {
124 t.Fatalf("AsTest.Name is required")
125 }
126 t.Run(st.Name(), func(t *testing.T) {
127 testAs(t, newHarness, st)
128 })
129 }
130 })
131 }
132
133 // waitTimeForBlockingCheck returns a duration to wait when verifying that a
134 // call blocks. When in replay mode, it can be quite short to make tests run
135 // quickly. When in record mode, it has to be long enough that RPCs can
136 // consistently finish.
137 func waitTimeForBlockingCheck() time.Duration {
138 if *setup.Record {
139 return 5 * time.Second
140 }
141 return 10 * time.Millisecond
142 }
143
144 func testNonExistentVariable(t *testing.T, newHarness HarnessMaker) {
145 t.Helper()
146
147 h, err := newHarness(t)
148 if err != nil {
149 t.Fatal(err)
150 }
151 defer h.Close()
152 ctx := context.Background()
153
154 drv, err := h.MakeWatcher(ctx, "does-not-exist", runtimevar.StringDecoder)
155 if err != nil {
156 t.Fatal(err)
157 }
158 v := runtimevar.New(drv)
159 defer func() {
160 if err := v.Close(); err != nil {
161 t.Error(err)
162 }
163 }()
164 got, err := v.Watch(ctx)
165 if err == nil {
166 t.Errorf("got %v expected not-found error", got.Value)
167 } else if gcerrors.Code(err) != gcerrors.NotFound {
168 t.Error("got IsNotExist false, expected true")
169 }
170 }
171
172 func testString(t *testing.T, newHarness HarnessMaker) {
173 t.Helper()
174
175 const (
176 name = "test-config-variable"
177 content = "hello world"
178 )
179
180 h, err := newHarness(t)
181 if err != nil {
182 t.Fatal(err)
183 }
184 defer h.Close()
185 ctx := context.Background()
186
187 if err := h.CreateVariable(ctx, name, []byte(content)); err != nil {
188 t.Fatal(err)
189 }
190 if h.Mutable() {
191 defer func() {
192 if err := h.DeleteVariable(ctx, name); err != nil {
193 t.Fatal(err)
194 }
195 }()
196 }
197
198 drv, err := h.MakeWatcher(ctx, name, runtimevar.StringDecoder)
199 if err != nil {
200 t.Fatal(err)
201 }
202 v := runtimevar.New(drv)
203 defer func() {
204 if err := v.Close(); err != nil {
205 t.Error(err)
206 }
207 }()
208 got, err := v.Watch(ctx)
209 if err != nil {
210 t.Fatal(err)
211 }
212 // The variable is decoded to a string and matches the expected content.
213 if gotS, ok := got.Value.(string); !ok {
214 t.Fatalf("got value of type %T expected string", got.Value)
215 } else if gotS != content {
216 t.Errorf("got %q want %q", got.Value, content)
217 }
218
219 // A second watch should block forever since the value hasn't changed.
220 // A short wait here doesn't guarantee that this is working, but will catch
221 // most problems.
222 tCtx, cancel := context.WithTimeout(ctx, waitTimeForBlockingCheck())
223 defer cancel()
224 got, err = v.Watch(tCtx)
225 if err == nil {
226 t.Errorf("got %v want error", got)
227 }
228 // tCtx should be cancelled. However, tests using record/replay mode can
229 // be in the middle of an RPC when that happens, and save the resulting
230 // RPC error during record. During replay, that error can be returned
231 // immediately (before tCtx is cancelled). So, we accept deadline exceeded
232 // errors as well.
233 if tCtx.Err() == nil && gcerrors.Code(err) != gcerrors.DeadlineExceeded {
234 t.Errorf("got err %v/%v; want Watch to have blocked until context was Done, or for the error to be deadline exceeded", err, gcerrors.Code(err))
235 }
236 }
237
238 // Message is used as a target for JSON decoding.
239 type Message struct {
240 Name, Text string
241 }
242
243 func testJSON(t *testing.T, newHarness HarnessMaker) {
244 t.Helper()
245
246 const (
247 name = "test-config-variable"
248 jsonContent = `[
249 {"Name": "Ed", "Text": "Knock knock."},
250 {"Name": "Sam", "Text": "Who's there?"}
251 ]`
252 )
253 want := []*Message{{Name: "Ed", Text: "Knock knock."}, {Name: "Sam", Text: "Who's there?"}}
254
255 h, err := newHarness(t)
256 if err != nil {
257 t.Fatal(err)
258 }
259 defer h.Close()
260 ctx := context.Background()
261
262 if err := h.CreateVariable(ctx, name, []byte(jsonContent)); err != nil {
263 t.Fatal(err)
264 }
265 if h.Mutable() {
266 defer func() {
267 if err := h.DeleteVariable(ctx, name); err != nil {
268 t.Fatal(err)
269 }
270 }()
271 }
272
273 var jsonData []*Message
274 drv, err := h.MakeWatcher(ctx, name, runtimevar.NewDecoder(jsonData, runtimevar.JSONDecode))
275 if err != nil {
276 t.Fatal(err)
277 }
278 v := runtimevar.New(drv)
279 defer func() {
280 if err := v.Close(); err != nil {
281 t.Error(err)
282 }
283 }()
284 got, err := v.Watch(ctx)
285 if err != nil {
286 t.Fatal(err)
287 }
288 // The variable is decoded to a []*Message and matches the expected content.
289 if gotSlice, ok := got.Value.([]*Message); !ok {
290 t.Fatalf("got value of type %T expected []*Message", got.Value)
291 } else if !cmp.Equal(gotSlice, want) {
292 t.Errorf("got %v want %v", gotSlice, want)
293 }
294 }
295
296 func testInvalidJSON(t *testing.T, newHarness HarnessMaker) {
297 t.Helper()
298
299 const (
300 name = "test-config-variable"
301 content = "not-json"
302 )
303
304 h, err := newHarness(t)
305 if err != nil {
306 t.Fatal(err)
307 }
308 defer h.Close()
309 ctx := context.Background()
310
311 if err := h.CreateVariable(ctx, name, []byte(content)); err != nil {
312 t.Fatal(err)
313 }
314 if h.Mutable() {
315 defer func() {
316 if err := h.DeleteVariable(ctx, name); err != nil {
317 t.Fatal(err)
318 }
319 }()
320 }
321
322 var jsonData []*Message
323 drv, err := h.MakeWatcher(ctx, name, runtimevar.NewDecoder(jsonData, runtimevar.JSONDecode))
324 if err != nil {
325 t.Fatal(err)
326 }
327 v := runtimevar.New(drv)
328 defer func() {
329 if err := v.Close(); err != nil {
330 t.Error(err)
331 }
332 }()
333 got, err := v.Watch(ctx)
334 if err == nil {
335 t.Errorf("got %v wanted invalid-json error", got.Value)
336 }
337 }
338
339 func testUpdate(t *testing.T, newHarness HarnessMaker) {
340 t.Helper()
341
342 const (
343 name = "test-config-variable"
344 content1 = "hello world"
345 content2 = "goodbye world"
346 )
347
348 h, err := newHarness(t)
349 if err != nil {
350 t.Fatal(err)
351 }
352 defer h.Close()
353 if !h.Mutable() {
354 return
355 }
356 ctx := context.Background()
357
358 // Create the variable and verify WatchVariable sees the value.
359 if err := h.CreateVariable(ctx, name, []byte(content1)); err != nil {
360 t.Fatal(err)
361 }
362 defer func() {
363 if err := h.DeleteVariable(ctx, name); err != nil {
364 t.Fatal(err)
365 }
366 }()
367
368 drv, err := h.MakeWatcher(ctx, name, runtimevar.StringDecoder)
369 if err != nil {
370 t.Fatal(err)
371 }
372 defer func() {
373 if err := drv.Close(); err != nil {
374 t.Error(err)
375 }
376 }()
377 state, _ := drv.WatchVariable(ctx, nil)
378 if state == nil {
379 t.Fatalf("got nil state, want a non-nil state with a value")
380 }
381 got, err := state.Value()
382 if err != nil {
383 t.Fatal(err)
384 }
385 if gotS, ok := got.(string); !ok {
386 t.Fatalf("got value of type %T expected string", got)
387 } else if gotS != content1 {
388 t.Errorf("got %q want %q", got, content1)
389 }
390
391 // The variable hasn't changed, so drv.WatchVariable should either
392 // return nil or block.
393 cancelCtx, cancel := context.WithTimeout(ctx, waitTimeForBlockingCheck())
394 defer cancel()
395 unchangedState, _ := drv.WatchVariable(cancelCtx, state)
396 if unchangedState == nil {
397 // OK
398 } else {
399 got, err = unchangedState.Value()
400 if gcerrors.Code(err) != gcerrors.DeadlineExceeded {
401 t.Fatalf("got state %v/%v/%v, wanted nil or nil/DeadlineExceeded after no change", got, err, gcerrors.Code(err))
402 }
403 }
404
405 // Update the variable and verify WatchVariable sees the updated value.
406 if err := h.UpdateVariable(ctx, name, []byte(content2)); err != nil {
407 t.Fatal(err)
408 }
409 state, _ = drv.WatchVariable(ctx, state)
410 // In rare race conditions during replay, if the earlier WatchVariable
411 // was cancelled/timed out before actually calling an RPC, this one
412 // might have returned the old/unchanged value. This only happens during
413 // replay mode. Just try again, the next RPC should get the updated value.
414 // BTW this is easy to reproduce by setting the timeout in
415 // waitForBlockingCheck to 1 nanosecond.
416 if state == nil && !*setup.Record {
417 state, _ = drv.WatchVariable(ctx, state)
418 }
419 if state == nil {
420 t.Fatalf("got nil state, want a non-nil state with a value")
421 }
422 got, err = state.Value()
423 if err != nil {
424 t.Fatal(err)
425 }
426 if gotS, ok := got.(string); !ok {
427 t.Fatalf("got value of type %T expected string", got)
428 } else if gotS != content2 {
429 t.Errorf("got %q want %q", got, content2)
430 }
431 }
432
433 func testDelete(t *testing.T, newHarness HarnessMaker) {
434 t.Helper()
435
436 const (
437 name = "test-config-variable"
438 content1 = "hello world"
439 content2 = "goodbye world"
440 )
441
442 h, err := newHarness(t)
443 if err != nil {
444 t.Fatal(err)
445 }
446 defer h.Close()
447 if !h.Mutable() {
448 return
449 }
450 ctx := context.Background()
451
452 // Create the variable and verify WatchVariable sees the value.
453 if err := h.CreateVariable(ctx, name, []byte(content1)); err != nil {
454 t.Fatal(err)
455 }
456 needToDelete := true
457 defer func() {
458 if needToDelete {
459 if err := h.DeleteVariable(ctx, name); err != nil {
460 t.Fatal(err)
461 }
462 }
463 }()
464
465 drv, err := h.MakeWatcher(ctx, name, runtimevar.StringDecoder)
466 if err != nil {
467 t.Fatal(err)
468 }
469 defer func() {
470 if err := drv.Close(); err != nil {
471 t.Error(err)
472 }
473 }()
474 state, _ := drv.WatchVariable(ctx, nil)
475 if state == nil {
476 t.Fatalf("got nil state, want a non-nil state with a value")
477 }
478 got, err := state.Value()
479 if err != nil {
480 t.Fatal(err)
481 }
482 if gotS, ok := got.(string); !ok {
483 t.Fatalf("got value of type %T expected string", got)
484 } else if gotS != content1 {
485 t.Errorf("got %q want %q", got, content1)
486 }
487 prev := state
488
489 // Delete the variable.
490 if err := h.DeleteVariable(ctx, name); err != nil {
491 t.Fatal(err)
492 }
493 needToDelete = false
494
495 // WatchVariable should return a state with an error now.
496 state, _ = drv.WatchVariable(ctx, state)
497 if state == nil {
498 t.Fatalf("got nil state, want a non-nil state with an error")
499 }
500 got, err = state.Value()
501 if err == nil {
502 t.Fatalf("got %v want error because variable is deleted", got)
503 }
504
505 // Reset the variable with new content and verify via WatchVariable.
506 if err := h.CreateVariable(ctx, name, []byte(content2)); err != nil {
507 t.Fatal(err)
508 }
509 needToDelete = true
510 state, _ = drv.WatchVariable(ctx, state)
511 if state == nil {
512 t.Fatalf("got nil state, want a non-nil state with a value")
513 }
514 got, err = state.Value()
515 if err != nil {
516 t.Fatal(err)
517 }
518 if gotS, ok := got.(string); !ok {
519 t.Fatalf("got value of type %T expected string", got)
520 } else if gotS != content2 {
521 t.Errorf("got %q want %q", got, content2)
522 }
523 if state.UpdateTime().Before(prev.UpdateTime()) {
524 t.Errorf("got UpdateTime %v < previous %v, want >=", state.UpdateTime(), prev.UpdateTime())
525 }
526 }
527
528 func testUpdateWithErrors(t *testing.T, newHarness HarnessMaker) {
529 t.Helper()
530
531 const (
532 name = "test-updating-variable-to-error"
533 content1 = `[{"Name": "Foo", "Text": "Bar"}]`
534 content2 = "invalid-json"
535 content3 = "invalid-json2"
536 )
537 want := []*Message{{Name: "Foo", Text: "Bar"}}
538
539 h, err := newHarness(t)
540 if err != nil {
541 t.Fatal(err)
542 }
543 defer h.Close()
544 if !h.Mutable() {
545 return
546 }
547 ctx := context.Background()
548
549 // Create the variable and verify WatchVariable sees the value.
550 if err := h.CreateVariable(ctx, name, []byte(content1)); err != nil {
551 t.Fatal(err)
552 }
553 defer func() {
554 if err := h.DeleteVariable(ctx, name); err != nil {
555 t.Fatal(err)
556 }
557 }()
558
559 var jsonData []*Message
560 drv, err := h.MakeWatcher(ctx, name, runtimevar.NewDecoder(jsonData, runtimevar.JSONDecode))
561 if err != nil {
562 t.Fatal(err)
563 }
564 defer func() {
565 if err := drv.Close(); err != nil {
566 t.Error(err)
567 }
568 }()
569 state, _ := drv.WatchVariable(ctx, nil)
570 if state == nil {
571 t.Fatal("got nil state, want a non-nil state with a value")
572 }
573 got, err := state.Value()
574 if err != nil {
575 t.Fatal(err)
576 }
577 if gotSlice, ok := got.([]*Message); !ok {
578 t.Fatalf("got value of type %T expected []*Message", got)
579 } else if !cmp.Equal(gotSlice, want) {
580 t.Errorf("got %v want %v", gotSlice, want)
581 }
582
583 // Update the variable to invalid JSON and verify WatchVariable returns an error.
584 if err := h.UpdateVariable(ctx, name, []byte(content2)); err != nil {
585 t.Fatal(err)
586 }
587 state, _ = drv.WatchVariable(ctx, state)
588 if state == nil {
589 t.Fatal("got nil state, want a non-nil state with an error")
590 }
591 _, err = state.Value()
592 if err == nil {
593 t.Fatal("got nil err want invalid JSON error")
594 }
595
596 // Update the variable again, with different invalid JSON.
597 // WatchVariable should block or return nil since it's the same error as before.
598 if err := h.UpdateVariable(ctx, name, []byte(content3)); err != nil {
599 t.Fatal(err)
600 }
601 tCtx, cancel := context.WithTimeout(ctx, waitTimeForBlockingCheck())
602 defer cancel()
603 state, _ = drv.WatchVariable(tCtx, state)
604 if state == nil {
605 // OK: nil indicates no change.
606 } else {
607 // WatchVariable should have blocked until tCtx was cancelled, and we
608 // should have gotten that error back.
609 got, err := state.Value()
610 if err == nil {
611 t.Fatalf("got %v and nil error, want non-nil error", got)
612 }
613 // tCtx should be cancelled. However, tests using record/replay mode can
614 // be in the middle of an RPC when that happens, and save the resulting
615 // RPC error during record. During replay, that error can be returned
616 // immediately (before tCtx is cancelled). So, we accept deadline exceeded
617 // errors as well.
618 if tCtx.Err() == nil && gcerrors.Code(err) != gcerrors.DeadlineExceeded {
619 t.Errorf("got err %v/%v; want Watch to have blocked until context was Done, or for the error to be deadline exceeded", err, gcerrors.Code(err))
620 }
621 }
622 }
623
624 // testAs tests the various As functions, using AsTest.
625 func testAs(t *testing.T, newHarness HarnessMaker, st AsTest) {
626 t.Helper()
627
628 const (
629 name = "variable-for-as"
630 content = "hello world"
631 )
632
633 h, err := newHarness(t)
634 if err != nil {
635 t.Fatal(err)
636 }
637 defer h.Close()
638 ctx := context.Background()
639
640 // Try to read the variable before it exists.
641 drv, err := h.MakeWatcher(ctx, name, runtimevar.StringDecoder)
642 if err != nil {
643 t.Fatal(err)
644 }
645 v := runtimevar.New(drv)
646 s, gotErr := v.Watch(ctx)
647 if gotErr == nil {
648 t.Fatalf("got nil error and %v, expected non-nil error", v)
649 }
650 if err := st.ErrorCheck(v, gotErr); err != nil {
651 t.Error(err)
652 }
653 var dummy string
654 if s.As(&dummy) {
655 t.Error(errors.New("want Snapshot.As to return false when Snapshot is zero value"))
656 }
657 if err := v.Close(); err != nil {
658 t.Error(err)
659 }
660
661 // Create the variable and verify WatchVariable sees the value.
662 if err := h.CreateVariable(ctx, name, []byte(content)); err != nil {
663 t.Fatal(err)
664 }
665 if h.Mutable() {
666 defer func() {
667 if err := h.DeleteVariable(ctx, name); err != nil {
668 t.Fatal(err)
669 }
670 }()
671 }
672
673 drv, err = h.MakeWatcher(ctx, name, runtimevar.StringDecoder)
674 if err != nil {
675 t.Fatal(err)
676 }
677 v = runtimevar.New(drv)
678 defer func() {
679 if err := v.Close(); err != nil {
680 t.Error(err)
681 }
682 }()
683 s, err = v.Watch(ctx)
684 if err != nil {
685 t.Fatal(err)
686 }
687 if err := st.SnapshotCheck(&s); err != nil {
688 t.Error(err)
689 }
690 }