Datasets:
File size: 11,090 Bytes
0e239c6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 | 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", "<invalid>"},
- 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))
- })
- }
-}
|