Debian Codegraph @

internal/json/marshal_test.go

raw
1 // Copyright (c) 2021, Maxime Soulé
2 // All rights reserved.
3 //
4 // This source code is licensed under the BSD-style license found in the
5 // LICENSE file in the root directory of this source tree.
6
7 package json_test
8
9 import (
10 "bytes"
11 "errors"
12 "math"
13 "testing"
14
15 "github.com/maxatome/go-testdeep/internal/json"
16 "github.com/maxatome/go-testdeep/internal/test"
17 )
18
19 type marshalTest bool
20
21 func (m marshalTest) MarshalJSON() ([]byte, error) {
22 if m {
23 return []byte("marshal\ntest"), nil
24 }
25 return nil, errors.New("marshaling error")
26 }
27
28 func TestMarshal(t *testing.T) {
29 for i, tst := range []struct {
30 in any
31 expected string
32 }{
33 {
34 in: float64(123),
35 expected: "123",
36 },
37 {
38 in: math.NaN(),
39 expected: "NaN",
40 },
41 {
42 in: math.Inf(1),
43 expected: "+Inf",
44 },
45 {
46 in: 1e-7,
47 expected: "1e-7",
48 },
49 {
50 in: 1e22,
51 expected: "1e+22",
52 },
53 {
54 in: "foobar",
55 expected: `"foobar"`,
56 },
57 {
58 in: true,
59 expected: `true`,
60 },
61 {
62 in: false,
63 expected: `false`,
64 },
65 {
66 in: nil,
67 expected: `null`,
68 },
69 {
70 in: (map[string]any)(nil),
71 expected: `null`,
72 },
73 {
74 in: map[string]any{},
75 expected: `{}`,
76 },
77 {
78 in: map[string]any{"z": float64(123), "a": float64(890)},
79 expected: `{
80 "a": 890,
81 "z": 123
82 }`,
83 },
84 {
85 in: map[string]any{
86 "label": map[string]any{"age": float64(12), "name": "Bob"},
87 "zip": float64(456),
88 },
89 expected: `{
90 "label": {
91 "age": 12,
92 "name": "Bob"
93 },
94 "zip": 456
95 }`,
96 },
97 {
98 in: ([]any)(nil),
99 expected: `null`,
100 },
101 {
102 in: []any{},
103 expected: `[]`,
104 },
105 {
106 in: []any{"a", float64(123)},
107 expected: `[
108 "a",
109 123
110 ]`,
111 },
112 {
113 in: marshalTest(true),
114 expected: "marshal\ntest",
115 },
116 {
117 in: []any{float64(1), marshalTest(true), float64(3)},
118 expected: `[
119 1,
120 marshal
121 test,
122 3
123 ]`,
124 },
125 } {
126 b, err := json.Marshal(tst.in, 0)
127 test.NoError(t, err, "#%d", i)
128 test.EqualStr(t, string(b), tst.expected, "#%d", i)
129 }
130
131 for i, in := range []any{
132 marshalTest(false),
133 map[string]any{"z": float64(123), "a": marshalTest(false)},
134 []any{"a", marshalTest(false)},
135 } {
136 _, err := json.Marshal(in, 0)
137 if test.Error(t, err, "#%d", i) {
138 test.EqualStr(t, err.Error(), "marshaling error", "#%d", i)
139 }
140 }
141
142 _, err := json.Marshal(123, 0)
143 if test.Error(t, err) {
144 test.EqualStr(t, err.Error(), "cannot marshal int")
145 }
146 }
147
148 func TestAppendMarshal(t *testing.T) {
149 var buf bytes.Buffer
150
151 buf.WriteString("<<")
152 err := json.AppendMarshal(&buf, "foo", 0)
153 test.NoError(t, err)
154 buf.WriteString(">>")
155
156 test.EqualStr(t, buf.String(), `<<"foo">>`)
157 }