mirror of
https://github.com/gohugoio/hugo.git
synced 2025-08-30 22:39:58 +02:00
@@ -8,6 +8,7 @@ package template_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -124,6 +125,44 @@ func TestNumbers(t *testing.T) {
|
||||
c.mustExecute(c.root, nil, "12.34 7.5")
|
||||
}
|
||||
|
||||
func TestStringsInScriptsWithJsonContentTypeAreCorrectlyEscaped(t *testing.T) {
|
||||
// See #33671 and #37634 for more context on this.
|
||||
tests := []struct{ name, in string }{
|
||||
{"empty", ""},
|
||||
{"invalid", string(rune(-1))},
|
||||
{"null", "\u0000"},
|
||||
{"unit separator", "\u001F"},
|
||||
{"tab", "\t"},
|
||||
{"gt and lt", "<>"},
|
||||
{"quotes", `'"`},
|
||||
{"ASCII letters", "ASCII letters"},
|
||||
{"Unicode", "ʕ⊙ϖ⊙ʔ"},
|
||||
{"Pizza", "🍕"},
|
||||
}
|
||||
const (
|
||||
prefix = `<script type="application/ld+json">`
|
||||
suffix = `</script>`
|
||||
templ = prefix + `"{{.}}"` + suffix
|
||||
)
|
||||
tpl := Must(New("JS string is JSON string").Parse(templ))
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
if err := tpl.Execute(&buf, tt.in); err != nil {
|
||||
t.Fatalf("Cannot render template: %v", err)
|
||||
}
|
||||
trimmed := bytes.TrimSuffix(bytes.TrimPrefix(buf.Bytes(), []byte(prefix)), []byte(suffix))
|
||||
var got string
|
||||
if err := json.Unmarshal(trimmed, &got); err != nil {
|
||||
t.Fatalf("Cannot parse JS string %q as JSON: %v", trimmed[1:len(trimmed)-1], err)
|
||||
}
|
||||
if got != tt.in {
|
||||
t.Errorf("Serialization changed the string value: got %q want %q", got, tt.in)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type testCase struct {
|
||||
t *testing.T
|
||||
root *Template
|
||||
|
Reference in New Issue
Block a user