74 lines
1.8 KiB
Go
74 lines
1.8 KiB
Go
package media
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"image"
|
|
"image/color"
|
|
"image/jpeg"
|
|
"image/png"
|
|
"testing"
|
|
)
|
|
|
|
func testPNG(t *testing.T, w, h int) []byte {
|
|
t.Helper()
|
|
img := image.NewRGBA(image.Rect(0, 0, w, h))
|
|
for x := 0; x < w; x++ {
|
|
for y := 0; y < h; y++ {
|
|
img.Set(x, y, color.RGBA{R: uint8(x % 256), G: uint8(y % 256), B: 120, A: 255})
|
|
}
|
|
}
|
|
var buf bytes.Buffer
|
|
if err := png.Encode(&buf, img); err != nil {
|
|
t.Fatalf("png.Encode: %v", err)
|
|
}
|
|
return buf.Bytes()
|
|
}
|
|
|
|
func TestGenerateSkipsSmallImage(t *testing.T) {
|
|
data := testPNG(t, 64, 64)
|
|
out, err := Generate(context.Background(), bytes.NewReader(data), "image/png", 256)
|
|
if err != nil {
|
|
t.Fatalf("Generate: %v", err)
|
|
}
|
|
if out != nil {
|
|
t.Fatalf("small image produced thumbnail, want nil")
|
|
}
|
|
}
|
|
|
|
func TestGenerateResizesLargeImage(t *testing.T) {
|
|
data := testPNG(t, 512, 512)
|
|
out, err := Generate(context.Background(), bytes.NewReader(data), "image/png", 256)
|
|
if err != nil {
|
|
t.Fatalf("Generate: %v", err)
|
|
}
|
|
if out == nil {
|
|
t.Fatal("large image produced nil thumbnail")
|
|
}
|
|
img, err := jpeg.Decode(bytes.NewReader(out))
|
|
if err != nil {
|
|
t.Fatalf("thumbnail is not valid JPEG: %v", err)
|
|
}
|
|
b := img.Bounds()
|
|
if b.Dx() > 256 || b.Dy() > 256 {
|
|
t.Fatalf("thumbnail size = %dx%d, want <= 256x256", b.Dx(), b.Dy())
|
|
}
|
|
}
|
|
|
|
func TestGenerateNonImageReturnsNil(t *testing.T) {
|
|
out, err := Generate(context.Background(), bytes.NewReader([]byte("plain")), "text/plain", 256)
|
|
if err != nil {
|
|
t.Fatalf("Generate: %v", err)
|
|
}
|
|
if out != nil {
|
|
t.Fatal("non-image produced thumbnail, want nil")
|
|
}
|
|
}
|
|
|
|
func TestGenerateCorruptImageFails(t *testing.T) {
|
|
_, err := Generate(context.Background(), bytes.NewReader([]byte("not an image")), "image/png", 256)
|
|
if err == nil {
|
|
t.Fatal("corrupt image: Generate = nil error, want error")
|
|
}
|
|
}
|