cron_test.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package cron
  2. import (
  3. "testing"
  4. "time"
  5. )
  6. // Start and stop cron with no entries.
  7. func TestNoEntries(t *testing.T) {
  8. cron := New()
  9. done := startAndSignal(cron)
  10. go cron.Stop()
  11. select {
  12. case <-time.After(1 * time.Second):
  13. t.FailNow()
  14. case <-done:
  15. }
  16. }
  17. // Add a job, start cron, expect it runs.
  18. func TestAddBeforeRunning(t *testing.T) {
  19. cron := New()
  20. cron.Add("* * * * * ?", func() {
  21. cron.Stop()
  22. })
  23. done := startAndSignal(cron)
  24. // Give cron 2 seconds to run our job (which is always activated).
  25. select {
  26. case <-time.After(2 * time.Second):
  27. t.FailNow()
  28. case <-done:
  29. }
  30. }
  31. // Start cron, add a job, expect it runs.
  32. func TestAddWhileRunning(t *testing.T) {
  33. cron := New()
  34. done := startAndSignal(cron)
  35. go func() {
  36. cron.Add("* * * * * ?", func() {
  37. cron.Stop()
  38. })
  39. }()
  40. select {
  41. case <-time.After(2 * time.Second):
  42. t.FailNow()
  43. case <-done:
  44. }
  45. }
  46. // Return a channel that signals when the cron's Start() method returns.
  47. func startAndSignal(cron *Cron) <-chan struct{} {
  48. ch := make(chan struct{})
  49. go func() {
  50. cron.Start()
  51. ch <- struct{}{}
  52. }()
  53. return ch
  54. }