github.com/thajeztah/cli@v0.0.0-20240223162942-dc6bfac81a8b/cli/command/image/history_test.go (about) 1 package image 2 3 import ( 4 "fmt" 5 "io" 6 "testing" 7 "time" 8 9 "github.com/docker/cli/internal/test" 10 "github.com/docker/docker/api/types/image" 11 "github.com/pkg/errors" 12 "gotest.tools/v3/assert" 13 "gotest.tools/v3/golden" 14 ) 15 16 func TestNewHistoryCommandErrors(t *testing.T) { 17 testCases := []struct { 18 name string 19 args []string 20 expectedError string 21 imageHistoryFunc func(img string) ([]image.HistoryResponseItem, error) 22 }{ 23 { 24 name: "wrong-args", 25 args: []string{}, 26 expectedError: "requires exactly 1 argument.", 27 }, 28 { 29 name: "client-error", 30 args: []string{"image:tag"}, 31 expectedError: "something went wrong", 32 imageHistoryFunc: func(img string) ([]image.HistoryResponseItem, error) { 33 return []image.HistoryResponseItem{{}}, errors.Errorf("something went wrong") 34 }, 35 }, 36 } 37 for _, tc := range testCases { 38 cmd := NewHistoryCommand(test.NewFakeCli(&fakeClient{imageHistoryFunc: tc.imageHistoryFunc})) 39 cmd.SetOut(io.Discard) 40 cmd.SetArgs(tc.args) 41 assert.ErrorContains(t, cmd.Execute(), tc.expectedError) 42 } 43 } 44 45 func TestNewHistoryCommandSuccess(t *testing.T) { 46 testCases := []struct { 47 name string 48 args []string 49 imageHistoryFunc func(img string) ([]image.HistoryResponseItem, error) 50 }{ 51 { 52 name: "simple", 53 args: []string{"image:tag"}, 54 imageHistoryFunc: func(img string) ([]image.HistoryResponseItem, error) { 55 return []image.HistoryResponseItem{{ 56 ID: "1234567890123456789", 57 Created: time.Now().Unix(), 58 Comment: "none", 59 }}, nil 60 }, 61 }, 62 { 63 name: "quiet", 64 args: []string{"--quiet", "image:tag"}, 65 }, 66 { 67 name: "non-human", 68 args: []string{"--human=false", "image:tag"}, 69 imageHistoryFunc: func(img string) ([]image.HistoryResponseItem, error) { 70 return []image.HistoryResponseItem{{ 71 ID: "abcdef", 72 Created: time.Date(2017, 1, 1, 12, 0, 3, 0, time.UTC).Unix(), 73 CreatedBy: "rose", 74 Comment: "new history item!", 75 }}, nil 76 }, 77 }, 78 { 79 name: "quiet-no-trunc", 80 args: []string{"--quiet", "--no-trunc", "image:tag"}, 81 imageHistoryFunc: func(img string) ([]image.HistoryResponseItem, error) { 82 return []image.HistoryResponseItem{{ 83 ID: "1234567890123456789", 84 Created: time.Now().Unix(), 85 }}, nil 86 }, 87 }, 88 } 89 for _, tc := range testCases { 90 tc := tc 91 t.Run(tc.name, func(t *testing.T) { 92 // Set to UTC timezone as timestamps in output are 93 // printed in the current timezone 94 t.Setenv("TZ", "UTC") 95 cli := test.NewFakeCli(&fakeClient{imageHistoryFunc: tc.imageHistoryFunc}) 96 cmd := NewHistoryCommand(cli) 97 cmd.SetOut(io.Discard) 98 cmd.SetArgs(tc.args) 99 err := cmd.Execute() 100 assert.NilError(t, err) 101 actual := cli.OutBuffer().String() 102 golden.Assert(t, actual, fmt.Sprintf("history-command-success.%s.golden", tc.name)) 103 }) 104 } 105 }