views_test.go
798 lines1
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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
package application
import (
"context"
"embed"
"errors"
"html/template"
"io/fs"
"net/http"
"net/http/httptest"
"strings"
"testing"
"testing/fstest"
)
func TestRenderError_Returns200WithErrorHTML(t *testing.T) {
rec := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/test", nil)
RenderError(rec, req, errors.New("something went wrong"))
if rec.Code != http.StatusOK {
t.Errorf("expected status 200, got %d", rec.Code)
}
ct := rec.Header().Get("Content-Type")
if ct != "text/html; charset=utf-8" {
t.Errorf("expected Content-Type 'text/html; charset=utf-8', got %q", ct)
}
body := rec.Body.String()
if !strings.Contains(body, "alert-error") {
t.Errorf("expected alert-error class, got: %s", body)
}
if !strings.Contains(body, "something went wrong") {
t.Errorf("expected error message in body, got: %s", body)
}
}
func TestRenderError_ProductionHidesDetails(t *testing.T) {
t.Setenv("ENV", "production")
rec := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/test", nil)
RenderError(rec, req, errors.New("database connection refused at 10.0.0.1:5432"))
body := rec.Body.String()
if strings.Contains(body, "database") {
t.Errorf("production mode should hide internal error details, got: %s", body)
}
if strings.Contains(body, "10.0.0.1") {
t.Errorf("production mode should hide IP addresses, got: %s", body)
}
if !strings.Contains(body, "An error occurred. Please try again.") {
t.Errorf("expected generic error message, got: %s", body)
}
}
func TestRenderError_DevShowsDetails(t *testing.T) {
t.Setenv("ENV", "development")
rec := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/test", nil)
RenderError(rec, req, errors.New("specific dev error"))
body := rec.Body.String()
if !strings.Contains(body, "specific dev error") {
t.Errorf("dev mode should show error details, got: %s", body)
}
}
func TestRenderError_HTMLEscapesMessage(t *testing.T) {
t.Setenv("ENV", "development")
rec := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/test", nil)
RenderError(rec, req, errors.New(`<script>alert("xss")</script>`))
body := rec.Body.String()
if strings.Contains(body, "<script>") {
t.Errorf("error message should be HTML-escaped, got: %s", body)
}
if !strings.Contains(body, "<script>") {
t.Errorf("expected HTML-escaped script tag, got: %s", body)
}
}
func TestRenderError_MethodOnController(t *testing.T) {
rec := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/test", nil)
c := &BaseController{}
c.RenderError(rec, req, errors.New("controller error"))
if rec.Code != http.StatusOK {
t.Errorf("expected status 200, got %d", rec.Code)
}
body := rec.Body.String()
if !strings.Contains(body, "controller error") {
t.Errorf("expected error message, got: %s", body)
}
}
func TestView_ServeHTTP_BouncerBlocks(t *testing.T) {
views := fstest.MapFS{
"views/layouts/base.html": {Data: []byte(`{{define "base.html"}}{{template "content" .}}{{end}}`)},
"views/blocked.html": {Data: []byte(`{{define "content"}}blocked{{end}}`)},
}
app := New(WithViews(views))
blocker := func(app *App, w http.ResponseWriter, r *http.Request) bool {
http.Error(w, "forbidden", http.StatusForbidden)
return false
}
view := app.Serve("blocked.html", blocker)
rec := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/blocked", nil)
view.ServeHTTP(rec, req)
if rec.Code != http.StatusForbidden {
t.Errorf("expected status 403, got %d", rec.Code)
}
body := rec.Body.String()
if !strings.Contains(body, "forbidden") {
t.Errorf("expected 'forbidden', got: %s", body)
}
}
func TestView_ServeHTTP_BouncerAllows(t *testing.T) {
views := fstest.MapFS{
"views/layouts/base.html": {Data: []byte(`{{define "base.html"}}base{{end}}`)},
"views/allowed.html": {Data: []byte(`hello from allowed`)},
}
app := New(WithViews(views))
allower := func(app *App, w http.ResponseWriter, r *http.Request) bool {
return true
}
view := app.Serve("allowed.html", allower)
rec := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/allowed", nil)
view.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Errorf("expected status 200, got %d", rec.Code)
}
body := rec.Body.String()
if !strings.Contains(body, "hello from allowed") {
t.Errorf("expected template content, got: %s", body)
}
}
func TestView_ServeHTTP_NilBouncer(t *testing.T) {
views := fstest.MapFS{
"views/layouts/base.html": {Data: []byte(`{{define "base.html"}}base{{end}}`)},
"views/open.html": {Data: []byte(`open page`)},
}
app := New(WithViews(views))
view := app.Serve("open.html", nil)
rec := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/open", nil)
view.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Errorf("expected status 200, got %d", rec.Code)
}
body := rec.Body.String()
if !strings.Contains(body, "open page") {
t.Errorf("expected template content, got: %s", body)
}
}
func TestDict_TemplateFuncEvenPairs(t *testing.T) {
app := New()
funcs := app.templateFuncs()
dictFn, ok := funcs["dict"].(func(...any) map[string]any)
if !ok {
t.Fatal("expected dict func to be present and have correct type")
}
result := dictFn("name", "alice", "age", 30)
if result == nil {
t.Fatal("expected non-nil result")
}
if result["name"] != "alice" {
t.Errorf("expected name='alice', got %v", result["name"])
}
if result["age"] != 30 {
t.Errorf("expected age=30, got %v", result["age"])
}
}
func TestDict_TemplateFuncOddPairs(t *testing.T) {
app := New()
funcs := app.templateFuncs()
dictFn := funcs["dict"].(func(...any) map[string]any)
result := dictFn("key1", "val1", "orphan")
if result != nil {
t.Errorf("expected nil for odd number of args, got %v", result)
}
}
func TestDict_TemplateFuncNonStringKey(t *testing.T) {
app := New()
funcs := app.templateFuncs()
dictFn := funcs["dict"].(func(...any) map[string]any)
result := dictFn(42, "value")
if result == nil {
t.Fatal("expected non-nil result")
}
// Non-string key should be skipped
if len(result) != 0 {
t.Errorf("expected empty map for non-string key, got %v", result)
}
}
func TestDict_InTemplate(t *testing.T) {
views := fstest.MapFS{
"views/layouts/base.html": {Data: []byte(`{{define "base.html"}}base{{end}}`)},
"views/dict-test.html": {Data: []byte(
`{{$d := dict "greeting" "hello" "target" "world"}}{{$d.greeting}} {{$d.target}}`,
)},
}
app := New(WithViews(views))
rec := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/dict-test", nil)
app.render(rec, req, "dict-test.html", nil)
body := rec.Body.String()
if !strings.Contains(body, "hello world") {
t.Errorf("expected 'hello world', got: %s", body)
}
}
func TestRenderToString(t *testing.T) {
views := fstest.MapFS{
"views/layouts/base.html": {Data: []byte(`{{define "base.html"}}base{{end}}`)},
"views/partials/greeting.html": {Data: []byte(`{{define "greeting.html"}}Hello, {{.}}!{{end}}`)},
"views/standalone.html": {Data: []byte(`standalone: {{.}}`)},
}
app := New(WithViews(views))
// Test rendering a partial (already in base templates)
html, err := app.RenderToString("greeting.html", "World")
if err != nil {
t.Fatalf("unexpected error rendering partial: %v", err)
}
if !strings.Contains(html, "Hello, World!") {
t.Errorf("expected 'Hello, World!', got: %s", html)
}
// Test rendering a view file
html, err = app.RenderToString("standalone.html", "data")
if err != nil {
t.Fatalf("unexpected error rendering view: %v", err)
}
if !strings.Contains(html, "standalone: data") {
t.Errorf("expected 'standalone: data', got: %s", html)
}
}
func TestRender_InjectsNonceFunc(t *testing.T) {
// Verify the nonce template function is available during render
views := fstest.MapFS{
"views/layouts/base.html": {Data: []byte(`{{define "base.html"}}base{{end}}`)},
"views/nonce-test.html": {Data: []byte(`nonce={{nonce}}`)},
}
app := New(WithViews(views))
rec := httptest.NewRecorder()
// Create a request with a nonce in context
req := httptest.NewRequest("GET", "/nonce-test", nil)
ctx := context.WithValue(req.Context(), nonceKey{}, "abc123")
req = req.WithContext(ctx)
app.render(rec, req, "nonce-test.html", nil)
body := rec.Body.String()
if !strings.Contains(body, "nonce=abc123") {
t.Errorf("expected 'nonce=abc123', got: %s", body)
}
}
func TestRender_TemplateNotFound(t *testing.T) {
views := fstest.MapFS{
"views/layouts/base.html": {Data: []byte(`{{define "base.html"}}base{{end}}`)},
}
app := New(WithViews(views))
rec := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/missing", nil)
app.render(rec, req, "nonexistent.html", nil)
if rec.Code != http.StatusInternalServerError {
t.Errorf("expected status 500 for missing template, got %d", rec.Code)
}
}
func TestRender_TemplateExecutionError(t *testing.T) {
views := fstest.MapFS{
"views/layouts/base.html": {Data: []byte(`{{define "base.html"}}base{{end}}`)},
"views/bad.html": {Data: []byte(`{{.MissingMethod}}`)},
}
app := New(WithViews(views))
rec := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/bad", nil)
app.render(rec, req, "bad.html", "not-a-struct")
if rec.Code != http.StatusInternalServerError {
t.Errorf("expected status 500 for template execution error, got %d", rec.Code)
}
}
func TestRender_SetsContentType(t *testing.T) {
views := fstest.MapFS{
"views/layouts/base.html": {Data: []byte(`{{define "base.html"}}base{{end}}`)},
"views/simple.html": {Data: []byte(`hello`)},
}
app := New(WithViews(views))
rec := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/simple", nil)
app.render(rec, req, "simple.html", nil)
ct := rec.Header().Get("Content-Type")
if ct != "text/html; charset=utf-8" {
t.Errorf("expected 'text/html; charset=utf-8', got %q", ct)
}
}
func TestRenderToString_TemplateNotFound(t *testing.T) {
views := fstest.MapFS{
"views/layouts/base.html": {Data: []byte(`{{define "base.html"}}base{{end}}`)},
}
app := New(WithViews(views))
_, err := app.RenderToString("nonexistent.html", nil)
if err == nil {
t.Fatal("expected error for nonexistent template")
}
if !strings.Contains(err.Error(), "template not found") {
t.Errorf("expected 'template not found' error, got: %v", err)
}
}
func TestRenderToString_PartialExecutionError(t *testing.T) {
views := fstest.MapFS{
"views/layouts/base.html": {Data: []byte(`{{define "base.html"}}base{{end}}`)},
"views/partials/bad.html": {Data: []byte(`{{define "bad.html"}}{{.MissingMethod}}{{end}}`)},
}
app := New(WithViews(views))
_, err := app.RenderToString("bad.html", "not-a-struct")
if err == nil {
t.Fatal("expected error for template execution failure")
}
}
func TestRenderToString_ViewExecutionError(t *testing.T) {
views := fstest.MapFS{
"views/layouts/base.html": {Data: []byte(`{{define "base.html"}}base{{end}}`)},
"views/bad-view.html": {Data: []byte(`{{.MissingMethod}}`)},
}
app := New(WithViews(views))
_, err := app.RenderToString("bad-view.html", "not-a-struct")
if err == nil {
t.Fatal("expected error for view execution failure")
}
}
func TestRenderToString_ViewParseError(t *testing.T) {
views := fstest.MapFS{
"views/layouts/base.html": {Data: []byte(`{{define "base.html"}}base{{end}}`)},
"views/parse-error.html": {Data: []byte(`{{invalid syntax`)},
}
app := New(WithViews(views))
_, err := app.RenderToString("parse-error.html", nil)
if err == nil {
t.Fatal("expected error for template parse failure")
}
}
func TestLoadView_NotFound(t *testing.T) {
views := fstest.MapFS{
"views/layouts/base.html": {Data: []byte(`{{define "base.html"}}base{{end}}`)},
}
app := New(WithViews(views))
_, err := app.loadView("missing.html")
if err == nil {
t.Fatal("expected error for missing view")
}
if !strings.Contains(err.Error(), "view not found") {
t.Errorf("expected 'view not found' error, got: %v", err)
}
}
func TestLoadView_ParseError(t *testing.T) {
views := fstest.MapFS{
"views/layouts/base.html": {Data: []byte(`{{define "base.html"}}base{{end}}`)},
"views/bad-parse.html": {Data: []byte(`{{invalid syntax`)},
}
app := New(WithViews(views))
_, err := app.loadView("bad-parse.html")
if err == nil {
t.Fatal("expected error for template parse failure")
}
}
func TestParseBaseTemplates_WithPartials(t *testing.T) {
views := fstest.MapFS{
"views/layouts/base.html": {Data: []byte(`{{define "base.html"}}layout{{end}}`)},
"views/partials/header.html": {Data: []byte(`{{define "header.html"}}header{{end}}`)},
"views/partials/footer.html": {Data: []byte(`{{define "footer.html"}}footer{{end}}`)},
}
app := New(WithViews(views))
// Verify partials were loaded
if app.base.Lookup("header.html") == nil {
t.Error("expected header.html partial to be loaded")
}
if app.base.Lookup("footer.html") == nil {
t.Error("expected footer.html partial to be loaded")
}
}
func TestParseBaseTemplates_SkipsNonHTMLFiles(t *testing.T) {
views := fstest.MapFS{
"views/layouts/base.html": {Data: []byte(`{{define "base.html"}}layout{{end}}`)},
"views/partials/note.txt": {Data: []byte(`not a template`)},
}
app := New(WithViews(views))
// The txt file should not be parsed as a template
if app.base.Lookup("note.txt") != nil {
t.Error("expected non-HTML files to be skipped")
}
}
func TestParseBaseTemplates_MissingDirs(t *testing.T) {
// No layouts or partials directories at all
views := fstest.MapFS{}
app := New(WithViews(views))
// Should not panic; base should still be usable
if app.base == nil {
t.Fatal("expected base template to be non-nil even without layout/partial dirs")
}
}
func TestParseBaseTemplates_WithControllerPlaceholders(t *testing.T) {
views := fstest.MapFS{
"views/layouts/base.html": {Data: []byte(`{{define "base.html"}}layout{{end}}`)},
}
ctrl := &testController{}
app := New(
WithController("home", ctrl),
WithViews(views),
)
// The controller placeholder func should exist in base
if app.base == nil {
t.Fatal("expected base templates to be parsed")
}
}
func TestView_ServeHTTP_WithData(t *testing.T) {
views := fstest.MapFS{
"views/layouts/base.html": {Data: []byte(`{{define "base.html"}}base{{end}}`)},
"views/data-test.html": {Data: []byte(`value={{.}}`)},
}
app := New(WithViews(views))
// Directly render via the app
rec := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/data-test", nil)
app.render(rec, req, "data-test.html", "myvalue")
body := rec.Body.String()
if !strings.Contains(body, "value=myvalue") {
t.Errorf("expected 'value=myvalue', got: %s", body)
}
}
func TestTemplateFuncs_IncludesUserFuncs(t *testing.T) {
app := New(WithFunc("upper", strings.ToUpper))
funcs := app.templateFuncs()
if _, ok := funcs["upper"]; !ok {
t.Error("expected 'upper' func to be in templateFuncs")
}
// dict should always be present
if _, ok := funcs["dict"]; !ok {
t.Error("expected 'dict' func to be in templateFuncs")
}
}
func TestDict_EmptyArgs(t *testing.T) {
app := New()
funcs := app.templateFuncs()
dictFn := funcs["dict"].(func(...any) map[string]any)
result := dictFn()
if result == nil {
t.Fatal("expected non-nil result for empty args")
}
if len(result) != 0 {
t.Errorf("expected empty map, got %v", result)
}
}
func TestParseBaseTemplates_BadPartialSyntax(t *testing.T) {
// A partial with invalid template syntax should log a warning but not crash
views := fstest.MapFS{
"views/layouts/base.html": {Data: []byte(`{{define "base.html"}}layout{{end}}`)},
"views/partials/bad-syntax.html": {Data: []byte(`{{invalid unparseable`)},
}
app := New(WithViews(views))
// Should not panic; base should still be usable
if app.base == nil {
t.Fatal("expected base template to be non-nil even with bad partial")
}
}
func TestParseBaseTemplates_ReadFileError(t *testing.T) {
// Use a custom FS that returns an error from ReadFile for a specific file.
// WalkDir finds the file, but ReadFile fails.
views := &readErrorFS{
MapFS: fstest.MapFS{
"views/layouts/base.html": {Data: []byte(`{{define "base.html"}}layout{{end}}`)},
"views/partials/failing.html": {Data: []byte(`content`)},
},
failFile: "views/partials/failing.html",
}
app := &App{
funcs: template.FuncMap{},
controllers: map[string]Controller{},
}
app.viewsFS = views
app.base = app.parseBaseTemplates(views)
// Should not panic; base should still be usable
if app.base == nil {
t.Fatal("expected base template to be non-nil")
}
}
// readErrorFS wraps a MapFS but makes ReadFile fail for a specific path.
type readErrorFS struct {
fstest.MapFS
failFile string
}
func (r *readErrorFS) Open(name string) (fs.File, error) {
return r.MapFS.Open(name)
}
func (r *readErrorFS) ReadFile(name string) ([]byte, error) {
if name == r.failFile {
return nil, errors.New("simulated read error")
}
return r.MapFS.ReadFile(name)
}
func TestParseBaseTemplates_PlaceholderFuncsCallable(t *testing.T) {
// Exercise the placeholder func bodies registered by parseBaseTemplates.
// These are normally overridden per-request in render(), but the placeholder
// bodies are registered to satisfy template parsing.
views := fstest.MapFS{
"views/layouts/base.html": {Data: []byte(`{{define "base.html"}}layout{{end}}`)},
"views/partials/test-ph.html": {Data: []byte(`{{define "test-ph.html"}}nonce={{nonce}} script={{frontend_script}}{{end}}`)},
}
ctrl := &testController{}
app := New(
WithController("test", ctrl),
WithViews(views),
)
// Execute the partial directly from base (without render() overriding the funcs)
// This calls the placeholder func bodies.
var buf strings.Builder
err := app.base.ExecuteTemplate(&buf, "test-ph.html", nil)
if err != nil {
t.Fatalf("unexpected error executing template: %v", err)
}
body := buf.String()
// Placeholder nonce returns ""
if !strings.Contains(body, "nonce=") {
t.Errorf("expected nonce= in output, got: %s", body)
}
}
func TestParseBaseTemplates_ControllerPlaceholderCallable(t *testing.T) {
views := fstest.MapFS{
"views/layouts/base.html": {Data: []byte(`{{define "base.html"}}layout{{end}}`)},
"views/partials/ctrl-ph.html": {Data: []byte(`{{define "ctrl-ph.html"}}ctrl={{home}}{{end}}`)},
}
ctrl := &nameController{name: "Test"}
app := New(
WithController("home", ctrl),
WithViews(views),
)
// Execute the partial directly from base - calls the controller placeholder
var buf strings.Builder
err := app.base.ExecuteTemplate(&buf, "ctrl-ph.html", nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// The placeholder controller func returns nil, which Go templates render as empty.
// The test just needs to verify the template executes without error.
_ = buf.String()
}
func TestBaseEmailer_Render_NotInitialized(t *testing.T) {
b := &BaseEmailer{} // emails is nil
_, err := b.Render("welcome.html", nil)
if err == nil {
t.Fatal("expected error when templates not initialized")
}
if !strings.Contains(err.Error(), "not initialized") {
t.Errorf("expected 'not initialized' error, got: %v", err)
}
}
func TestBaseEmailer_Render_Success(t *testing.T) {
b := &BaseEmailer{}
// Manually set up the template (same-package access)
tmpl := template.Must(template.New("welcome.html").Parse("Hello, {{.name}}!"))
b.emails = tmpl
result, err := b.Render("welcome.html", map[string]any{"name": "Alice"})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if result != "Hello, Alice!" {
t.Errorf("expected 'Hello, Alice!', got %q", result)
}
}
func TestBaseEmailer_Render_MissingTemplate(t *testing.T) {
b := &BaseEmailer{}
b.emails = template.New("")
_, err := b.Render("nonexistent.html", nil)
if err == nil {
t.Fatal("expected error for missing template")
}
if !strings.Contains(err.Error(), "execute template") {
t.Errorf("expected 'execute template' error, got: %v", err)
}
}
func TestBaseEmailer_Render_ExecutionError(t *testing.T) {
b := &BaseEmailer{}
// Use a template that calls a method on nil, which will fail at execution
tmpl := template.New("")
template.Must(tmpl.New("bad.html").Parse(`{{template "missing-partial.html"}}`))
b.emails = tmpl
_, err := b.Render("bad.html", map[string]any{})
if err == nil {
t.Fatal("expected error for template execution failure")
}
}
func TestBaseEmailer_Render_WithFuncs(t *testing.T) {
b := &BaseEmailer{}
tmpl := template.New("")
tmpl.Funcs(template.FuncMap{
"shout": strings.ToUpper,
})
template.Must(tmpl.New("shout.html").Parse(`{{shout .name}}`))
b.emails = tmpl
result, err := b.Render("shout.html", map[string]any{"name": "hello"})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if result != "HELLO" {
t.Errorf("expected 'HELLO', got %q", result)
}
}
//go:embed emails
var testEmails embed.FS
func TestBaseEmailer_Init_WithValidEmails(t *testing.T) {
b := &BaseEmailer{}
b.Init(testEmails, nil)
// After Init with valid emails dir, should be able to render
result, err := b.Render("test.html", map[string]any{"name": "Alice"})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if result != "Hello, Alice!" {
t.Errorf("expected 'Hello, Alice!', got %q", result)
}
}
func TestBaseEmailer_Init_WithFuncsAndValidEmails(t *testing.T) {
b := &BaseEmailer{}
// Note: we pass funcs, but the test email doesn't use custom funcs.
// This tests the funcs != nil branch in Init.
funcs := template.FuncMap{
"upper": strings.ToUpper,
}
b.Init(testEmails, funcs)
if b.emails == nil {
t.Error("expected emails to be non-nil")
}
result, err := b.Render("test.html", map[string]any{"name": "Bob"})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if result != "Hello, Bob!" {
t.Errorf("expected 'Hello, Bob!', got %q", result)
}
}
func TestBaseEmailer_Init_WithEmptyFS(t *testing.T) {
// Test Init with a missing "emails" directory - should log warning and reset
var emptyFS embed.FS
b := &BaseEmailer{}
b.Init(emptyFS, nil)
// After Init with missing dir, emails should still be set (reset to empty)
if b.emails == nil {
t.Error("expected emails to be non-nil after Init with missing dir")
}
// Rendering should fail gracefully
_, err := b.Render("anything.html", nil)
if err == nil {
t.Error("expected error rendering from empty emailer")
}
}
func TestBaseEmailer_Init_WithNilFuncs(t *testing.T) {
var emptyFS embed.FS
b := &BaseEmailer{}
b.Init(emptyFS, nil)
// Should not panic
if b.emails == nil {
t.Error("expected emails to be non-nil")
}
}