github.com/decred/dcrlnd@v0.7.6/subscribe/subscribe_test.go (about) 1 package subscribe_test 2 3 import ( 4 "testing" 5 "time" 6 7 "github.com/decred/dcrlnd/subscribe" 8 ) 9 10 // TestSubscribe tests that the subscription clients receive the updates sent 11 // to them after they subscribe, and that canceled clients don't get more 12 // updates. 13 func TestSubscribe(t *testing.T) { 14 t.Parallel() 15 16 server := subscribe.NewServer() 17 if err := server.Start(); err != nil { 18 t.Fatalf("unable to start server") 19 } 20 21 const numClients = 300 22 const numUpdates = 1000 23 24 var clients [numClients]*subscribe.Client 25 26 // Start by registering two thirds the clients. 27 for i := 0; i < numClients*2/3; i++ { 28 c, err := server.Subscribe() 29 if err != nil { 30 t.Fatalf("unable to subscribe: %v", err) 31 } 32 33 clients[i] = c 34 } 35 36 // Send half the updates. 37 for i := 0; i < numUpdates/2; i++ { 38 if err := server.SendUpdate(i); err != nil { 39 t.Fatalf("unable to send update") 40 } 41 } 42 43 // Register the rest of the clients. 44 for i := numClients * 2 / 3; i < numClients; i++ { 45 c, err := server.Subscribe() 46 if err != nil { 47 t.Fatalf("unable to subscribe: %v", err) 48 } 49 50 clients[i] = c 51 } 52 53 // Cancel one third of the clients. 54 for i := 0; i < numClients/3; i++ { 55 clients[i].Cancel() 56 } 57 58 // Send the rest of the updates. 59 for i := numUpdates / 2; i < numUpdates; i++ { 60 if err := server.SendUpdate(i); err != nil { 61 t.Fatalf("unable to send update") 62 } 63 } 64 65 // Now ensure the clients got the updates we expect. 66 for i, c := range clients { 67 68 var from, to int 69 switch { 70 71 // We expect the first third of the clients to quit, since they 72 // were canceled. 73 case i < numClients/3: 74 select { 75 case <-c.Quit(): 76 continue 77 case <-time.After(1 * time.Second): 78 t.Fatalf("canceled client %v did not quit", i) 79 } 80 81 // The next third should receive all updates. 82 case i < numClients*2/3: 83 from = 0 84 to = numUpdates 85 86 // And finally the last third should receive the last half of 87 // the updates. 88 default: 89 from = numUpdates / 2 90 to = numUpdates 91 } 92 93 for cnt := from; cnt < to; cnt++ { 94 select { 95 case upd := <-c.Updates(): 96 j := upd.(int) 97 if j != cnt { 98 t.Fatalf("expected %v, got %v, for "+ 99 "client %v", cnt, j, i) 100 } 101 102 case <-time.After(1 * time.Second): 103 t.Fatalf("did not receive expected update %v "+ 104 "for client %v", cnt, i) 105 } 106 } 107 108 } 109 110 }