Files
mtusi2026lab5/internal/imaging/render_test.go
T

271 lines
8.0 KiB
Go

package imaging
import (
"bytes"
"context"
"encoding/binary"
"errors"
"fmt"
"hash/crc32"
"image"
"image/color"
"image/jpeg"
"image/png"
"os"
"os/exec"
"path/filepath"
"testing"
)
func TestMain(m *testing.M) {
if len(os.Args) == 2 && os.Args[1] == "--prepare-large-png" {
if err := PrepareLargePNG(os.Stdin); err != nil {
os.Exit(1)
}
return
}
os.Exit(m.Run())
}
func TestWidePNGPreservesCenterPixelAndAveragesStripes(t *testing.T) {
requireCodec(t)
img := image.NewNRGBA(image.Rect(0, 0, 70_001, 1))
for x := range img.Bounds().Dx() {
shade := uint8((x % 2) * 255)
img.SetNRGBA(x, 0, color.NRGBA{shade, shade, shade, 255})
}
img.SetNRGBA(35_000, 0, color.NRGBA{255, 0, 0, 255})
var source bytes.Buffer
if err := png.Encode(&source, img); err != nil {
t.Fatal(err)
}
results := variants(t, source.Bytes(), 1)
thumb := decodedJPEG(t, results["thumbnail"], 256, 1)
r, _, _, _ := thumb.At(2, 0).RGBA()
if r < 0x7000 || r > 0x9000 {
t.Fatalf("stripes were not averaged: %x", r)
}
crop := decodedJPEG(t, results["crop"], 128, 128)
r, g, b, _ := crop.At(64, 64).RGBA()
if r < 0xe000 || max(g, b) > 0x2000 {
t.Fatalf("center crop used reduced image: %x/%x/%x", r, g, b)
}
}
func TestWorkerPNGChildStartsWithoutServiceConfig(t *testing.T) {
if os.Getenv("CODEC_REQUIRED") != "1" {
t.Skip("run make codec-test in the packaged worker runtime")
}
cmd := exec.CommandContext(t.Context(), "worker", "--prepare-large-png")
cmd.Dir = t.TempDir()
cmd.Stdin = bytes.NewReader(testPicture(t, 70_000, 1))
if output, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("worker PNG child: %v, %s", err, output)
}
for name, wantWidth := range map[string]int{"preview.png": 1280, "center.png": 1} {
data, err := os.ReadFile(filepath.Join(cmd.Dir, name))
if err != nil {
t.Fatal(err)
}
cfg, err := png.DecodeConfig(bytes.NewReader(data))
if err != nil || cfg.Width != wantWidth || cfg.Height != 1 {
t.Fatalf("%s %dx%d: %v", name, cfg.Width, cfg.Height, err)
}
}
}
func testPicture(t *testing.T, width, height int) []byte {
t.Helper()
img := image.NewNRGBA(image.Rect(0, 0, width, height))
for y := range height {
for x := range width {
// Transparent margins, fine detail in the centre to distinguish WebP profiles.
if x >= width/4 && x < width-width/4 {
img.SetNRGBA(x, y, color.NRGBA{uint8(x * 29), uint8(y * 7), uint8(x ^ y), 255})
}
}
}
var buf bytes.Buffer
if err := png.Encode(&buf, img); err != nil {
t.Fatal(err)
}
return buf.Bytes()
}
func TestRejectInvalidSources(t *testing.T) {
huge := testPicture(t, 2, 2)
binary.BigEndian.PutUint32(huge[16:20], 20_000_001)
binary.BigEndian.PutUint32(huge[29:33], crc32.ChecksumIEEE(huge[12:29]))
for _, tc := range []struct {
name string
data []byte
version int
}{
{"unrecognized image", []byte("hello"), 1},
{"oversize body", make([]byte, (10<<20)+1), 1},
{"oversize pixel count", huge, 1},
{"unsupported version", testPicture(t, 2, 2), 3},
} {
t.Run(tc.name, func(t *testing.T) {
results, err := Render(context.Background(), tc.data, tc.version)
if !errors.Is(err, ErrInvalidImage) || len(results) != 0 {
t.Fatalf("got %d variants, err %v", len(results), err)
}
})
}
}
func requireCodec(t *testing.T) {
t.Helper()
if _, err := exec.LookPath("magick"); err != nil {
if os.Getenv("CODEC_REQUIRED") == "1" {
t.Fatal(err)
}
t.Skip("ImageMagick 7 with JPEG, PNG and WebP coders required")
}
}
func TestFortyMegapixelFixtures(t *testing.T) {
dir := os.Getenv("CODEC_FIXTURES")
if dir == "" {
t.Skip("run make codec-test CODEC_STRESS=1 with generated decoder fixtures")
}
requireCodec(t)
for _, tc := range []struct {
name string
thumbnail, optimized image.Point
}{
{"progressive-rgb-444-40mp.jpg", image.Pt(256, 160), image.Pt(1280, 800)},
{"progressive-cmyk-444-40mp.jpg", image.Pt(256, 160), image.Pt(1280, 800)},
{"wide-rgba64-40mp.png", image.Pt(256, 1), image.Pt(1280, 1)},
} {
t.Run(tc.name, func(t *testing.T) {
source, err := os.ReadFile(filepath.Join(dir, tc.name))
if err != nil {
t.Fatal(err)
}
out := variants(t, source, 1)
decodedJPEG(t, out["thumbnail"], tc.thumbnail.X, tc.thumbnail.Y)
decodedJPEG(t, out["crop"], 128, 128)
decodedWebP(t, out["optimized"], tc.optimized.X, tc.optimized.Y)
t.Logf("encoded bytes: thumbnail=%d crop=%d optimized=%d", len(out["thumbnail"].Data), len(out["crop"].Data), len(out["optimized"].Data))
})
}
}
func variants(t *testing.T, source []byte, version int) map[string]Variant {
t.Helper()
out, err := Render(context.Background(), source, version)
if err != nil {
t.Fatal(err)
}
if len(out) != 3 {
t.Fatalf("expected 3 variants, got %d", len(out))
}
result := make(map[string]Variant)
for _, v := range out {
result[v.Name] = v
}
return result
}
func decodedJPEG(t *testing.T, v Variant, width, height int) image.Image {
t.Helper()
im, err := jpeg.Decode(bytes.NewReader(v.Data))
if err != nil {
t.Fatal(err)
}
if v.MIMEType != "image/jpeg" || im.Bounds() != image.Rect(0, 0, width, height) || v.Width != width || v.Height != height {
t.Fatalf("JPEG metadata %s %dx%d, actual %v, want %dx%d", v.MIMEType, v.Width, v.Height, im.Bounds(), width, height)
}
return im
}
func decodedWebP(t *testing.T, v Variant, width, height int) {
t.Helper()
if v.MIMEType != "image/webp" || v.Width != width || v.Height != height {
t.Fatalf("invalid optimized metadata %s %dx%d", v.MIMEType, v.Width, v.Height)
}
probe := exec.Command("magick", "webp:-", "-format", "%wx%h", "info:")
probe.Stdin = bytes.NewReader(v.Data)
got, err := probe.CombinedOutput()
if err != nil || string(got) != fmt.Sprintf("%dx%d", width, height) {
t.Fatalf("decode optimized: %s, %v", got, err)
}
}
func TestRenderProfiles(t *testing.T) {
requireCodec(t)
source := testPicture(t, 1301, 707)
v1 := variants(t, source, 1)
thumb := decodedJPEG(t, v1["thumbnail"], 256, 139)
r, g, b, _ := thumb.At(7, 5).RGBA()
if min(r, g, b) < 0xf000 {
t.Fatalf("transparent thumbnail margin became %x/%x/%x", r, g, b)
}
crop := decodedJPEG(t, v1["crop"], 128, 128)
r, g, b, _ = crop.At(13, 64).RGBA()
if min(r, g, b) > 0xe000 {
t.Error("crop retained the outer transparent margin")
}
webp := v1["optimized"]
decodedWebP(t, webp, 1280, 695)
if bytes.Equal(webp.Data, variants(t, source, 2)["optimized"].Data) {
t.Error("two WebP profiles gave identical bytes on a detailed image")
}
if !bytes.Equal(webp.Data, variants(t, source, 1)["optimized"].Data) {
t.Error("same version produced different bytes")
}
}
func TestTinyRotatedJPEG(t *testing.T) {
requireCodec(t)
img := image.NewRGBA(image.Rect(0, 0, 32, 16))
for y := range 16 {
for x := range 32 {
if x < 16 {
img.Set(x, y, color.RGBA{255, 0, 0, 255})
} else {
img.Set(x, y, color.RGBA{0, 0, 255, 255})
}
}
}
var buf bytes.Buffer
if err := jpeg.Encode(&buf, img, nil); err != nil {
t.Fatal(err)
}
// APP1 with a little-endian TIFF orientation of 6 (rotate 90 degrees clockwise).
exif := []byte("\xff\xe1\x00\x22Exif\x00\x00II\x2a\x00\x08\x00\x00\x00\x01\x00\x12\x01\x03\x00\x01\x00\x00\x00\x06\x00\x00\x00\x00\x00\x00\x00")
source := bytes.Join([][]byte{buf.Bytes()[:2], exif, buf.Bytes()[2:]}, nil)
v := variants(t, source, 1)
thumb := decodedJPEG(t, v["thumbnail"], 16, 32)
r, _, b, _ := thumb.At(8, 5).RGBA()
if r < 0xc000 || b > 0x3000 {
t.Fatal("thumbnail was not rotated clockwise")
}
decodedJPEG(t, v["crop"], 128, 128)
if v["optimized"].Width != 16 || v["optimized"].Height != 32 {
t.Fatal("optimized tiny image was enlarged or not rotated")
}
for name, variant := range v {
if bytes.Contains(bytes.ToUpper(variant.Data), []byte("EXIF")) {
t.Errorf("%s retained EXIF", name)
}
}
}
func TestRenderHonorsCancelledContext(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err := Render(ctx, testPicture(t, 2, 2), 1)
if !errors.Is(err, context.Canceled) {
t.Fatalf("got %v", err)
}
}
func TestOnePixelMinorAxis(t *testing.T) {
requireCodec(t)
v := variants(t, testPicture(t, 1, 4096), 1)
decodedJPEG(t, v["thumbnail"], 1, 256)
}