~bigbes/sr-ht-ecore

ref: 92fea80afcf9d123988f58fbf2aea125124d7a1c sr-ht-ecore/pages/pages_test.go -rw-r--r-- 9.0 KiB
92fea80a — Eugene Blikh benchmarks for the hot path 2 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
package pages

import (
	"errors"
	"html/template"
	"net/http"
	"net/http/httptest"
	"testing"
	"testing/fstest"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

// view is the dot every test renders through: the shape the donors' view
// structs have — chrome fields (here only a title) plus the page's payload
// under .Data, which is what the shipped error page reads.
type view struct {
	Title string
	Data  any
}

// chromeMark is written by the layout before it reaches the content hole, so a
// test can tell "nothing was written" from "half a page was written".
const chromeMark = "CHROME-MARK"

// boomer fails at execution and only there: html/template reports an error
// returned by a method as a render error, which is the mid-render failure the
// buffering exists for. Its message names something a viewer must never see.
type boomer struct{}

func (boomer) Boom() (string, error) { return "", errors.New("kaboom /etc/srht/config.ini") }

// testFS is a service's template tree: a layout, a page, a partial, and a page
// that fails halfway through rendering.
func testFS() fstest.MapFS {
	return fstest.MapFS{
		"templates/layout.html": &fstest.MapFile{Data: []byte(
			`<!doctype html><title>{{.Title}}</title><body>` + chromeMark +
				`{{template "content" .}}</body>`)},
		"templates/index.html": &fstest.MapFile{Data: []byte(
			`{{define "content"}}<p>index {{template "_row" .Data}}</p>{{end}}`)},
		"templates/_row.html": &fstest.MapFile{Data: []byte(
			`{{define "_row"}}<i>{{.}}</i>{{end}}`)},
		"templates/boom.html": &fstest.MapFile{Data: []byte(
			`{{define "content"}}<p>{{.Data.Boom}}</p>{{end}}`)},
	}
}

func TestLoadDiscoversPagesPartialsAndTheShippedErrorPage(t *testing.T) {
	set, err := Load(testFS(), Options{})
	require.NoError(t, err)

	// The pages, plus the error page this package ships. The layout and the
	// partial are not pages and must not be renderable by name.
	assert.ElementsMatch(t, []string{"index", "boom", ErrorPage}, keys(set))
}

func TestLoadParsesEveryPartialIntoEveryPage(t *testing.T) {
	set, err := Load(testFS(), Options{})
	require.NoError(t, err)

	// A partial is parsed into every set, not only into the page that invokes
	// it today — including the error page, which invokes none of them.
	for name, tmpl := range set {
		assert.NotNil(t, tmpl.Lookup("_row"), "local partial missing from %q", name)
		assert.NotNil(t, tmpl.Lookup(ErrorPartial), "error partial missing from %q", name)
		assert.NotNil(t, tmpl.Lookup("srht-nav"), "chrome partial missing from %q", name)
	}
}

func TestLoadRefusesAPageThatDefinesNoContent(t *testing.T) {
	fsys := testFS()
	// A page that renders nothing into the hole: executed, it would answer 200
	// with the chrome around an empty document.
	fsys["templates/blank.html"] = &fstest.MapFile{Data: []byte(`<p>forgot the define</p>`)}

	_, err := Load(fsys, Options{})
	require.Error(t, err)
	assert.ErrorIs(t, err, ErrNoContent)
	assert.Contains(t, err.Error(), "blank.html")
}

func TestLoadRefusesATreeWithoutALayout(t *testing.T) {
	fsys := testFS()
	delete(fsys, "templates/layout.html")

	_, err := Load(fsys, Options{})
	require.Error(t, err)
	assert.Contains(t, err.Error(), "no layout")
}

func TestLoadRefusesATreeWithNoPages(t *testing.T) {
	fsys := fstest.MapFS{
		"templates/layout.html": &fstest.MapFile{Data: []byte(`{{template "content" .}}`)},
		"templates/_row.html":   &fstest.MapFile{Data: []byte(`{{define "_row"}}{{end}}`)},
	}

	_, err := Load(fsys, Options{})
	require.Error(t, err)
	assert.Contains(t, err.Error(), "no page templates")
}

func TestLoadMergesTheServiceFuncsOverChromes(t *testing.T) {
	fsys := testFS()
	fsys["templates/index.html"] = &fstest.MapFile{Data: []byte(
		`{{define "content"}}{{shortsha "0123456789"}}|{{shout "hi"}}{{end}}`)}

	set, err := Load(fsys, Options{Funcs: template.FuncMap{
		"shout":    func(s string) string { return s + "!" },
		"shortsha": func(string) string { return "SHADOWED" },
	}})
	require.NoError(t, err)

	rec := httptest.NewRecorder()
	require.NoError(t, set.Render(rec, http.StatusOK, "index", view{}))
	assert.Contains(t, rec.Body.String(), "SHADOWED|hi!")
}

func TestRenderWritesTheStatusAndTheBufferedPage(t *testing.T) {
	set, err := Load(testFS(), Options{})
	require.NoError(t, err)

	rec := httptest.NewRecorder()
	require.NoError(t, set.Render(rec, http.StatusCreated, "index", view{Title: "T", Data: "payload"}))

	assert.Equal(t, http.StatusCreated, rec.Code)
	assert.Equal(t, "text/html; charset=utf-8", rec.Header().Get("Content-Type"))
	body := rec.Body.String()
	assert.Contains(t, body, "<title>T</title>")
	assert.Contains(t, body, chromeMark)
	assert.Contains(t, body, "<i>payload</i>")
}

func TestRenderFailureLeavesNoPartialPageAndNoTemplateText(t *testing.T) {
	set, err := Load(testFS(), Options{})
	require.NoError(t, err)

	rec := httptest.NewRecorder()
	err = set.Render(rec, http.StatusOK, "boom", view{Title: "T", Data: boomer{}})

	// The caller gets the error to log, naming the page and carrying the cause.
	require.Error(t, err)
	assert.Contains(t, err.Error(), `"boom"`)
	assert.Contains(t, err.Error(), "kaboom")

	// The viewer gets a clean 500 and nothing else: not the status the handler
	// asked for, not the chrome the template had already produced when it
	// failed, and above all not the template's own error text — which is what
	// the dolt donor wrote into the body.
	assert.Equal(t, http.StatusInternalServerError, rec.Code)
	assert.Equal(t, internalServerError+"\n", rec.Body.String())
	assert.NotContains(t, rec.Body.String(), chromeMark)
	assert.NotContains(t, rec.Body.String(), "kaboom")
	assert.NotContains(t, rec.Body.String(), "config.ini")
}

func TestRenderRefusesAnUnknownPage(t *testing.T) {
	set, err := Load(testFS(), Options{})
	require.NoError(t, err)

	rec := httptest.NewRecorder()
	err = set.Render(rec, http.StatusOK, "nope", view{})

	require.Error(t, err)
	assert.ErrorIs(t, err, ErrUnknownPage)
	assert.Equal(t, http.StatusInternalServerError, rec.Code)
	assert.Equal(t, internalServerError+"\n", rec.Body.String())
}

func TestErrorPageRendersTheStatusTheMessageAndTheWayBack(t *testing.T) {
	set, err := Load(testFS(), Options{})
	require.NoError(t, err)

	data := Error(http.StatusNotFound, "").BackTo("/tokens", "Back to your tokens")
	rec := httptest.NewRecorder()
	require.NoError(t, set.Render(rec, data.Status, ErrorPage,
		view{Title: data.StatusText, Data: data}))

	assert.Equal(t, http.StatusNotFound, rec.Code)
	body := rec.Body.String()
	assert.Contains(t, body, chromeMark, "the error page is rendered inside the chrome")
	assert.Contains(t, body, "404")
	assert.Contains(t, body, "Not Found")
	assert.Contains(t, body, NotFoundMessage)
	assert.Contains(t, body, `<a href="/tokens">Back to your tokens</a>`)
}

func TestErrorPageEscapesTheMessage(t *testing.T) {
	set, err := Load(testFS(), Options{})
	require.NoError(t, err)

	// A 400's message quotes what the caller typed, so it is the one that can
	// carry markup.
	data := Error(http.StatusBadRequest, `<script>alert(1)</script> is not a duration`)
	rec := httptest.NewRecorder()
	require.NoError(t, set.Render(rec, data.Status, ErrorPage, view{Data: data}))

	body := rec.Body.String()
	assert.NotContains(t, body, "<script>")
	assert.Contains(t, body, "&lt;script&gt;")
}

func TestErrorPageOmitsAWayBackItWasNotGiven(t *testing.T) {
	set, err := Load(testFS(), Options{})
	require.NoError(t, err)

	rec := httptest.NewRecorder()
	require.NoError(t, set.Render(rec, http.StatusForbidden, ErrorPage,
		view{Data: ErrorData{Status: 403, StatusText: "Forbidden", Message: ForbiddenMessage}}))

	assert.NotContains(t, rec.Body.String(), "<a href=", "no link rather than a link to nowhere")
}

func TestAServiceErrorPageWinsOverTheShippedOne(t *testing.T) {
	fsys := testFS()
	fsys["templates/error.html"] = &fstest.MapFile{Data: []byte(
		`{{define "content"}}<div class="own">{{template "srht-error" .Data}}</div>{{end}}`)}

	set, err := Load(fsys, Options{})
	require.NoError(t, err)

	rec := httptest.NewRecorder()
	data := Error(http.StatusServiceUnavailable, "")
	require.NoError(t, set.Render(rec, data.Status, ErrorPage, view{Data: data}))

	body := rec.Body.String()
	assert.Contains(t, body, `<div class="own">`, "the service's own error page is used")
	assert.Contains(t, body, UnavailableMessage, "and it can still invoke the shared body")
}

func TestErrorTakesTheStandardMessageForItsStatus(t *testing.T) {
	assert.Equal(t, NotFoundMessage, Error(http.StatusNotFound, "").Message)
	assert.Equal(t, InternalMessage, Error(http.StatusInternalServerError, "").Message)
	assert.Equal(t, "Not Found", Error(http.StatusNotFound, "").StatusText)
	assert.Equal(t, DefaultBack, Error(http.StatusNotFound, "").Back)

	// A caller's own message is never replaced, and a status with no standard
	// message keeps the empty one rather than inventing a phrase.
	assert.Equal(t, "1y is not a duration", Error(http.StatusBadRequest, "1y is not a duration").Message)
	assert.Empty(t, Error(http.StatusBadRequest, "").Message)
	assert.Empty(t, Message(http.StatusTeapot))
}

func keys(s Set) []string {
	out := make([]string, 0, len(s))
	for name := range s {
		out = append(out, name)
	}
	return out
}