| 16 | ) |
| 17 | |
| 18 | func TestEventsFormat(t *testing.T) { |
| 19 | var evts []events.Message //nolint:prealloc |
| 20 | for i, action := range []events.Action{events.ActionCreate, events.ActionStart, events.ActionAttach, events.ActionDie} { |
| 21 | evts = append(evts, events.Message{ |
| 22 | Type: events.ContainerEventType, |
| 23 | Action: action, |
| 24 | Actor: events.Actor{ |
| 25 | ID: "abc123", |
| 26 | Attributes: map[string]string{"image": "ubuntu:latest"}, |
| 27 | }, |
| 28 | Scope: "local", |
| 29 | Time: int64(time.Second) * int64(i+1), |
| 30 | TimeNano: int64(time.Second) * int64(i+1), |
| 31 | }) |
| 32 | } |
| 33 | tests := []struct { |
| 34 | name string |
| 35 | args []string |
| 36 | }{ |
| 37 | { |
| 38 | name: "default", |
| 39 | args: []string{}, |
| 40 | }, |
| 41 | { |
| 42 | name: "json", |
| 43 | args: []string{"--format", "json"}, |
| 44 | }, |
| 45 | { |
| 46 | name: "json template", |
| 47 | args: []string{"--format", "{{ json . }}"}, |
| 48 | }, |
| 49 | { |
| 50 | name: "json action", |
| 51 | args: []string{"--format", "{{ json .Action }}"}, |
| 52 | }, |
| 53 | } |
| 54 | |
| 55 | for _, tc := range tests { |
| 56 | t.Run(tc.name, func(t *testing.T) { |
| 57 | // Set to UTC timezone as timestamps in output are |
| 58 | // printed in the current timezone |
| 59 | t.Setenv("TZ", "UTC") |
| 60 | fakeCLI := test.NewFakeCli(&fakeClient{eventsFn: func(context.Context, client.EventsListOptions) (<-chan events.Message, <-chan error) { |
| 61 | messages := make(chan events.Message) |
| 62 | errs := make(chan error, 1) |
| 63 | go func() { |
| 64 | for _, msg := range evts { |
| 65 | messages <- msg |
| 66 | } |
| 67 | errs <- io.EOF |
| 68 | }() |
| 69 | return messages, errs |
| 70 | }}) |
| 71 | cmd := newEventsCommand(fakeCLI) |
| 72 | cmd.SetArgs(tc.args) |
| 73 | cmd.SetOut(io.Discard) |
| 74 | cmd.SetErr(io.Discard) |
| 75 | assert.Check(t, cmd.Execute()) |