Files
mtusi2026lab5/internal/messenger/attachment/transform/processor_test.go
T

262 lines
8.1 KiB
Go

package transform
import (
"bytes"
"context"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"errors"
"image"
"image/color"
"image/jpeg"
"image/png"
"testing"
"github.com/deepteams/webp"
)
func TestProcessProducesExpectedVariants(t *testing.T) {
source := image.NewNRGBA(image.Rect(0, 0, 320, 200))
fillGradient(source)
data := encodePNG(t, source)
processor := newTestProcessor(t, int64(len(data))+1, 320*200)
result, err := processor.Process(context.Background(), data, "image/png")
if err != nil {
t.Fatalf("process image: %v", err)
}
assertVariant(t, result.Original, "image/png", 320, 200)
assertVariant(t, result.Thumbnail, "image/jpeg", 256, 160)
assertVariant(t, result.Crop, "image/jpeg", 128, 128)
assertVariant(t, result.Optimized, "image/webp", 320, 200)
if !bytes.Equal(result.Original.Bytes, data) {
t.Fatal("original bytes changed")
}
digest := sha256.Sum256(data)
if result.Original.SHA256 != hex.EncodeToString(digest[:]) {
t.Fatalf("unexpected original digest: %s", result.Original.SHA256)
}
if _, err := webp.Decode(bytes.NewReader(result.Optimized.Bytes)); err != nil {
t.Fatalf("decode optimized WebP: %v", err)
}
}
func TestProcessDoesNotUpscaleFitVariants(t *testing.T) {
source := image.NewNRGBA(image.Rect(0, 0, 64, 32))
fillGradient(source)
data := encodePNG(t, source)
processor := newTestProcessor(t, int64(len(data))+1, 64*32)
result, err := processor.Process(context.Background(), data, "image/png")
if err != nil {
t.Fatalf("process image: %v", err)
}
assertVariant(t, result.Thumbnail, "image/jpeg", 64, 32)
assertVariant(t, result.Optimized, "image/webp", 64, 32)
assertVariant(t, result.Crop, "image/jpeg", 128, 128)
}
func TestFlattenWhiteCompositesAlpha(t *testing.T) {
source := image.NewNRGBA(image.Rect(0, 0, 2, 1))
source.SetNRGBA(0, 0, color.NRGBA{R: 10, G: 20, B: 30, A: 0})
source.SetNRGBA(1, 0, color.NRGBA{R: 100, G: 50, B: 0, A: 128})
result, err := flattenWhite(context.Background(), source)
if err != nil {
t.Fatalf("flatten image: %v", err)
}
if got := result.NRGBAAt(0, 0); got != (color.NRGBA{R: 255, G: 255, B: 255, A: 255}) {
t.Fatalf("transparent pixel: got %#v", got)
}
if got := result.NRGBAAt(1, 0); got != (color.NRGBA{R: 177, G: 152, B: 127, A: 255}) {
t.Fatalf("semi-transparent pixel: got %#v", got)
}
}
func TestProcessAppliesEXIFOrientation(t *testing.T) {
source := image.NewNRGBA(image.Rect(0, 0, 3, 2))
fillGradient(source)
data := injectOrientation(t, encodeJPEGForTest(t, source), 6)
processor := newTestProcessor(t, int64(len(data))+1, 3*2)
result, err := processor.Process(context.Background(), data, "image/jpeg")
if err != nil {
t.Fatalf("process image: %v", err)
}
if result.Orientation != 6 {
t.Fatalf("orientation: got %d, want 6", result.Orientation)
}
assertVariant(t, result.Original, "image/jpeg", 3, 2)
assertVariant(t, result.Thumbnail, "image/jpeg", 2, 3)
assertVariant(t, result.Optimized, "image/webp", 2, 3)
}
func TestProcessRejectsInvalidInputs(t *testing.T) {
valid := encodePNG(t, image.NewNRGBA(image.Rect(0, 0, 11, 10)))
tests := []struct {
name string
data []byte
contentType string
maxPixels int64
want error
}{
{name: "MIME mismatch", data: valid, contentType: "image/jpeg", maxPixels: 200, want: ErrUnsupportedMedia},
{name: "unsupported MIME", data: valid, contentType: "image/gif", maxPixels: 200, want: ErrUnsupportedMedia},
{name: "pixel limit", data: valid, contentType: "image/png", maxPixels: 100, want: ErrPayloadTooLarge},
{name: "corrupted", data: valid[:len(valid)-12], contentType: "image/png", maxPixels: 200, want: ErrInvalidImage},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
processor := newTestProcessor(t, int64(len(valid))+1, test.maxPixels)
_, err := processor.Process(context.Background(), test.data, test.contentType)
if !errors.Is(err, test.want) {
t.Fatalf("error: got %v, want %v", err, test.want)
}
})
}
}
func TestProcessIsDeterministic(t *testing.T) {
source := image.NewNRGBA(image.Rect(0, 0, 48, 31))
fillGradient(source)
data := encodePNG(t, source)
processor := newTestProcessor(t, int64(len(data))+1, 48*31)
first, err := processor.Process(context.Background(), data, "image/png")
if err != nil {
t.Fatalf("first process: %v", err)
}
second, err := processor.Process(context.Background(), data, "image/png")
if err != nil {
t.Fatalf("second process: %v", err)
}
for name, variants := range map[string][2]Variant{
"thumbnail": {first.Thumbnail, second.Thumbnail},
"crop": {first.Crop, second.Crop},
"optimized": {first.Optimized, second.Optimized},
} {
if !bytes.Equal(variants[0].Bytes, variants[1].Bytes) {
t.Fatalf("%s bytes differ", name)
}
}
}
func TestProcessHonorsCanceledContext(t *testing.T) {
processor := newTestProcessor(t, 1024, 100)
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err := processor.Process(ctx, []byte("unused"), "image/png")
if !errors.Is(err, context.Canceled) {
t.Fatalf("error: got %v, want %v", err, context.Canceled)
}
}
func TestResizeStopsAfterCancellation(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
source := cancelingImage{
Image: image.NewNRGBA(image.Rect(0, 0, 256, 256)),
cancel: cancel,
}
_, err := resizeContext(ctx, source, 128, 128)
if !errors.Is(err, context.Canceled) {
t.Fatalf("error: got %v, want %v", err, context.Canceled)
}
}
type cancelingImage struct {
image.Image
cancel context.CancelFunc
}
func (i cancelingImage) At(x, y int) color.Color {
i.cancel()
return i.Image.At(x, y)
}
func TestEstimateMemoryWeight(t *testing.T) {
weight, err := EstimateMemoryWeight(1000, 320, 200)
if err != nil {
t.Fatalf("estimate memory: %v", err)
}
want := int64(1000 + 320*200*16 + (320*200+256*160+128*128)*4)
if weight != want {
t.Fatalf("weight: got %d, want %d", weight, want)
}
}
func newTestProcessor(t *testing.T, maxBytes, maxPixels int64) *Processor {
t.Helper()
processor, err := NewProcessor(DefaultConfig(maxBytes, maxPixels))
if err != nil {
t.Fatalf("new processor: %v", err)
}
return processor
}
func assertVariant(t *testing.T, variant Variant, contentType string, width, height int) {
t.Helper()
if variant.ContentType != contentType || variant.Width != width || variant.Height != height {
t.Fatalf("variant: got type=%s dimensions=%dx%d, want type=%s dimensions=%dx%d",
variant.ContentType, variant.Width, variant.Height, contentType, width, height)
}
if len(variant.Bytes) == 0 || variant.SHA256 == "" {
t.Fatal("variant has no bytes or digest")
}
}
func fillGradient(img *image.NRGBA) {
for y := 0; y < img.Bounds().Dy(); y++ {
for x := 0; x < img.Bounds().Dx(); x++ {
img.SetNRGBA(x, y, color.NRGBA{R: uint8(x), G: uint8(y), B: uint8(x + y), A: 255})
}
}
}
func encodePNG(t *testing.T, img image.Image) []byte {
t.Helper()
var output bytes.Buffer
if err := png.Encode(&output, img); err != nil {
t.Fatalf("encode PNG: %v", err)
}
return output.Bytes()
}
func encodeJPEGForTest(t *testing.T, img image.Image) []byte {
t.Helper()
var output bytes.Buffer
if err := jpeg.Encode(&output, img, &jpeg.Options{Quality: 100}); err != nil {
t.Fatalf("encode JPEG: %v", err)
}
return output.Bytes()
}
func injectOrientation(t *testing.T, data []byte, orientation uint16) []byte {
t.Helper()
if len(data) < 2 || data[0] != 0xff || data[1] != 0xd8 {
t.Fatal("not a JPEG")
}
tiff := make([]byte, 26)
copy(tiff[:2], "II")
binary.LittleEndian.PutUint16(tiff[2:4], 42)
binary.LittleEndian.PutUint32(tiff[4:8], 8)
binary.LittleEndian.PutUint16(tiff[8:10], 1)
binary.LittleEndian.PutUint16(tiff[10:12], 0x0112)
binary.LittleEndian.PutUint16(tiff[12:14], 3)
binary.LittleEndian.PutUint32(tiff[14:18], 1)
binary.LittleEndian.PutUint16(tiff[18:20], orientation)
payload := append([]byte("Exif\x00\x00"), tiff...)
segment := []byte{0xff, 0xe1, 0, 0}
binary.BigEndian.PutUint16(segment[2:4], uint16(len(payload)+2))
result := make([]byte, 0, len(data)+len(segment)+len(payload))
result = append(result, data[:2]...)
result = append(result, segment...)
result = append(result, payload...)
return append(result, data[2:]...)
}