task_test.go 2.2 KB

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