shutdown_test.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package engine
  2. import (
  3. "testing"
  4. "time"
  5. )
  6. func TestShutdownEmpty(t *testing.T) {
  7. eng := New()
  8. if eng.IsShutdown() {
  9. t.Fatalf("IsShutdown should be false")
  10. }
  11. eng.Shutdown()
  12. if !eng.IsShutdown() {
  13. t.Fatalf("IsShutdown should be true")
  14. }
  15. }
  16. func TestShutdownAfterRun(t *testing.T) {
  17. eng := New()
  18. eng.Register("foo", func(job *Job) error {
  19. return nil
  20. })
  21. if err := eng.Job("foo").Run(); err != nil {
  22. t.Fatal(err)
  23. }
  24. eng.Shutdown()
  25. if err := eng.Job("foo").Run(); err == nil {
  26. t.Fatalf("%#v", *eng)
  27. }
  28. }
  29. // An approximate and racy, but better-than-nothing test that
  30. //
  31. func TestShutdownDuringRun(t *testing.T) {
  32. var (
  33. jobDelay time.Duration = 500 * time.Millisecond
  34. jobDelayLow time.Duration = 100 * time.Millisecond
  35. jobDelayHigh time.Duration = 700 * time.Millisecond
  36. )
  37. eng := New()
  38. var completed bool
  39. eng.Register("foo", func(job *Job) error {
  40. time.Sleep(jobDelay)
  41. completed = true
  42. return nil
  43. })
  44. go eng.Job("foo").Run()
  45. time.Sleep(50 * time.Millisecond)
  46. done := make(chan struct{})
  47. var startShutdown time.Time
  48. go func() {
  49. startShutdown = time.Now()
  50. eng.Shutdown()
  51. close(done)
  52. }()
  53. time.Sleep(50 * time.Millisecond)
  54. if err := eng.Job("foo").Run(); err == nil {
  55. t.Fatalf("run on shutdown should fail: %#v", *eng)
  56. }
  57. <-done
  58. // Verify that Shutdown() blocks for roughly 500ms, instead
  59. // of returning almost instantly.
  60. //
  61. // We use >100ms to leave ample margin for race conditions between
  62. // goroutines. It's possible (but unlikely in reasonable testing
  63. // conditions), that this test will cause a false positive or false
  64. // negative. But it's probably better than not having any test
  65. // for the 99.999% of time where testing conditions are reasonable.
  66. if d := time.Since(startShutdown); d.Nanoseconds() < jobDelayLow.Nanoseconds() {
  67. t.Fatalf("shutdown did not block long enough: %v", d)
  68. } else if d.Nanoseconds() > jobDelayHigh.Nanoseconds() {
  69. t.Fatalf("shutdown blocked too long: %v", d)
  70. }
  71. if !completed {
  72. t.Fatalf("job did not complete")
  73. }
  74. }