state_test.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package container
  2. import (
  3. "sync/atomic"
  4. "testing"
  5. "time"
  6. )
  7. func TestStateRunStop(t *testing.T) {
  8. s := NewState()
  9. for i := 1; i < 3; i++ { // full lifecycle two times
  10. s.Lock()
  11. s.SetRunning(i+100, false)
  12. s.Unlock()
  13. if !s.IsRunning() {
  14. t.Fatal("State not running")
  15. }
  16. if s.Pid != i+100 {
  17. t.Fatalf("Pid %v, expected %v", s.Pid, i+100)
  18. }
  19. if s.ExitCode() != 0 {
  20. t.Fatalf("ExitCode %v, expected 0", s.ExitCode())
  21. }
  22. stopped := make(chan struct{})
  23. var exit int64
  24. go func() {
  25. exitCode, _ := s.WaitStop(-1 * time.Second)
  26. atomic.StoreInt64(&exit, int64(exitCode))
  27. close(stopped)
  28. }()
  29. s.SetStoppedLocking(&ExitStatus{ExitCode: i})
  30. if s.IsRunning() {
  31. t.Fatal("State is running")
  32. }
  33. if s.ExitCode() != i {
  34. t.Fatalf("ExitCode %v, expected %v", s.ExitCode(), i)
  35. }
  36. if s.Pid != 0 {
  37. t.Fatalf("Pid %v, expected 0", s.Pid)
  38. }
  39. select {
  40. case <-time.After(100 * time.Millisecond):
  41. t.Fatal("Stop callback doesn't fire in 100 milliseconds")
  42. case <-stopped:
  43. t.Log("Stop callback fired")
  44. }
  45. exitCode := int(atomic.LoadInt64(&exit))
  46. if exitCode != i {
  47. t.Fatalf("ExitCode %v, expected %v", exitCode, i)
  48. }
  49. if exitCode, err := s.WaitStop(-1 * time.Second); err != nil || exitCode != i {
  50. t.Fatalf("WaitStop returned exitCode: %v, err: %v, expected exitCode: %v, err: %v", exitCode, err, i, nil)
  51. }
  52. }
  53. }
  54. func TestStateTimeoutWait(t *testing.T) {
  55. s := NewState()
  56. stopped := make(chan struct{})
  57. go func() {
  58. s.WaitStop(100 * time.Millisecond)
  59. close(stopped)
  60. }()
  61. select {
  62. case <-time.After(200 * time.Millisecond):
  63. t.Fatal("Stop callback doesn't fire in 100 milliseconds")
  64. case <-stopped:
  65. t.Log("Stop callback fired")
  66. }
  67. s.SetStoppedLocking(&ExitStatus{ExitCode: 1})
  68. stopped = make(chan struct{})
  69. go func() {
  70. s.WaitStop(100 * time.Millisecond)
  71. close(stopped)
  72. }()
  73. select {
  74. case <-time.After(200 * time.Millisecond):
  75. t.Fatal("Stop callback doesn't fire in 100 milliseconds")
  76. case <-stopped:
  77. t.Log("Stop callback fired")
  78. }
  79. }