peers_test.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package main
  2. import (
  3. "testing"
  4. "time"
  5. )
  6. func TestPeers(t *testing.T) {
  7. peers := &Peers{m: make(map[string]chan<- Message)}
  8. done := make(chan bool, 1)
  9. var chA, chB <-chan Message
  10. go func() {
  11. defer func() { done <- true }()
  12. if chA = peers.Add("a"); chA == nil {
  13. t.Fatal(`peers.Add("a") returned nil, want channel`)
  14. }
  15. }()
  16. go func() {
  17. defer func() { done <- true }()
  18. if chB = peers.Add("b"); chB == nil {
  19. t.Fatal(`peers.Add("b") returned nil, want channel`)
  20. }
  21. }()
  22. <-done
  23. <-done
  24. if chA == chB {
  25. t.Fatal(`peers.Add("b") returned same channel as "a"!`)
  26. }
  27. if ch := peers.Add("a"); ch != nil {
  28. t.Fatal(`second peers.Add("a") returned non-nil channel, want nil`)
  29. }
  30. if ch := peers.Add("b"); ch != nil {
  31. t.Fatal(`second peers.Add("b") returned non-nil channel, want nil`)
  32. }
  33. list := peers.List()
  34. if len(list) != 2 {
  35. t.Fatalf("peers.List() returned a list of length %d, want 2", len(list))
  36. }
  37. go func() {
  38. for _, ch := range list {
  39. select {
  40. case ch <- Message{Body: "foo"}:
  41. case <-time.After(10 * time.Millisecond):
  42. }
  43. }
  44. done <- true
  45. }()
  46. select {
  47. case m := <-chA:
  48. if m.Body != "foo" {
  49. t.Fatal("received message %q, want %q", m.Body, "foo")
  50. }
  51. case <-done:
  52. t.Fatal(`didn't receive message on "a" channel`)
  53. }
  54. <-done
  55. peers.Remove("a")
  56. list = peers.List()
  57. if len(list) != 1 {
  58. t.Fatalf("peers.List() returned a list of length %d, want 1", len(list))
  59. }
  60. go func() {
  61. select {
  62. case list[0] <- Message{Body: "bar"}:
  63. case <-time.After(10 * time.Millisecond):
  64. }
  65. done <- true
  66. }()
  67. select {
  68. case m := <-chB:
  69. if m.Body != "bar" {
  70. t.Fatalf("received message %q, want %q", m.Body, "bar")
  71. }
  72. case <-done:
  73. t.Fatal(`didn't receive message on "b" channel`)
  74. }
  75. }