v4/templates/components/role_test.go
2025-04-05 23:38:02 -07:00

58 lines
2.1 KiB
Go

package components_test
import (
"bytes"
"fmt"
"html/template"
"testing"
"git.sapphic.engineer/roleypoly/v4/presentation"
"git.sapphic.engineer/roleypoly/v4/templates"
"git.sapphic.engineer/roleypoly/v4/types"
"git.sapphic.engineer/roleypoly/v4/types/fixtures"
"git.sapphic.engineer/roleypoly/v4/utils"
"github.com/stretchr/testify/assert"
)
var (
Templates = template.Must(template.ParseFS(templates.FS, "components/*.html"))
)
func renderRole(t *testing.T, c *types.Category, r *types.Role, s bool) string {
data := presentation.Role(c, r, s)
buf := bytes.Buffer{}
err := Templates.ExecuteTemplate(&buf, "role.html", data)
if err != nil {
t.Fatal("template failed to render", err)
}
return buf.String()
}
func TestRole(t *testing.T) {
c := &fixtures.CategoryMulti
r := &fixtures.RoleWithDarkColor
html := renderRole(t, c, r, false)
assert.Contains(t, html, "--role-color: #a20000;", "role color is set")
assert.Contains(t, html, `type="checkbox"`, "multi has input type=checkbox")
assert.Contains(t, html, fmt.Sprintf("--contrast-color: %s;", utils.RgbToString(utils.AltColor(162, 0, 0))), "contrast color is set")
assert.Contains(t, html, fmt.Sprintf(`id="%s"`, roleInputID(c, r)), "input has ID attr")
assert.Contains(t, html, fmt.Sprintf(`for="%s"`, roleInputID(c, r)), "label has for attr")
assert.NotContains(t, html, fmt.Sprintf(`name="%s"`, roleInputName(c)), "multi has no name attr")
// TODO: selected?
c = &fixtures.CategorySingle
r = &fixtures.RoleWithLightColor
html = renderRole(t, c, r, true)
assert.Contains(t, html, `type="radio"`, "single has input type=radio")
assert.Contains(t, html, fmt.Sprintf("--contrast-color: %s;", utils.RgbToString(utils.AltColor(0xff, 0xaa, 0x88))), "contrast color")
assert.Contains(t, html, fmt.Sprintf(`name="%s"`, roleInputName(c)), "single has name attr")
}
// TODO: these can probably be string utils that are injected as functions into template
func roleInputID(c *types.Category, r *types.Role) string {
return fmt.Sprintf("category-%s_role-%s", c.ID, r.ID)
}
func roleInputName(c *types.Category) string {
return fmt.Sprintf("category_group_%s", c.ID)
}