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

     1  package image
     2  
     3  import (
     4  	"io"
     5  	"strings"
     6  	"testing"
     7  
     8  	"github.com/docker/docker/api/types/image"
     9  	"github.com/khulnasoft/cli/internal/test"
    10  	"github.com/pkg/errors"
    11  	"gotest.tools/v3/assert"
    12  )
    13  
    14  func TestNewPushCommandErrors(t *testing.T) {
    15  	testCases := []struct {
    16  		name          string
    17  		args          []string
    18  		expectedError string
    19  		imagePushFunc func(ref string, options image.PushOptions) (io.ReadCloser, error)
    20  	}{
    21  		{
    22  			name:          "wrong-args",
    23  			args:          []string{},
    24  			expectedError: "requires exactly 1 argument.",
    25  		},
    26  		{
    27  			name:          "invalid-name",
    28  			args:          []string{"UPPERCASE_REPO"},
    29  			expectedError: "invalid reference format: repository name (library/UPPERCASE_REPO) must be lowercase",
    30  		},
    31  		{
    32  			name:          "push-failed",
    33  			args:          []string{"image:repo"},
    34  			expectedError: "Failed to push",
    35  			imagePushFunc: func(ref string, options image.PushOptions) (io.ReadCloser, error) {
    36  				return io.NopCloser(strings.NewReader("")), errors.Errorf("Failed to push")
    37  			},
    38  		},
    39  	}
    40  	for _, tc := range testCases {
    41  		cli := test.NewFakeCli(&fakeClient{imagePushFunc: tc.imagePushFunc})
    42  		cmd := NewPushCommand(cli)
    43  		cmd.SetOut(io.Discard)
    44  		cmd.SetArgs(tc.args)
    45  		assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
    46  	}
    47  }
    48  
    49  func TestNewPushCommandSuccess(t *testing.T) {
    50  	testCases := []struct {
    51  		name   string
    52  		args   []string
    53  		output string
    54  	}{
    55  		{
    56  			name: "push",
    57  			args: []string{"image:tag"},
    58  		},
    59  		{
    60  			name: "push quiet",
    61  			args: []string{"--quiet", "image:tag"},
    62  			output: `docker.io/library/image:tag
    63  `,
    64  		},
    65  	}
    66  	for _, tc := range testCases {
    67  		tc := tc
    68  		t.Run(tc.name, func(t *testing.T) {
    69  			cli := test.NewFakeCli(&fakeClient{
    70  				imagePushFunc: func(ref string, options image.PushOptions) (io.ReadCloser, error) {
    71  					return io.NopCloser(strings.NewReader("")), nil
    72  				},
    73  			})
    74  			cmd := NewPushCommand(cli)
    75  			cmd.SetOut(cli.OutBuffer())
    76  			cmd.SetArgs(tc.args)
    77  			assert.NilError(t, cmd.Execute())
    78  			if tc.output != "" {
    79  				assert.Equal(t, tc.output, cli.OutBuffer().String())
    80  			}
    81  		})
    82  	}
    83  }