queue_test.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package timerqueue
  2. import (
  3. "math/rand"
  4. "testing"
  5. "time"
  6. )
  7. type object struct {
  8. value int
  9. }
  10. var executed int
  11. func (o *object) OnTimer(t time.Time) {
  12. executed++
  13. }
  14. func populateQueue(t *testing.T, now time.Time) *Queue {
  15. q := New()
  16. count := 200
  17. objects := make([]*object, count)
  18. // Add a bunch of objects to the queue in random order.
  19. for i, j := range rand.Perm(count) {
  20. tm := now.Add(time.Duration(i+1) * time.Hour)
  21. objects[j] = &object{j}
  22. q.Schedule(objects[j], tm)
  23. }
  24. if q.Len() != count {
  25. t.Error("invalid queue length:", q.Len())
  26. }
  27. return q
  28. }
  29. func TestQueue(t *testing.T) {
  30. for iter := 0; iter < 100; iter++ {
  31. now := time.Date(2015, 1, 1, 0, 0, 0, 0, time.UTC)
  32. queue := populateQueue(t, now)
  33. // Make sure objects are removed from the queue in order.
  34. for prev := now; queue.Len() > 0; {
  35. _, tm := queue.PopFirst()
  36. if tm.Sub(prev) != time.Hour {
  37. t.Errorf("Invalid queue ordering.\n"+
  38. " Got: %v\n"+
  39. "Expected: %v\n", tm, prev.Add(time.Hour))
  40. }
  41. prev = tm
  42. }
  43. }
  44. }
  45. func TestAdvance(t *testing.T) {
  46. for iter := 0; iter < 100; iter++ {
  47. now := time.Date(2015, 1, 1, 0, 0, 0, 0, time.UTC)
  48. queue := populateQueue(t, now)
  49. executed = 0
  50. count := queue.Len()
  51. lastTime := now.Add(time.Duration(count) * time.Hour)
  52. for adv := 0; adv < 5; adv++ {
  53. queue.Advance(lastTime)
  54. if executed != count {
  55. t.Errorf("Advance failed.\n"+
  56. "Should have executed %d times.\n"+
  57. "Only executed %d times.\n", count, executed)
  58. }
  59. }
  60. }
  61. }