From 6c8f0c235287edf7252fe239d4c9beb258c6ff01 Mon Sep 17 00:00:00 2001 From: Markus Wüstenberg Date: Mon, 2 Nov 2020 10:03:05 +0100 Subject: Render to Writer instead of string (#39) The Render function has been changed to take a `Writer` instead of returning a string. This makes it possible to generate documents without having the whole content in memory. This also removes the `gomponents.Write` function, which is now redundant. Furthermore, the `el.Document` function has been changed to only take one child, as multiple children never make sense for it. (It's not even a child, more a sibling.)--- gomponents_test.go | 81 +++++++++++++++++++++++++++++------------------------- 1 file changed, 44 insertions(+), 37 deletions(-) (limited to 'gomponents_test.go') diff --git a/gomponents_test.go b/gomponents_test.go index 2efdd7a..3028723 100644 --- a/gomponents_test.go +++ b/gomponents_test.go @@ -3,6 +3,7 @@ package gomponents_test import ( "errors" "fmt" + "io" "strings" "testing" @@ -12,7 +13,10 @@ import ( func TestNodeFunc(t *testing.T) { t.Run("implements fmt.Stringer", func(t *testing.T) { - fn := g.NodeFunc(func() string { return "hat" }) + fn := g.NodeFunc(func(w io.Writer) error { + _, _ = w.Write([]byte("hat")) + return nil + }) if fn.String() != "hat" { t.FailNow() } @@ -56,24 +60,29 @@ func BenchmarkAttr(b *testing.B) { b.Run("boolean attributes", func(b *testing.B) { for i := 0; i < b.N; i++ { a := g.Attr("hat") - a.Render() + _ = a.Render(&strings.Builder{}) } }) b.Run("name-value attributes", func(b *testing.B) { for i := 0; i < b.N; i++ { a := g.Attr("hat", "party") - a.Render() + _ = a.Render(&strings.Builder{}) } }) } type outsider struct{} -func (o outsider) Render() string { +func (o outsider) String() string { return "outsider" } +func (o outsider) Render(w io.Writer) error { + _, _ = w.Write([]byte("outsider")) + return nil +} + func TestEl(t *testing.T) { t.Run("renders an empty element if no children given", func(t *testing.T) { e := g.El("div") @@ -101,9 +110,21 @@ func TestEl(t *testing.T) { }) t.Run("does not fail on nil node", func(t *testing.T) { - e := g.El("div", g.El("span"), nil, g.El("span")) + e := g.El("div", nil, g.El("span"), nil, g.El("span")) assert.Equal(t, `