go-paste/image/image_test.go
xuu 1b8e8ad26a
All checks were successful
Go Bump / bump (push) Successful in 37s
chore: add favicon
2023-11-09 13:47:42 -07:00

119 lines
2.4 KiB
Go

package image_test
import (
"bytes"
"context"
"encoding/base64"
"fmt"
"mime/multipart"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"github.com/matryer/is"
"go.sour.is/paste/v2/image"
)
var testImage = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z/C/HgAGgwJ/lK3Q6wAAAABJRU5ErkJggg=="
func TestPostImgur(t *testing.T) {
is := is.New(t)
ctx := context.Background()
dir, err := os.MkdirTemp("", "image")
is.NoErr(err)
im, err := image.New(ctx, dir, 0)
is.NoErr(err)
{
body := &bytes.Buffer{}
wr := multipart.NewWriter(body)
w, err := wr.CreateFormField("type")
is.NoErr(err)
fmt.Fprint(w, "base64")
w, err = wr.CreateFormField("image")
is.NoErr(err)
fmt.Fprint(w, testImage)
err = wr.Close()
is.NoErr(err)
t.Log(body.String())
req := httptest.NewRequest("POST", "/3/upload", body)
req.Header.Set("Content-Type", "multipart/form-data; boundary="+wr.Boundary())
res := httptest.NewRecorder()
im.ServeHTTP(res, req)
is.Equal(res.Code, http.StatusOK)
is.Equal(res.Body.String(), `{"data":{"link":"https://example.com/i/Igg59VTi6JNuXVriXMR3U_lzfAc","deletehash":""},"success":true,"status":200}
`)
}
{
req := httptest.NewRequest("GET", "/Igg59VTi6JNuXVriXMR3U_lzfAc", nil)
res := httptest.NewRecorder()
im.ServeHTTP(res, req)
is.Equal(res.Code, http.StatusOK)
s := base64.StdEncoding.EncodeToString(res.Body.Bytes())
is.Equal(s, testImage)
t.Log(res.Header())
is.Equal(res.Header().Get("ETag"), "Igg59VTi6JNuXVriXMR3U_lzfAc")
}
err = os.RemoveAll(dir)
is.NoErr(err)
}
func TestPost(t *testing.T) {
is := is.New(t)
ctx := context.Background()
dir, err := os.MkdirTemp("", "image")
is.NoErr(err)
im, err := image.New(ctx, dir, 0)
is.NoErr(err)
{
req := httptest.NewRequest("POST", "/i", base64.NewDecoder(base64.StdEncoding, strings.NewReader(testImage)))
res := httptest.NewRecorder()
im.ServeHTTP(res, req)
is.Equal(res.Code, http.StatusCreated)
is.Equal(res.Body.String(), `{"data":{"link":"https://example.com/i/Igg59VTi6JNuXVriXMR3U_lzfAc","deletehash":""},"success":true,"status":200}
`)
}
{
req := httptest.NewRequest("GET", "/Igg59VTi6JNuXVriXMR3U_lzfAc", nil)
res := httptest.NewRecorder()
im.ServeHTTP(res, req)
is.Equal(res.Code, http.StatusOK)
s := base64.StdEncoding.EncodeToString(res.Body.Bytes())
is.Equal(s, testImage)
}
err = os.RemoveAll(dir)
is.NoErr(err)
}