-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathwatcher_test.go
1085 lines (1003 loc) · 27 KB
/
watcher_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package hcat
import (
"context"
"fmt"
"strconv"
"testing"
"time"
"github.com/hashicorp/hcat/dep"
idep "github.com/hashicorp/hcat/internal/dependency"
"github.com/pkg/errors"
)
func TestWatcherClients(t *testing.T) {
w := newWatcher()
defer w.Stop()
var _ Watcherer = Watcherer(newWatcher())
clients := w.Clients()
switch clients.(type) {
case *ClientSet:
default:
t.Errorf("w.Clients() returning wrong type")
}
}
func TestWatcherAdd(t *testing.T) {
t.Run("updates-tracker", func(t *testing.T) {
w := newWatcher()
defer w.Stop()
d := &idep.FakeDep{}
n := fakeNotifier("foo")
w.Register(n)
if added := w.track(n, d); added == nil {
t.Fatal("Register returned nil")
}
if !w.Watching(d.ID()) {
t.Errorf("expected add to append to map")
}
})
t.Run("exists", func(t *testing.T) {
w := newWatcher()
defer w.Stop()
d := &idep.FakeDep{}
n := fakeNotifier("foo")
w.Register(n)
var added *view
if added = w.track(n, d); added == nil {
t.Fatal("Register returned nil")
}
if readded := w.track(n, d); readded != added {
t.Fatal("Register should have returned the already created"+
"view, instead got:", added)
}
})
t.Run("startsViewPoll", func(t *testing.T) {
w := newWatcher()
defer w.Stop()
d := &idep.FakeDep{}
n := fakeNotifier("foo")
w.Register(n)
if added := w.track(n, d); added == nil {
t.Fatal("Register returned nil")
}
w.Poll(d)
select {
case err := <-w.errCh:
t.Fatal(err)
case <-w.dataCh:
// Got data, which means the poll was started
}
})
t.Run("consul-retry-func", func(t *testing.T) {
w := newWatcher()
w.retryFuncConsul = func(n int) (bool, time.Duration) {
return false, 0 * time.Second
}
defer w.Stop()
d := &idep.FakeDep{}
n := fakeNotifier("foo")
w.Register(n)
added := w.track(n, d)
if added == nil {
t.Fatal("Register returned nil")
}
if added.retryFunc == nil {
t.Fatal("Retry func was nil")
}
})
}
func TestWatcherRegister(t *testing.T) {
t.Run("base", func(t *testing.T) {
w := blindWatcher()
tt := echoTemplate("foo")
if err := w.Register(tt); err != nil {
t.Fatal("error should be nil, got:", err)
}
if _, ok := w.tracker.notifiers[tt.ID()]; !ok {
t.Fatal("registered template not tracked")
}
})
t.Run("duplicate-template-error", func(t *testing.T) {
w := blindWatcher()
tt := echoTemplate("foo")
if err := w.Register(tt); err != nil {
t.Fatal("error should be nil, got:", err)
}
if err := w.Register(tt); err != ErrRegistry {
t.Fatal("should have errored")
}
})
}
func TestWatcherDeregister(t *testing.T) {
tcs := []struct {
tt *Template
deregister bool
}{
{
echoTemplate("foo"),
false,
},
{
echoTemplate("bar"),
true,
},
}
w := blindWatcher()
d := &idep.FakeDep{}
// Register two templates
for _, tc := range tcs {
if err := w.Register(tc.tt); err != nil {
t.Fatal("error should be nil, got:", err)
}
w.track(tc.tt, d)
}
// Deregister one of the templates
for _, tc := range tcs {
if tc.deregister {
w.Deregister(tc.tt)
}
}
// Verify that only the de-registered template is no longer
// tracked
for _, tc := range tcs {
if tc.deregister {
if w.tracker.notifierTracked(tc.tt) {
t.Fatal("de-registered template tracked")
}
if _, ok := w.tracker.notifiers[tc.tt.ID()]; ok {
t.Fatal("de-registered template tracked")
}
} else {
if !w.tracker.notifierTracked(tc.tt) {
t.Fatal("registered template not tracked")
}
if _, ok := w.tracker.notifiers[tc.tt.ID()]; !ok {
t.Fatal("registered template not tracked")
}
}
}
}
// test propagation of vault's DefaultLease through to view
func TestWatcherViewLease(t *testing.T) {
testLease := time.Second * 9
w := newWatcher()
w.defaultLease = testLease
defer w.Stop()
d := &idep.FakeDep{}
n := fakeNotifier("foo")
w.Track(n, d)
v := w.view(d.ID())
if v.defaultLease != testLease {
t.Errorf("default lease not propagated to view; want: %v, got: %v",
testLease, v.defaultLease)
}
}
func TestWatcherWatching(t *testing.T) {
t.Run("not-exists", func(t *testing.T) {
w := newWatcher()
defer w.Stop()
d := &idep.FakeDep{}
if w.Watching(d.ID()) == true {
t.Errorf("expected to not be Watching")
}
})
t.Run("exists", func(t *testing.T) {
w := newWatcher()
defer w.Stop()
d := &idep.FakeDep{}
n := fakeNotifier("foo")
w.Track(n, d)
if w.Watching(d.ID()) == false {
t.Errorf("expected to be Watching")
}
})
// below are tracking related
t.Run("ignore-duplicates", func(t *testing.T) {
w := newWatcher()
defer w.Stop()
d := &idep.FakeDep{}
n := fakeNotifier("foo")
w.Track(n, d)
if w.Watching(d.ID()) == false {
t.Errorf("expected to be Watching")
}
if w.Size() != 1 {
t.Errorf("should ignore duplicate entries")
}
})
t.Run("multi-notifiers-same-dep", func(t *testing.T) {
w := newWatcher()
defer w.Stop()
d := &idep.FakeDep{}
n0 := fakeNotifier("foo")
n1 := fakeNotifier("bar")
w.Track(n0, d)
v0 := w.tracker.view(d.ID())
w.Track(n1, d)
v1 := w.tracker.view(d.ID())
// be sure view created for dependency is reused
if v0 != v1 {
t.Errorf("previous view overwritten, should reuse first one")
}
if w.Watching(d.ID()) == false {
t.Errorf("expected to be Watching")
}
if len(w.tracker.tracked) != 2 {
t.Errorf("should have 2 entries")
}
if w.Complete(n0) {
t.Errorf("dep has not received data, should not be completed: %s", n0.ID())
}
if w.Complete(n1) {
t.Errorf("dep has not received data, should not be completed: %s", n1.ID())
}
if notifiers := w.tracker.notifiersFor(v0); len(notifiers) != 2 {
t.Errorf("unexpected number of notifiers for view: %s %v", d.ID(), notifiers)
}
})
t.Run("same-notifier-multiple-deps", func(t *testing.T) {
w := newWatcher()
defer w.Stop()
d0 := &idep.FakeDep{Name: "foo"}
d1 := &idep.FakeDep{Name: "bar"}
n := fakeNotifier("foo")
w.Track(n, d0)
w.Track(n, d1)
if w.Watching(d0.ID()) == false {
t.Errorf("expected to be Watching")
}
if w.Watching(d1.ID()) == false {
t.Errorf("expected to be Watching")
}
if len(w.tracker.tracked) != 2 {
t.Errorf("should have 2 entries")
}
})
t.Run("multi-notifiers-multi-dep", func(t *testing.T) {
w := newWatcher()
defer w.Stop()
d0 := &idep.FakeDep{Name: "taco"} // dep for foo and bar
d1 := &idep.FakeDep{Name: "burrito"} // dep for bar
nFoo := fakeNotifier("foo")
nBar := fakeNotifier("bar")
w.Track(nFoo, d0)
w.Track(nBar, d0)
w.Track(nBar, d1)
// Test that 2 views were created for the 2 dependencies
if w.tracker.viewCount() != 2 {
t.Errorf("unexpected number of views, expected 2: %d", w.tracker.viewCount())
}
if w.Watching(d0.ID()) == false {
t.Errorf("expected to be Watching: %s", d0.ID())
}
if w.Watching(d1.ID()) == false {
t.Errorf("expected to be Watching: %s", d1.ID())
}
// 2 tracked pairs for foo (taco and burrito), 1 tracked pair for bar (burrito)
if len(w.tracker.tracked) != 3 {
t.Errorf("should have 3 entries")
}
if w.Complete(nFoo) {
t.Fatalf("dep has not received data, should not be completed: %s", nFoo.ID())
}
if w.Complete(nBar) {
t.Fatalf("dep has not received data, should not be completed: %s", nBar.ID())
}
v0 := w.tracker.view(d0.ID())
if v0 == nil || w.Watching(d0.ID()) == false {
t.Errorf("expected to be Watching after Complete: %s", d0.ID())
}
if notifiers := w.tracker.notifiersFor(v0); len(notifiers) != 2 {
t.Errorf("unexpected number of notifiers for view: %s %v", d0.ID(), notifiers)
}
v1 := w.tracker.view(d1.ID())
if v1 == nil || w.Watching(d1.ID()) == false {
t.Errorf("expected to be Watching after Complete: %s", d1.ID())
}
if notifiers := w.tracker.notifiersFor(v1); len(notifiers) != 1 {
t.Errorf("unexpected number of notifiers for view: %s %v", d1.ID(), notifiers)
}
})
// GH-44
t.Run("register-complete-race", func(t *testing.T) {
w := newWatcher()
defer w.Stop()
// fake template/notifier and dependencies (fields in template)
n := fakeNotifier("foo") // template stand-in
w.Register(n)
d0 := &idep.FakeDep{Name: "taco"}
d1 := &idep.FakeDep{Name: "burrito"}
// The race is between template's Execute and watcher's Complete.
// First Execute renders the template, registering dependencies
// and starting the polling. The polling then returns before the
// Complete call marking everything as retrieved and Complete
// erroneously returns true. It should require a second pass of the
// template to render the values into the form before being Complete.
//
// To replicate we want to manually force the condition instead of
// relying on the race, so we're testing by replicating the
// corresponding behavior sans some timing aspects (no rate limiting,
// etc.)
// First template Execute call..
// 1. each dependency gets registered
v0 := w.track(n, d0)
v1 := w.track(n, d1)
// 2. polling should start, but we'll simulate that manually below
// Template Execute is now done.
// Polling now returns data, stores it on the view and marks the
// view as having received the data (view.receivedData = true)
fakePollReturn := func(v *view, d dep.Dependency) {
v.store(d.ID())
}
fakePollReturn(v0, d0)
fakePollReturn(v1, d1)
// Then the Complete check happens. Should return false as the data
// hasn't been rendered into the template yet.
if w.Complete(n) {
t.Fatalf("Complete should return false until the notifier says it's done.")
}
})
}
func TestWatcherVaultToken(t *testing.T) {
t.Run("empty-token", func(t *testing.T) {
w := newWatcher()
defer w.Stop()
err := w.WatchVaultToken("")
if err != nil {
t.Fatal("Didn't expect and error:", err)
}
if w.Size() > 0 {
t.Fatal("dependency should not have been added")
}
})
t.Run("token-added", func(t *testing.T) {
w := newWatcher()
defer w.Stop()
err := w.WatchVaultToken("fake-token")
if err != nil {
t.Fatal("Didn't expect and error:", err)
}
test_id := (&idep.VaultTokenQuery{}).ID()
if !w.Watching(test_id) {
t.Fatal("token dep not added to watcher")
}
})
t.Run("not-cleaned", func(t *testing.T) {
w := newWatcher()
defer w.Stop()
err := w.WatchVaultToken("fake-token")
if err != nil {
t.Fatal("Didn't expect and error:", err)
}
test_id := (&idep.VaultTokenQuery{}).ID()
if !w.Watching(test_id) {
t.Fatal("token dep not added to watcher")
}
n := fakeNotifier("some-random-notifier")
w.Complete(n)
if !w.Watching(test_id) {
t.Fatal("token dep should not have been cleaned")
}
})
}
func TestWatcherSize(t *testing.T) {
t.Run("empty", func(t *testing.T) {
w := newWatcher()
defer w.Stop()
if w.Size() != 0 {
t.Errorf("expected %d to be %d", w.Size(), 0)
}
})
t.Run("returns-num-views", func(t *testing.T) {
w := newWatcher()
defer w.Stop()
for i := 0; i < 10; i++ {
d := &idep.FakeDep{Name: fmt.Sprintf("%d", i)}
n := fakeNotifier("foo")
w.Track(n, d)
}
if w.Size() != 10 {
t.Errorf("expected %d to be %d", w.Size(), 10)
}
})
}
func TestWatcherWait(t *testing.T) {
t.Run("timeout", func(t *testing.T) {
w := newWatcher()
defer w.Stop()
t1 := time.Now()
ctx, cancel := context.WithTimeout(context.Background(), time.Microsecond*100)
defer cancel()
err := w.Wait(ctx)
if err != nil {
t.Fatal("Error not expected")
}
dur := time.Since(t1)
if dur < time.Microsecond*100 || dur > time.Millisecond*10 {
t.Fatal("Wait call was off;", dur)
}
})
t.Run("deadline", func(t *testing.T) {
w := newWatcher()
defer w.Stop()
t1 := time.Now()
ctx, cancel := context.WithDeadline(context.Background(),
time.Now().Add(time.Microsecond*100))
defer cancel()
err := w.Wait(ctx)
if err != nil {
t.Fatal("Error not expected")
}
dur := time.Since(t1)
if dur < time.Microsecond*100 || dur > time.Millisecond*10 {
t.Fatal("Wait call was off;", dur)
}
})
t.Run("cancel", func(t *testing.T) {
w := newWatcher()
defer w.Stop()
errCh := make(chan error)
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
go func() {
err := w.Wait(ctx)
if err != nil {
errCh <- err
}
}()
cancel()
err := <-errCh
if ctx.Err() != context.Canceled {
t.Fatal("unexpected context error:", ctx.Err())
}
if err != ctx.Err() {
t.Fatal("unexpected wait error:", err)
}
})
t.Run("0-timeout", func(t *testing.T) {
w := newWatcher()
defer w.Stop()
t1 := time.Now()
testerr := errors.New("test")
go func() {
time.Sleep(time.Microsecond * 100)
w.errCh <- testerr
}()
w.Wait(context.Background())
dur := time.Since(t1)
if dur < time.Microsecond*100 || dur > time.Millisecond*10 {
t.Fatal("Wait call was off;", dur)
}
})
t.Run("error", func(t *testing.T) {
w := newWatcher()
defer w.Stop()
testerr := errors.New("test")
go func() {
w.errCh <- testerr
}()
err := w.Wait(context.Background())
if err != testerr {
t.Fatal("None or Unexpected Error;", err)
}
})
// Test cache updates
t.Run("simple-update", func(t *testing.T) {
w := newWatcher(1)
defer w.Stop()
foodep := &idep.FakeDep{Name: "foo"}
n := fakeNotifier("foo")
w.Register(n)
// doesn't need goroutine as dataCh has a buffer
w.dataCh <- w.track(n, foodep).store("foo")
w.Wait(context.Background())
store := w.cache.(*Store)
if v, ok := store.data[foodep.ID()]; !ok || v != "foo" {
t.Fatal("failed update")
}
})
t.Run("multi-update", func(t *testing.T) {
N := 5
w := newWatcher(N)
defer w.Stop()
n := fakeNotifier("foo")
w.Register(n)
deps := make([]dep.Dependency, N)
for i := 0; i < N; i++ {
data := strconv.Itoa(i)
deps[i] = &idep.FakeDep{Name: data}
// doesn't need goroutine as dataCh has a large buffer
w.dataCh <- w.track(n, deps[i]).store(data)
}
store := w.cache.(*Store)
if err := w.Wait(context.Background()); err != nil {
t.Fatal("Wait error:", err)
}
if len(store.data) != 5 {
t.Fatal("failed update")
}
if _, ok := store.data[deps[3].ID()]; !ok {
t.Fatal("failed update")
}
})
// test tracking of updated dependencies
t.Run("simple-updated-tracking", func(t *testing.T) {
w := newWatcher(1)
defer w.Stop()
foodep := &idep.FakeDep{Name: "foo"}
n := fakeNotifier("foo")
w.Register(n)
w.dataCh <- w.track(n, foodep).store("foo")
w.Wait(context.Background())
if len(w.tracker.tracked) != 1 {
fmt.Printf("%#v\n", w.tracker)
t.Fatal("failed to track updated dependency")
}
if _, found := w.cache.Recall(foodep.ID()); !found {
fmt.Printf("%#v\n", w.cache)
t.Fatal("failed to update cache")
}
})
t.Run("multi-updated-tracking", func(t *testing.T) {
N := 5
w := newWatcher(N)
n := fakeNotifier("multi")
w.Register(n)
defer w.Stop()
deps := make([]dep.Dependency, N)
for i := 0; i < N; i++ {
deps[i] = &idep.FakeDep{Name: strconv.Itoa(i)}
w.dataCh <- w.track(n, deps[i])
w.Wait(context.Background())
}
if n.count() != len(deps) {
t.Fatal("failed to track updated dependency")
}
})
t.Run("duplicate-updated-tracking", func(t *testing.T) {
N := 2
w := newWatcher(N)
n := fakeNotifier("dup")
w.Register(n)
defer w.Stop()
for i := 0; i < N; i++ {
foodep := &idep.FakeDep{Name: "foo"}
w.dataCh <- w.track(n, foodep)
}
w.Wait(context.Background())
if n.count() != N {
t.Fatal("didn't receive all notifications")
}
if len(w.tracker.views) != 1 {
t.Fatal("duplicate views for same dependency")
}
})
t.Run("wait-channel", func(t *testing.T) {
w := newWatcher(1)
defer w.Stop()
n := fakeNotifier("foo")
w.Register(n)
foodep := &idep.FakeDep{Name: "foo"}
w.dataCh <- w.track(n, foodep).store("foo")
err := <-w.WaitCh(context.Background())
if err != nil {
t.Fatal("wait error:", err)
}
store := w.cache.(*Store)
if _, ok := store.data[foodep.ID()]; !ok {
t.Fatal("failed update")
}
})
t.Run("wait-channel-cancel", func(t *testing.T) {
w := newWatcher()
defer w.Stop()
errCh := make(chan error)
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond)
go func() {
errCh <- <-w.WaitCh(ctx)
}()
cancel()
err := <-errCh
if ctx.Err() != context.Canceled {
t.Fatal("unexpected context error:", ctx.Err())
}
if err != ctx.Err() {
t.Fatal("unexpected wait error:", err)
}
})
t.Run("wait-stop-leak", func(t *testing.T) {
w := newWatcher()
errCh := make(chan error)
go func() {
errCh <- w.Wait(context.Background())
}()
leaked := make(chan bool, 1)
defer close(leaked)
<-w.waitingCh
w.Stop()
select {
case <-errCh:
leaked <- false
case <-time.After(time.Millisecond):
leaked <- true
}
if ok := <-leaked; ok {
t.Fatal("goroutine leak")
}
})
t.Run("wait-stop-order", func(t *testing.T) {
w := newWatcher()
// can Stop can be run before Wait and have Wait work correctly
w.Stop()
errCh := make(chan error)
go func() {
errCh <- w.Wait(context.Background())
}()
bad_stop := make(chan bool, 1)
defer close(bad_stop)
<-w.waitingCh
select {
case <-errCh:
bad_stop <- true
case <-time.After(time.Millisecond):
bad_stop <- false
}
if ok := <-bad_stop; ok {
t.Fatal("Stop->Wait shouldn't stop Wait")
}
w.Stop()
})
}
func TestWatcherWatch(t *testing.T) {
t.Run("ctx-handling", func(t *testing.T) {
testCases := []struct {
name string
ctxFunc func() (context.Context, context.CancelFunc)
}{
{
"timeout",
func() (context.Context, context.CancelFunc) {
return context.WithTimeout(context.Background(), time.Microsecond*100)
},
}, {
"deadline",
func() (context.Context, context.CancelFunc) {
return context.WithDeadline(context.Background(), time.Now().Add(time.Microsecond*100))
},
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
w := NewWatcher(WatcherInput{})
defer w.Stop()
ctx, cancel := tc.ctxFunc()
defer cancel()
err := w.Watch(ctx, make(chan string))
if err != nil {
t.Fatal("unexpected watch error from context handling")
}
})
}
})
t.Run("error-handling", func(t *testing.T) {
testErr := fmt.Errorf("test")
testCases := []struct {
name string
errFunc func(*Watcher, context.CancelFunc)
expectedErr error
}{
{
"stop",
func(w *Watcher, cancel context.CancelFunc) {
w.Stop()
},
nil,
}, {
"ctx-cancelled",
func(w *Watcher, cancel context.CancelFunc) {
cancel()
},
context.Canceled,
}, {
"error-chan",
func(w *Watcher, cancel context.CancelFunc) {
w.errCh <- testErr
},
testErr,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
w := NewWatcher(WatcherInput{})
defer w.Stop()
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
errCh := make(chan error, 1)
go func() {
errCh <- w.Watch(ctx, make(chan string))
}()
<-w.waitingCh
tc.errFunc(w, cancel)
select {
case <-time.After(time.Second):
t.Fatal("got timeout, should get an error")
case err := <-errCh:
if err != tc.expectedErr {
t.Fatalf("unexpected watch error: expected %+v, actual %+v", tc.expectedErr, err)
}
}
})
}
})
t.Run("continous-monitoring-and-notify", func(t *testing.T) {
tmplCh := make(chan string, 10)
N := 2
w := NewWatcher(WatcherInput{DataBufferSize: &N})
defer w.Stop()
fooDep := &idep.FakeDep{Name: "foo"}
fooNotifier := fakeNotifier("foo")
w.Register(fooNotifier)
w.dataCh <- w.track(fooNotifier, fooDep)
barDep := &idep.FakeDep{Name: "bar"}
barNotifier := fakeNotifier("bar")
w.Register(barNotifier)
w.dataCh <- w.track(barNotifier, barDep)
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
errCh := make(chan error)
go func() {
errCh <- w.Watch(ctx, tmplCh)
}()
// Expect 2 notifications
for i := 0; i < 2; i++ {
select {
case <-ctx.Done():
t.Fatal("unexpected stop of Watch from context:", ctx.Err())
case err := <-errCh:
t.Fatal("unexpected Watch return:", err)
case tmplID := <-tmplCh:
if tmplID != "foo" && tmplID != "bar" {
t.Fatal("unexpected template notification:", tmplID)
}
}
}
})
t.Run("notify-buffer", func(t *testing.T) {
testCases := []struct {
name string
dataFunc func(w *Watcher, n Notifier, d dep.Dependency)
expected time.Duration
}{
{
"min",
func(w *Watcher, n Notifier, d dep.Dependency) {
w.dataCh <- w.track(n, d)
w.Buffering(n)
},
2 * time.Millisecond,
}, {
"multiple",
func(w *Watcher, n Notifier, d dep.Dependency) {
// Emulate multiple changes but still expect just a single
// notifications within max buffer delay
// NOTE max buffer delay is hardcoded below as maxDuration.
w.dataCh <- w.track(n, d)
w.Buffering(n)
w.Buffering(n)
w.Buffering(n)
},
4 * time.Millisecond,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
N := 0
w := NewWatcher(WatcherInput{DataBufferSize: &N})
defer w.Stop()
fooDep := &idep.FakeDep{Name: "foo"}
fooNotifier := fakeNotifier("foo")
w.Register(fooNotifier)
minDuration := time.Millisecond
maxDuration := 5 * time.Millisecond
w.bufferTimers.testAdd(minDuration, maxDuration, "foo")
var timer *testTimer
go func() {
tc.dataFunc(w, fooNotifier, fooDep)
// timer created during dataFunc run
timer = getTestTimer(w.bufferTimers, "foo")
timer.send() // fake send timer notification
}()
// mimicing Watch's use of Wait to keep test code sane
if err := w.Wait(context.Background()); err != nil {
t.Error("Unexpected error:", err)
}
if timer.totalTime != tc.expected {
t.Fatal("unexpected duration waited:", timer.totalTime)
}
})
}
})
}
func TestWatcherNotify(t *testing.T) {
t.Run("single-notify-true", func(t *testing.T) {
w := newWatcher(1)
defer w.Stop()
foodep := &idep.FakeDep{Name: "foo"}
n := fakeNotifier("foo")
w.Register(n)
w.dataCh <- w.track(n, foodep)
ctx, cc := context.WithCancel(context.Background())
go func() { time.Sleep(time.Millisecond); cc() }()
if err := w.Wait(ctx); err != nil {
t.Fatalf("wait should have returned nil, got: %v\n", err)
}
})
t.Run("single-notify-false", func(t *testing.T) {
w := newWatcher(1)
defer w.Stop()
foodep := &idep.FakeDep{Name: "foo"}
n := fakeNotifier("foo")
w.Register(n)
w.dataCh <- w.track(n, foodep)
ctx, cc := context.WithCancel(context.Background())
go func() { time.Sleep(time.Millisecond); cc() }()
n.notify = false
if err := w.Wait(ctx); err != context.Canceled {
t.Fatalf("wait should have returned context.Canceled, got: %v", err)
}
})
t.Run("multi-notify-true", func(t *testing.T) {
w := newWatcher(2)
defer w.Stop()
foodep := &idep.FakeDep{Name: "foo"}
bardep := &idep.FakeDep{Name: "bar"}
n := fakeNotifier("foo")
w.Register(n)
w.dataCh <- w.track(n, foodep)
w.dataCh <- w.track(n, bardep)
ctx, cc := context.WithCancel(context.Background())
go func() { time.Sleep(time.Millisecond); cc() }()
if err := w.Wait(ctx); err != nil {
t.Fatalf("wait should have returned nil, got: %v\n", err)
}
})
t.Run("multi-notify-false", func(t *testing.T) {
w := newWatcher(2)
defer w.Stop()
foodep := &idep.FakeDep{Name: "foo"}
bardep := &idep.FakeDep{Name: "bar"}
n := fakeNotifier("foo")
w.Register(n)
n.notify = false
w.dataCh <- w.track(n, foodep)
w.dataCh <- w.track(n, bardep)
ctx, cc := context.WithCancel(context.Background())
go func() { time.Sleep(time.Millisecond); cc() }()
if err := w.Wait(ctx); err != context.Canceled {
t.Fatalf("wait should have returned context.Canceled, got: %v", err)
}
})
t.Run("notify-true-then-false", func(t *testing.T) {
w := newWatcher(2)
defer w.Stop()
foodep := &idep.FakeDep{Name: "foo"}
nf := fakeNotifier("foo")
bardep := &idep.FakeDep{Name: "bar"}
nb := fakeNotifier("bar")
w.Register(nf, nb)
nb.notify = false
w.dataCh <- w.track(nf, foodep)
w.dataCh <- w.track(nb, bardep)
ctx, cc := context.WithCancel(context.Background())
go func() { time.Sleep(time.Millisecond); cc() }()
if err := w.Wait(ctx); err != nil {
t.Fatalf("wait should have returned nil, got: %v\n", err)
}
})
t.Run("notify-false-then-true", func(t *testing.T) {
w := newWatcher(2)
defer w.Stop()
foodep := &idep.FakeDep{Name: "foo"}
nf := fakeNotifier("foo")
nf.notify = false
bardep := &idep.FakeDep{Name: "bar"}
nb := fakeNotifier("bar")
w.Register(nf, nb)
w.dataCh <- w.track(nf, foodep)
w.dataCh <- w.track(nb, bardep)
ctx, cc := context.WithCancel(context.Background())
go func() { time.Sleep(time.Millisecond); cc() }()
if err := w.Wait(ctx); err != nil {
t.Fatalf("wait should have returned nil, got: %v\n", err)
}
})
t.Run("notify-assert", func(t *testing.T) {
w := newWatcher(2)
defer w.Stop()
foodep := &idep.FakeDep{Name: "foo"}
bardep := &idep.FakeListDep{Name: "bar"}
n := fakeNotifier("foo")
w.Register(n)
fooview := w.track(n, foodep)
fooview.store("foo")
barview := w.track(n, bardep)
barview.store([]string{"bar", "zed"})
w.dataCh <- fooview
w.dataCh <- barview