github.com/yinchengtsinghua/golang-Eos-dpos-Ethereum@v0.0.0-20190121132951-92cc4225ed8e/swarm/network/simulation/events_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  //
    10  //
    11  //
    12  //
    13  //
    14  //
    15  //
    16  //
    17  //
    18  //
    19  //
    20  //
    21  //
    22  //
    23  //
    24  
    25  package simulation
    26  
    27  import (
    28  	"context"
    29  	"sync"
    30  	"testing"
    31  	"time"
    32  )
    33  
    34  //
    35  //
    36  //
    37  //
    38  func TestPeerEvents(t *testing.T) {
    39  	sim := New(noopServiceFuncMap)
    40  	defer sim.Close()
    41  
    42  	_, err := sim.AddNodes(2)
    43  	if err != nil {
    44  		t.Fatal(err)
    45  	}
    46  
    47  	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    48  	defer cancel()
    49  	events := sim.PeerEvents(ctx, sim.NodeIDs())
    50  
    51  //
    52  	expectedEventCount := 2
    53  
    54  	var wg sync.WaitGroup
    55  	wg.Add(expectedEventCount)
    56  
    57  	go func() {
    58  		for e := range events {
    59  			if e.Error != nil {
    60  				if e.Error == context.Canceled {
    61  					return
    62  				}
    63  				t.Error(e.Error)
    64  				continue
    65  			}
    66  			wg.Done()
    67  		}
    68  	}()
    69  
    70  	err = sim.ConnectNodesChain(sim.NodeIDs())
    71  	if err != nil {
    72  		t.Fatal(err)
    73  	}
    74  
    75  	wg.Wait()
    76  }
    77  
    78  func TestPeerEventsTimeout(t *testing.T) {
    79  	sim := New(noopServiceFuncMap)
    80  	defer sim.Close()
    81  
    82  	_, err := sim.AddNodes(2)
    83  	if err != nil {
    84  		t.Fatal(err)
    85  	}
    86  
    87  	ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
    88  	defer cancel()
    89  	events := sim.PeerEvents(ctx, sim.NodeIDs())
    90  
    91  	done := make(chan struct{})
    92  	go func() {
    93  		for e := range events {
    94  			if e.Error == context.Canceled {
    95  				return
    96  			}
    97  			if e.Error == context.DeadlineExceeded {
    98  				close(done)
    99  				return
   100  			} else {
   101  				t.Fatal(e.Error)
   102  			}
   103  		}
   104  	}()
   105  
   106  	select {
   107  	case <-time.After(time.Second):
   108  		t.Error("no context deadline received")
   109  	case <-done:
   110  //
   111  	}
   112  }