Last active
April 10, 2020 16:29
-
-
Save isutton/4958fafab2ad21410ffe0e742af0e375 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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