wait_time_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. Copyright 2015 CoreOS, Inc.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package wait
  14. import (
  15. "testing"
  16. "time"
  17. )
  18. func TestWaitTime(t *testing.T) {
  19. wt := NewTimeList()
  20. ch1 := wt.Wait(time.Now())
  21. t1 := time.Now()
  22. wt.Trigger(t1)
  23. select {
  24. case <-ch1:
  25. case <-time.After(10 * time.Millisecond):
  26. t.Fatalf("cannot receive from ch as expected")
  27. }
  28. ch2 := wt.Wait(time.Now())
  29. t2 := time.Now()
  30. wt.Trigger(t1)
  31. select {
  32. case <-ch2:
  33. t.Fatalf("unexpected to receive from ch")
  34. case <-time.After(10 * time.Millisecond):
  35. }
  36. wt.Trigger(t2)
  37. select {
  38. case <-ch2:
  39. case <-time.After(10 * time.Millisecond):
  40. t.Fatalf("cannot receive from ch as expected")
  41. }
  42. }
  43. func TestWaitTestStress(t *testing.T) {
  44. chs := make([]<-chan struct{}, 0)
  45. wt := NewTimeList()
  46. for i := 0; i < 10000; i++ {
  47. chs = append(chs, wt.Wait(time.Now()))
  48. // sleep one nanosecond before waiting on the next event
  49. time.Sleep(time.Nanosecond)
  50. }
  51. wt.Trigger(time.Now())
  52. for _, ch := range chs {
  53. select {
  54. case <-ch:
  55. case <-time.After(time.Second):
  56. t.Fatalf("cannot receive from ch as expected")
  57. }
  58. }
  59. }
  60. func BenchmarkWaitTime(b *testing.B) {
  61. t := time.Now()
  62. wt := NewTimeList()
  63. for i := 0; i < b.N; i++ {
  64. wt.Wait(t)
  65. }
  66. }
  67. func BenchmarkTriggerAnd10KWaitTime(b *testing.B) {
  68. for i := 0; i < b.N; i++ {
  69. t := time.Now()
  70. wt := NewTimeList()
  71. for j := 0; j < 10000; j++ {
  72. wt.Wait(t)
  73. }
  74. wt.Trigger(time.Now())
  75. }
  76. }