Skip to content

Instantly share code, notes, and snippets.

@isutton
Last active April 10, 2020 16:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isutton/4958fafab2ad21410ffe0e742af0e375 to your computer and use it in GitHub Desktop.
Save isutton/4958fafab2ad21410ffe0e742af0e375 to your computer and use it in GitHub Desktop.
package main
import (
"bytes"
"testing"
"text/template"
"github.com/stretchr/testify/require"
)
func TestTemplate(t *testing.T) {
data := map[string]interface{}{
"v1": map[string]interface{}{
"postgres.io": map[string]interface{}{
"Database": map[string]interface{}{
"sales": map[string]interface{}{
"host": "sales1.local",
"port": "5432",
},
"analytics": map[string]interface{}{
"host": "analytics1.local",
"port": "5432",
},
},
},
},
}
type args struct {
template string
data interface{}
expected string
}
assertTemplate := func(args args) func(*testing.T) {
return func(t *testing.T) {
tmpl, err := template.New("").Parse(args.template)
require.NoError(t, err)
var buf bytes.Buffer
err = tmpl.Execute(&buf, args.data)
require.NoError(t, err)
require.Equal(t, args.expected, buf.String())
}
}
t.Run("", assertTemplate(args{
data: data,
expected: "sales1.local",
template: `{{ index . "v1" "postgres.io" "Database" "sales" "host" }}`,
}))
t.Run("", assertTemplate(args{
data: data,
expected: "analytics1.local;sales1.local;",
template: `{{ range $k, $v := (index . "v1" "postgres.io" "Database") }}{{ $v.host }};{{ end }}`,
}))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment