github.com/spotmaxtech/k8s-apimachinery-v0260@v0.0.1/pkg/watch/streamwatcher_test.go (about) 1 /* 2 Copyright 2014 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 watch_test 18 19 import ( 20 "fmt" 21 "io" 22 "reflect" 23 "testing" 24 "time" 25 26 "github.com/spotmaxtech/k8s-apimachinery-v0260/pkg/runtime" 27 . "github.com/spotmaxtech/k8s-apimachinery-v0260/pkg/watch" 28 ) 29 30 type fakeDecoder struct { 31 items chan Event 32 err error 33 } 34 35 func (f fakeDecoder) Decode() (action EventType, object runtime.Object, err error) { 36 if f.err != nil { 37 return "", nil, f.err 38 } 39 item, open := <-f.items 40 if !open { 41 return action, nil, io.EOF 42 } 43 return item.Type, item.Object, nil 44 } 45 46 func (f fakeDecoder) Close() { 47 if f.items != nil { 48 close(f.items) 49 } 50 } 51 52 type fakeReporter struct { 53 err error 54 } 55 56 func (f *fakeReporter) AsObject(err error) runtime.Object { 57 f.err = err 58 return runtime.Unstructured(nil) 59 } 60 61 func TestStreamWatcher(t *testing.T) { 62 table := []Event{ 63 {Type: Added, Object: testType("foo")}, 64 } 65 66 fd := fakeDecoder{items: make(chan Event, 5)} 67 sw := NewStreamWatcher(fd, nil) 68 69 for _, item := range table { 70 fd.items <- item 71 got, open := <-sw.ResultChan() 72 if !open { 73 t.Errorf("unexpected early close") 74 } 75 if e, a := item, got; !reflect.DeepEqual(e, a) { 76 t.Errorf("expected %v, got %v", e, a) 77 } 78 } 79 80 sw.Stop() 81 _, open := <-sw.ResultChan() 82 if open { 83 t.Errorf("Unexpected failure to close") 84 } 85 } 86 87 func TestStreamWatcherError(t *testing.T) { 88 fd := fakeDecoder{err: fmt.Errorf("test error")} 89 fr := &fakeReporter{} 90 sw := NewStreamWatcher(fd, fr) 91 evt, ok := <-sw.ResultChan() 92 if !ok { 93 t.Fatalf("unexpected close") 94 } 95 if evt.Type != Error || evt.Object != runtime.Unstructured(nil) { 96 t.Fatalf("unexpected object: %#v", evt) 97 } 98 _, ok = <-sw.ResultChan() 99 if ok { 100 t.Fatalf("unexpected open channel") 101 } 102 103 sw.Stop() 104 _, ok = <-sw.ResultChan() 105 if ok { 106 t.Fatalf("unexpected open channel") 107 } 108 } 109 110 func TestStreamWatcherRace(t *testing.T) { 111 fd := fakeDecoder{err: fmt.Errorf("test error")} 112 fr := &fakeReporter{} 113 sw := NewStreamWatcher(fd, fr) 114 time.Sleep(10 * time.Millisecond) 115 sw.Stop() 116 time.Sleep(10 * time.Millisecond) 117 _, ok := <-sw.ResultChan() 118 if ok { 119 t.Fatalf("unexpected pending send") 120 } 121 }