github.com/linapex/ethereum-go-chinese@v0.0.0-20190316121929-f8b7a73c3fa1/event/subscription_test.go (about) 1 2 //<developer> 3 // <name>linapex 曹一峰</name> 4 // <email>linapex@163.com</email> 5 // <wx>superexc</wx> 6 // <qqgroup>128148617</qqgroup> 7 // <url>https://jsq.ink</url> 8 // <role>pku engineer</role> 9 // <date>2019-03-16 19:16:38</date> 10 //</624450091217850368> 11 12 13 package event 14 15 import ( 16 "context" 17 "errors" 18 "testing" 19 "time" 20 ) 21 22 var errInts = errors.New("error in subscribeInts") 23 24 func subscribeInts(max, fail int, c chan<- int) Subscription { 25 return NewSubscription(func(quit <-chan struct{}) error { 26 for i := 0; i < max; i++ { 27 if i >= fail { 28 return errInts 29 } 30 select { 31 case c <- i: 32 case <-quit: 33 return nil 34 } 35 } 36 return nil 37 }) 38 } 39 40 func TestNewSubscriptionError(t *testing.T) { 41 t.Parallel() 42 43 channel := make(chan int) 44 sub := subscribeInts(10, 2, channel) 45 loop: 46 for want := 0; want < 10; want++ { 47 select { 48 case got := <-channel: 49 if got != want { 50 t.Fatalf("wrong int %d, want %d", got, want) 51 } 52 case err := <-sub.Err(): 53 if err != errInts { 54 t.Fatalf("wrong error: got %q, want %q", err, errInts) 55 } 56 if want != 2 { 57 t.Fatalf("got errInts at int %d, should be received at 2", want) 58 } 59 break loop 60 } 61 } 62 sub.Unsubscribe() 63 64 err, ok := <-sub.Err() 65 if err != nil { 66 t.Fatal("got non-nil error after Unsubscribe") 67 } 68 if ok { 69 t.Fatal("channel still open after Unsubscribe") 70 } 71 } 72 73 func TestResubscribe(t *testing.T) { 74 t.Parallel() 75 76 var i int 77 nfails := 6 78 sub := Resubscribe(100*time.Millisecond, func(ctx context.Context) (Subscription, error) { 79 //fmt.printf(“调用%d@%v\n”,i,time.now()) 80 i++ 81 if i == 2 { 82 //将第二次失败延迟一点以重置重新预订间隔。 83 time.Sleep(200 * time.Millisecond) 84 } 85 if i < nfails { 86 return nil, errors.New("oops") 87 } 88 sub := NewSubscription(func(unsubscribed <-chan struct{}) error { return nil }) 89 return sub, nil 90 }) 91 92 <-sub.Err() 93 if i != nfails { 94 t.Fatalf("resubscribe function called %d times, want %d times", i, nfails) 95 } 96 } 97 98 func TestResubscribeAbort(t *testing.T) { 99 t.Parallel() 100 101 done := make(chan error) 102 sub := Resubscribe(0, func(ctx context.Context) (Subscription, error) { 103 select { 104 case <-ctx.Done(): 105 done <- nil 106 case <-time.After(2 * time.Second): 107 done <- errors.New("context given to resubscribe function not canceled within 2s") 108 } 109 return nil, nil 110 }) 111 112 sub.Unsubscribe() 113 if err := <-done; err != nil { 114 t.Fatal(err) 115 } 116 } 117