internal/httpd/chip_test.go

v1.22.1
gitbay/internal/httpd/chip_test.go history · blame · raw

43 lines · 1250 bytes

 1package httpd
 2
 3import (
 4	"math"
 5	"strconv"
 6	"testing"
 7)
 8
 9// relLum is WCAG relative luminance of a #rrggbb colour.
10func relLum(hex string) float64 {
11	lin := func(s string) float64 {
12		n, _ := strconv.ParseInt(s, 16, 32)
13		v := float64(n) / 255
14		if v <= 0.04045 {
15			return v / 12.92
16		}
17		return math.Pow((v+0.055)/1.055, 2.4)
18	}
19	return 0.2126*lin(hex[1:3]) + 0.7152*lin(hex[3:5]) + 0.0722*lin(hex[5:7])
20}
21
22// A label colour is text on the chip. The palette passes through; a
23// stored yellow, white, black or pastel comes back with a luminance that
24// clears 3:1 against both white and the dark ground (#120).
25func TestClampChip(t *testing.T) {
26	for _, keep := range labelPalette {
27		if got := clampChip(keep); got != keep {
28			t.Errorf("palette colour %s changed to %s", keep, got)
29		}
30	}
31	for _, in := range []string{"#ffff00", "#FFFFFF", "#000000", "#ffcccc", "#00ff00", "#101010"} {
32		got := clampChip(in)
33		y := relLum(got)
34		onWhite := 1.05 / (y + 0.05)
35		onDark := (y + 0.05) / (relLum("#0a0a0a") + 0.05)
36		if onWhite < 3 || onDark < 3 {
37			t.Errorf("clampChip(%s) = %s: %.2f:1 on white, %.2f:1 on dark", in, got, onWhite, onDark)
38		}
39	}
40	if got := clampChip("#ffff00"); got == "#ffff00" {
41		t.Error("yellow passed through unchanged")
42	}
43}