a73x

internal/site/og_test.go

Ref:   Size: 2.6 KiB   History

package site

import (
	"bytes"
	"image"
	"image/png"
	"strings"
	"testing"
)

func decodeCard(t *testing.T, label string) image.Image {
	t.Helper()
	raw, err := renderCard(label)
	if err != nil {
		t.Fatal(err)
	}
	img, format, err := image.Decode(bytes.NewReader(raw))
	if err != nil {
		t.Fatal(err)
	}
	if format != "png" {
		t.Fatalf("format = %q, want png", format)
	}
	return img
}

// Every scraper crops to 1200x630; a card of any other size gets letterboxed.
func TestRenderCardIsTheScraperSize(t *testing.T) {
	got := decodeCard(t, "quickstart").Bounds()
	if want := image.Rect(0, 0, 1200, 630); got != want {
		t.Errorf("bounds = %v, want %v", got, want)
	}
}

func TestRenderCardDrawsInkOnTheBackground(t *testing.T) {
	img := decodeCard(t, "quickstart")
	bg := cardPalette[cardBG]
	if got := img.At(0, 0); got != bg {
		t.Errorf("corner = %v, want the background %v", got, bg)
	}
	var ink int
	b := img.Bounds()
	for y := b.Min.Y; y < b.Max.Y; y++ {
		for x := b.Min.X; x < b.Max.X; x++ {
			if img.At(x, y) != bg {
				ink++
			}
		}
	}
	// The block is mark plus three lines of text: tens of thousands of
	// pixels. A near-empty card means the font or the layout went missing.
	if ink < 20000 {
		t.Errorf("card carries %d ink pixels, want a drawn block", ink)
	}
}

// The card is per-page, so the label has to reach the image.
func TestRenderCardLabelChangesTheImage(t *testing.T) {
	quickstart, err := renderCard("quickstart")
	if err != nil {
		t.Fatal(err)
	}
	faq, err := renderCard("faq")
	if err != nil {
		t.Fatal(err)
	}
	if bytes.Equal(quickstart, faq) {
		t.Error("two labels produced the same card")
	}
	home, err := renderCard("")
	if err != nil {
		t.Fatal(err)
	}
	if bytes.Equal(home, quickstart) {
		t.Error("the unlabelled card matches a labelled one")
	}
}

// A label wider than the card would be cropped by whoever renders it.
func TestRenderCardRejectsAnOverlongLabel(t *testing.T) {
	if _, err := renderCard(strings.Repeat("long ", 12)); err == nil {
		t.Error("want an error: the label does not fit the card")
	}
}

func TestRenderCardRejectsUndrawableLabel(t *testing.T) {
	if _, err := renderCard("日本語"); err == nil {
		t.Error("want an error: the font has no glyph for these runes")
	}
}

// A paletted three-colour card should stay small enough to inline anywhere.
func TestRenderCardStaysSmall(t *testing.T) {
	raw, err := renderCard("credential revocation")
	if err != nil {
		t.Fatal(err)
	}
	if len(raw) > 40_000 {
		t.Errorf("card is %d bytes, want under 40KB", len(raw))
	}
	if _, err := png.Decode(bytes.NewReader(raw)); err != nil {
		t.Fatal(err)
	}
}