forked from mtusi2026/mtusi2026lab5
74 lines
2.1 KiB
Go
74 lines
2.1 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"image"
|
|
"image/color"
|
|
"image/jpeg"
|
|
"os/exec"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
func TestImageContract(t *testing.T) {
|
|
im := image.NewNRGBA(image.Rect(0, 0, 320, 200))
|
|
im.SetNRGBA(160, 100, color.NRGBA{R: 255, A: 128})
|
|
data, w, h, err := thumbnail(im)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
cfg, err := jpeg.DecodeConfig(bytes.NewReader(data))
|
|
if err != nil || w != 256 || h != 160 || cfg.Width != 256 || cfg.Height != 160 {
|
|
t.Fatal("thumbnail contract", cfg, err)
|
|
}
|
|
// Transparent input must become white, not black.
|
|
small := image.NewNRGBA(image.Rect(0, 0, 8, 4))
|
|
data, w, h, err = thumbnail(small)
|
|
decoded, err := jpeg.Decode(bytes.NewReader(data))
|
|
if err != nil || w != 8 || h != 4 {
|
|
t.Fatal("small image enlarged", err)
|
|
}
|
|
r, g, b, _ := decoded.At(0, 0).RGBA()
|
|
if r < 65000 || g < 65000 || b < 65000 {
|
|
t.Fatal("alpha not composited on white")
|
|
}
|
|
}
|
|
|
|
func TestRetryDelayBounds(t *testing.T) {
|
|
for attempt := 1; attempt <= 12; attempt++ {
|
|
ceiling := time.Second << min(attempt-1, 6)
|
|
for i := 0; i < 100; i++ {
|
|
delay := retryDelay(attempt)
|
|
if delay < ceiling/2 || delay > ceiling {
|
|
t.Fatalf("attempt %d delay %s outside [%s, %s]", attempt, delay, ceiling/2, ceiling)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
func TestRealVariants(t *testing.T) {
|
|
if _, err := exec.LookPath("cwebp"); err != nil {
|
|
t.Skip("cwebp is installed in the worker image")
|
|
}
|
|
outputs, err := variants(context.Background(), image.NewRGBA(image.Rect(0, 0, 320, 200)))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for _, output := range outputs {
|
|
sum := sha256.Sum256(output.data)
|
|
if hex.EncodeToString(sum[:]) != output.meta.SHA256 || int64(len(output.data)) != output.meta.SizeBytes {
|
|
t.Fatalf("%s bytes differ from metadata", output.meta.Name)
|
|
}
|
|
}
|
|
crop, err := jpeg.DecodeConfig(bytes.NewReader(outputs[1].data))
|
|
if err != nil || crop.Width != 128 || crop.Height != 128 {
|
|
t.Fatal("crop", err)
|
|
}
|
|
webp := outputs[2]
|
|
if webp.meta.Width != 320 || webp.meta.Height != 200 || !bytes.Equal(webp.data[:4], []byte("RIFF")) || !bytes.Equal(webp.data[8:12], []byte("WEBP")) {
|
|
t.Fatal("WebP contract")
|
|
}
|
|
}
|