collage-maker/collage/collage_test.go

127 lines
2.2 KiB
Go

package collage
import (
"embed"
"fmt"
"image"
"image/jpeg"
"io"
"io/fs"
"log"
"os"
"testing"
)
//go:embed test_data/*
var testData embed.FS
var testDataFS fs.FS
func init() {
var err error
testDataFS, err = fs.Sub(testData, "test_data")
if err != nil {
log.Panicf("getting test_data subdir failed %v", err)
}
}
func TestMake(t *testing.T) {
req := Request{
BackgroundImage: "",
Aspect: Dimension{
Width: 816 * 4,
Height: 528 * 4 * 2,
},
Dimension: Dimension{
Width: 816,
Height: 528 * 2,
},
Photos: []Photo{
{
ImageName: "img1.jpg",
Crop: Rectangle{
Start: Point{
X: 431,
Y: 697,
},
End: Point{
X: 2514,
Y: 2047,
},
},
Frame: Rectangle{
Start: Point{
X: 0,
Y: 0,
},
End: Point{
X: 816,
Y: 528,
},
},
},
},
}
out, err := os.Create("./test_op.jpg")
if err != nil {
t.Fatalf("failed to create ouput image file %v", err)
}
err = Make(&req, testDataFS, out)
if err != nil {
t.Fatalf("failed to make collage %v", err)
}
}
func TestCrop(t *testing.T) {
img, err := GetImage(testDataFS, "img1.jpg")
if err != nil {
t.Fatalf("failed to get image %v", err)
}
r := Rectangle{
Start: Point{X: 431, Y: 697},
End: Point{X: 2514, Y: 2047},
}
cropped, err := Crop(img, r)
if err != nil {
t.Fatalf("failed to crop image %v", err)
}
croppedImgPrefix := fmt.Sprint(cropped)[:1000]
refPrefixf, err := testDataFS.Open("cropped_image_prefix.txt")
if err != nil {
t.Fatalf("failed to open ref prefix %v", err)
}
refImgPrefix, err := io.ReadAll(refPrefixf)
if err != nil {
t.Fatalf("failed to read ref prefix %v", err)
}
if string(refImgPrefix) != croppedImgPrefix {
t.Fatalf("Cropped image is not the same as reference image")
}
}
// Save first 1000 bytes of string representation to compare against reference
func SavePrefix(img image.Image) error {
imgStr := fmt.Sprint(img)
prefix := imgStr[:1000]
return os.WriteFile("./test_data_prefix.txt", []byte(prefix), 0644)
}
func SaveImage(img image.Image) {
out, err := os.Create("./test_output.jpg")
if err != nil {
fmt.Println(err)
}
var opt jpeg.Options
opt.Quality = 100
jpeg.Encode(out, img, &opt)
}