-
-
Notifications
You must be signed in to change notification settings - Fork 277
/
runtime_test.go
595 lines (571 loc) · 16.5 KB
/
runtime_test.go
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
package templ_test
import (
"bytes"
"context"
"errors"
"fmt"
"html/template"
"io"
"net/http"
"net/http/httptest"
"testing"
"github.com/a-h/templ"
"github.com/google/go-cmp/cmp"
)
func TestCSSID(t *testing.T) {
t.Run("minimum hash suffix length is 8", func(t *testing.T) {
// See issue #978.
name := "classA"
css := "background-color:white;"
actual := len(templ.CSSID(name, css))
expected := len(name) + 1 + 8
if expected != actual {
t.Errorf("expected length %d, got %d", expected, actual)
}
})
t.Run("known hash collisions are avoided", func(t *testing.T) {
name := "classA"
// Note that the first 4 characters of the hash are the same.
css1 := "grid-column:1;grid-row:1;" // After hash: f781266f
css2 := "grid-column:13;grid-row:6;" // After hash: f781f18b
id1 := templ.CSSID(name, css1)
id2 := templ.CSSID(name, css2)
if id1 == id2 {
t.Errorf("hash collision: %s == %s", id1, id2)
}
})
}
func TestCSSHandler(t *testing.T) {
tests := []struct {
name string
input []templ.CSSClass
expectedMIMEType string
expectedBody string
}{
{
name: "no classes",
input: nil,
expectedMIMEType: "text/css",
expectedBody: "",
},
{
name: "classes are rendered",
input: []templ.CSSClass{templ.ComponentCSSClass{ID: "className", Class: templ.SafeCSS(".className{background-color:white;}")}},
expectedMIMEType: "text/css",
expectedBody: ".className{background-color:white;}",
},
{
name: "classes are rendered",
input: []templ.CSSClass{
templ.ComponentCSSClass{ID: "classA", Class: templ.SafeCSS(".classA{background-color:white;}")},
templ.ComponentCSSClass{ID: "classB", Class: templ.SafeCSS(".classB{background-color:green;}")},
},
expectedMIMEType: "text/css",
expectedBody: ".classA{background-color:white;}.classB{background-color:green;}",
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
w := httptest.NewRecorder()
h := templ.NewCSSHandler(tt.input...)
h.ServeHTTP(w, &http.Request{})
if diff := cmp.Diff(tt.expectedMIMEType, w.Header().Get("Content-Type")); diff != "" {
t.Errorf(diff)
}
if diff := cmp.Diff(tt.expectedBody, w.Body.String()); diff != "" {
t.Errorf(diff)
}
})
}
}
func TestCSSMiddleware(t *testing.T) {
pageHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if _, err := io.WriteString(w, "Hello, World!"); err != nil {
t.Fatalf("failed to write string: %v", err)
}
})
c1 := templ.ComponentCSSClass{
ID: "c1",
Class: ".c1{color:red}",
}
c2 := templ.ComponentCSSClass{
ID: "c2",
Class: ".c2{color:blue}",
}
tests := []struct {
name string
input *http.Request
handler http.Handler
expectedMIMEType string
expectedBody string
}{
{
name: "accessing /style/templ.css renders CSS, even if it's empty",
input: httptest.NewRequest("GET", "/styles/templ.css", nil),
handler: templ.NewCSSMiddleware(pageHandler),
expectedMIMEType: "text/css",
expectedBody: "",
},
{
name: "accessing /style/templ.css renders CSS that includes the classes",
input: httptest.NewRequest("GET", "/styles/templ.css", nil),
handler: templ.NewCSSMiddleware(pageHandler, c1, c2),
expectedMIMEType: "text/css",
expectedBody: ".c1{color:red}.c2{color:blue}",
},
{
name: "the pageHandler is rendered",
input: httptest.NewRequest("GET", "/index.html", nil),
handler: templ.NewCSSMiddleware(pageHandler, c1, c2),
expectedMIMEType: "text/plain; charset=utf-8",
expectedBody: "Hello, World!",
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
w := httptest.NewRecorder()
tt.handler.ServeHTTP(w, tt.input)
if diff := cmp.Diff(tt.expectedMIMEType, w.Header().Get("Content-Type")); diff != "" {
t.Errorf(diff)
}
if diff := cmp.Diff(tt.expectedBody, w.Body.String()); diff != "" {
t.Errorf(diff)
}
})
}
}
var cssInputs = []any{
[]string{"a", "b"}, // []string
"c", // string
templ.ConstantCSSClass("d"), // ConstantCSSClass
templ.ComponentCSSClass{ID: "e", Class: ".e{color:red}"}, // ComponentCSSClass
map[string]bool{"f": true, "ff": false}, // map[string]bool
templ.KV[string, bool]("g", true), // KeyValue[string, bool]
templ.KV[string, bool]("gg", false), // KeyValue[string, bool]
[]templ.KeyValue[string, bool]{
templ.KV("h", true),
templ.KV("hh", false),
}, // []KeyValue[string, bool]
templ.KV[templ.CSSClass, bool](templ.ConstantCSSClass("i"), true), // KeyValue[CSSClass, bool]
templ.KV[templ.CSSClass, bool](templ.ConstantCSSClass("ii"), false), // KeyValue[CSSClass, bool]
templ.KV[templ.ComponentCSSClass, bool](templ.ComponentCSSClass{
ID: "j",
Class: ".j{color:red}",
}, true), // KeyValue[ComponentCSSClass, bool]
templ.KV[templ.ComponentCSSClass, bool](templ.ComponentCSSClass{
ID: "jj",
Class: ".jj{color:red}",
}, false), // KeyValue[ComponentCSSClass, bool]
templ.CSSClasses{templ.ConstantCSSClass("k")}, // CSSClasses
func() templ.CSSClass { return templ.ConstantCSSClass("l") }, // func() CSSClass
templ.CSSClass(templ.ConstantCSSClass("m")), // CSSClass
customClass{name: "n"}, // CSSClass
[]templ.CSSClass{customClass{name: "n"}}, // []CSSClass
templ.KV[templ.ConstantCSSClass, bool](templ.ConstantCSSClass("o"), true), // KeyValue[ConstantCSSClass, bool]
[]templ.KeyValue[templ.ConstantCSSClass, bool]{
templ.KV(templ.ConstantCSSClass("p"), true),
templ.KV(templ.ConstantCSSClass("pp"), false),
}, // []KeyValue[ConstantCSSClass, bool]
}
type customClass struct {
name string
}
func (cc customClass) ClassName() string {
return cc.name
}
func TestRenderCSS(t *testing.T) {
c1 := templ.ComponentCSSClass{
ID: "c1",
Class: ".c1{color:red}",
}
c2 := templ.ComponentCSSClass{
ID: "c2",
Class: ".c2{color:blue}",
}
tests := []struct {
name string
toIgnore []any
toRender []any
expected string
}{
{
name: "if none are ignored, everything is rendered",
toIgnore: nil,
toRender: []any{c1, c2},
expected: `<style type="text/css">.c1{color:red}.c2{color:blue}</style>`,
},
{
name: "if something outside the expected is ignored, if has no effect",
toIgnore: []any{
templ.ComponentCSSClass{
ID: "c3",
Class: templ.SafeCSS(".c3{color:yellow}"),
},
},
toRender: []any{c1, c2},
expected: `<style type="text/css">.c1{color:red}.c2{color:blue}</style>`,
},
{
name: "if one is ignored, it's not rendered",
toIgnore: []any{c1},
toRender: []any{c1, c2},
expected: `<style type="text/css">.c2{color:blue}</style>`,
},
{
name: "if all are ignored, not even style tags are rendered",
toIgnore: []any{
c1,
c2,
templ.ComponentCSSClass{
ID: "c3",
Class: templ.SafeCSS(".c3{color:yellow}"),
},
},
toRender: []any{c1, c2},
expected: ``,
},
{
name: "CSS classes are rendered",
toIgnore: nil,
toRender: cssInputs,
expected: `<style type="text/css">.e{color:red}.j{color:red}</style>`,
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
ctx := context.Background()
b := new(bytes.Buffer)
// Render twice, reusing the same context so that there's a memory of which classes have been rendered.
ctx = templ.InitializeContext(ctx)
err := templ.RenderCSSItems(ctx, b, tt.toIgnore...)
if err != nil {
t.Fatalf("failed to render initial CSS: %v", err)
}
// Now render again to check that only the expected classes were rendered.
b.Reset()
err = templ.RenderCSSItems(ctx, b, tt.toRender...)
if err != nil {
t.Fatalf("failed to render CSS: %v", err)
}
if diff := cmp.Diff(tt.expected, b.String()); diff != "" {
t.Error(diff)
}
})
}
}
func TestClassesFunction(t *testing.T) {
tests := []struct {
name string
input []any
expected string
}{
{
name: "constants are allowed",
input: []any{"a", "b", "c", "</style>"},
expected: "a b c </style>",
},
{
name: "legacy CSS types are supported",
input: []any{"a", templ.SafeClass("b"), templ.Class("c")},
expected: "a b c",
},
{
name: "CSS components are included in the output",
input: []any{
templ.ComponentCSSClass{ID: "classA", Class: templ.SafeCSS(".classA{background-color:white;}")},
templ.ComponentCSSClass{ID: "classB", Class: templ.SafeCSS(".classB{background-color:green;}")},
"c",
},
expected: "classA classB c",
},
{
name: "optional classes can be applied with expressions",
input: []any{
"a",
templ.ComponentCSSClass{ID: "classA", Class: templ.SafeCSS(".classA{background-color:white;}")},
templ.ComponentCSSClass{ID: "classB", Class: templ.SafeCSS(".classB{background-color:green;}")},
"c",
map[string]bool{
"a": false,
"classA": false,
"classB": false,
"c": true,
"d": false,
},
},
expected: "c",
},
{
name: "unknown types for classes get rendered as --templ-css-class-unknown-type",
input: []any{
123,
map[string]string{"test": "no"},
false,
"c",
},
expected: "--templ-css-class-unknown-type c",
},
{
name: "string arrays are supported",
input: []any{
[]string{"a", "b", "c", "</style>"},
"d",
},
expected: "a b c </style> d",
},
{
name: "strings are broken up",
input: []any{
"a </style>",
},
expected: "a </style>",
},
{
name: "if a templ.CSSClasses is passed in, the nested CSSClasses are extracted",
input: []any{
templ.Classes(
"a",
templ.SafeClass("b"),
templ.Class("c"),
templ.ComponentCSSClass{
ID: "d",
Class: "{}",
},
),
},
expected: "a b c d",
},
{
name: "kv types can be used to show or hide classes",
input: []any{
"a",
templ.KV("b", true),
"c",
templ.KV("c", false),
templ.KV(templ.SafeClass("d"), true),
templ.KV(templ.SafeClass("e"), false),
},
expected: "a b d",
},
{
name: "an array of KV types can be used to show or hide classes",
input: []any{
"a",
"c",
[]templ.KeyValue[string, bool]{
templ.KV("b", true),
templ.KV("c", false),
{"d", true},
},
},
expected: "a b d",
},
{
name: "the brackets on component CSS function calls can be elided",
input: []any{
func() templ.CSSClass {
return templ.ComponentCSSClass{
ID: "a",
Class: "",
}
},
},
expected: "a",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
actual := templ.Classes(test.input...).String()
if actual != test.expected {
t.Errorf("expected %q, got %q", test.expected, actual)
}
})
}
}
type baseError struct {
Value int
}
func (baseError) Error() string { return "base error" }
type nonMatchedError struct{}
func (nonMatchedError) Error() string { return "non matched error" }
func TestErrorWrapping(t *testing.T) {
baseErr := baseError{
Value: 1,
}
wrappedErr := templ.Error{Err: baseErr, Line: 1, Col: 2}
t.Run("errors.Is() returns true for the base error", func(t *testing.T) {
if !errors.Is(wrappedErr, baseErr) {
t.Error("errors.Is() returned false for the base error")
}
})
t.Run("errors.Is() returns false for a different error", func(t *testing.T) {
if errors.Is(wrappedErr, errors.New("different error")) {
t.Error("errors.Is() returned true for a different error")
}
})
t.Run("errors.As() returns true for the base error", func(t *testing.T) {
var err baseError
if !errors.As(wrappedErr, &err) {
t.Error("errors.As() returned false for the base error")
}
if err.Value != 1 {
t.Errorf("errors.As() returned a different value: %v", err.Value)
}
})
t.Run("errors.As() returns false for a different error", func(t *testing.T) {
var err nonMatchedError
if errors.As(wrappedErr, &err) {
t.Error("errors.As() returned true for a different error")
}
})
}
func TestRawComponent(t *testing.T) {
tests := []struct {
name string
input templ.Component
expected string
expectedErr error
}{
{
name: "Raw content is not escaped",
input: templ.Raw("<div>Test &</div>"),
expected: `<div>Test &</div>`,
},
{
name: "Raw will return errors first",
input: templ.Raw("", nil, errors.New("test error")),
expected: `<div>Test &</div>`,
expectedErr: errors.New("test error"),
},
{
name: "Strings marked as safe are rendered without escaping",
input: templ.Raw(template.HTML("<div>")),
expected: `<div>`,
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
b := new(bytes.Buffer)
err := tt.input.Render(context.Background(), b)
if tt.expectedErr != nil {
expected := tt.expectedErr.Error()
actual := fmt.Sprintf("%v", err)
if actual != expected {
t.Errorf("expected error %q, got %q", expected, actual)
}
return
}
if err != nil {
t.Fatalf("failed to render content: %v", err)
}
if diff := cmp.Diff(tt.expected, b.String()); diff != "" {
t.Error(diff)
}
})
}
t.Run("Raw does not require allocations", func(t *testing.T) {
actualAllocs := testing.AllocsPerRun(4, func() {
c := templ.Raw("<div>")
if c == nil {
t.Fatalf("unexpected nil value")
}
})
if actualAllocs > 0 {
t.Errorf("expected no allocs, got %v", actualAllocs)
}
})
}
var goTemplate = template.Must(template.New("example").Parse("<div>{{ . }}</div>"))
func TestGoHTMLComponents(t *testing.T) {
t.Run("Go templates can be rendered as templ components", func(t *testing.T) {
b := new(bytes.Buffer)
err := templ.FromGoHTML(goTemplate, "Test &").Render(context.Background(), b)
if err != nil {
t.Fatalf("failed to render content: %v", err)
}
if diff := cmp.Diff("<div>Test &</div>", b.String()); diff != "" {
t.Error(diff)
}
})
t.Run("templ components can be rendered in Go templates", func(t *testing.T) {
b := new(bytes.Buffer)
c := templ.ComponentFunc(func(ctx context.Context, w io.Writer) (err error) {
_, err = io.WriteString(w, "<div>Unsanitized &</div>")
return err
})
h, err := templ.ToGoHTML(context.Background(), c)
if err != nil {
t.Fatalf("failed to convert to Go HTML: %v", err)
}
if err = goTemplate.Execute(b, h); err != nil {
t.Fatalf("failed to render content: %v", err)
}
if diff := cmp.Diff("<div><div>Unsanitized &</div></div>", b.String()); diff != "" {
t.Error(diff)
}
})
t.Run("errors in ToGoHTML are returned", func(t *testing.T) {
expectedErr := errors.New("test error")
c := templ.ComponentFunc(func(ctx context.Context, w io.Writer) (err error) {
return expectedErr
})
_, err := templ.ToGoHTML(context.Background(), c)
if err == nil {
t.Fatalf("expected error, got nil")
}
if err != expectedErr {
t.Fatalf("expected error %q, got %q", expectedErr, err)
}
})
t.Run("FromGoHTML does not require allocations", func(t *testing.T) {
actualAllocs := testing.AllocsPerRun(4, func() {
c := templ.FromGoHTML(goTemplate, "test &")
if c == nil {
t.Fatalf("unexpected nil value")
}
})
if actualAllocs > 0 {
t.Errorf("expected no allocs, got %v", actualAllocs)
}
})
t.Run("ToGoHTML requires one allocation", func(t *testing.T) {
expected := "<div>Unsanitized &</div>"
c := templ.ComponentFunc(func(ctx context.Context, w io.Writer) (err error) {
_, err = io.WriteString(w, expected)
return err
})
actualAllocs := testing.AllocsPerRun(4, func() {
h, err := templ.ToGoHTML(context.Background(), c)
if err != nil {
t.Fatalf("failed to convert to Go HTML: %v", err)
}
if h != template.HTML(expected) {
t.Fatalf("unexpected value")
}
})
if actualAllocs > 1 {
t.Errorf("expected 1 alloc, got %v", actualAllocs)
}
})
}
func TestNonce(t *testing.T) {
ctx := context.Background()
t.Run("returns empty string if not set", func(t *testing.T) {
actual := templ.GetNonce(ctx)
if actual != "" {
t.Errorf("expected empty string got %q", actual)
}
})
t.Run("returns value if one has been set", func(t *testing.T) {
expected := "abc123"
ctx := templ.WithNonce(context.Background(), expected)
actual := templ.GetNonce(ctx)
if actual != expected {
t.Errorf("expected %q got %q", expected, actual)
}
})
}