Luigit
repositories / bugabinga.net

bugabinga.net

personal infrastructure for bugabinga!

owned by admin

services/luci/internal/web/css_contract_test.go

Raw
package web

import (
	"regexp"
	"strings"
	"testing"
)

func cssMatch(css, pattern string) bool {
	matched, err := regexp.MatchString(pattern, css)
	return err == nil && matched
}

func embeddedPageCSS(t *testing.T, body string) string {
	t.Helper()
	const open = "<style>"
	const close = "</style>"
	start := strings.Index(body, open)
	if start < 0 {
		t.Fatal("embedded page style missing")
	}
	start += len(open)
	end := strings.Index(body[start:], close)
	if end < 0 {
		t.Fatal("embedded page style is not closed")
	}
	css := body[start : start+end]
	if strings.TrimSpace(css) == "" {
		t.Fatal("embedded page style is empty")
	}
	return css
}

func TestCSSContractMatcher(t *testing.T) {
	const factsRule = `(?:^|[{}])\s*\.facts\s+span\s*\{\s*min-width\s*:\s*0\s*;\s*overflow-wrap\s*:\s*anywhere\s*;?\s*\}`
	const mediaRule = `@media\s*\(\s*max-width\s*:\s*700px\s*\)`
	const maxHeight = `max-height\s*:\s*60vh\s*;?`
	const minified = `.facts span{min-width:0;overflow-wrap:anywhere}@media(max-width:700px){.facts span{max-height:60vh}}`
	const formatted = ".facts span { min-width: 0; overflow-wrap: anywhere; }\n@media (max-width: 700px) { .facts span { max-height: 60vh; } }"

	for _, test := range []struct {
		name, css, pattern string
		want               bool
	}{
		{"minified facts rule", minified, factsRule, true},
		{"formatted facts rule", formatted, factsRule, true},
		{"minified media rule", minified, mediaRule, true},
		{"formatted media rule", formatted, mediaRule, true},
		{"minified max height", minified, maxHeight, true},
		{"formatted max height", formatted, maxHeight, true},
		{"altered selector", `.facts > span{min-width:0;overflow-wrap:anywhere}`, factsRule, false},
		{"altered property", `.facts span{min-width:0;word-break:anywhere}`, factsRule, false},
		{"altered value", `.facts span{min-width:0;overflow-wrap:normal}`, factsRule, false},
		{"collapsed descendant", `.factsspan{min-width:0;overflow-wrap:anywhere}`, factsRule, false},
		{"wrong palette role", `:root { --raised: var(--nugu-ui-focus,#dbdbdb); }`, `--raised\s*:\s*var\s*\(\s*--nugu-ui-backdrop\s*,\s*#dbdbdb\s*\)`, false},
	} {
		t.Run(test.name, func(t *testing.T) {
			if got := cssMatch(test.css, test.pattern); got != test.want {
				t.Fatalf("cssMatch() = %t, want %t: %q", got, test.want, test.css)
			}
		})
	}
}