Debian Codegraph @

jsonstring_test.go

raw
1 package utils
2
3 import (
4 "encoding/json"
5 "strings"
6 "testing"
7
8 "github.com/stretchr/testify/require"
9 )
10
11 func jsonStringInputs() []string {
12 return []string{
13 "",
14 "plain ascii value",
15 "with \"quotes\" and \\backslashes\\",
16 "tabs\tnewlines\nreturns\r",
17 "controls \x00\x01\x1f\x7f",
18 "html <b>bold</b> & more",
19 "café naïve 日本語",
20 "line\u2028and\u2029separators",
21 "invalid \xff\xfe utf8 \xc3(",
22 "trailing continuation \xc3",
23 strings.Repeat("0123456789abcdef", 8),
24 strings.Repeat("x", 7) + "\"" + strings.Repeat("y", 9),
25 }
26 }
27
28 func Test_AppendJSONString(t *testing.T) {
29 t.Parallel()
30 for _, in := range jsonStringInputs() {
31 assertJSONStringParity(t, in)
32 }
33
34 // Every single byte value agrees with encoding/json.
35 for i := range 256 {
36 assertJSONStringParity(t, string([]byte{byte(i)}))
37 }
38
39 // Appending must preserve existing dst content.
40 got := AppendJSONString([]byte(`{"msg":`), "hi \"there\"")
41 require.Equal(t, `{"msg":"hi \"there\""`, string(got)) //nolint:testifylint // byte-exact comparison is the contract; JSONEq would hide encoding differences
42 }
43
44 func Benchmark_AppendJSONString(b *testing.B) {
45 inputs := []struct {
46 name string
47 value string
48 }{
49 {"clean-16B", "GET /index.html"},
50 {"clean-64B", strings.Repeat("clean-log", 7) + "x"},
51 {"escaped-64B", strings.Repeat(`says "hi" `, 6) + "done"},
52 {"unicode-64B", strings.Repeat("café 日本 ", 6) + "end"},
53 }
54 for _, input := range inputs {
55 dst := make([]byte, 0, 3*len(input.value))
56 b.Run(input.name+"/fiber", func(b *testing.B) {
57 b.ReportAllocs()
58 for b.Loop() {
59 AppendJSONString(dst, input.value)
60 }
61 })
62 b.Run(input.name+"/default", func(b *testing.B) {
63 b.ReportAllocs()
64 for b.Loop() {
65 if _, err := json.Marshal(input.value); err != nil {
66 b.Fatal(err)
67 }
68 }
69 })
70 }
71 }