1
0
html/query_test.go

151 lines
3.2 KiB
Go

package html_test
import (
"bytes"
"code.squareroundforest.org/arpio/html"
. "code.squareroundforest.org/arpio/html/tag"
"testing"
)
func TestQuery(t *testing.T) {
t.Run("group children", func(t *testing.T) {
inlineDiv := html.Inline(Div(Attr("foo", "bar"), "baz"))
attr := html.AllAttributes(inlineDiv)
if len(attr.Names()) != 1 || attr.Value("foo") != "bar" {
t.Fatal()
}
c := html.Children(inlineDiv)
if len(c) != 1 || c[0] != "baz" {
t.Fatal()
}
var b bytes.Buffer
if err := html.WriteRaw(&b, inlineDiv); err != nil {
t.Fatal(err)
}
h := b.String()
if h != `<div foo="bar">baz</div>` {
t.Fatal()
}
})
t.Run("merge attributes", func(t *testing.T) {
t.Run("has attributes", func(t *testing.T) {
div := Div(Attr("foo", "bar"))
attr := html.AllAttributes(div)
if len(attr.Names()) != 1 || attr.Value("foo") != "bar" {
t.Fatal()
}
})
t.Run("no attributes", func(t *testing.T) {
div := Div()
attr := html.AllAttributes(div)
if len(attr.Names()) != 0 {
t.Fatal()
}
})
})
t.Run("find attributes", func(t *testing.T) {
t.Run("exists", func(t *testing.T) {
div := Div(Attr("foo", "bar"))
if html.Attribute(div, "foo") != "bar" {
t.Fatal()
}
})
t.Run("does not exist", func(t *testing.T) {
div := Div(Attr("foo", "bar"))
if html.Attribute(div, "qux") != nil {
t.Fatal()
}
})
})
t.Run("handle query", func(t *testing.T) {
t.Run("no chlidren", func(t *testing.T) {
div := Div()
div2 := div()
if html.Name(div2) != "div" || !html.Eq(div, div2) {
t.Fatal(html.Name(div2))
}
})
t.Run("name", func(t *testing.T) {
div := Div()
if html.Name(div) != "div" {
t.Fatal()
}
})
t.Run("all attributes", func(t *testing.T) {
div := Div(Attr("foo", "bar", "baz", "qux"))
attr := html.AllAttributes(div)
if len(attr.Names()) != 2 || attr.Value("foo") != "bar" || attr.Value("baz") != "qux" {
t.Fatal()
}
})
t.Run("one attribute", func(t *testing.T) {
div := Div(Attr("foo", "bar", "baz", "qux"))
foo := html.Attribute(div, "foo")
if foo != "bar" {
t.Fatal()
}
})
t.Run("children", func(t *testing.T) {
div := Div("foo", "bar", "baz")
c := html.Children(div)
if len(c) != 3 || c[0] != "foo" || c[1] != "bar" || c[2] != "baz" {
t.Fatal()
}
})
t.Run("render guides", func(t *testing.T) {
div := Div(Span("foo"))
var b bytes.Buffer
if err := html.Write(&b, div); err != nil {
t.Fatal(err)
}
if b.String() != "<div>\n\t<span>foo</span>\n</div>" {
t.Fatal(b.String())
}
})
t.Run("validate and render", func(t *testing.T) {
t.Run("valid", func(t *testing.T) {
script := Script(`function() { return "Hello, world!" }`)
var b bytes.Buffer
if err := html.WriteRaw(&b, script); err != nil {
t.Fatal(err)
}
})
t.Run("invalid", func(t *testing.T) {
div := Div(Attr("foo+", "bar"))
var b bytes.Buffer
if err := html.WriteRaw(&b, div); err == nil {
t.Fatal()
}
})
t.Run("invalid child", func(t *testing.T) {
div := Div(Div(Attr("foo+", "bar")))
var b bytes.Buffer
if err := html.WriteRaw(&b, div); err == nil {
t.Fatal()
}
})
})
})
}