diff --git a/cli/command/image/load_test.go b/cli/command/image/load_test.go --- a/cli/command/image/load_test.go +++ b/cli/command/image/load_test.go @@ -1,168 +1,86 @@ package image import ( - "errors" - "fmt" - "io" - "reflect" - "strings" - "testing" - "unsafe" + "io" + "net/http" + "os" + "path/filepath" + "strings" + "testing" - "github.com/docker/cli/internal/test" - "github.com/moby/moby/client" - "gotest.tools/v3/assert" - "gotest.tools/v3/golden" + "github.com/docker/cli/internal/test" + "github.com/moby/moby/client" ) -func TestNewLoadCommandErrors(t *testing.T) { - testCases := []struct { - name string - args []string - isTerminalIn bool - expectedError string - imageLoadFunc func(input io.Reader, options ...client.ImageLoadOption) (client.ImageLoadResult, error) - }{ - { - name: "wrong-args", - args: []string{"arg"}, - expectedError: "accepts no arguments", - }, - { - name: "input-to-terminal", - args: []string{}, - isTerminalIn: true, - expectedError: "requested load from stdin, but stdin is empty", - }, - { - name: "pull-error", - args: []string{}, - expectedError: "something went wrong", - imageLoadFunc: func(input io.Reader, options ...client.ImageLoadOption) (client.ImageLoadResult, error) { - return client.ImageLoadResult{}, errors.New("something went wrong") - }, - }, - { - name: "invalid platform", - args: []string{"--platform", ""}, - expectedError: `invalid platform`, - imageLoadFunc: func(input io.Reader, options ...client.ImageLoadOption) (client.ImageLoadResult, error) { - return client.ImageLoadResult{}, nil - }, - }, - } - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - cli := test.NewFakeCli(&fakeClient{imageLoadFunc: tc.imageLoadFunc}) - cli.In().SetIsTerminal(tc.isTerminalIn) - cmd := newLoadCommand(cli) - cmd.SetOut(io.Discard) - cmd.SetErr(io.Discard) - cmd.SetArgs(tc.args) - assert.ErrorContains(t, cmd.Execute(), tc.expectedError) - }) - } +type cross90Transport func(*http.Request) (*http.Response, error) +func (f cross90Transport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } +type cross90Body struct { io.Reader; closed bool } +func (b *cross90Body) Close() error { b.closed = true; return nil } + +func cross90Load(t *testing.T, contentType, payload string, args []string, wantOutput, wantError string) { + t.Helper() + body := &cross90Body{Reader: strings.NewReader(payload)} + calls := 0 + httpClient := &http.Client{Transport: cross90Transport(func(r *http.Request) (*http.Response, error) { + calls++ + if r.Method != "POST" || !strings.HasSuffix(r.URL.Path, "/images/load") { t.Errorf("unexpected request %s %s", r.Method, r.URL.Path) } + if r.Header.Get("Content-Type") != "application/x-tar" { t.Error("request body content type changed") } + if _, err := io.ReadAll(r.Body); err != nil { t.Fatal(err) } + if strings.Contains(strings.Join(args, " "), "--quiet") && r.URL.Query().Get("quiet") != "1" { t.Error("quiet option lost") } + if strings.Contains(strings.Join(args, " "), "--platform") && len(r.URL.Query()["platform"]) != 2 { t.Error("platform options lost") } + h := make(http.Header) + if contentType != "" { h.Set("Content-Type", contentType) } + return &http.Response{StatusCode: 200, Header: h, Body: body, Request: r}, nil + })} + api, err := client.NewClientWithOpts(client.WithHost("http://example.test"), client.WithVersion("1.48"), client.WithHTTPClient(httpClient)) + if err != nil { t.Fatal(err) } + defer api.Close() + cli := test.NewFakeCli(api) + cmd := newLoadCommand(cli) + cmd.SetOut(io.Discard) + cmd.SetErr(io.Discard) + cmd.SetArgs(args) + err = cmd.Execute() + if wantError != "" { + if err == nil || (wantError != "any" && !strings.Contains(err.Error(), wantError)) { t.Errorf("expected error %q, got %v", wantError, err) } + } else { + if err != nil { t.Fatalf("load failed: %v", err) } + if got := cli.OutBuffer().String(); got != wantOutput { t.Errorf("JSON stream not consumed: got %q want %q", got, wantOutput) } + } + if calls != 1 { t.Errorf("expected one real client request, got %d", calls) } + if !body.closed { t.Error("image load response body leaked") } } -func TestNewLoadCommandInvalidInput(t *testing.T) { - expectedError := "open *" - cmd := newLoadCommand(test.NewFakeCli(&fakeClient{})) - cmd.SetOut(io.Discard) - cmd.SetErr(io.Discard) - cmd.SetArgs([]string{"--input", "*"}) - err := cmd.Execute() - assert.ErrorContains(t, err, expectedError) +func TestCross90LoadBehavior(t *testing.T) { + for _, ct := range []string{"text/plain", "", "application/json; charset=utf-8"} { + t.Run("multi-message/"+ct, func(t *testing.T) { + cross90Load(t, ct, "{\"stream\":\"alpha\\n\"}\n{\"stream\":\"beta\\n\"}\n", nil, "alpha\nbeta\n", "") + }) + t.Run("daemon-error/"+ct, func(t *testing.T) { + cross90Load(t, ct, "{\"errorDetail\":{\"message\":\"bad image archive\"},\"error\":\"bad image archive\"}\n", nil, "", "bad image archive") + }) + } + t.Run("malformed", func(t *testing.T) { cross90Load(t, "text/plain", "{not-json", nil, "", "any") }) } -func mockImageLoadResult(content string, json bool) client.ImageLoadResult { - out := client.ImageLoadResult{JSON: json} - - // Set unexported field "body" - v := reflect.ValueOf(&out).Elem() - f := v.FieldByName("body") - r := io.NopCloser(strings.NewReader(content)) - reflect.NewAt(f.Type(), unsafe.Pointer(f.UnsafeAddr())).Elem().Set(reflect.ValueOf(r)) - return out +func TestCross90LoadRegression(t *testing.T) { + t.Run("json-stream", func(t *testing.T) { cross90Load(t, "application/json", "{\"stream\":\"ok\\n\"}\n", nil, "ok\n", "") }) + t.Run("quiet", func(t *testing.T) { cross90Load(t, "application/json", "{\"stream\":\"ok\\n\"}\n", []string{"--quiet"}, "ok\n", "") }) + t.Run("platforms", func(t *testing.T) { cross90Load(t, "application/json", "{\"stream\":\"ok\\n\"}\n", []string{"--platform", "linux/amd64", "--platform", "linux/arm64/v8"}, "ok\n", "") }) + t.Run("file-input", func(t *testing.T) { + path := filepath.Join(t.TempDir(), "image.tar") + if err := os.WriteFile(path, []byte("image-content"), 0600); err != nil { t.Fatal(err) } + cross90Load(t, "application/json", "{\"stream\":\"ok\\n\"}\n", []string{"--input", path}, "ok\n", "") + }) + t.Run("empty-response", func(t *testing.T) { cross90Load(t, "application/json", "", nil, "", "") }) + t.Run("invalid-args", func(t *testing.T) { + cli := test.NewFakeCli(&fakeClient{}) + cmd := newLoadCommand(cli); cmd.SetOut(io.Discard); cmd.SetErr(io.Discard); cmd.SetArgs([]string{"unexpected"}) + if cmd.Execute() == nil { t.Error("unexpected positional argument accepted") } + }) + t.Run("missing-file", func(t *testing.T) { + cli := test.NewFakeCli(&fakeClient{}) + cmd := newLoadCommand(cli); cmd.SetOut(io.Discard); cmd.SetErr(io.Discard); cmd.SetArgs([]string{"--input", filepath.Join(t.TempDir(), "missing")}) + if cmd.Execute() == nil { t.Error("missing input accepted") } + }) } - -func TestNewLoadCommandSuccess(t *testing.T) { - testCases := []struct { - name string - args []string - imageLoadFunc func(input io.Reader, options ...client.ImageLoadOption) (client.ImageLoadResult, error) - }{ - { - name: "simple", - args: []string{}, - imageLoadFunc: func(input io.Reader, options ...client.ImageLoadOption) (client.ImageLoadResult, error) { - // FIXME(thaJeztah): how to mock this? - // return client.ImageLoadResult{Body: io.NopCloser(strings.NewReader("Success"))}, nil - return mockImageLoadResult(`Success`, false), nil - }, - }, - { - name: "json", - args: []string{}, - imageLoadFunc: func(input io.Reader, options ...client.ImageLoadOption) (client.ImageLoadResult, error) { - // FIXME(thaJeztah): how to mock this? - // return client.ImageLoadResult{ - // Body: io.NopCloser(strings.NewReader(`{"ID": "1"}`)), - // JSON: true, - // }, nil - return mockImageLoadResult(`{"ID":"1"}`, true), nil - }, - }, - { - name: "input-file", - args: []string{"--input", "testdata/load-command-success.input.txt"}, - imageLoadFunc: func(input io.Reader, options ...client.ImageLoadOption) (client.ImageLoadResult, error) { - // FIXME(thaJeztah): how to mock this? - // return client.ImageLoadResult{Body: io.NopCloser(strings.NewReader("Success"))}, nil - return mockImageLoadResult(`Success`, false), nil - }, - }, - { - name: "with-single-platform", - args: []string{"--platform", "linux/amd64"}, - imageLoadFunc: func(input io.Reader, options ...client.ImageLoadOption) (client.ImageLoadResult, error) { - // FIXME(thaJeztah): need to find appropriate way to test the result of "ImageHistoryWithPlatform" being applied - assert.Check(t, len(options) > 0) // can be 1 or two depending on whether a terminal is attached :/ - // assert.Check(t, is.Contains(options, client.ImageHistoryWithPlatform(ocispec.Platform{OS: "linux", Architecture: "amd64"}))) - // FIXME(thaJeztah): how to mock this? - // return client.ImageLoadResult{Body: io.NopCloser(strings.NewReader("Success"))}, nil - return mockImageLoadResult(`Success`, false), nil - }, - }, - { - name: "with-comma-separated-platforms", - args: []string{"--platform", "linux/amd64,linux/arm64/v8,linux/riscv64"}, - imageLoadFunc: func(input io.Reader, options ...client.ImageLoadOption) (client.ImageLoadResult, error) { - assert.Check(t, len(options) > 0) // can be 1 or two depending on whether a terminal is attached :/ - // FIXME(thaJeztah): how to mock this? - // return client.ImageLoadResult{Body: io.NopCloser(strings.NewReader("Success"))}, nil - return mockImageLoadResult(`Success`, false), nil - }, - }, - { - name: "with-multiple-platform-options", - args: []string{"--platform", "linux/amd64", "--platform", "linux/arm64/v8", "--platform", "linux/riscv64"}, - imageLoadFunc: func(input io.Reader, options ...client.ImageLoadOption) (client.ImageLoadResult, error) { - assert.Check(t, len(options) > 0) // can be 1 or two depending on whether a terminal is attached :/ - // FIXME(thaJeztah): how to mock this? - // return client.ImageLoadResult{Body: io.NopCloser(strings.NewReader("Success"))}, nil - return mockImageLoadResult(`Success`, false), nil - }, - }, - } - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - cli := test.NewFakeCli(&fakeClient{imageLoadFunc: tc.imageLoadFunc}) - cmd := newLoadCommand(cli) - cmd.SetOut(io.Discard) - cmd.SetArgs(tc.args) - err := cmd.Execute() - assert.NilError(t, err) - golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("load-command-success.%s.golden", tc.name)) - }) - } -}