shutdown_test.go 2.0 KB

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