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