package mapatest import ( "bytes" "encoding/json" "image" "image/color" "image/png" "mime/multipart" "net/http" "net/http/httptest" "net/url" "testing" ) // The images' outside helpers: a picture, an upload through POST // /images, and a copy through POST /images/copy. // pngOf is a small PNG, different for each seed. func pngOf(t *testing.T, seed int) []byte { t.Helper() canvas := image.NewRGBA(image.Rect(0, 0, 24, 16)) for column := range 24 { for line := range 16 { canvas.Set(column, line, color.RGBA{uint8(column * seed), uint8(line * 9), uint8(seed), 255}) } } var out bytes.Buffer if err := png.Encode(&out, canvas); err != nil { t.Fatal(err) } return out.Bytes() } // multipartOf is a multipart body: fields, then the file. func multipartOf(t *testing.T, fields url.Values, name string, file []byte) (*bytes.Buffer, string) { t.Helper() var body bytes.Buffer writer := multipart.NewWriter(&body) for key, values := range fields { for _, value := range values { _ = writer.WriteField(key, value) } } part, err := writer.CreateFormFile("file", name) if err != nil { t.Fatal(err) } _, _ = part.Write(file) if err := writer.Close(); err != nil { t.Fatal(err) } return &body, writer.FormDataContentType() } // sendFile posts a multipart request. func (rig *rig) sendFile(t *testing.T, who, target string, fields url.Values, name string, file []byte) *httptest.ResponseRecorder { t.Helper() body, kind := multipartOf(t, fields, name, file) request := httptest.NewRequest(http.MethodPost, target, body) request.Header.Set("Content-Type", kind) request.Header.Set("Accept", "application/json") request.Header.Set("Origin", testOrigin) recorder := httptest.NewRecorder() rig.built.As(who).ServeHTTP(recorder, request) return recorder } // uploaded is one upload's reply. type uploaded struct { ID string `json:"id"` Src string `json:"src"` Width int `json:"width"` Height int `json:"height"` } // upload sends raw to POST /images as who and answers its reply. func (rig *rig) upload(t *testing.T, who string, raw []byte) uploaded { t.Helper() reply := rig.sendFile(t, who, "/images", nil, "photo.png", raw) if reply.Code != http.StatusOK { t.Fatalf("upload: %d %s", reply.Code, reply.Body.String()) } var out uploaded if err := json.Unmarshal(reply.Body.Bytes(), &out); err != nil { t.Fatal(err) } return out } func (image uploaded) markdown(alt string) string { return "![" + alt + "](" + image.Src + ")" }