collage-maker/collage/collage_test.go

138 lines
2.6 KiB
Go
Raw Permalink Normal View History

2023-08-11 00:27:32 -04:00
package collage
import (
"embed"
"fmt"
2023-08-11 22:16:24 -04:00
"image"
"image/jpeg"
"io"
2023-08-11 00:27:32 -04:00
"io/fs"
2023-08-11 22:16:24 -04:00
"log"
"os"
2023-08-11 00:27:32 -04:00
"testing"
)
//go:embed test_data/*
var testData embed.FS
2023-08-11 22:16:24 -04:00
var testDataFS fs.FS
func init() {
var err error
testDataFS, err = fs.Sub(testData, "test_data")
2023-08-11 00:27:32 -04:00
if err != nil {
2023-08-11 22:16:24 -04:00
log.Panicf("getting test_data subdir failed %v", err)
2023-08-11 00:27:32 -04:00
}
2023-08-11 22:16:24 -04:00
}
func TestMake(t *testing.T) {
2023-08-11 23:20:53 -04:00
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")
2023-08-11 00:27:32 -04:00
if err != nil {
2023-08-11 23:20:53 -04:00
t.Fatalf("failed to create ouput image file %v", err)
2023-08-11 00:27:32 -04:00
}
2023-08-11 23:20:53 -04:00
err = Make(req, testDataFS, out)
if err != nil {
t.Fatalf("failed to make collage %v", err)
}
2023-08-11 00:27:32 -04:00
}
2023-08-11 22:16:24 -04:00
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")
}
// SavePrefix(cropped)
// expectedImage, err := GetImage(testDataFS, "test_output.jpg")
// if err != nil {
// t.Fatalf("failed to get reference crop image %v", err)
// }
// fmt.Printf("%v\n", cropped)
// fmt.Printf("%v\n", expectedImage)
// if fmt.Sprintf("%#v", cropped) != fmt.Sprintf("%#v", expectedImage) {
// t.Fatalf("Cropped image is not the same as reference image")
// }
// SaveImage(cropped)
}
// 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)
}