1package clib
2
3import (
4 "bytes"
5 "image"
6 "image/color"
7 "image/png"
8 "testing"
9)
10
11// createTestPNG generates a small PNG image in memory for testing.
12func createTestPNG(w, h int) []byte {
13 img := image.NewRGBA(image.Rect(0, 0, w, h))
14 for y := 0; y < h; y++ {
15 for x := 0; x < w; x++ {
16 img.Set(x, y, color.RGBA{R: uint8(x), G: uint8(y), B: 128, A: 255})
17 }
18 }
19 var buf bytes.Buffer
20 png.Encode(&buf, img)
21 return buf.Bytes()
22}
23
24func TestDecodeToPNGValid(t *testing.T) {
25 input := createTestPNG(16, 32)
26
27 result, ok := DecodeToPNG(input)
28 if !ok {
29 t.Fatal("DecodeToPNG failed for valid PNG")
30 }
31 if result.Width != 16 {
32 t.Errorf("expected width=16, got %d", result.Width)
33 }
34 if result.Height != 32 {
35 t.Errorf("expected height=32, got %d", result.Height)
36 }
37 if len(result.PNGData) == 0 {
38 t.Error("expected non-empty PNG data")
39 }
40
41 // Verify output is valid PNG by decoding with Go
42 img, err := png.Decode(bytes.NewReader(result.PNGData))
43 if err != nil {
44 t.Fatalf("output is not valid PNG: %v", err)
45 }
46 if img.Bounds().Dx() != 16 || img.Bounds().Dy() != 32 {
47 t.Errorf("decoded dimensions mismatch: got %dx%d", img.Bounds().Dx(), img.Bounds().Dy())
48 }
49}
50
51func TestDecodeToPNGEmpty(t *testing.T) {
52 _, ok := DecodeToPNG(nil)
53 if ok {
54 t.Error("expected failure for nil input")
55 }
56
57 _, ok = DecodeToPNG([]byte{})
58 if ok {
59 t.Error("expected failure for empty input")
60 }
61}
62
63func TestDecodeToPNGInvalid(t *testing.T) {
64 _, ok := DecodeToPNG([]byte("not an image"))
65 if ok {
66 t.Error("expected failure for invalid image data")
67 }
68}
69
70func TestImageDimensionsValid(t *testing.T) {
71 input := createTestPNG(64, 48)
72
73 w, h, ok := ImageDimensions(input)
74 if !ok {
75 t.Fatal("ImageDimensions failed for valid PNG")
76 }
77 if w != 64 {
78 t.Errorf("expected width=64, got %d", w)
79 }
80 if h != 48 {
81 t.Errorf("expected height=48, got %d", h)
82 }
83}
84
85func TestImageDimensionsEmpty(t *testing.T) {
86 _, _, ok := ImageDimensions(nil)
87 if ok {
88 t.Error("expected failure for nil input")
89 }
90}
91
92func TestImageDimensionsInvalid(t *testing.T) {
93 _, _, ok := ImageDimensions([]byte("garbage"))
94 if ok {
95 t.Error("expected failure for invalid data")
96 }
97}