Skip to content

Commit c284b91

Browse files
Add tests for valyala#87
Tests for string escape conformance with standard lib
1 parent d1b921a commit c284b91

File tree

1 file changed

+37
-1
lines changed

1 file changed

+37
-1
lines changed

parser_test.go

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package fastjson
22

33
import (
4+
"bytes"
5+
"encoding/json"
46
"fmt"
57
"math"
68
"strings"
@@ -68,6 +70,40 @@ func TestParseRawNumber(t *testing.T) {
6870
})
6971
}
7072

73+
func TestEscapeString(t *testing.T) {
74+
t.Run("controlchars", func(t *testing.T) {
75+
var r rune
76+
for r = 0; r <= 0x20; r++ {
77+
testEscapeString(t, string(r))
78+
testEscapeString(t, string(r)+" hello")
79+
testEscapeString(t, "hello "+string(r))
80+
testEscapeString(t, "hello "+string(r)+" world")
81+
}
82+
})
83+
t.Run("misc", func(t *testing.T) {
84+
testEscapeString(t, `hello � world`)
85+
testEscapeString(t, "hello \u0014 world")
86+
testEscapeString(t, "newline\ntab\ndoublequote\"reversesolidus\\solidus/formfeed\fcarriagereturn\r")
87+
})
88+
t.Run("unicode", func(t *testing.T) {
89+
testEscapeString(t, `你好,世界`)
90+
testEscapeString(t, "こんにちは、世界")
91+
testEscapeString(t, "ສະບາຍດີ, ໂລກ")
92+
})
93+
}
94+
95+
func testEscapeString(t *testing.T, s string) {
96+
t.Helper()
97+
98+
// Check that fastjson encoding is identical to standard library encoding
99+
expected, _ := json.Marshal(s)
100+
a := Arena{}
101+
actual := a.NewString(s).MarshalTo(nil)
102+
if !bytes.Equal(actual, expected) {
103+
t.Fatalf("expected='%s', actual='%s'", expected, actual)
104+
}
105+
}
106+
71107
func TestUnescapeStringBestEffort(t *testing.T) {
72108
t.Run("success", func(t *testing.T) {
73109
testUnescapeStringBestEffort(t, ``, ``)
@@ -349,7 +385,7 @@ func TestValueGetTyped(t *testing.T) {
349385
}
350386
un64 = v.GetUint64("bar")
351387
if n != 0 {
352-
t.Fatalf("unexpected non-zero value; got %d", n64)
388+
t.Fatalf("unexpected non-zero value; got %d", un64)
353389
}
354390
f := v.GetFloat64("foo")
355391
if f != 123.0 {

0 commit comments

Comments
 (0)