github.com/khulnasoft/cli@v0.0.0-20240402070845-01bcad7beefa/cli/command/system/events_test.go (about)

     1  package system
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"io"
     7  	"strings"
     8  	"testing"
     9  	"time"
    10  
    11  	"github.com/docker/docker/api/types"
    12  	"github.com/docker/docker/api/types/events"
    13  	"github.com/khulnasoft/cli/internal/test"
    14  	"gotest.tools/v3/assert"
    15  	"gotest.tools/v3/golden"
    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  			Status: string(action),
    23  			ID:     "abc123",
    24  			From:   "ubuntu:latest",
    25  			Type:   events.ContainerEventType,
    26  			Action: action,
    27  			Actor: events.Actor{
    28  				ID:         "abc123",
    29  				Attributes: map[string]string{"image": "ubuntu:latest"},
    30  			},
    31  			Scope:    "local",
    32  			Time:     int64(time.Second) * int64(i+1),
    33  			TimeNano: int64(time.Second) * int64(i+1),
    34  		})
    35  	}
    36  	tests := []struct {
    37  		name, format string
    38  	}{
    39  		{
    40  			name: "default",
    41  		},
    42  		{
    43  			name:   "json",
    44  			format: "json",
    45  		},
    46  		{
    47  			name:   "json template",
    48  			format: "{{ json . }}",
    49  		},
    50  		{
    51  			name:   "json action",
    52  			format: "{{ json .Action }}",
    53  		},
    54  	}
    55  
    56  	for _, tc := range tests {
    57  		tc := tc
    58  		t.Run(tc.name, func(t *testing.T) {
    59  			// Set to UTC timezone as timestamps in output are
    60  			// printed in the current timezone
    61  			t.Setenv("TZ", "UTC")
    62  			cli := test.NewFakeCli(&fakeClient{eventsFn: func(context.Context, types.EventsOptions) (<-chan events.Message, <-chan error) {
    63  				messages := make(chan events.Message)
    64  				errs := make(chan error, 1)
    65  				go func() {
    66  					for _, msg := range evts {
    67  						messages <- msg
    68  					}
    69  					errs <- io.EOF
    70  				}()
    71  				return messages, errs
    72  			}})
    73  			cmd := NewEventsCommand(cli)
    74  			if tc.format != "" {
    75  				cmd.Flags().Set("format", tc.format)
    76  			}
    77  			assert.Check(t, cmd.Execute())
    78  			out := cli.OutBuffer().String()
    79  			assert.Check(t, golden.String(out, fmt.Sprintf("docker-events-%s.golden", strings.ReplaceAll(tc.name, " ", "-"))))
    80  			cli.OutBuffer().Reset()
    81  		})
    82  	}
    83  }