internal/httpd/badgepng_test.go

5daf169d25da8ed4b6ac17d1c7becff026f45513
gitbay/internal/httpd/badgepng_test.go history · blame · raw

69 lines · 2105 bytes

 1package httpd
 2
 3import (
 4	"bytes"
 5	"image"
 6	"image/color"
 7	"image/png"
 8	"testing"
 9)
10
11func decodeBadge(t *testing.T, label, state string) image.Image {
12	t.Helper()
13	out, err := badgePNG(label, state)
14	if err != nil {
15		t.Fatalf("badgePNG(%q, %q): %v", label, state, err)
16	}
17	img, err := png.Decode(bytes.NewReader(out))
18	if err != nil {
19		t.Fatalf("decode %q: %v", state, err)
20	}
21	return img
22}
23
24func TestBadgePNGGeometry(t *testing.T) {
25	img := decodeBadge(t, "build", "success")
26	if got, want := img.Bounds().Dy(), badgeHeight*badgeScale; got != want {
27		t.Errorf("height = %d, want %d", got, want)
28	}
29	// A longer label makes a wider badge; the pill is sized to its text.
30	if decodeBadge(t, "integration", "success").Bounds().Dx() <= img.Bounds().Dx() {
31		t.Error("a longer label did not widen the badge")
32	}
33}
34
35func TestBadgePNGUsesTheStateColour(t *testing.T) {
36	// A point inside the right-hand pill, clear of the rounded corners.
37	for state, hex := range badgeColors {
38		img := decodeBadge(t, "build", state)
39		b := img.Bounds()
40		got := color.RGBAModel.Convert(img.At(b.Max.X-4, b.Dy()/2)).(color.RGBA)
41		if want := mustHex(hex); got != want {
42			t.Errorf("%s: pill colour = %v, want %v", state, got, want)
43		}
44	}
45}
46
47// An unknown state takes the grey the SVG gives it rather than a transparent pill.
48func TestBadgePNGUnknownStateFallsBack(t *testing.T) {
49	img := decodeBadge(t, "build", "no-such-state")
50	b := img.Bounds()
51	got := color.RGBAModel.Convert(img.At(b.Max.X-4, b.Dy()/2)).(color.RGBA)
52	if want := mustHex(badgeColors["unknown"]); got != want {
53		t.Errorf("pill colour = %v, want %v", got, want)
54	}
55}
56
57// The corners are rounded, so the very corner pixel is left transparent.
58func TestBadgePNGCornersAreRounded(t *testing.T) {
59	img := decodeBadge(t, "build", "success")
60	if _, _, _, a := img.At(img.Bounds().Min.X, img.Bounds().Min.Y).RGBA(); a != 0 {
61		t.Errorf("top-left alpha = %d, want 0", a)
62	}
63}
64
65func TestMustHex(t *testing.T) {
66	if got, want := mustHex("#2da44e"), (color.RGBA{R: 0x2d, G: 0xa4, B: 0x4e, A: 255}); got != want {
67		t.Errorf("mustHex = %v, want %v", got, want)
68	}
69}