github.com/vieux/docker@v0.6.3-0.20161004191708-e097c2a938c7/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.Lock() 34 s.SetStopped(&ExitStatus{ExitCode: i}) 35 s.Unlock() 36 if s.IsRunning() { 37 t.Fatal("State is running") 38 } 39 if s.ExitCode() != i { 40 t.Fatalf("ExitCode %v, expected %v", s.ExitCode(), i) 41 } 42 if s.Pid != 0 { 43 t.Fatalf("Pid %v, expected 0", s.Pid) 44 } 45 select { 46 case <-time.After(100 * time.Millisecond): 47 t.Fatal("Stop callback doesn't fire in 100 milliseconds") 48 case <-stopped: 49 t.Log("Stop callback fired") 50 } 51 exitCode := int(atomic.LoadInt64(&exit)) 52 if exitCode != i { 53 t.Fatalf("ExitCode %v, expected %v", exitCode, i) 54 } 55 if exitCode, err := s.WaitStop(-1 * time.Second); err != nil || exitCode != i { 56 t.Fatalf("WaitStop returned exitCode: %v, err: %v, expected exitCode: %v, err: %v", exitCode, err, i, nil) 57 } 58 } 59 } 60 61 func TestStateTimeoutWait(t *testing.T) { 62 s := NewState() 63 stopped := make(chan struct{}) 64 go func() { 65 s.WaitStop(100 * time.Millisecond) 66 close(stopped) 67 }() 68 select { 69 case <-time.After(200 * time.Millisecond): 70 t.Fatal("Stop callback doesn't fire in 200 milliseconds") 71 case <-stopped: 72 t.Log("Stop callback fired") 73 } 74 75 s.Lock() 76 s.SetStopped(&ExitStatus{ExitCode: 1}) 77 s.Unlock() 78 79 stopped = make(chan struct{}) 80 go func() { 81 s.WaitStop(100 * time.Millisecond) 82 close(stopped) 83 }() 84 select { 85 case <-time.After(200 * time.Millisecond): 86 t.Fatal("Stop callback doesn't fire in 100 milliseconds") 87 case <-stopped: 88 t.Log("Stop callback fired") 89 } 90 91 }