wait_time_test.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. "testing"
  17. "time"
  18. )
  19. func TestWaitTime(t *testing.T) {
  20. wt := NewTimeList()
  21. ch1 := wt.Wait(time.Now())
  22. t1 := time.Now()
  23. wt.Trigger(t1)
  24. select {
  25. case <-ch1:
  26. case <-time.After(100 * time.Millisecond):
  27. t.Fatalf("cannot receive from ch as expected")
  28. }
  29. ch2 := wt.Wait(time.Now())
  30. t2 := time.Now()
  31. wt.Trigger(t1)
  32. select {
  33. case <-ch2:
  34. t.Fatalf("unexpected to receive from ch")
  35. case <-time.After(10 * time.Millisecond):
  36. }
  37. wt.Trigger(t2)
  38. select {
  39. case <-ch2:
  40. case <-time.After(10 * time.Millisecond):
  41. t.Fatalf("cannot receive from ch as expected")
  42. }
  43. }
  44. func TestWaitTestStress(t *testing.T) {
  45. chs := make([]<-chan struct{}, 0)
  46. wt := NewTimeList()
  47. for i := 0; i < 10000; i++ {
  48. chs = append(chs, wt.Wait(time.Now()))
  49. // sleep one nanosecond before waiting on the next event
  50. time.Sleep(time.Nanosecond)
  51. }
  52. wt.Trigger(time.Now())
  53. for _, ch := range chs {
  54. select {
  55. case <-ch:
  56. case <-time.After(time.Second):
  57. t.Fatalf("cannot receive from ch as expected")
  58. }
  59. }
  60. }
  61. func BenchmarkWaitTime(b *testing.B) {
  62. t := time.Now()
  63. wt := NewTimeList()
  64. for i := 0; i < b.N; i++ {
  65. wt.Wait(t)
  66. }
  67. }
  68. func BenchmarkTriggerAnd10KWaitTime(b *testing.B) {
  69. for i := 0; i < b.N; i++ {
  70. t := time.Now()
  71. wt := NewTimeList()
  72. for j := 0; j < 10000; j++ {
  73. wt.Wait(t)
  74. }
  75. wt.Trigger(time.Now())
  76. }
  77. }