github.com/zhouyu0/docker-note@v0.0.0-20190722021225-b8d3825084db/client/image_load_test.go (about) 1 package client // import "github.com/docker/docker/client" 2 3 import ( 4 "bytes" 5 "context" 6 "fmt" 7 "io/ioutil" 8 "net/http" 9 "strings" 10 "testing" 11 ) 12 13 func TestImageLoadError(t *testing.T) { 14 client := &Client{ 15 client: newMockClient(errorMock(http.StatusInternalServerError, "Server error")), 16 } 17 18 _, err := client.ImageLoad(context.Background(), nil, true) 19 if err == nil || err.Error() != "Error response from daemon: Server error" { 20 t.Fatalf("expected a Server Error, got %v", err) 21 } 22 } 23 24 func TestImageLoad(t *testing.T) { 25 expectedURL := "/images/load" 26 expectedInput := "inputBody" 27 expectedOutput := "outputBody" 28 loadCases := []struct { 29 quiet bool 30 responseContentType string 31 expectedResponseJSON bool 32 expectedQueryParams map[string]string 33 }{ 34 { 35 quiet: false, 36 responseContentType: "text/plain", 37 expectedResponseJSON: false, 38 expectedQueryParams: map[string]string{ 39 "quiet": "0", 40 }, 41 }, 42 { 43 quiet: true, 44 responseContentType: "application/json", 45 expectedResponseJSON: true, 46 expectedQueryParams: map[string]string{ 47 "quiet": "1", 48 }, 49 }, 50 } 51 for _, loadCase := range loadCases { 52 client := &Client{ 53 client: newMockClient(func(req *http.Request) (*http.Response, error) { 54 if !strings.HasPrefix(req.URL.Path, expectedURL) { 55 return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) 56 } 57 contentType := req.Header.Get("Content-Type") 58 if contentType != "application/x-tar" { 59 return nil, fmt.Errorf("content-type not set in URL headers properly. Expected 'application/x-tar', got %s", contentType) 60 } 61 query := req.URL.Query() 62 for key, expected := range loadCase.expectedQueryParams { 63 actual := query.Get(key) 64 if actual != expected { 65 return nil, fmt.Errorf("%s not set in URL query properly. Expected '%s', got %s", key, expected, actual) 66 } 67 } 68 headers := http.Header{} 69 headers.Add("Content-Type", loadCase.responseContentType) 70 return &http.Response{ 71 StatusCode: http.StatusOK, 72 Body: ioutil.NopCloser(bytes.NewReader([]byte(expectedOutput))), 73 Header: headers, 74 }, nil 75 }), 76 } 77 78 input := bytes.NewReader([]byte(expectedInput)) 79 imageLoadResponse, err := client.ImageLoad(context.Background(), input, loadCase.quiet) 80 if err != nil { 81 t.Fatal(err) 82 } 83 if imageLoadResponse.JSON != loadCase.expectedResponseJSON { 84 t.Fatalf("expected a JSON response, was not.") 85 } 86 body, err := ioutil.ReadAll(imageLoadResponse.Body) 87 if err != nil { 88 t.Fatal(err) 89 } 90 if string(body) != expectedOutput { 91 t.Fatalf("expected %s, got %s", expectedOutput, string(body)) 92 } 93 } 94 }