github.com/yinchengtsinghua/golang-Eos-dpos-Ethereum@v0.0.0-20190121132951-92cc4225ed8e/event/subscription_test.go (about) 1 2 //此源码被清华学神尹成大魔王专业翻译分析并修改 3 //尹成QQ77025077 4 //尹成微信18510341407 5 //尹成所在QQ群721929980 6 //尹成邮箱 yinc13@mails.tsinghua.edu.cn 7 //尹成毕业于清华大学,微软区块链领域全球最有价值专家 8 //https://mvp.microsoft.com/zh-cn/PublicProfile/4033620 9 //版权所有2016 Go Ethereum作者 10 //此文件是Go以太坊库的一部分。 11 // 12 //Go-Ethereum库是免费软件:您可以重新分发它和/或修改 13 //根据GNU发布的较低通用公共许可证的条款 14 //自由软件基金会,或者许可证的第3版,或者 15 //(由您选择)任何更高版本。 16 // 17 //Go以太坊图书馆的发行目的是希望它会有用, 18 //但没有任何保证;甚至没有 19 //适销性或特定用途的适用性。见 20 //GNU较低的通用公共许可证,了解更多详细信息。 21 // 22 //你应该收到一份GNU较低级别的公共许可证副本 23 //以及Go以太坊图书馆。如果没有,请参见<http://www.gnu.org/licenses/>。 24 25 package event 26 27 import ( 28 "context" 29 "errors" 30 "testing" 31 "time" 32 ) 33 34 var errInts = errors.New("error in subscribeInts") 35 36 func subscribeInts(max, fail int, c chan<- int) Subscription { 37 return NewSubscription(func(quit <-chan struct{}) error { 38 for i := 0; i < max; i++ { 39 if i >= fail { 40 return errInts 41 } 42 select { 43 case c <- i: 44 case <-quit: 45 return nil 46 } 47 } 48 return nil 49 }) 50 } 51 52 func TestNewSubscriptionError(t *testing.T) { 53 t.Parallel() 54 55 channel := make(chan int) 56 sub := subscribeInts(10, 2, channel) 57 loop: 58 for want := 0; want < 10; want++ { 59 select { 60 case got := <-channel: 61 if got != want { 62 t.Fatalf("wrong int %d, want %d", got, want) 63 } 64 case err := <-sub.Err(): 65 if err != errInts { 66 t.Fatalf("wrong error: got %q, want %q", err, errInts) 67 } 68 if want != 2 { 69 t.Fatalf("got errInts at int %d, should be received at 2", want) 70 } 71 break loop 72 } 73 } 74 sub.Unsubscribe() 75 76 err, ok := <-sub.Err() 77 if err != nil { 78 t.Fatal("got non-nil error after Unsubscribe") 79 } 80 if ok { 81 t.Fatal("channel still open after Unsubscribe") 82 } 83 } 84 85 func TestResubscribe(t *testing.T) { 86 t.Parallel() 87 88 var i int 89 nfails := 6 90 sub := Resubscribe(100*time.Millisecond, func(ctx context.Context) (Subscription, error) { 91 //fmt.printf(“调用%d@%v\n”,i,time.now()) 92 i++ 93 if i == 2 { 94 //将第二次失败延迟一点以重置重新预订间隔。 95 time.Sleep(200 * time.Millisecond) 96 } 97 if i < nfails { 98 return nil, errors.New("oops") 99 } 100 sub := NewSubscription(func(unsubscribed <-chan struct{}) error { return nil }) 101 return sub, nil 102 }) 103 104 <-sub.Err() 105 if i != nfails { 106 t.Fatalf("resubscribe function called %d times, want %d times", i, nfails) 107 } 108 } 109 110 func TestResubscribeAbort(t *testing.T) { 111 t.Parallel() 112 113 done := make(chan error) 114 sub := Resubscribe(0, func(ctx context.Context) (Subscription, error) { 115 select { 116 case <-ctx.Done(): 117 done <- nil 118 case <-time.After(2 * time.Second): 119 done <- errors.New("context given to resubscribe function not canceled within 2s") 120 } 121 return nil, nil 122 }) 123 124 sub.Unsubscribe() 125 if err := <-done; err != nil { 126 t.Fatal(err) 127 } 128 }