wait_test.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. // Copyright 2015 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package wait
  15. import (
  16. "fmt"
  17. "testing"
  18. "time"
  19. )
  20. func TestWait(t *testing.T) {
  21. const eid = 1
  22. wt := New()
  23. ch := wt.Register(eid)
  24. wt.Trigger(eid, "foo")
  25. v := <-ch
  26. if g, w := fmt.Sprintf("%v (%T)", v, v), "foo (string)"; g != w {
  27. t.Errorf("<-ch = %v, want %v", g, w)
  28. }
  29. if g := <-ch; g != nil {
  30. t.Errorf("unexpected non-nil value: %v (%T)", g, g)
  31. }
  32. }
  33. func TestRegisterDupPanic(t *testing.T) {
  34. const eid = 1
  35. wt := New()
  36. ch1 := wt.Register(eid)
  37. panicC := make(chan struct{}, 1)
  38. func() {
  39. defer func() {
  40. if r := recover(); r != nil {
  41. panicC <- struct{}{}
  42. }
  43. }()
  44. wt.Register(eid)
  45. }()
  46. select {
  47. case <-panicC:
  48. case <-time.After(1 * time.Second):
  49. t.Errorf("failed to receive panic")
  50. }
  51. wt.Trigger(eid, "foo")
  52. <-ch1
  53. }
  54. func TestTriggerDupSuppression(t *testing.T) {
  55. const eid = 1
  56. wt := New()
  57. ch := wt.Register(eid)
  58. wt.Trigger(eid, "foo")
  59. wt.Trigger(eid, "bar")
  60. v := <-ch
  61. if g, w := fmt.Sprintf("%v (%T)", v, v), "foo (string)"; g != w {
  62. t.Errorf("<-ch = %v, want %v", g, w)
  63. }
  64. if g := <-ch; g != nil {
  65. t.Errorf("unexpected non-nil value: %v (%T)", g, g)
  66. }
  67. }
  68. func TestIsRegistered(t *testing.T) {
  69. wt := New()
  70. wt.Register(0)
  71. wt.Register(1)
  72. wt.Register(2)
  73. for i := uint64(0); i < 3; i++ {
  74. if !wt.IsRegistered(i) {
  75. t.Errorf("event ID %d isn't registered", i)
  76. }
  77. }
  78. if wt.IsRegistered(4) {
  79. t.Errorf("event ID 4 shouldn't be registered")
  80. }
  81. wt.Trigger(0, "foo")
  82. if wt.IsRegistered(0) {
  83. t.Errorf("event ID 0 is already triggered, shouldn't be registered")
  84. }
  85. }