Search Apps Documentation Source Content File Folder Download Copy Actions Download State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

color_test.gno

2.04 Kb · 73 lines
 1package art
 2
 3import (
 4	"testing"
 5
 6	"gno.land/p/nt/uassert/v0"
 7)
 8
 9func TestParseHex(t *testing.T) {
10	cases := []struct {
11		name string
12		in   string
13		want int
14		ok   bool
15	}{
16		{"six with hash", "#e8c39e", 0xe8c39e, true},
17		{"six without hash", "e8c39e", 0xe8c39e, true},
18		{"uppercase", "#E8C39E", 0xe8c39e, true},
19		{"short expands by duplication", "#abc", 0xaabbcc, true},
20		{"short is not zero padded", "#abc", 0x0a0b0c, false},
21		{"surrounding space", "  #000000 ", 0x000000, true},
22		{"white", "#ffffff", 0xffffff, true},
23		{"empty is not a colour", "", Default, false},
24		{"four digits", "#abcd", Default, false},
25		{"non hex digit", "#gggggg", Default, false},
26	}
27	for _, tc := range cases {
28		got, ok := ParseHex(tc.in)
29		if !tc.ok {
30			// Either it failed to parse, or it parsed to something other than
31			// the value this case says it must not produce.
32			uassert.False(t, ok && got == tc.want, tc.name)
33			continue
34		}
35		uassert.True(t, ok, tc.name+": parsed")
36		uassert.Equal(t, tc.want, got, tc.name)
37	}
38}
39
40func TestHexRoundTrip(t *testing.T) {
41	for _, s := range []string{"#000000", "#ffffff", "#e8c39e", "#0a0b0c"} {
42		c, ok := ParseHex(s)
43		uassert.True(t, ok, s)
44		uassert.Equal(t, s, Hex(c), s)
45	}
46	uassert.Equal(t, "", Hex(Default), "Default has no hex spelling")
47}
48
49func TestRGBClamps(t *testing.T) {
50	uassert.Equal(t, 0xffffff, RGB(300, 300, 300), "over range clamps to ff")
51	uassert.Equal(t, 0x000000, RGB(-5, -5, -5), "under range clamps to 00")
52	// The point of clamping rather than masking: 256 must not alias to 0 and
53	// carry a bit into the next channel.
54	uassert.Equal(t, 0x00ff00, RGB(0, 256, 0), "256 does not carry into red")
55}
56
57func TestLuminance(t *testing.T) {
58	cases := []struct {
59		name string
60		in   int
61		want int
62	}{
63		{"black", 0x000000, 0},
64		{"white", 0xffffff, 255},
65		{"pure green is the brightest primary", 0x00ff00, 182},
66		{"pure blue is the darkest primary", 0x0000ff, 18},
67		{"pure red", 0xff0000, 54},
68		{"Default reads as black", Default, 0},
69	}
70	for _, tc := range cases {
71		uassert.Equal(t, tc.want, Luminance(tc.in), tc.name)
72	}
73}