| 1 |
package json |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"compress/gzip" |
| 6 |
"encoding" |
| 7 |
"encoding/json" |
| 8 |
"errors" |
| 9 |
"flag" |
| 10 |
"fmt" |
| 11 |
"io" |
| 12 |
"math" |
| 13 |
"math/big" |
| 14 |
"os" |
| 15 |
"path/filepath" |
| 16 |
"reflect" |
| 17 |
"runtime" |
| 18 |
"strconv" |
| 19 |
"strings" |
| 20 |
"testing" |
| 21 |
"time" |
| 22 |
) |
| 23 |
|
| 24 |
// The encoding/json package does not export the msg field of json.SyntaxError, |
| 25 |
// so we use this replacement type in tests. |
| 26 |
type testSyntaxError struct { |
| 27 |
msg string |
| 28 |
Offset int64 |
| 29 |
} |
| 30 |
|
| 31 |
func (e *testSyntaxError) Error() string { return e.msg } |
| 32 |
|
| 33 |
var ( |
| 34 |
marshal func([]byte, any) ([]byte, error) |
| 35 |
unmarshal func([]byte, any) error |
| 36 |
escapeHTML bool |
| 37 |
) |
| 38 |
|
| 39 |
func TestMain(m *testing.M) { |
| 40 |
var pkg string |
| 41 |
flag.StringVar(&pkg, "package", ".", "The name of the package to test (encoding/json, or default to this package)") |
| 42 |
flag.BoolVar(&escapeHTML, "escapehtml", false, "Whether to enable HTML escaping or not") |
| 43 |
flag.Parse() |
| 44 |
|
| 45 |
switch pkg { |
| 46 |
case "encoding/json": |
| 47 |
buf := &buffer{} |
| 48 |
enc := json.NewEncoder(buf) |
| 49 |
enc.SetEscapeHTML(escapeHTML) |
| 50 |
|
| 51 |
marshal = func(b []byte, v any) ([]byte, error) { |
| 52 |
buf.data = b |
| 53 |
err := enc.Encode(v) |
| 54 |
return buf.data, err |
| 55 |
} |
| 56 |
|
| 57 |
unmarshal = json.Unmarshal |
| 58 |
|
| 59 |
default: |
| 60 |
flags := AppendFlags(0) |
| 61 |
if escapeHTML { |
| 62 |
flags |= EscapeHTML |
| 63 |
} |
| 64 |
|
| 65 |
marshal = func(b []byte, v any) ([]byte, error) { |
| 66 |
return Append(b, v, flags) |
| 67 |
} |
| 68 |
|
| 69 |
unmarshal = func(b []byte, v any) error { |
| 70 |
_, err := Parse(b, v, ZeroCopy) |
| 71 |
return err |
| 72 |
} |
| 73 |
} |
| 74 |
|
| 75 |
os.Exit(m.Run()) |
| 76 |
} |
| 77 |
|
| 78 |
type point struct { |
| 79 |
X int `json:"x"` |
| 80 |
Y int `json:"y"` |
| 81 |
} |
| 82 |
|
| 83 |
type tree struct { |
| 84 |
Value string |
| 85 |
Left *tree |
| 86 |
Right *tree |
| 87 |
} |
| 88 |
|
| 89 |
var ( |
| 90 |
// bigPos128 and bigNeg128 are 1<<128 and -1<<128 |
| 91 |
// certainly neither is representable using a uint64/int64. |
| 92 |
bigPos128 = new(big.Int).Lsh(big.NewInt(1), 128) |
| 93 |
bigNeg128 = new(big.Int).Neg(bigPos128) |
| 94 |
) |
| 95 |
|
| 96 |
var testValues = [...]any{ |
| 97 |
// constants |
| 98 |
nil, |
| 99 |
false, |
| 100 |
true, |
| 101 |
|
| 102 |
// int |
| 103 |
int(0), |
| 104 |
int(1), |
| 105 |
int(42), |
| 106 |
int(-1), |
| 107 |
int(-42), |
| 108 |
int8(math.MaxInt8), |
| 109 |
int8(math.MinInt8), |
| 110 |
int16(math.MaxInt16), |
| 111 |
int16(math.MinInt16), |
| 112 |
int32(math.MaxInt32), |
| 113 |
int32(math.MinInt32), |
| 114 |
int64(math.MaxInt64), |
| 115 |
int64(math.MinInt64), |
| 116 |
|
| 117 |
// uint |
| 118 |
uint(0), |
| 119 |
uint(1), |
| 120 |
uintptr(0), |
| 121 |
uintptr(1), |
| 122 |
uint8(math.MaxUint8), |
| 123 |
uint16(math.MaxUint16), |
| 124 |
uint32(math.MaxUint32), |
| 125 |
uint64(math.MaxUint64), |
| 126 |
|
| 127 |
// float |
| 128 |
float32(0), |
| 129 |
float32(0.5), |
| 130 |
float32(math.SmallestNonzeroFloat32), |
| 131 |
float32(math.MaxFloat32), |
| 132 |
float64(0), |
| 133 |
float64(0.5), |
| 134 |
float64(math.SmallestNonzeroFloat64), |
| 135 |
float64(math.MaxFloat64), |
| 136 |
|
| 137 |
bigPos128, |
| 138 |
bigNeg128, |
| 139 |
|
| 140 |
// number |
| 141 |
Number("0"), |
| 142 |
Number("1234567890"), |
| 143 |
Number("-0.5"), |
| 144 |
Number("-1e+2"), |
| 145 |
|
| 146 |
// string |
| 147 |
"", |
| 148 |
"Hello World!", |
| 149 |
"Hello\"World!", |
| 150 |
"Hello\\World!", |
| 151 |
"Hello\nWorld!", |
| 152 |
"Hello\rWorld!", |
| 153 |
"Hello\tWorld!", |
| 154 |
"Hello\bWorld!", |
| 155 |
"Hello\fWorld!", |
| 156 |
"你好", |
| 157 |
"<", |
| 158 |
">", |
| 159 |
"&", |
| 160 |
"\u001944", |
| 161 |
"\u00c2e>", |
| 162 |
"\u00c2V?", |
| 163 |
"\u000e=8", |
| 164 |
"\u001944\u00c2e>\u00c2V?\u000e=8", |
| 165 |
"ir\u001bQJ\u007f\u0007y\u0015)", |
| 166 |
strings.Repeat("A", 32), |
| 167 |
strings.Repeat("A", 250), |
| 168 |
strings.Repeat("A", 1020), |
| 169 |
|
| 170 |
// bytes |
| 171 |
[]byte(""), |
| 172 |
[]byte("Hello World!"), |
| 173 |
bytes.Repeat([]byte("A"), 250), |
| 174 |
bytes.Repeat([]byte("A"), 1020), |
| 175 |
|
| 176 |
// time |
| 177 |
time.Unix(0, 0).In(time.UTC), |
| 178 |
time.Unix(1, 42).In(time.UTC), |
| 179 |
time.Unix(17179869184, 999999999).In(time.UTC), |
| 180 |
time.Date(2016, 12, 20, 0, 20, 1, 0, time.UTC), |
| 181 |
|
| 182 |
// array |
| 183 |
[...]int{}, |
| 184 |
[...]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, |
| 185 |
|
| 186 |
// slice |
| 187 |
[]int{}, |
| 188 |
[]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, |
| 189 |
makeSlice(250), |
| 190 |
makeSlice(1020), |
| 191 |
[]string{"A", "B", "C"}, |
| 192 |
[]any{nil, true, false, 0.5, "Hello World!"}, |
| 193 |
|
| 194 |
// map |
| 195 |
makeMapStringBool(0), |
| 196 |
makeMapStringBool(15), |
| 197 |
makeMapStringBool(1020), |
| 198 |
makeMapStringString(0), |
| 199 |
makeMapStringString(15), |
| 200 |
makeMapStringString(1020), |
| 201 |
makeMapStringStringSlice(0), |
| 202 |
makeMapStringStringSlice(15), |
| 203 |
makeMapStringStringSlice(1020), |
| 204 |
makeMapStringInterface(0), |
| 205 |
makeMapStringInterface(15), |
| 206 |
makeMapStringInterface(1020), |
| 207 |
map[int]bool{1: false, 42: true}, |
| 208 |
map[textValue]bool{{1, 2}: true, {3, 4}: false}, |
| 209 |
map[string]*point{ |
| 210 |
"A": {1, 2}, |
| 211 |
"B": {3, 4}, |
| 212 |
"C": {5, 6}, |
| 213 |
}, |
| 214 |
map[string]RawMessage{ |
| 215 |
"A": RawMessage(`{}`), |
| 216 |
"B": RawMessage(`null`), |
| 217 |
"C": RawMessage(`42`), |
| 218 |
}, |
| 219 |
|
| 220 |
// struct |
| 221 |
struct{}{}, |
| 222 |
struct{ A int }{42}, |
| 223 |
struct{ A, B, C int }{1, 2, 3}, |
| 224 |
struct { |
| 225 |
A int |
| 226 |
T time.Time |
| 227 |
S string |
| 228 |
}{42, time.Date(2016, 12, 20, 0, 20, 1, 0, time.UTC), "Hello World!"}, |
| 229 |
// These types are interesting because they fit in a pointer so the compiler |
| 230 |
// puts their value directly into the pointer field of the any that |
| 231 |
// is passed to Marshal. |
| 232 |
struct{ X *int }{}, |
| 233 |
struct{ X *int }{new(int)}, |
| 234 |
struct{ X **int }{}, |
| 235 |
// Struct types with more than one pointer, those exercise the regular |
| 236 |
// pointer handling with code that dereferences the fields. |
| 237 |
struct{ X, Y *int }{}, |
| 238 |
struct{ X, Y *int }{new(int), new(int)}, |
| 239 |
struct { |
| 240 |
A string `json:"name"` |
| 241 |
B string `json:"-"` |
| 242 |
C string `json:",omitempty"` |
| 243 |
D map[string]any `json:",string"` //nolint:staticcheck // intentional |
| 244 |
e string |
| 245 |
}{A: "Luke", D: map[string]any{"answer": float64(42)}}, |
| 246 |
struct{ point }{point{1, 2}}, |
| 247 |
tree{ |
| 248 |
Value: "T", |
| 249 |
Left: &tree{Value: "L"}, |
| 250 |
Right: &tree{Value: "R", Left: &tree{Value: "R-L"}}, |
| 251 |
}, |
| 252 |
|
| 253 |
// pointer |
| 254 |
(*string)(nil), |
| 255 |
new(int), |
| 256 |
|
| 257 |
// Marshaler/Unmarshaler |
| 258 |
jsonValue{}, |
| 259 |
jsonValue{1, 2}, |
| 260 |
|
| 261 |
// encoding.TextMarshaler/encoding.TextUnmarshaler |
| 262 |
textValue{}, |
| 263 |
textValue{1, 2}, |
| 264 |
|
| 265 |
// RawMessage |
| 266 |
RawMessage(`{ |
| 267 |
"answer": 42, |
| 268 |
"hello": "world" |
| 269 |
}`), |
| 270 |
|
| 271 |
// fixtures |
| 272 |
loadTestdata(filepath.Join(runtime.GOROOT(), "src/encoding/json/testdata/code.json.gz")), |
| 273 |
} |
| 274 |
|
| 275 |
var durationTestValues = []any{ |
| 276 |
// duration |
| 277 |
time.Nanosecond, |
| 278 |
time.Microsecond, |
| 279 |
time.Millisecond, |
| 280 |
time.Second, |
| 281 |
time.Minute, |
| 282 |
time.Hour, |
| 283 |
|
| 284 |
// struct with duration |
| 285 |
struct{ D1, D2 time.Duration }{time.Millisecond, time.Hour}, |
| 286 |
} |
| 287 |
|
| 288 |
func makeSlice(n int) []int { |
| 289 |
s := make([]int, n) |
| 290 |
for i := range s { |
| 291 |
s[i] = i |
| 292 |
} |
| 293 |
return s |
| 294 |
} |
| 295 |
|
| 296 |
func makeMapStringBool(n int) map[string]bool { |
| 297 |
m := make(map[string]bool, n) |
| 298 |
for i := range n { |
| 299 |
m[strconv.Itoa(i)] = true |
| 300 |
} |
| 301 |
return m |
| 302 |
} |
| 303 |
|
| 304 |
func makeMapStringString(n int) map[string]string { |
| 305 |
m := make(map[string]string, n) |
| 306 |
for i := range n { |
| 307 |
m[strconv.Itoa(i)] = fmt.Sprintf("%d Hello, world!", i) |
| 308 |
} |
| 309 |
return m |
| 310 |
} |
| 311 |
|
| 312 |
func makeMapStringStringSlice(n int) map[string][]string { |
| 313 |
m := make(map[string][]string, n) |
| 314 |
for i := range n { |
| 315 |
m[strconv.Itoa(i)] = []string{strconv.Itoa(i), "Hello,", "world!"} |
| 316 |
} |
| 317 |
return m |
| 318 |
} |
| 319 |
|
| 320 |
func makeMapStringInterface(n int) map[string]any { |
| 321 |
m := make(map[string]any, n) |
| 322 |
for i := range n { |
| 323 |
m[strconv.Itoa(i)] = nil |
| 324 |
} |
| 325 |
return m |
| 326 |
} |
| 327 |
|
| 328 |
func testName(v any) string { |
| 329 |
return fmt.Sprintf("%T", v) |
| 330 |
} |
| 331 |
|
| 332 |
type codeResponse2 struct { |
| 333 |
Tree *codeNode2 `json:"tree"` |
| 334 |
Username string `json:"username"` |
| 335 |
} |
| 336 |
|
| 337 |
type codeNode2 struct { |
| 338 |
Name string `json:"name"` |
| 339 |
Kids []*codeNode `json:"kids"` |
| 340 |
CLWeight float64 `json:"cl_weight"` |
| 341 |
Touches int `json:"touches"` |
| 342 |
MinT int64 `json:"min_t"` |
| 343 |
MaxT int64 `json:"max_t"` |
| 344 |
MeanT int64 `json:"mean_t"` |
| 345 |
} |
| 346 |
|
| 347 |
func loadTestdata(path string) any { |
| 348 |
f, err := os.Open(path) |
| 349 |
if err != nil { |
| 350 |
return err.Error() |
| 351 |
} |
| 352 |
defer f.Close() |
| 353 |
|
| 354 |
r, err := gzip.NewReader(f) |
| 355 |
if err != nil { |
| 356 |
return err.Error() |
| 357 |
} |
| 358 |
defer r.Close() |
| 359 |
|
| 360 |
testdata := new(codeResponse2) |
| 361 |
if err := json.NewDecoder(r).Decode(testdata); err != nil { |
| 362 |
return err.Error() |
| 363 |
} |
| 364 |
return testdata |
| 365 |
} |
| 366 |
|
| 367 |
func TestCodec(t *testing.T) { |
| 368 |
for _, v1 := range testValues { |
| 369 |
t.Run(testName(v1), func(t *testing.T) { |
| 370 |
v2 := newValue(v1) |
| 371 |
|
| 372 |
a, err := json.MarshalIndent(v1, "", "\t") |
| 373 |
if err != nil { |
| 374 |
t.Error(err) |
| 375 |
return |
| 376 |
} |
| 377 |
a = append(a, '\n') |
| 378 |
|
| 379 |
buf := &bytes.Buffer{} |
| 380 |
enc := NewEncoder(buf) |
| 381 |
enc.SetIndent("", "\t") |
| 382 |
|
| 383 |
if err := enc.Encode(v1); err != nil { |
| 384 |
t.Error(err) |
| 385 |
return |
| 386 |
} |
| 387 |
b := buf.Bytes() |
| 388 |
|
| 389 |
if !Valid(b) { |
| 390 |
t.Error("invalid JSON representation") |
| 391 |
} |
| 392 |
|
| 393 |
if !bytes.Equal(a, b) { |
| 394 |
t.Error("JSON representations mismatch") |
| 395 |
t.Log("expected:", string(a)) |
| 396 |
t.Log("found: ", string(b)) |
| 397 |
} |
| 398 |
|
| 399 |
dec := NewDecoder(bytes.NewBuffer(b)) |
| 400 |
|
| 401 |
if err := dec.Decode(v2.Interface()); err != nil { |
| 402 |
t.Errorf("%T: %v", err, err) |
| 403 |
return |
| 404 |
} |
| 405 |
|
| 406 |
x1 := v1 |
| 407 |
x2 := v2.Elem().Interface() |
| 408 |
|
| 409 |
if !reflect.DeepEqual(x1, x2) { |
| 410 |
t.Error("values mismatch") |
| 411 |
t.Logf("expected: %#v", x1) |
| 412 |
t.Logf("found: %#v", x2) |
| 413 |
} |
| 414 |
|
| 415 |
if b, err := io.ReadAll(dec.Buffered()); err != nil { |
| 416 |
t.Error(err) |
| 417 |
} else if len(b) != 0 { |
| 418 |
t.Errorf("leftover trailing bytes in the decoder: %q", b) |
| 419 |
} |
| 420 |
}) |
| 421 |
} |
| 422 |
} |
| 423 |
|
| 424 |
// TestCodecDuration isolates testing of time.Duration. The stdlib un/marshals |
| 425 |
// this type as integers whereas this library un/marshals formatted string |
| 426 |
// values. Therefore, plugging durations into TestCodec would cause fail since |
| 427 |
// it checks equality on the marshaled strings from the two libraries. |
| 428 |
func TestCodecDuration(t *testing.T) { |
| 429 |
for _, v1 := range durationTestValues { |
| 430 |
t.Run(testName(v1), func(t *testing.T) { |
| 431 |
v2 := newValue(v1) |
| 432 |
|
| 433 |
// encode using stdlib. (will be an int) |
| 434 |
std, err := json.MarshalIndent(v1, "", "\t") |
| 435 |
if err != nil { |
| 436 |
t.Error(err) |
| 437 |
return |
| 438 |
} |
| 439 |
std = append(std, '\n') |
| 440 |
|
| 441 |
// decode using our decoder. (reads int to duration) |
| 442 |
dec := NewDecoder(bytes.NewBuffer([]byte(std))) |
| 443 |
|
| 444 |
if err := dec.Decode(v2.Interface()); err != nil { |
| 445 |
t.Errorf("%T: %v", err, err) |
| 446 |
return |
| 447 |
} |
| 448 |
|
| 449 |
x1 := v1 |
| 450 |
x2 := v2.Elem().Interface() |
| 451 |
|
| 452 |
if !reflect.DeepEqual(x1, x2) { |
| 453 |
t.Error("values mismatch") |
| 454 |
t.Logf("expected: %#v", x1) |
| 455 |
t.Logf("found: %#v", x2) |
| 456 |
} |
| 457 |
|
| 458 |
// encoding using our encoder. (writes duration as string) |
| 459 |
buf := &bytes.Buffer{} |
| 460 |
enc := NewEncoder(buf) |
| 461 |
enc.SetIndent("", "\t") |
| 462 |
|
| 463 |
if err := enc.Encode(v1); err != nil { |
| 464 |
t.Error(err) |
| 465 |
return |
| 466 |
} |
| 467 |
b := buf.Bytes() |
| 468 |
|
| 469 |
if !Valid(b) { |
| 470 |
t.Error("invalid JSON representation") |
| 471 |
} |
| 472 |
|
| 473 |
if reflect.DeepEqual(std, b) { |
| 474 |
t.Error("encoded durations should not match stdlib") |
| 475 |
t.Logf("got: %s", b) |
| 476 |
} |
| 477 |
|
| 478 |
// decode using our decoder. (reads string to duration) |
| 479 |
dec = NewDecoder(bytes.NewBuffer([]byte(std))) |
| 480 |
|
| 481 |
if err := dec.Decode(v2.Interface()); err != nil { |
| 482 |
t.Errorf("%T: %v", err, err) |
| 483 |
return |
| 484 |
} |
| 485 |
|
| 486 |
x1 = v1 |
| 487 |
x2 = v2.Elem().Interface() |
| 488 |
|
| 489 |
if !reflect.DeepEqual(x1, x2) { |
| 490 |
t.Error("values mismatch") |
| 491 |
t.Logf("expected: %#v", x1) |
| 492 |
t.Logf("found: %#v", x2) |
| 493 |
} |
| 494 |
}) |
| 495 |
} |
| 496 |
} |
| 497 |
|
| 498 |
var numericParseTests = [...]struct { |
| 499 |
name string |
| 500 |
input string |
| 501 |
flags ParseFlags |
| 502 |
want any |
| 503 |
}{ |
| 504 |
{ |
| 505 |
name: "zero_flags_default", |
| 506 |
input: `0`, |
| 507 |
flags: 0, |
| 508 |
want: float64(0), |
| 509 |
}, |
| 510 |
{ |
| 511 |
name: "zero_flags_int_uint_bigint_number", |
| 512 |
input: `0`, |
| 513 |
flags: UseInt64 | UseUint64 | UseBigInt | UseNumber, |
| 514 |
want: uint64(0), |
| 515 |
}, |
| 516 |
{ |
| 517 |
name: "zero_flags_int_bigint_number", |
| 518 |
input: `0`, |
| 519 |
flags: UseInt64 | UseBigInt | UseNumber, |
| 520 |
want: int64(0), |
| 521 |
}, |
| 522 |
{ |
| 523 |
name: "zero_flags_bigint_number", |
| 524 |
input: `0`, |
| 525 |
flags: UseBigInt | UseNumber, |
| 526 |
want: big.NewInt(0), |
| 527 |
}, |
| 528 |
{ |
| 529 |
name: "zero_flags_number", |
| 530 |
input: `0`, |
| 531 |
flags: UseNumber, |
| 532 |
want: json.Number(`0`), |
| 533 |
}, |
| 534 |
{ |
| 535 |
name: "max_uint64_flags_default", |
| 536 |
input: fmt.Sprint(uint64(math.MaxUint64)), |
| 537 |
flags: 0, |
| 538 |
want: float64(math.MaxUint64), |
| 539 |
}, |
| 540 |
{ |
| 541 |
name: "max_uint64_flags_int_uint_bigint_number", |
| 542 |
input: fmt.Sprint(uint64(math.MaxUint64)), |
| 543 |
flags: UseInt64 | UseUint64 | UseBigInt | UseNumber, |
| 544 |
want: uint64(math.MaxUint64), |
| 545 |
}, |
| 546 |
{ |
| 547 |
name: "min_int64_flags_uint_int_bigint_number", |
| 548 |
input: fmt.Sprint(int64(math.MinInt64)), |
| 549 |
flags: UseInt64 | UseBigInt | UseNumber, |
| 550 |
want: int64(math.MinInt64), |
| 551 |
}, |
| 552 |
{ |
| 553 |
name: "max_uint64_flags_int_bigint_number", |
| 554 |
input: fmt.Sprint(uint64(math.MaxUint64)), |
| 555 |
flags: UseInt64 | UseBigInt | UseNumber, |
| 556 |
want: new(big.Int).SetUint64(math.MaxUint64), |
| 557 |
}, |
| 558 |
{ |
| 559 |
name: "overflow_uint64_flags_uint_int_bigint_number", |
| 560 |
input: bigPos128.String(), |
| 561 |
flags: UseUint64 | UseInt64 | UseBigInt | UseNumber, |
| 562 |
want: bigPos128, |
| 563 |
}, |
| 564 |
{ |
| 565 |
name: "underflow_uint64_flags_uint_int_bigint_number", |
| 566 |
input: bigNeg128.String(), |
| 567 |
flags: UseUint64 | UseInt64 | UseBigInt | UseNumber, |
| 568 |
want: bigNeg128, |
| 569 |
}, |
| 570 |
{ |
| 571 |
name: "overflow_uint64_flags_uint_int_number", |
| 572 |
input: bigPos128.String(), |
| 573 |
flags: UseUint64 | UseInt64 | UseNumber, |
| 574 |
want: json.Number(bigPos128.String()), |
| 575 |
}, |
| 576 |
{ |
| 577 |
name: "underflow_uint64_flags_uint_int_number", |
| 578 |
input: bigNeg128.String(), |
| 579 |
flags: UseUint64 | UseInt64 | UseNumber, |
| 580 |
want: json.Number(bigNeg128.String()), |
| 581 |
}, |
| 582 |
{ |
| 583 |
name: "overflow_uint64_flags_uint_int", |
| 584 |
input: bigPos128.String(), |
| 585 |
flags: UseUint64 | UseInt64, |
| 586 |
want: float64(1 << 128), |
| 587 |
}, |
| 588 |
{ |
| 589 |
name: "underflow_uint64_flags_uint_int", |
| 590 |
input: bigNeg128.String(), |
| 591 |
flags: UseUint64 | UseInt64, |
| 592 |
want: float64(-1 << 128), |
| 593 |
}, |
| 594 |
} |
| 595 |
|
| 596 |
func TestParse_numeric(t *testing.T) { |
| 597 |
t.Parallel() |
| 598 |
|
| 599 |
for _, test := range numericParseTests { |
| 600 |
test := test |
| 601 |
|
| 602 |
t.Run(test.name, func(t *testing.T) { |
| 603 |
t.Parallel() |
| 604 |
|
| 605 |
var got any |
| 606 |
|
| 607 |
rem, err := Parse([]byte(test.input), &got, test.flags) |
| 608 |
if err != nil { |
| 609 |
format := "Parse(%#q, ..., %#b) = %q [error], want nil" |
| 610 |
t.Errorf(format, test.input, test.flags, err) |
| 611 |
} |
| 612 |
|
| 613 |
if len(rem) != 0 { |
| 614 |
format := "Parse(%#q, ..., %#b) = %#q, want zero length" |
| 615 |
t.Errorf(format, test.input, test.flags, rem) |
| 616 |
} |
| 617 |
|
| 618 |
if !reflect.DeepEqual(got, test.want) { |
| 619 |
format := "Parse(%#q, %#b) -> %T(%#[3]v), want %T(%#[4]v)" |
| 620 |
t.Errorf(format, test.input, test.flags, got, test.want) |
| 621 |
} |
| 622 |
}) |
| 623 |
} |
| 624 |
} |
| 625 |
|
| 626 |
func newValue(model any) reflect.Value { |
| 627 |
if model == nil { |
| 628 |
return reflect.New(reflect.TypeOf(&model).Elem()) |
| 629 |
} |
| 630 |
return reflect.New(reflect.TypeOf(model)) |
| 631 |
} |
| 632 |
|
| 633 |
func BenchmarkMarshal(b *testing.B) { |
| 634 |
j := make([]byte, 0, 128*1024) |
| 635 |
|
| 636 |
for _, v := range testValues { |
| 637 |
b.Run(testName(v), func(b *testing.B) { |
| 638 |
if marshal == nil { |
| 639 |
return |
| 640 |
} |
| 641 |
|
| 642 |
for range b.N { |
| 643 |
j, _ = marshal(j[:0], v) |
| 644 |
} |
| 645 |
|
| 646 |
b.SetBytes(int64(len(j))) |
| 647 |
}) |
| 648 |
} |
| 649 |
} |
| 650 |
|
| 651 |
func BenchmarkUnmarshal(b *testing.B) { |
| 652 |
for _, v := range testValues { |
| 653 |
b.Run(testName(v), func(b *testing.B) { |
| 654 |
if unmarshal == nil { |
| 655 |
return |
| 656 |
} |
| 657 |
|
| 658 |
x := v |
| 659 |
if d, ok := x.(time.Duration); ok { |
| 660 |
x = duration(d) |
| 661 |
} |
| 662 |
|
| 663 |
j, _ := json.Marshal(x) |
| 664 |
x = newValue(v).Interface() |
| 665 |
|
| 666 |
for range b.N { |
| 667 |
unmarshal(j, x) |
| 668 |
} |
| 669 |
|
| 670 |
b.SetBytes(int64(len(j))) |
| 671 |
}) |
| 672 |
} |
| 673 |
} |
| 674 |
|
| 675 |
type buffer struct{ data []byte } |
| 676 |
|
| 677 |
func (buf *buffer) Write(b []byte) (int, error) { |
| 678 |
buf.data = append(buf.data, b...) |
| 679 |
return len(b), nil |
| 680 |
} |
| 681 |
|
| 682 |
func (buf *buffer) WriteString(s string) (int, error) { |
| 683 |
buf.data = append(buf.data, s...) |
| 684 |
return len(s), nil |
| 685 |
} |
| 686 |
|
| 687 |
type jsonValue struct { |
| 688 |
x int32 |
| 689 |
y int32 |
| 690 |
} |
| 691 |
|
| 692 |
func (v jsonValue) MarshalJSON() ([]byte, error) { |
| 693 |
return Marshal([2]int32{v.x, v.y}) |
| 694 |
} |
| 695 |
|
| 696 |
func (v *jsonValue) UnmarshalJSON(b []byte) error { |
| 697 |
var a [2]int32 |
| 698 |
err := Unmarshal(b, &a) |
| 699 |
v.x = a[0] |
| 700 |
v.y = a[1] |
| 701 |
return err |
| 702 |
} |
| 703 |
|
| 704 |
type textValue struct { |
| 705 |
x int32 |
| 706 |
y int32 |
| 707 |
} |
| 708 |
|
| 709 |
func (v textValue) MarshalText() ([]byte, error) { |
| 710 |
return []byte(fmt.Sprintf("(%d,%d)", v.x, v.y)), nil |
| 711 |
} |
| 712 |
|
| 713 |
func (v *textValue) UnmarshalText(b []byte) error { |
| 714 |
_, err := fmt.Sscanf(string(b), "(%d,%d)", &v.x, &v.y) |
| 715 |
return err |
| 716 |
} |
| 717 |
|
| 718 |
type duration time.Duration |
| 719 |
|
| 720 |
func (d duration) MarshalJSON() ([]byte, error) { |
| 721 |
return []byte(`"` + time.Duration(d).String() + `"`), nil |
| 722 |
} |
| 723 |
|
| 724 |
func (d *duration) UnmarshalJSON(b []byte) error { |
| 725 |
var s string |
| 726 |
if err := json.Unmarshal(b, &s); err != nil { |
| 727 |
return err |
| 728 |
} |
| 729 |
x, err := time.ParseDuration(s) |
| 730 |
*d = duration(x) |
| 731 |
return err |
| 732 |
} |
| 733 |
|
| 734 |
var ( |
| 735 |
_ Marshaler = jsonValue{} |
| 736 |
_ Marshaler = duration(0) |
| 737 |
|
| 738 |
_ encoding.TextMarshaler = textValue{} |
| 739 |
|
| 740 |
_ Unmarshaler = (*jsonValue)(nil) |
| 741 |
_ Unmarshaler = (*duration)(nil) |
| 742 |
|
| 743 |
_ encoding.TextUnmarshaler = (*textValue)(nil) |
| 744 |
) |
| 745 |
|
| 746 |
func TestDecodeStructFieldCaseInsensitive(t *testing.T) { |
| 747 |
b := []byte(`{ "type": "changed" }`) |
| 748 |
s := struct { |
| 749 |
Type string |
| 750 |
}{"unchanged"} |
| 751 |
|
| 752 |
if err := Unmarshal(b, &s); err != nil { |
| 753 |
t.Error(err) |
| 754 |
} |
| 755 |
|
| 756 |
if s.Type != "changed" { |
| 757 |
t.Error("s.Type: expected to be changed but found", s.Type) |
| 758 |
} |
| 759 |
} |
| 760 |
|
| 761 |
func TestDecodeLines(t *testing.T) { |
| 762 |
tests := []struct { |
| 763 |
desc string |
| 764 |
reader io.Reader |
| 765 |
expectCount int |
| 766 |
}{ |
| 767 |
// simple |
| 768 |
|
| 769 |
{ |
| 770 |
desc: "bare object", |
| 771 |
reader: strings.NewReader("{\"Good\":true}"), |
| 772 |
expectCount: 1, |
| 773 |
}, |
| 774 |
{ |
| 775 |
desc: "multiple objects on one line", |
| 776 |
reader: strings.NewReader("{\"Good\":true}{\"Good\":true}\n"), |
| 777 |
expectCount: 2, |
| 778 |
}, |
| 779 |
{ |
| 780 |
desc: "object spanning multiple lines", |
| 781 |
reader: strings.NewReader("{\n\"Good\":true\n}\n"), |
| 782 |
expectCount: 1, |
| 783 |
}, |
| 784 |
|
| 785 |
// whitespace handling |
| 786 |
|
| 787 |
{ |
| 788 |
desc: "trailing newline", |
| 789 |
reader: strings.NewReader("{\"Good\":true}\n{\"Good\":true}\n"), |
| 790 |
expectCount: 2, |
| 791 |
}, |
| 792 |
{ |
| 793 |
desc: "multiple trailing newlines", |
| 794 |
reader: strings.NewReader("{\"Good\":true}\n{\"Good\":true}\n\n"), |
| 795 |
expectCount: 2, |
| 796 |
}, |
| 797 |
{ |
| 798 |
desc: "blank lines", |
| 799 |
reader: strings.NewReader("{\"Good\":true}\n\n{\"Good\":true}"), |
| 800 |
expectCount: 2, |
| 801 |
}, |
| 802 |
{ |
| 803 |
desc: "no trailing newline", |
| 804 |
reader: strings.NewReader("{\"Good\":true}\n{\"Good\":true}"), |
| 805 |
expectCount: 2, |
| 806 |
}, |
| 807 |
{ |
| 808 |
desc: "leading whitespace", |
| 809 |
reader: strings.NewReader(" {\"Good\":true}\n\t{\"Good\":true}"), |
| 810 |
expectCount: 2, |
| 811 |
}, |
| 812 |
|
| 813 |
// multiple reads |
| 814 |
|
| 815 |
{ |
| 816 |
desc: "one object, multiple reads", |
| 817 |
reader: io.MultiReader( |
| 818 |
strings.NewReader("{"), |
| 819 |
strings.NewReader("\"Good\": true"), |
| 820 |
strings.NewReader("}\n"), |
| 821 |
), |
| 822 |
expectCount: 1, |
| 823 |
}, |
| 824 |
|
| 825 |
// EOF reads |
| 826 |
|
| 827 |
{ |
| 828 |
desc: "one object + EOF", |
| 829 |
reader: &eofReader{"{\"Good\":true}\n"}, |
| 830 |
expectCount: 1, |
| 831 |
}, |
| 832 |
{ |
| 833 |
desc: "leading whitespace + EOF", |
| 834 |
reader: &eofReader{"\n{\"Good\":true}\n"}, |
| 835 |
expectCount: 1, |
| 836 |
}, |
| 837 |
{ |
| 838 |
desc: "multiple objects + EOF", |
| 839 |
reader: &eofReader{"{\"Good\":true}\n{\"Good\":true}\n"}, |
| 840 |
expectCount: 2, |
| 841 |
}, |
| 842 |
{ |
| 843 |
desc: "one object + multiple reads + EOF", |
| 844 |
reader: io.MultiReader( |
| 845 |
strings.NewReader("{"), |
| 846 |
strings.NewReader(" \"Good\": true"), |
| 847 |
&eofReader{"}\n"}, |
| 848 |
), |
| 849 |
expectCount: 1, |
| 850 |
}, |
| 851 |
{ |
| 852 |
desc: "multiple objects + multiple reads + EOF", |
| 853 |
reader: io.MultiReader( |
| 854 |
strings.NewReader("{"), |
| 855 |
strings.NewReader(" \"Good\": true}{\"Good\": true}"), |
| 856 |
&eofReader{"\n"}, |
| 857 |
), |
| 858 |
expectCount: 2, |
| 859 |
}, |
| 860 |
|
| 861 |
{ |
| 862 |
// the 2nd object should be discarded, as 42 cannot be cast to bool |
| 863 |
desc: "unmarshal error while decoding", |
| 864 |
reader: strings.NewReader("{\"Good\":true}\n{\"Good\":42}\n{\"Good\":true}\n"), |
| 865 |
expectCount: 2, |
| 866 |
}, |
| 867 |
{ |
| 868 |
// the 2nd object should be discarded, as 42 cannot be cast to bool |
| 869 |
desc: "unmarshal error while decoding last object", |
| 870 |
reader: strings.NewReader("{\"Good\":true}\n{\"Good\":42}\n"), |
| 871 |
expectCount: 1, |
| 872 |
}, |
| 873 |
} |
| 874 |
|
| 875 |
type obj struct { |
| 876 |
Good bool |
| 877 |
} |
| 878 |
|
| 879 |
for _, test := range tests { |
| 880 |
t.Run(test.desc, func(t *testing.T) { |
| 881 |
d := NewDecoder(test.reader) |
| 882 |
var count int |
| 883 |
for { |
| 884 |
var o obj |
| 885 |
err := d.Decode(&o) |
| 886 |
if err != nil { |
| 887 |
if errors.Is(err, io.EOF) { |
| 888 |
break |
| 889 |
} |
| 890 |
|
| 891 |
switch err.(type) { |
| 892 |
case *SyntaxError, *UnmarshalTypeError, *UnmarshalFieldError: |
| 893 |
t.Log("unmarshal error", err) |
| 894 |
continue |
| 895 |
} |
| 896 |
|
| 897 |
t.Error("decode error", err) |
| 898 |
break |
| 899 |
} |
| 900 |
if !o.Good { |
| 901 |
t.Errorf("object was not unmarshaled correctly: %#v", o) |
| 902 |
} |
| 903 |
count++ |
| 904 |
} |
| 905 |
|
| 906 |
if count != test.expectCount { |
| 907 |
t.Errorf("expected %d objects, got %d", test.expectCount, count) |
| 908 |
} |
| 909 |
}) |
| 910 |
} |
| 911 |
} |
| 912 |
|
| 913 |
// eofReader is a simple io.Reader that reads its full contents _and_ returns |
| 914 |
// and EOF in the first call. Subsequent Read calls only return EOF. |
| 915 |
type eofReader struct { |
| 916 |
s string |
| 917 |
} |
| 918 |
|
| 919 |
func (r *eofReader) Read(p []byte) (n int, err error) { |
| 920 |
n = copy(p, r.s) |
| 921 |
r.s = r.s[n:] |
| 922 |
if r.s == "" { |
| 923 |
err = io.EOF |
| 924 |
} |
| 925 |
return |
| 926 |
} |
| 927 |
|
| 928 |
func TestDontMatchCaseIncensitiveStructFields(t *testing.T) { |
| 929 |
b := []byte(`{ "type": "changed" }`) |
| 930 |
s := struct { |
| 931 |
Type string |
| 932 |
}{"unchanged"} |
| 933 |
|
| 934 |
if _, err := Parse(b, &s, DontMatchCaseInsensitiveStructFields); err != nil { |
| 935 |
t.Error(err) |
| 936 |
} |
| 937 |
|
| 938 |
if s.Type != "unchanged" { |
| 939 |
t.Error("s.Type: expected to be unchanged but found", s.Type) |
| 940 |
} |
| 941 |
} |
| 942 |
|
| 943 |
func TestMarshalFuzzBugs(t *testing.T) { |
| 944 |
tests := []struct { |
| 945 |
value any |
| 946 |
output string |
| 947 |
}{ |
| 948 |
{ // html sequences are escaped even in RawMessage |
| 949 |
value: struct { |
| 950 |
P RawMessage |
| 951 |
}{P: RawMessage(`"<"`)}, |
| 952 |
output: "{\"P\":\"\\u003c\"}", |
| 953 |
}, |
| 954 |
{ // raw message output is compacted |
| 955 |
value: struct { |
| 956 |
P RawMessage |
| 957 |
}{P: RawMessage(`{"" :{}}`)}, |
| 958 |
output: "{\"P\":{\"\":{}}}", |
| 959 |
}, |
| 960 |
} |
| 961 |
|
| 962 |
for _, test := range tests { |
| 963 |
t.Run("", func(t *testing.T) { |
| 964 |
b, err := Marshal(test.value) |
| 965 |
if err != nil { |
| 966 |
t.Fatal(err) |
| 967 |
} |
| 968 |
|
| 969 |
if string(b) != test.output { |
| 970 |
t.Error("values mismatch") |
| 971 |
t.Logf("expected: %#v", test.output) |
| 972 |
t.Logf("found: %#v", string(b)) |
| 973 |
} |
| 974 |
}) |
| 975 |
} |
| 976 |
} |
| 977 |
|
| 978 |
func TestUnmarshalFuzzBugs(t *testing.T) { |
| 979 |
tests := []struct { |
| 980 |
input string |
| 981 |
value any |
| 982 |
}{ |
| 983 |
{ // non-UTF8 sequences must be converted to the utf8.RuneError character. |
| 984 |
input: "[\"00000\xef\"]", |
| 985 |
value: []any{"00000�"}, |
| 986 |
}, |
| 987 |
{ // UTF16 surrogate followed by null character |
| 988 |
input: "[\"\\ud800\\u0000\"]", |
| 989 |
value: []any{"�\x00"}, |
| 990 |
}, |
| 991 |
{ // UTF16 surrogate followed by ascii character |
| 992 |
input: "[\"\\uDF00\\u000e\"]", |
| 993 |
value: []any{"�\x0e"}, |
| 994 |
}, |
| 995 |
{ // UTF16 surrogate followed by unicode character |
| 996 |
input: "[[\"\\uDF00\\u0800\"]]", |
| 997 |
value: []any{[]any{"�ࠀ"}}, |
| 998 |
}, |
| 999 |
{ // invalid UTF16 surrogate sequenced followed by a valid UTF16 surrogate sequence |
| 1000 |
input: "[\"\\udf00\\udb00\\udf00\"]", |
| 1001 |
value: []any{"�\U000d0300"}, |
| 1002 |
}, |
| 1003 |
{ // decode single-element slice into []byte field |
| 1004 |
input: "{\"f\":[0],\"0\":[0]}", |
| 1005 |
value: struct{ F []byte }{F: []byte{0}}, |
| 1006 |
}, |
| 1007 |
{ // decode multi-element slice into []byte field |
| 1008 |
input: "{\"F\":[3,1,1,1,9,9]}", |
| 1009 |
value: struct{ F []byte }{F: []byte{3, 1, 1, 1, 9, 9}}, |
| 1010 |
}, |
| 1011 |
{ // decode string with escape sequence into []byte field |
| 1012 |
input: "{\"F\":\"0p00\\r\"}", |
| 1013 |
value: struct{ F []byte }{F: []byte("ҝ4")}, |
| 1014 |
}, |
| 1015 |
{ // decode unicode code points which fold into ascii characters |
| 1016 |
input: "{\"ſ\":\"8\"}", |
| 1017 |
value: struct { |
| 1018 |
S int `json:",string"` |
| 1019 |
}{S: 8}, |
| 1020 |
}, |
| 1021 |
{ // decode unicode code points which don't fold into ascii characters |
| 1022 |
input: "{\"İ\":\"\"}", |
| 1023 |
value: struct{ I map[string]string }{I: nil}, |
| 1024 |
}, |
| 1025 |
{ // override pointer-to-pointer field clears the inner pointer only |
| 1026 |
input: "{\"o\":0,\"o\":null}", |
| 1027 |
value: struct{ O **int }{O: new(*int)}, |
| 1028 |
}, |
| 1029 |
{ // subsequent occurrences of a map field retain keys previously loaded |
| 1030 |
input: "{\"i\":{\"\":null},\"i\":{}}", |
| 1031 |
value: struct{ I map[string]string }{I: map[string]string{"": ""}}, |
| 1032 |
}, |
| 1033 |
{ // an empty string is an invalid JSON input |
| 1034 |
input: "", |
| 1035 |
}, |
| 1036 |
{ // ASCII character below 0x20 are invalid JSON input |
| 1037 |
input: "[\"\b\"]", |
| 1038 |
}, |
| 1039 |
{ // random byte before any value |
| 1040 |
input: "\xad", |
| 1041 |
}, |
| 1042 |
{ // cloud be the beginning of a false value but not |
| 1043 |
input: "f", |
| 1044 |
value: false, |
| 1045 |
}, |
| 1046 |
{ // random ASCII character |
| 1047 |
input: "}", |
| 1048 |
value: []any{}, |
| 1049 |
}, |
| 1050 |
{ // random byte after valid JSON, decoded to a nil type |
| 1051 |
input: "0\x93", |
| 1052 |
}, |
| 1053 |
{ // random byte after valid JSON, decoded to a int type |
| 1054 |
input: "0\x93", |
| 1055 |
value: 0, |
| 1056 |
}, |
| 1057 |
{ // random byte after valid JSON, decoded to a slice type |
| 1058 |
input: "0\x93", |
| 1059 |
value: []any{}, |
| 1060 |
}, |
| 1061 |
{ // decode integer into slice |
| 1062 |
input: "0", |
| 1063 |
value: []any{}, |
| 1064 |
}, |
| 1065 |
{ // decode integer with trailing space into slice |
| 1066 |
input: "0\t", |
| 1067 |
value: []any{}, |
| 1068 |
}, |
| 1069 |
{ // decode integer with leading random bytes into slice |
| 1070 |
input: "\b0", |
| 1071 |
value: []any{}, |
| 1072 |
}, |
| 1073 |
{ // decode string into slice followed by number |
| 1074 |
input: "\"\"0", |
| 1075 |
value: []any{}, |
| 1076 |
}, |
| 1077 |
{ // decode what looks like an object followed by a number into a string |
| 1078 |
input: "{0", |
| 1079 |
value: "", |
| 1080 |
}, |
| 1081 |
{ // decode what looks like an object followed by a number into a map |
| 1082 |
input: "{0", |
| 1083 |
value: map[string]string{}, |
| 1084 |
}, |
| 1085 |
{ // decode string into string with trailing random byte |
| 1086 |
input: "\"\"\f", |
| 1087 |
value: "", |
| 1088 |
}, |
| 1089 |
{ // decode weird number value into nil |
| 1090 |
input: "-00", |
| 1091 |
}, |
| 1092 |
{ // decode an invalid escaped sequence |
| 1093 |
input: "\"\\0\"", |
| 1094 |
value: "", |
| 1095 |
}, |
| 1096 |
{ // decode what looks like an array followed by a number into a slice |
| 1097 |
input: "[9E600", |
| 1098 |
value: []any{}, |
| 1099 |
}, |
| 1100 |
{ // decode a number which is too large to fit in a float64 |
| 1101 |
input: "[1e900]", |
| 1102 |
value: []any{}, |
| 1103 |
}, |
| 1104 |
{ // many nested arrays openings |
| 1105 |
input: "[[[[[[", |
| 1106 |
value: []any{}, |
| 1107 |
}, |
| 1108 |
{ // decode a map with value type mismatch and missing closing character |
| 1109 |
input: "{\"\":0", |
| 1110 |
value: map[string]string{}, |
| 1111 |
}, |
| 1112 |
{ // decode a struct with value type mismatch and missing closing character |
| 1113 |
input: "{\"E\":\"\"", |
| 1114 |
value: struct{ E uint8 }{}, |
| 1115 |
}, |
| 1116 |
{ // decode a map with value type mismatch |
| 1117 |
input: "{\"\":0}", |
| 1118 |
value: map[string]string{}, |
| 1119 |
}, |
| 1120 |
{ // decode number with exponent into integer field |
| 1121 |
input: "{\"e\":0e0}", |
| 1122 |
value: struct{ E uint8 }{}, |
| 1123 |
}, |
| 1124 |
{ // decode invalid integer representation into integer field |
| 1125 |
input: "{\"e\":00}", |
| 1126 |
value: struct{ E uint8 }{}, |
| 1127 |
}, |
| 1128 |
{ // decode unterminated array into byte slice |
| 1129 |
input: "{\"F\":[", |
| 1130 |
value: struct{ F []byte }{}, |
| 1131 |
}, |
| 1132 |
{ // attempt to decode string into in |
| 1133 |
input: "{\"S\":\"\"}", |
| 1134 |
value: struct { |
| 1135 |
S int `json:",string"` |
| 1136 |
}{}, |
| 1137 |
}, |
| 1138 |
{ // decode object with null key into map |
| 1139 |
input: "{null:0}", |
| 1140 |
value: map[string]any{}, |
| 1141 |
}, |
| 1142 |
{ // decode unquoted integer into struct field with string tag |
| 1143 |
input: "{\"S\":0}", |
| 1144 |
value: struct { |
| 1145 |
S int `json:",string"` |
| 1146 |
}{}, |
| 1147 |
}, |
| 1148 |
{ // invalid base64 content when decoding string into byte slice |
| 1149 |
input: "{\"F\":\"0\"}", |
| 1150 |
value: struct{ F []byte }{}, |
| 1151 |
}, |
| 1152 |
{ // decode an object with a "null" string as key |
| 1153 |
input: "{\"null\":null}", |
| 1154 |
value: struct { |
| 1155 |
S int `json:",string"` |
| 1156 |
}{}, |
| 1157 |
}, |
| 1158 |
{ // decode an invalid floating point number representation into an integer field with string tag |
| 1159 |
input: "{\"s\":8e800}", |
| 1160 |
value: struct { |
| 1161 |
S int `json:",string"` |
| 1162 |
}{}, |
| 1163 |
}, |
| 1164 |
{ // decode a string with leading zeroes into an integer field with string tag |
| 1165 |
input: "{\"S\":\"00\"}", |
| 1166 |
value: struct { |
| 1167 |
S int `json:",string"` |
| 1168 |
}{}, |
| 1169 |
}, |
| 1170 |
{ // decode a string with invalid leading sign and zeroes into an integer field with string tag |
| 1171 |
input: "{\"S\":\"+00\"}", |
| 1172 |
value: struct { |
| 1173 |
S int `json:",string"` |
| 1174 |
}{}, |
| 1175 |
}, |
| 1176 |
{ // decode a string with valid leading sign and zeroes into an integer field with string tag |
| 1177 |
input: "{\"S\":\"-00\"}", |
| 1178 |
value: struct { |
| 1179 |
S int `json:",string"` |
| 1180 |
}{}, |
| 1181 |
}, |
| 1182 |
{ // decode non-ascii string into integer field with string tag |
| 1183 |
input: "{\"ſ\":\"\xbf\"}", |
| 1184 |
value: struct { |
| 1185 |
S int `json:",string"` |
| 1186 |
}{}, |
| 1187 |
}, |
| 1188 |
{ // decode a valid floating point number representation into an integer field with string tag |
| 1189 |
input: "{\"S\":0.0}", |
| 1190 |
value: struct { |
| 1191 |
S int `json:",string"` |
| 1192 |
}{}, |
| 1193 |
}, |
| 1194 |
{ // decode string with invalid leading sign to integer field with string tag |
| 1195 |
input: "{\"S\":\"+0\"}", |
| 1196 |
value: struct { |
| 1197 |
S int `json:",string"` |
| 1198 |
}{}, |
| 1199 |
}, |
| 1200 |
{ // decode string with valid leading sign to integer field with string tag |
| 1201 |
input: "{\"S\":\"-0\"}", |
| 1202 |
value: struct { |
| 1203 |
S int `json:",string"` |
| 1204 |
}{}, |
| 1205 |
}, |
| 1206 |
{ // decode string with object representation to integer field with string tag |
| 1207 |
input: "{\"s\":{}}", |
| 1208 |
value: struct { |
| 1209 |
S int `json:",string"` |
| 1210 |
}{}, |
| 1211 |
}, |
| 1212 |
{ // decoding integer with leading zeroes |
| 1213 |
input: "{\"o\":00}", |
| 1214 |
value: struct{ O **int }{}, |
| 1215 |
}, |
| 1216 |
{ // codeding string with invalid float representation into integer field with string tag |
| 1217 |
input: "{\"s\":\"0.\"}", |
| 1218 |
value: struct { |
| 1219 |
S int `json:",string"` |
| 1220 |
}{}, |
| 1221 |
}, |
| 1222 |
{ // malformed negative integer in object value |
| 1223 |
input: "{\"N\":-00}", |
| 1224 |
value: struct{ N *int }{}, |
| 1225 |
}, |
| 1226 |
{ // integer overflow |
| 1227 |
input: "{\"a\":9223372036854775808}", |
| 1228 |
value: struct { |
| 1229 |
A int `json:",omitempty"` |
| 1230 |
}{}, |
| 1231 |
}, |
| 1232 |
{ // decode string with number followed by random byte into integer field with string tag |
| 1233 |
input: "{\"s\":\"0]\"}", |
| 1234 |
value: struct { |
| 1235 |
S int `json:",string"` |
| 1236 |
}{}, |
| 1237 |
}, |
| 1238 |
{ // decode object into integer field |
| 1239 |
input: "{\"n\":{}}", |
| 1240 |
value: struct{ N *int }{}, |
| 1241 |
}, |
| 1242 |
{ // decode negative integer into unsigned type |
| 1243 |
input: "{\"E\":-0}", |
| 1244 |
value: struct{ E uint8 }{}, |
| 1245 |
}, |
| 1246 |
{ // decode string with number followed by random byte into integer field with string tag |
| 1247 |
input: "{\"s\":\"03�\"}", |
| 1248 |
value: struct { |
| 1249 |
S int `json:",string"` |
| 1250 |
}{}, |
| 1251 |
}, |
| 1252 |
{ // decode string with leading zeroes into integer field with string tag |
| 1253 |
input: "{\"s\":\"03\"}", |
| 1254 |
value: struct { |
| 1255 |
S int `json:",string"` |
| 1256 |
}{S: 3}, |
| 1257 |
}, |
| 1258 |
{ // decode string containing what looks like an object into integer field with string tag |
| 1259 |
input: "{\"S\":\"{}\"}", |
| 1260 |
value: struct { |
| 1261 |
S int `json:",string"` |
| 1262 |
}{}, |
| 1263 |
}, |
| 1264 |
{ // decode an empty string followed by the same field with a null value into a byte slice |
| 1265 |
input: "{\"F\":\"\",\"F\":null}", |
| 1266 |
value: struct{ F []byte }{}, |
| 1267 |
}, |
| 1268 |
{ // decode string containing a float into an integer field with string tag |
| 1269 |
input: "{\"S\":\"0e0\"}", |
| 1270 |
value: struct { |
| 1271 |
S int `json:",string"` |
| 1272 |
}{}, |
| 1273 |
}, |
| 1274 |
{ // decode string with negative sign into a an integer field with string tag |
| 1275 |
input: "{\"s\":\"-\"}", |
| 1276 |
value: struct { |
| 1277 |
S int `json:",string"` |
| 1278 |
}{}, |
| 1279 |
}, |
| 1280 |
{ // decode string with positive sign into a an integer field with string tag |
| 1281 |
input: "{\"s\":\"+\"}", |
| 1282 |
value: struct { |
| 1283 |
S int `json:",string"` |
| 1284 |
}{}, |
| 1285 |
}, |
| 1286 |
{ // decode an integer into a json unmarshaler |
| 1287 |
input: "{\"q\":0}", |
| 1288 |
value: struct { |
| 1289 |
Q testMarshaller |
| 1290 |
}{}, |
| 1291 |
}, |
| 1292 |
// This test fails because it appears that the encoding/json package |
| 1293 |
// will decode "q" before "s", so it returns an error about "q" being of |
| 1294 |
// the wrong type while this package will prase object keys in the order |
| 1295 |
// that they appear in the JSON input, so it detects the error from "s" |
| 1296 |
// first. |
| 1297 |
// |
| 1298 |
//{ |
| 1299 |
// input: "{\"s\":0,\"q\":0}", |
| 1300 |
// value: struct { |
| 1301 |
// Q testMarshaller |
| 1302 |
// S int `json:",string"` |
| 1303 |
// }{}, |
| 1304 |
//}, |
| 1305 |
} |
| 1306 |
|
| 1307 |
for _, test := range tests { |
| 1308 |
t.Run("", func(t *testing.T) { |
| 1309 |
var ptr1 any |
| 1310 |
var ptr2 any |
| 1311 |
|
| 1312 |
if test.value != nil { |
| 1313 |
ptr1 = reflect.New(reflect.TypeOf(test.value)).Interface() |
| 1314 |
ptr2 = reflect.New(reflect.TypeOf(test.value)).Interface() |
| 1315 |
} |
| 1316 |
|
| 1317 |
err1 := json.Unmarshal([]byte(test.input), ptr1) |
| 1318 |
err2 := Unmarshal([]byte(test.input), ptr2) |
| 1319 |
|
| 1320 |
if reflect.TypeOf(err1) != reflect.TypeOf(err2) { |
| 1321 |
t.Error("errors mismatch") |
| 1322 |
t.Logf("expected: %T: %v", err1, err1) |
| 1323 |
t.Logf("found: %T: %v", err2, err2) |
| 1324 |
} else if err1 == nil && test.value != nil { |
| 1325 |
if value := reflect.ValueOf(ptr2).Elem().Interface(); !reflect.DeepEqual(test.value, value) { |
| 1326 |
t.Error("values mismatch") |
| 1327 |
t.Logf("expected: %#v", test.value) |
| 1328 |
t.Logf("found: %#v", value) |
| 1329 |
} |
| 1330 |
} |
| 1331 |
}) |
| 1332 |
} |
| 1333 |
} |
| 1334 |
|
| 1335 |
func BenchmarkEasyjsonUnmarshalSmallStruct(b *testing.B) { |
| 1336 |
type Hashtag struct { |
| 1337 |
Indices []int `json:"indices"` |
| 1338 |
Text string `json:"text"` |
| 1339 |
} |
| 1340 |
|
| 1341 |
//easyjson:json |
| 1342 |
type Entities struct { |
| 1343 |
Hashtags []Hashtag `json:"hashtags"` |
| 1344 |
Urls []*string `json:"urls"` |
| 1345 |
UserMentions []*string `json:"user_mentions"` |
| 1346 |
} |
| 1347 |
|
| 1348 |
json := []byte(`{"hashtags":[{"indices":[5, 10],"text":"some-text"}],"urls":[],"user_mentions":[]}`) |
| 1349 |
|
| 1350 |
for range b.N { |
| 1351 |
var value Entities |
| 1352 |
if err := Unmarshal(json, &value); err != nil { |
| 1353 |
b.Fatal(err) |
| 1354 |
} |
| 1355 |
} |
| 1356 |
} |
| 1357 |
|
| 1358 |
type testMarshaller struct { |
| 1359 |
v string |
| 1360 |
} |
| 1361 |
|
| 1362 |
func (m *testMarshaller) MarshalJSON() ([]byte, error) { |
| 1363 |
return Marshal(m.v) |
| 1364 |
} |
| 1365 |
|
| 1366 |
func (m *testMarshaller) UnmarshalJSON(data []byte) error { |
| 1367 |
return Unmarshal(data, &m.v) |
| 1368 |
} |
| 1369 |
|
| 1370 |
func TestGithubIssue11(t *testing.T) { |
| 1371 |
// https://github.com/segmentio/encoding/issues/11 |
| 1372 |
v := struct{ F float64 }{ |
| 1373 |
F: math.NaN(), |
| 1374 |
} |
| 1375 |
|
| 1376 |
_, err := Marshal(v) |
| 1377 |
if err == nil { |
| 1378 |
t.Error("no error returned when marshalling NaN value") |
| 1379 |
} else if s := err.Error(); !strings.Contains(s, "NaN") { |
| 1380 |
t.Error("error returned when marshalling NaN value does not mention 'NaN':", s) |
| 1381 |
} else { |
| 1382 |
t.Log(s) |
| 1383 |
} |
| 1384 |
} |
| 1385 |
|
| 1386 |
type Issue13 struct { |
| 1387 |
Stringer fmt.Stringer |
| 1388 |
Field int `json:"MyInt"` |
| 1389 |
} |
| 1390 |
|
| 1391 |
type S string |
| 1392 |
|
| 1393 |
func (s S) String() string { return string(s) } |
| 1394 |
|
| 1395 |
func TestGithubIssue13(t *testing.T) { |
| 1396 |
// https://github.com/segmentio/encoding/issues/13 |
| 1397 |
v := Issue13{} |
| 1398 |
|
| 1399 |
b, err := Marshal(v) |
| 1400 |
if err != nil { |
| 1401 |
t.Error("unexpected errror:", err) |
| 1402 |
} else { |
| 1403 |
t.Log(string(b)) |
| 1404 |
} |
| 1405 |
|
| 1406 |
v = Issue13{Stringer: S("")} |
| 1407 |
if err := Unmarshal([]byte(`{"Stringer":null}`), &v); err != nil { |
| 1408 |
t.Error("unexpected error:", err) |
| 1409 |
} |
| 1410 |
if v.Stringer != nil { |
| 1411 |
t.Error("Stringer field was not overwritten") |
| 1412 |
} |
| 1413 |
|
| 1414 |
v = Issue13{} |
| 1415 |
if err := Unmarshal([]byte(`{"Stringer":"whatever"}`), &v); err == nil { |
| 1416 |
t.Error("expected error but decoding string value into nil fmt.Stringer but got <nil>") |
| 1417 |
} |
| 1418 |
|
| 1419 |
v = Issue13{Stringer: S("")} |
| 1420 |
if err := Unmarshal([]byte(`{"Stringer":"whatever"}`), &v); err == nil { |
| 1421 |
t.Error("expected error but decoding string value into non-pointer fmt.Stringer but got <nil>") |
| 1422 |
} |
| 1423 |
|
| 1424 |
s := S("") |
| 1425 |
v = Issue13{Stringer: &s} |
| 1426 |
if err := Unmarshal([]byte(`{"Stringer":"whatever"}`), &v); err != nil { |
| 1427 |
t.Error("unexpected error decoding string value into pointer fmt.Stringer:", err) |
| 1428 |
} |
| 1429 |
} |
| 1430 |
|
| 1431 |
func TestGithubIssue15(t *testing.T) { |
| 1432 |
// https://github.com/segmentio/encoding/issues/15 |
| 1433 |
tests := []struct { |
| 1434 |
m any |
| 1435 |
s string |
| 1436 |
}{ |
| 1437 |
{ |
| 1438 |
m: map[uint]bool{1: true, 123: true, 333: true, 42: true}, |
| 1439 |
s: `{"1":true,"123":true,"333":true,"42":true}`, |
| 1440 |
}, |
| 1441 |
{ |
| 1442 |
m: map[int]bool{-1: true, -123: true, 333: true, 42: true}, |
| 1443 |
s: `{"-1":true,"-123":true,"333":true,"42":true}`, |
| 1444 |
}, |
| 1445 |
} |
| 1446 |
|
| 1447 |
for _, test := range tests { |
| 1448 |
b, _ := Marshal(test.m) |
| 1449 |
|
| 1450 |
if string(b) != test.s { |
| 1451 |
t.Error("map with integer keys must be ordered by their string representation, got", string(b)) |
| 1452 |
} |
| 1453 |
|
| 1454 |
} |
| 1455 |
} |
| 1456 |
|
| 1457 |
type sliceA []byte |
| 1458 |
|
| 1459 |
func (sliceA) MarshalJSON() ([]byte, error) { |
| 1460 |
return []byte(`"A"`), nil |
| 1461 |
} |
| 1462 |
|
| 1463 |
type sliceB []byte |
| 1464 |
|
| 1465 |
func (sliceB) MarshalText() ([]byte, error) { |
| 1466 |
return []byte("B"), nil |
| 1467 |
} |
| 1468 |
|
| 1469 |
type mapA map[string]string |
| 1470 |
|
| 1471 |
func (mapA) MarshalJSON() ([]byte, error) { |
| 1472 |
return []byte(`"A"`), nil |
| 1473 |
} |
| 1474 |
|
| 1475 |
type mapB map[string]string |
| 1476 |
|
| 1477 |
func (mapB) MarshalText() ([]byte, error) { |
| 1478 |
return []byte("B"), nil |
| 1479 |
} |
| 1480 |
|
| 1481 |
type intPtrA int |
| 1482 |
|
| 1483 |
func (*intPtrA) MarshalJSON() ([]byte, error) { |
| 1484 |
return []byte(`"A"`), nil |
| 1485 |
} |
| 1486 |
|
| 1487 |
type intPtrB int |
| 1488 |
|
| 1489 |
func (*intPtrB) MarshalText() ([]byte, error) { |
| 1490 |
return []byte("B"), nil |
| 1491 |
} |
| 1492 |
|
| 1493 |
type ( |
| 1494 |
structA struct{ I intPtrA } |
| 1495 |
structB struct{ I intPtrB } |
| 1496 |
structC struct{ M Marshaler } |
| 1497 |
structD struct{ M encoding.TextMarshaler } |
| 1498 |
) |
| 1499 |
|
| 1500 |
func TestGithubIssue16(t *testing.T) { |
| 1501 |
// https://github.com/segmentio/encoding/issues/16 |
| 1502 |
tests := []struct { |
| 1503 |
value any |
| 1504 |
output string |
| 1505 |
}{ |
| 1506 |
{value: sliceA(nil), output: `"A"`}, |
| 1507 |
{value: sliceB(nil), output: `"B"`}, |
| 1508 |
{value: mapA(nil), output: `"A"`}, |
| 1509 |
{value: mapB(nil), output: `"B"`}, |
| 1510 |
{value: intPtrA(1), output: `1`}, |
| 1511 |
{value: intPtrB(2), output: `2`}, |
| 1512 |
{value: new(intPtrA), output: `"A"`}, |
| 1513 |
{value: new(intPtrB), output: `"B"`}, |
| 1514 |
{value: (*intPtrA)(nil), output: `null`}, |
| 1515 |
{value: (*intPtrB)(nil), output: `null`}, |
| 1516 |
{value: structA{I: 1}, output: `{"I":1}`}, |
| 1517 |
{value: structB{I: 2}, output: `{"I":2}`}, |
| 1518 |
{value: structC{}, output: `{"M":null}`}, |
| 1519 |
{value: structD{}, output: `{"M":null}`}, |
| 1520 |
{value: &structA{I: 1}, output: `{"I":"A"}`}, |
| 1521 |
{value: &structB{I: 2}, output: `{"I":"B"}`}, |
| 1522 |
{value: &structC{}, output: `{"M":null}`}, |
| 1523 |
{value: &structD{}, output: `{"M":null}`}, |
| 1524 |
} |
| 1525 |
|
| 1526 |
for _, test := range tests { |
| 1527 |
t.Run(fmt.Sprintf("%T", test.value), func(t *testing.T) { |
| 1528 |
if b, _ := Marshal(test.value); string(b) != test.output { |
| 1529 |
t.Errorf(`%s != %s`, string(b), test.output) |
| 1530 |
} |
| 1531 |
}) |
| 1532 |
} |
| 1533 |
} |
| 1534 |
|
| 1535 |
func TestDecoderInputOffset(t *testing.T) { |
| 1536 |
checkOffset := func(o, expected int64) { |
| 1537 |
if o != expected { |
| 1538 |
t.Error("unexpected input offset", o, expected) |
| 1539 |
} |
| 1540 |
} |
| 1541 |
|
| 1542 |
b := []byte(`{"userId": "blah"}{"userId": "blah"} |
| 1543 |
{"userId": "blah"}{"num": 0}`) |
| 1544 |
d := NewDecoder(bytes.NewReader(b)) |
| 1545 |
|
| 1546 |
var expected int64 |
| 1547 |
checkOffset(d.InputOffset(), expected) |
| 1548 |
|
| 1549 |
var a struct { |
| 1550 |
UserId string `json:"userId"` |
| 1551 |
} |
| 1552 |
|
| 1553 |
if err := d.Decode(&a); err != nil { |
| 1554 |
t.Error("unexpected decode error", err) |
| 1555 |
} |
| 1556 |
expected = int64(18) |
| 1557 |
checkOffset(d.InputOffset(), expected) |
| 1558 |
|
| 1559 |
if err := d.Decode(&a); err != nil { |
| 1560 |
t.Error("unexpected decode error", err) |
| 1561 |
} |
| 1562 |
expected = int64(38) |
| 1563 |
checkOffset(d.InputOffset(), expected) |
| 1564 |
|
| 1565 |
if err := d.Decode(&a); err != nil { |
| 1566 |
t.Error("unexpected decode error", err) |
| 1567 |
} |
| 1568 |
expected = int64(56) |
| 1569 |
checkOffset(d.InputOffset(), expected) |
| 1570 |
|
| 1571 |
var z struct { |
| 1572 |
Num int64 `json:"num"` |
| 1573 |
} |
| 1574 |
if err := d.Decode(&z); err != nil { |
| 1575 |
t.Error("unexpected decode error", err) |
| 1576 |
} |
| 1577 |
expected = int64(66) |
| 1578 |
checkOffset(d.InputOffset(), expected) |
| 1579 |
} |
| 1580 |
|
| 1581 |
func TestGithubIssue18(t *testing.T) { |
| 1582 |
// https://github.com/segmentio/encoding/issues/18 |
| 1583 |
b := []byte(`{ |
| 1584 |
"userId": "blah", |
| 1585 |
}`) |
| 1586 |
|
| 1587 |
d := NewDecoder(bytes.NewReader(b)) |
| 1588 |
|
| 1589 |
var a struct { |
| 1590 |
UserId string `json:"userId"` |
| 1591 |
} |
| 1592 |
switch err := d.Decode(&a).(type) { |
| 1593 |
case *SyntaxError: |
| 1594 |
default: |
| 1595 |
t.Error("expected syntax error but found:", err) |
| 1596 |
} |
| 1597 |
|
| 1598 |
for i := 1; i <= 18; i++ { // up to the invalid ',' character |
| 1599 |
d := NewDecoder(bytes.NewReader(b[:i])) // cut somewhere in the middle |
| 1600 |
switch err := d.Decode(&a); err { |
| 1601 |
case io.ErrUnexpectedEOF: |
| 1602 |
default: |
| 1603 |
t.Error("expected 'unexpected EOF' error but found:", err) |
| 1604 |
} |
| 1605 |
} |
| 1606 |
} |
| 1607 |
|
| 1608 |
func TestGithubIssue23(t *testing.T) { |
| 1609 |
t.Run("marshal-1", func(t *testing.T) { |
| 1610 |
type d struct{ S map[string]string } |
| 1611 |
|
| 1612 |
b, _ := Marshal(map[string]d{"1": {S: map[string]string{"2": "3"}}}) |
| 1613 |
if string(b) != `{"1":{"S":{"2":"3"}}}` { |
| 1614 |
t.Error(string(b)) |
| 1615 |
} |
| 1616 |
}) |
| 1617 |
|
| 1618 |
t.Run("marshal-2", func(t *testing.T) { |
| 1619 |
type testInner struct { |
| 1620 |
InnerMap map[string]string `json:"inner_map"` |
| 1621 |
} |
| 1622 |
|
| 1623 |
type testOuter struct { |
| 1624 |
OuterMap map[string]testInner `json:"outer_map"` |
| 1625 |
} |
| 1626 |
|
| 1627 |
b, _ := Marshal(testOuter{ |
| 1628 |
OuterMap: map[string]testInner{ |
| 1629 |
"outer": { |
| 1630 |
InnerMap: map[string]string{"inner": "value"}, |
| 1631 |
}, |
| 1632 |
}, |
| 1633 |
}) |
| 1634 |
|
| 1635 |
if string(b) != `{"outer_map":{"outer":{"inner_map":{"inner":"value"}}}}` { |
| 1636 |
t.Error(string(b)) |
| 1637 |
} |
| 1638 |
}) |
| 1639 |
|
| 1640 |
t.Run("marshal-3", func(t *testing.T) { |
| 1641 |
type A struct{ A map[string]string } |
| 1642 |
type B struct{ B map[string]A } |
| 1643 |
type C struct{ C map[string]B } |
| 1644 |
|
| 1645 |
b, _ := Marshal(C{ |
| 1646 |
C: map[string]B{ |
| 1647 |
"1": { |
| 1648 |
B: map[string]A{ |
| 1649 |
"2": { |
| 1650 |
A: map[string]string{"3": "!"}, |
| 1651 |
}, |
| 1652 |
}, |
| 1653 |
}, |
| 1654 |
}, |
| 1655 |
}) |
| 1656 |
|
| 1657 |
if string(b) != `{"C":{"1":{"B":{"2":{"A":{"3":"!"}}}}}}` { |
| 1658 |
t.Error(string(b)) |
| 1659 |
} |
| 1660 |
}) |
| 1661 |
|
| 1662 |
t.Run("unmarshal-1", func(t *testing.T) { |
| 1663 |
var d struct{ S map[string]string } |
| 1664 |
|
| 1665 |
if err := Unmarshal([]byte(`{"1":{"S":{"2":"3"}}}`), &d); err != nil { |
| 1666 |
t.Error(err) |
| 1667 |
} |
| 1668 |
}) |
| 1669 |
} |
| 1670 |
|
| 1671 |
func TestGithubIssue26(t *testing.T) { |
| 1672 |
type interfaceType any |
| 1673 |
|
| 1674 |
var value interfaceType |
| 1675 |
data := []byte(`{}`) |
| 1676 |
|
| 1677 |
if err := Unmarshal(data, &value); err != nil { |
| 1678 |
t.Error(err) |
| 1679 |
} |
| 1680 |
} |
| 1681 |
|
| 1682 |
func TestGithubIssue28(t *testing.T) { |
| 1683 |
type A struct { |
| 1684 |
Err error `json:"err"` |
| 1685 |
} |
| 1686 |
|
| 1687 |
if b, err := Marshal(&A{Err: errors.New("ABC")}); err != nil { |
| 1688 |
t.Error(err) |
| 1689 |
} else if string(b) != `{"err":{}}` { |
| 1690 |
t.Error(string(b)) |
| 1691 |
} |
| 1692 |
} |
| 1693 |
|
| 1694 |
func TestGithubIssue41(t *testing.T) { |
| 1695 |
expectedString := `{"Zero":0,"Three":3}` |
| 1696 |
type M struct { |
| 1697 |
One int |
| 1698 |
Two int |
| 1699 |
} |
| 1700 |
type N struct { |
| 1701 |
Zero int |
| 1702 |
*M |
| 1703 |
Three int |
| 1704 |
} |
| 1705 |
|
| 1706 |
if b, err := Marshal(N{Three: 3}); err != nil { |
| 1707 |
t.Error(err) |
| 1708 |
} else if string(b) != expectedString { |
| 1709 |
t.Error( |
| 1710 |
"got: ", string(b), |
| 1711 |
"expected: ", expectedString, |
| 1712 |
) |
| 1713 |
} |
| 1714 |
} |
| 1715 |
|
| 1716 |
func TestGithubIssue44(t *testing.T) { |
| 1717 |
var out rawJsonString |
| 1718 |
if err := Unmarshal([]byte("null"), &out); err != nil { |
| 1719 |
t.Fatal(err) |
| 1720 |
} |
| 1721 |
if out != "null" { |
| 1722 |
t.Errorf("wanted \"null\" but got %q", out) |
| 1723 |
} |
| 1724 |
} |
| 1725 |
|
| 1726 |
type issue107Foo struct { |
| 1727 |
Bar *issue107Bar |
| 1728 |
} |
| 1729 |
|
| 1730 |
type issue107Bar struct { |
| 1731 |
Foo *issue107Foo |
| 1732 |
} |
| 1733 |
|
| 1734 |
func TestGithubIssue107(t *testing.T) { |
| 1735 |
f := &issue107Foo{} |
| 1736 |
b := &issue107Bar{} |
| 1737 |
f.Bar = b |
| 1738 |
b.Foo = f |
| 1739 |
|
| 1740 |
_, err := Marshal(f) // must not crash |
| 1741 |
switch err.(type) { |
| 1742 |
case *UnsupportedValueError: |
| 1743 |
default: |
| 1744 |
t.Errorf("marshaling a cycling data structure was expected to return an unsupported value error but got %T", err) |
| 1745 |
} |
| 1746 |
} |
| 1747 |
|
| 1748 |
type rawJsonString string |
| 1749 |
|
| 1750 |
func (r *rawJsonString) UnmarshalJSON(b []byte) error { |
| 1751 |
if len(b) == 0 { |
| 1752 |
*r = "null" |
| 1753 |
} else { |
| 1754 |
*r = rawJsonString(b) |
| 1755 |
} |
| 1756 |
return nil |
| 1757 |
} |
| 1758 |
|
| 1759 |
func TestSetTrustRawMessage(t *testing.T) { |
| 1760 |
buf := &bytes.Buffer{} |
| 1761 |
enc := NewEncoder(buf) |
| 1762 |
enc.SetTrustRawMessage(true) |
| 1763 |
|
| 1764 |
// "Good" values are encoded in the regular way |
| 1765 |
m := map[string]json.RawMessage{ |
| 1766 |
"k": json.RawMessage(`"value"`), |
| 1767 |
} |
| 1768 |
if err := enc.Encode(m); err != nil { |
| 1769 |
t.Error(err) |
| 1770 |
} |
| 1771 |
|
| 1772 |
b := buf.Bytes() |
| 1773 |
exp := []byte(`{"k":"value"}`) |
| 1774 |
exp = append(exp, '\n') |
| 1775 |
if !bytes.Equal(exp, b) { |
| 1776 |
t.Error( |
| 1777 |
"unexpected encoding:", |
| 1778 |
"expected", exp, |
| 1779 |
"got", b, |
| 1780 |
) |
| 1781 |
} |
| 1782 |
|
| 1783 |
// "Bad" values are encoded without checking and throwing an error |
| 1784 |
buf.Reset() |
| 1785 |
m = map[string]json.RawMessage{ |
| 1786 |
"k": json.RawMessage(`bad"value`), |
| 1787 |
} |
| 1788 |
if err := enc.Encode(m); err != nil { |
| 1789 |
t.Error(err) |
| 1790 |
} |
| 1791 |
|
| 1792 |
b = buf.Bytes() |
| 1793 |
exp = []byte(`{"k":bad"value}`) |
| 1794 |
exp = append(exp, '\n') |
| 1795 |
if !bytes.Equal(exp, b) { |
| 1796 |
t.Error( |
| 1797 |
"unexpected encoding:", |
| 1798 |
"expected", exp, |
| 1799 |
"got", b, |
| 1800 |
) |
| 1801 |
} |
| 1802 |
} |
| 1803 |
|
| 1804 |
func TestSetAppendNewline(t *testing.T) { |
| 1805 |
buf := &bytes.Buffer{} |
| 1806 |
enc := NewEncoder(buf) |
| 1807 |
|
| 1808 |
m := "value" |
| 1809 |
|
| 1810 |
// Default encoding adds an extra newline |
| 1811 |
if err := enc.Encode(m); err != nil { |
| 1812 |
t.Error(err) |
| 1813 |
} |
| 1814 |
b := buf.Bytes() |
| 1815 |
exp := []byte(`"value"`) |
| 1816 |
exp = append(exp, '\n') |
| 1817 |
if !bytes.Equal(exp, b) { |
| 1818 |
t.Error( |
| 1819 |
"unexpected encoding:", |
| 1820 |
"expected", exp, |
| 1821 |
"got", b, |
| 1822 |
) |
| 1823 |
} |
| 1824 |
|
| 1825 |
// With SetAppendNewline(false), there shouldn't be a newline in the output |
| 1826 |
buf.Reset() |
| 1827 |
enc.SetAppendNewline(false) |
| 1828 |
if err := enc.Encode(m); err != nil { |
| 1829 |
t.Error(err) |
| 1830 |
} |
| 1831 |
b = buf.Bytes() |
| 1832 |
exp = []byte(`"value"`) |
| 1833 |
if !bytes.Equal(exp, b) { |
| 1834 |
t.Error( |
| 1835 |
"unexpected encoding:", |
| 1836 |
"expected", exp, |
| 1837 |
"got", b, |
| 1838 |
) |
| 1839 |
} |
| 1840 |
} |
| 1841 |
|
| 1842 |
func TestEscapeString(t *testing.T) { |
| 1843 |
b := Escape(`value`) |
| 1844 |
x := []byte(`"value"`) |
| 1845 |
|
| 1846 |
if !bytes.Equal(x, b) { |
| 1847 |
t.Error( |
| 1848 |
"unexpected encoding:", |
| 1849 |
"expected", string(x), |
| 1850 |
"got", string(b), |
| 1851 |
) |
| 1852 |
} |
| 1853 |
} |
| 1854 |
|
| 1855 |
func TestAppendEscape(t *testing.T) { |
| 1856 |
if runtime.GOARCH == "s390x" { |
| 1857 |
t.Skipf("Test does not work correctly on %s.", runtime.GOARCH) |
| 1858 |
} |
| 1859 |
t.Run("basic", func(t *testing.T) { |
| 1860 |
b := AppendEscape([]byte{}, `value`, AppendFlags(0)) |
| 1861 |
exp := []byte(`"value"`) |
| 1862 |
if !bytes.Equal(exp, b) { |
| 1863 |
t.Error( |
| 1864 |
"unexpected encoding:", |
| 1865 |
"expected", exp, |
| 1866 |
"got", b, |
| 1867 |
) |
| 1868 |
} |
| 1869 |
}) |
| 1870 |
|
| 1871 |
t.Run("escaped", func(t *testing.T) { |
| 1872 |
b := AppendEscape([]byte{}, `"escaped" <value>`, EscapeHTML) |
| 1873 |
exp := []byte(`"\"escaped\"\t\u003cvalue\u003e"`) |
| 1874 |
if !bytes.Equal(exp, b) { |
| 1875 |
t.Error( |
| 1876 |
"unexpected encoding:", |
| 1877 |
"expected", exp, |
| 1878 |
"got", b, |
| 1879 |
) |
| 1880 |
} |
| 1881 |
}) |
| 1882 |
|
| 1883 |
t.Run("build", func(t *testing.T) { |
| 1884 |
b := []byte{} |
| 1885 |
b = append(b, '{') |
| 1886 |
b = AppendEscape(b, `key`, EscapeHTML) |
| 1887 |
b = append(b, ':') |
| 1888 |
b = AppendEscape(b, `"escaped" <value>`, EscapeHTML) |
| 1889 |
b = append(b, '}') |
| 1890 |
exp := []byte(`{"key":"\"escaped\"\t\u003cvalue\u003e"}`) |
| 1891 |
if !bytes.Equal(exp, b) { |
| 1892 |
t.Error( |
| 1893 |
"unexpected encoding:", |
| 1894 |
"expected", exp, |
| 1895 |
"got", b, |
| 1896 |
) |
| 1897 |
} |
| 1898 |
}) |
| 1899 |
} |
| 1900 |
|
| 1901 |
func TestUnescapeString(t *testing.T) { |
| 1902 |
b := Unescape([]byte(`"value"`)) |
| 1903 |
x := []byte(`value`) |
| 1904 |
|
| 1905 |
if !bytes.Equal(x, b) { |
| 1906 |
t.Error( |
| 1907 |
"unexpected decoding:", |
| 1908 |
"expected", string(x), |
| 1909 |
"got", string(b), |
| 1910 |
) |
| 1911 |
} |
| 1912 |
} |
| 1913 |
|
| 1914 |
func TestAppendUnescape(t *testing.T) { |
| 1915 |
t.Run("basic", func(t *testing.T) { |
| 1916 |
out := AppendUnescape([]byte{}, []byte(`"value"`), ParseFlags(0)) |
| 1917 |
exp := []byte("value") |
| 1918 |
if !bytes.Equal(exp, out) { |
| 1919 |
t.Error( |
| 1920 |
"unexpected decoding:", |
| 1921 |
"expected", exp, |
| 1922 |
"got", out, |
| 1923 |
) |
| 1924 |
} |
| 1925 |
}) |
| 1926 |
|
| 1927 |
t.Run("escaped", func(t *testing.T) { |
| 1928 |
b := AppendUnescape([]byte{}, []byte(`"\"escaped\"\t\u003cvalue\u003e"`), ParseFlags(0)) |
| 1929 |
exp := []byte(`"escaped" <value>`) |
| 1930 |
if !bytes.Equal(exp, b) { |
| 1931 |
t.Error( |
| 1932 |
"unexpected encoding:", |
| 1933 |
"expected", exp, |
| 1934 |
"got", b, |
| 1935 |
) |
| 1936 |
} |
| 1937 |
}) |
| 1938 |
|
| 1939 |
t.Run("build", func(t *testing.T) { |
| 1940 |
b := []byte{} |
| 1941 |
b = append(b, []byte(`{"key":`)...) |
| 1942 |
b = AppendUnescape(b, []byte(`"\"escaped\"\t\u003cvalue\u003e"`), ParseFlags(0)) |
| 1943 |
b = append(b, '}') |
| 1944 |
exp := []byte(`{"key":"escaped" <value>}`) |
| 1945 |
if !bytes.Equal(exp, b) { |
| 1946 |
t.Error( |
| 1947 |
"unexpected encoding:", |
| 1948 |
"expected", string(exp), |
| 1949 |
"got", string(b), |
| 1950 |
) |
| 1951 |
} |
| 1952 |
}) |
| 1953 |
} |
| 1954 |
|
| 1955 |
func BenchmarkUnescape(b *testing.B) { |
| 1956 |
s := []byte(`"\"escaped\"\t\u003cvalue\u003e"`) |
| 1957 |
out := []byte{} |
| 1958 |
for range b.N { |
| 1959 |
out = Unescape(s) |
| 1960 |
} |
| 1961 |
|
| 1962 |
b.Log(string(out)) |
| 1963 |
} |
| 1964 |
|
| 1965 |
func BenchmarkUnmarshalField(b *testing.B) { |
| 1966 |
s := []byte(`"\"escaped\"\t\u003cvalue\u003e"`) |
| 1967 |
var v string |
| 1968 |
|
| 1969 |
for range b.N { |
| 1970 |
json.Unmarshal(s, &v) |
| 1971 |
} |
| 1972 |
|
| 1973 |
b.Log(v) |
| 1974 |
} |
| 1975 |
|
| 1976 |
func TestKind(t *testing.T) { |
| 1977 |
for _, test := range []struct { |
| 1978 |
kind Kind |
| 1979 |
class Kind |
| 1980 |
}{ |
| 1981 |
{kind: 0, class: 0}, |
| 1982 |
{kind: Null, class: Null}, |
| 1983 |
{kind: False, class: Bool}, |
| 1984 |
{kind: True, class: Bool}, |
| 1985 |
{kind: Num, class: Num}, |
| 1986 |
{kind: Uint, class: Num}, |
| 1987 |
{kind: Int, class: Num}, |
| 1988 |
{kind: Float, class: Num}, |
| 1989 |
{kind: String, class: String}, |
| 1990 |
{kind: Unescaped, class: String}, |
| 1991 |
{kind: Array, class: Array}, |
| 1992 |
{kind: Object, class: Object}, |
| 1993 |
} { |
| 1994 |
if class := test.kind.Class(); class != test.class { |
| 1995 |
t.Errorf("class of kind(%d) mismatch: want=%d got=%d", test.kind, test.class, class) |
| 1996 |
} |
| 1997 |
} |
| 1998 |
} |