@@ -3,6 +3,7 @@ package main
33import (
44 "bytes"
55 "encoding/json"
6+ "fmt"
67 "reflect"
78 "testing"
89 "text/template"
@@ -518,6 +519,37 @@ func TestJson(t *testing.T) {
518519 }
519520}
520521
522+ func TestParseJson (t * testing.T ) {
523+ tests := []struct {
524+ tmpl string
525+ context interface {}
526+ expected string
527+ }{
528+ {`{{parseJson .}}` , `null` , `<no value>` },
529+ {`{{parseJson .}}` , `true` , `true` },
530+ {`{{parseJson .}}` , `1` , `1` },
531+ {`{{parseJson .}}` , `0.5` , `0.5` },
532+ {`{{index (parseJson .) "enabled"}}` , `{"enabled":true}` , `true` },
533+ {`{{index (parseJson . | first) "enabled"}}` , `[{"enabled":true}]` , `true` },
534+ }
535+
536+ for n , test := range tests {
537+ tmplName := fmt .Sprintf ("parseJson-test-%d" , n )
538+ tmpl := template .Must (newTemplate (tmplName ).Parse (test .tmpl ))
539+
540+ var b bytes.Buffer
541+ err := tmpl .ExecuteTemplate (& b , tmplName , test .context )
542+ if err != nil {
543+ t .Fatalf ("Error executing template: %v" , err )
544+ }
545+
546+ got := b .String ()
547+ if test .expected != got {
548+ t .Fatalf ("Incorrect output found; expected %s, got %s" , test .expected , got )
549+ }
550+ }
551+ }
552+
521553func TestArrayClosestExact (t * testing.T ) {
522554 if arrayClosest ([]string {"foo.bar.com" , "bar.com" }, "foo.bar.com" ) != "foo.bar.com" {
523555 t .Fatal ("Expected foo.bar.com" )
0 commit comments