github.com/KyaXTeam/consul@v1.4.5/watch/plan_test.go (about) 1 package watch 2 3 import ( 4 "testing" 5 "time" 6 ) 7 8 func init() { 9 watchFuncFactory["noop"] = noopWatch 10 } 11 12 func noopWatch(params map[string]interface{}) (WatcherFunc, error) { 13 fn := func(p *Plan) (BlockingParamVal, interface{}, error) { 14 idx := WaitIndexVal(0) 15 if i, ok := p.lastParamVal.(WaitIndexVal); ok { 16 idx = i 17 } 18 return idx + 1, uint64(idx + 1), nil 19 } 20 return fn, nil 21 } 22 23 func mustParse(t *testing.T, q string) *Plan { 24 params := makeParams(t, q) 25 plan, err := Parse(params) 26 if err != nil { 27 t.Fatalf("err: %v", err) 28 } 29 return plan 30 } 31 32 func TestRun_Stop(t *testing.T) { 33 t.Parallel() 34 plan := mustParse(t, `{"type":"noop"}`) 35 36 var expect uint64 = 1 37 doneCh := make(chan struct{}) 38 plan.Handler = func(idx uint64, val interface{}) { 39 if idx != expect { 40 t.Fatalf("Bad: %d %d", expect, idx) 41 } 42 if val != expect { 43 t.Fatalf("Bad: %d %d", expect, val) 44 } 45 if expect == 1 { 46 close(doneCh) 47 } 48 expect++ 49 } 50 51 errCh := make(chan error, 1) 52 go func() { 53 errCh <- plan.Run("127.0.0.1:8500") 54 }() 55 56 select { 57 case <-doneCh: 58 plan.Stop() 59 60 case <-time.After(1 * time.Second): 61 t.Fatalf("handler never ran") 62 } 63 64 select { 65 case err := <-errCh: 66 if err != nil { 67 t.Fatalf("err: %v", err) 68 } 69 70 case <-time.After(1 * time.Second): 71 t.Fatalf("watcher didn't exit") 72 } 73 74 if expect == 1 { 75 t.Fatalf("Bad: %d", expect) 76 } 77 } 78 79 func TestRun_Stop_Hybrid(t *testing.T) { 80 t.Parallel() 81 plan := mustParse(t, `{"type":"noop"}`) 82 83 var expect uint64 = 1 84 doneCh := make(chan struct{}) 85 plan.HybridHandler = func(blockParamVal BlockingParamVal, val interface{}) { 86 idxVal, ok := blockParamVal.(WaitIndexVal) 87 if !ok { 88 t.Fatalf("expected index-based watch") 89 } 90 idx := uint64(idxVal) 91 if idx != expect { 92 t.Fatalf("Bad: %d %d", expect, idx) 93 } 94 if val != expect { 95 t.Fatalf("Bad: %d %d", expect, val) 96 } 97 if expect == 1 { 98 close(doneCh) 99 } 100 expect++ 101 } 102 103 errCh := make(chan error, 1) 104 go func() { 105 errCh <- plan.Run("127.0.0.1:8500") 106 }() 107 108 select { 109 case <-doneCh: 110 plan.Stop() 111 112 case <-time.After(1 * time.Second): 113 t.Fatalf("handler never ran") 114 } 115 116 select { 117 case err := <-errCh: 118 if err != nil { 119 t.Fatalf("err: %v", err) 120 } 121 122 case <-time.After(1 * time.Second): 123 t.Fatalf("watcher didn't exit") 124 } 125 126 if expect == 1 { 127 t.Fatalf("Bad: %d", expect) 128 } 129 }