1 package libcontainer
2
3 import (
4 "errors"
5 "reflect"
6 "testing"
7 )
8
9 var states = map[containerState]Status{
10 &createdState{}: Created,
11 &runningState{}: Running,
12 &restoredState{}: Running,
13 &pausedState{}: Paused,
14 &stoppedState{}: Stopped,
15 &loadedState{s: Running}: Running,
16 }
17
18 func TestStateStatus(t *testing.T) {
19 for s, status := range states {
20 if s.status() != status {
21 t.Fatalf("state returned %s but expected %s", s.status(), status)
22 }
23 }
24 }
25
26 func testTransitions(t *testing.T, initialState containerState, valid []containerState) {
27 validMap := map[reflect.Type]interface{}{}
28 for _, validState := range valid {
29 validMap[reflect.TypeOf(validState)] = nil
30 t.Run(validState.status().String(), func(t *testing.T) {
31 if err := initialState.transition(validState); err != nil {
32 t.Fatal(err)
33 }
34 })
35 }
36 for state := range states {
37 if _, ok := validMap[reflect.TypeOf(state)]; ok {
38 continue
39 }
40 t.Run(state.status().String(), func(t *testing.T) {
41 err := initialState.transition(state)
42 if err == nil {
43 t.Fatal("transition should fail")
44 }
45 var stErr *stateTransitionError
46 if !errors.As(err, &stErr) {
47 t.Fatal("expected stateTransitionError")
48 }
49 })
50 }
51 }
52
53 func TestStoppedStateTransition(t *testing.T) {
54 testTransitions(
55 t,
56 &stoppedState{c: &linuxContainer{}},
57 []containerState{
58 &stoppedState{},
59 &runningState{},
60 &restoredState{},
61 },
62 )
63 }
64
65 func TestPausedStateTransition(t *testing.T) {
66 testTransitions(
67 t,
68 &pausedState{c: &linuxContainer{}},
69 []containerState{
70 &pausedState{},
71 &runningState{},
72 &stoppedState{},
73 },
74 )
75 }
76
77 func TestRestoredStateTransition(t *testing.T) {
78 testTransitions(
79 t,
80 &restoredState{c: &linuxContainer{}},
81 []containerState{
82 &stoppedState{},
83 &runningState{},
84 },
85 )
86 }
87
88 func TestRunningStateTransition(t *testing.T) {
89 testTransitions(
90 t,
91 &runningState{c: &linuxContainer{}},
92 []containerState{
93 &stoppedState{},
94 &pausedState{},
95 &runningState{},
96 },
97 )
98 }
99
100 func TestCreatedStateTransition(t *testing.T) {
101 testTransitions(
102 t,
103 &createdState{c: &linuxContainer{}},
104 []containerState{
105 &stoppedState{},
106 &pausedState{},
107 &runningState{},
108 &createdState{},
109 },
110 )
111 }
112
View as plain text