saasitone/pkg/services/template_renderer_test.go

104 lines
2.5 KiB
Go
Raw Permalink Normal View History

package services
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/labstack/echo/v4"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
2024-07-09 17:57:05 -07:00
"git.grosinger.net/tgrosinger/saasitone/config"
"git.grosinger.net/tgrosinger/saasitone/pkg/htmx"
2024-07-25 20:35:08 -07:00
"git.grosinger.net/tgrosinger/saasitone/pkg/models"
2024-07-09 17:57:05 -07:00
"git.grosinger.net/tgrosinger/saasitone/pkg/page"
"git.grosinger.net/tgrosinger/saasitone/pkg/tests"
2024-07-25 20:35:08 -07:00
"git.grosinger.net/tgrosinger/saasitone/templ/layouts"
"git.grosinger.net/tgrosinger/saasitone/templ/pages"
)
func TestTemplateRenderer(t *testing.T) {
group := "test"
id := "parse"
// Should not exist yet
_, err := c.TemplateRenderer.Load(group, id)
assert.Error(t, err)
// Parse in to the cache
tpl, err := c.TemplateRenderer.
Parse().
Group(group).
Key(id).
2024-07-25 20:35:08 -07:00
Base("test").
Files("emails/test").
Store()
require.NoError(t, err)
// Should exist now
parsed, err := c.TemplateRenderer.Load(group, id)
require.NoError(t, err)
// Check that all expected templates are included
expectedTemplates := make(map[string]bool)
2024-07-25 20:35:08 -07:00
expectedTemplates["test"+config.TemplateExt] = true
for _, v := range parsed.Template.Templates() {
delete(expectedTemplates, v.Name())
}
assert.Empty(t, expectedTemplates)
data := struct {
StatusCode int
}{
StatusCode: 500,
}
buf, err := tpl.Execute(data)
require.NoError(t, err)
require.NotNil(t, buf)
2024-07-25 20:35:08 -07:00
assert.Contains(t, buf.String(), "Test email template")
buf, err = c.TemplateRenderer.
Parse().
Group(group).
Key(id).
2024-07-25 20:35:08 -07:00
Base("test").
Files("email/test").
Execute(data)
require.NoError(t, err)
require.NotNil(t, buf)
2024-07-25 20:35:08 -07:00
assert.Contains(t, buf.String(), "Test email template")
}
func TestTemplateRenderer_RenderPage(t *testing.T) {
setup := func() (echo.Context, *httptest.ResponseRecorder, page.Page) {
ctx, rec := tests.NewContext(c.Web, "/test/TestTemplateRenderer_RenderPage")
tests.InitSession(ctx)
p := page.New(ctx)
p.Cache.Enabled = false
p.Headers["A"] = "b"
p.Headers["C"] = "d"
p.StatusCode = http.StatusCreated
return ctx, rec, p
}
t.Run("htmx rendering", func(t *testing.T) {
ctx, _, p := setup()
p.LayoutComponent = layouts.Main
p.HTMX.Request.Enabled = true
p.HTMX.Response = &htmx.Response{
Trigger: "trigger",
}
2024-07-25 20:35:08 -07:00
component := pages.Home(p, []models.Post{})
err := c.TemplateRenderer.RenderPageTempl(ctx, p, component)
require.NoError(t, err)
2024-07-25 20:35:08 -07:00
// Check HTMX header
assert.Equal(t, "trigger", ctx.Response().Header().Get(htmx.HeaderTrigger))
})
}
2024-07-25 20:35:08 -07:00