Skip to content

Commit

Permalink
chore: include tests
Browse files Browse the repository at this point in the history
  • Loading branch information
ivanvc committed Jul 17, 2023
1 parent 7f1f816 commit 147d0c4
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
4 changes: 4 additions & 0 deletions pkg/template/include.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,14 @@ import (
"io"
)

// Template defines the interface which expects the ExecuteTemplate function
// to be defined, so it can be used by the include function.
type Template interface {
ExecuteTemplate(io.Writer, string, any) error
}

// Returns the function map defining the include template function. Which allows
// to call defined templates from within a template.
func IncludeFunc(tpl Template) map[string]any {
return map[string]any{
"include": func(name string, data any) (string, error) {
Expand Down
60 changes: 60 additions & 0 deletions pkg/template/include_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package template

import (
htmlTemplate "html/template"
"strings"
"testing"
textTemplate "text/template"
)

var (
validTemplate = `
{{- define "test" -}}
{{ . }}
{{- end -}}
{{ include "test" "abc" -}}
`
invalidTemplate = `{{ include "test" "abc" }}`
)

func TestWithValidTemplate(t *testing.T) {
tp := htmlTemplate.New("testValid")
tpl, err := tp.Funcs(IncludeFunc(tp)).Parse(validTemplate)
if err != nil {
t.Errorf("Error parsing template %q", err)
}
var b strings.Builder
if err := tpl.Execute(&b, nil); err != nil {
t.Errorf("Error executing template %q", err)
}
if b.String() != "abc" {
t.Errorf("Expecting output to be %q, got %q", "abc", b.String())
}
}

func TestWithATextTemplate(t *testing.T) {
tp := textTemplate.New("testValid")
tpl, err := tp.Funcs(IncludeFunc(tp)).Parse(validTemplate)
if err != nil {
t.Errorf("Error parsing template %q", err)
}
var b strings.Builder
if err := tpl.Execute(&b, nil); err != nil {
t.Errorf("Error executing template %q", err)
}
if b.String() != "abc" {
t.Errorf("Expecting output to be %q, got %q", "abc", b.String())
}
}

func TestWithAnInvalidTemplate(t *testing.T) {
tp := textTemplate.New("testInvalid")
tpl, err := tp.Funcs(IncludeFunc(tp)).Parse(invalidTemplate)
if err != nil {
t.Errorf("Error parsing template %q", err)
}
var b strings.Builder
if err := tpl.Execute(&b, nil); err == nil {
t.Error("Expecting error, got nothing")
}
}

0 comments on commit 147d0c4

Please sign in to comment.