cron_test.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package cron
  2. import (
  3. "fmt"
  4. "testing"
  5. "time"
  6. )
  7. // Start and stop cron with no entries.
  8. func TestNoEntries(t *testing.T) {
  9. cron := New()
  10. done := startAndSignal(cron)
  11. go cron.Stop()
  12. select {
  13. case <-time.After(1 * time.Second):
  14. t.FailNow()
  15. case <-done:
  16. }
  17. }
  18. // Add a job, start cron, expect it runs.
  19. func TestAddBeforeRunning(t *testing.T) {
  20. cron := New()
  21. cron.Add("* * * * * ?", func() {
  22. cron.Stop()
  23. })
  24. done := startAndSignal(cron)
  25. // Give cron 2 seconds to run our job (which is always activated).
  26. select {
  27. case <-time.After(2 * time.Second):
  28. t.FailNow()
  29. case <-done:
  30. }
  31. }
  32. // Start cron, add a job, expect it runs.
  33. func TestAddWhileRunning(t *testing.T) {
  34. cron := New()
  35. done := startAndSignal(cron)
  36. go func() {
  37. cron.Add("* * * * * ?", func() {
  38. cron.Stop()
  39. })
  40. }()
  41. select {
  42. case <-time.After(2 * time.Second):
  43. t.FailNow()
  44. case <-done:
  45. }
  46. }
  47. // Test that the entries are correctly sorted.
  48. // Add a bunch of long-in-the-future entries, and an immediate entry, and ensure
  49. // that the immediate entry runs immediately.
  50. func TestMultipleEntries(t *testing.T) {
  51. cron := New()
  52. cron.Add("0 0 0 1 1 ?", func() {})
  53. cron.Add("* * * * * ?", func() {
  54. cron.Stop()
  55. })
  56. cron.Add("0 0 0 31 12 ?", func() {})
  57. done := startAndSignal(cron)
  58. select {
  59. case <-time.After(2 * time.Second):
  60. t.FailNow()
  61. case <-done:
  62. }
  63. }
  64. // Test that the cron is run in the local time zone (as opposed to UTC).
  65. func TestLocalTimezone(t *testing.T) {
  66. cron := New()
  67. now := time.Now().Local()
  68. spec := fmt.Sprintf("%d %d %d %d %d ?",
  69. now.Second()+1, now.Minute(), now.Hour(), now.Day(), now.Month())
  70. cron.Add(spec, func() { cron.Stop() })
  71. done := startAndSignal(cron)
  72. select {
  73. case <-time.After(2 * time.Second):
  74. t.FailNow()
  75. case <-done:
  76. }
  77. }
  78. // Return a channel that signals when the cron's Start() method returns.
  79. func startAndSignal(cron *Cron) <-chan struct{} {
  80. ch := make(chan struct{})
  81. go func() {
  82. cron.Run()
  83. ch <- struct{}{}
  84. }()
  85. return ch
  86. }