github.com/fabiokung/docker@v0.11.2-0.20170222101415-4534dcd49497/cli/command/formatter/task_test.go (about) 1 package formatter 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "strings" 7 "testing" 8 9 "github.com/docker/docker/api/types/swarm" 10 "github.com/docker/docker/pkg/testutil/assert" 11 ) 12 13 func TestTaskContextWrite(t *testing.T) { 14 cases := []struct { 15 context Context 16 expected string 17 }{ 18 { 19 Context{Format: "{{InvalidFunction}}"}, 20 `Template parsing error: template: :1: function "InvalidFunction" not defined 21 `, 22 }, 23 { 24 Context{Format: "{{nil}}"}, 25 `Template parsing error: template: :1:2: executing "" at <nil>: nil is not a command 26 `, 27 }, 28 { 29 Context{Format: NewTaskFormat("table", true)}, 30 `taskID1 31 taskID2 32 `, 33 }, 34 { 35 Context{Format: NewTaskFormat("table {{.Name}} {{.Node}} {{.Ports}}", false)}, 36 `NAME NODE PORTS 37 foobar_baz foo1 38 foobar_bar foo2 39 `, 40 }, 41 { 42 Context{Format: NewTaskFormat("table {{.Name}}", true)}, 43 `NAME 44 foobar_baz 45 foobar_bar 46 `, 47 }, 48 { 49 Context{Format: NewTaskFormat("raw", true)}, 50 `id: taskID1 51 id: taskID2 52 `, 53 }, 54 { 55 Context{Format: NewTaskFormat("{{.Name}} {{.Node}}", false)}, 56 `foobar_baz foo1 57 foobar_bar foo2 58 `, 59 }, 60 } 61 62 for _, testcase := range cases { 63 tasks := []swarm.Task{ 64 {ID: "taskID1"}, 65 {ID: "taskID2"}, 66 } 67 names := map[string]string{ 68 "taskID1": "foobar_baz", 69 "taskID2": "foobar_bar", 70 } 71 nodes := map[string]string{ 72 "taskID1": "foo1", 73 "taskID2": "foo2", 74 } 75 out := bytes.NewBufferString("") 76 testcase.context.Output = out 77 err := TaskWrite(testcase.context, tasks, names, nodes) 78 if err != nil { 79 assert.Error(t, err, testcase.expected) 80 } else { 81 assert.Equal(t, out.String(), testcase.expected) 82 } 83 } 84 } 85 86 func TestTaskContextWriteJSONField(t *testing.T) { 87 tasks := []swarm.Task{ 88 {ID: "taskID1"}, 89 {ID: "taskID2"}, 90 } 91 names := map[string]string{ 92 "taskID1": "foobar_baz", 93 "taskID2": "foobar_bar", 94 } 95 out := bytes.NewBufferString("") 96 err := TaskWrite(Context{Format: "{{json .ID}}", Output: out}, tasks, names, map[string]string{}) 97 if err != nil { 98 t.Fatal(err) 99 } 100 for i, line := range strings.Split(strings.TrimSpace(out.String()), "\n") { 101 var s string 102 if err := json.Unmarshal([]byte(line), &s); err != nil { 103 t.Fatal(err) 104 } 105 assert.Equal(t, s, tasks[i].ID) 106 } 107 }