You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1486 lines
33 KiB

  1. // Copyright 2010 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package fastjson
  5. import (
  6. "bytes"
  7. "encoding"
  8. "fmt"
  9. "image"
  10. "net"
  11. "reflect"
  12. "strings"
  13. "testing"
  14. "time"
  15. )
  16. type T struct {
  17. X string
  18. Y int
  19. Z int `json:"-"`
  20. }
  21. type U struct {
  22. Alphabet string `json:"alpha"`
  23. }
  24. type V struct {
  25. F1 interface{}
  26. F2 int32
  27. F3 Number
  28. }
  29. // ifaceNumAsFloat64/ifaceNumAsNumber are used to test unmarshaling with and
  30. // without UseNumber
  31. var ifaceNumAsFloat64 = map[string]interface{}{
  32. "k1": float64(1),
  33. "k2": "s",
  34. "k3": []interface{}{float64(1), float64(2.0), float64(3e-3)},
  35. "k4": map[string]interface{}{"kk1": "s", "kk2": float64(2)},
  36. }
  37. var ifaceNumAsNumber = map[string]interface{}{
  38. "k1": Number("1"),
  39. "k2": "s",
  40. "k3": []interface{}{Number("1"), Number("2.0"), Number("3e-3")},
  41. "k4": map[string]interface{}{"kk1": "s", "kk2": Number("2")},
  42. }
  43. type tx struct {
  44. x int
  45. }
  46. // A type that can unmarshal itself.
  47. type unmarshaler struct {
  48. T bool
  49. }
  50. func (u *unmarshaler) UnmarshalJSON(b []byte) error {
  51. *u = unmarshaler{true} // All we need to see that UnmarshalJSON is called.
  52. return nil
  53. }
  54. type ustruct struct {
  55. M unmarshaler
  56. }
  57. type unmarshalerText struct {
  58. T bool
  59. }
  60. // needed for re-marshaling tests
  61. func (u *unmarshalerText) MarshalText() ([]byte, error) {
  62. return []byte(""), nil
  63. }
  64. func (u *unmarshalerText) UnmarshalText(b []byte) error {
  65. *u = unmarshalerText{true} // All we need to see that UnmarshalText is called.
  66. return nil
  67. }
  68. var _ encoding.TextUnmarshaler = (*unmarshalerText)(nil)
  69. type ustructText struct {
  70. M unmarshalerText
  71. }
  72. var (
  73. um0, um1 unmarshaler // target2 of unmarshaling
  74. ump = &um1
  75. umtrue = unmarshaler{true}
  76. umslice = []unmarshaler{{true}}
  77. umslicep = new([]unmarshaler)
  78. umstruct = ustruct{unmarshaler{true}}
  79. um0T, um1T unmarshalerText // target2 of unmarshaling
  80. umpT = &um1T
  81. umtrueT = unmarshalerText{true}
  82. umsliceT = []unmarshalerText{{true}}
  83. umslicepT = new([]unmarshalerText)
  84. umstructT = ustructText{unmarshalerText{true}}
  85. )
  86. // Test data structures for anonymous fields.
  87. type Point struct {
  88. Z int
  89. }
  90. type Top struct {
  91. Level0 int
  92. Embed0
  93. *Embed0a
  94. *Embed0b `json:"e,omitempty"` // treated as named
  95. Embed0c `json:"-"` // ignored
  96. Loop
  97. Embed0p // has Point with X, Y, used
  98. Embed0q // has Point with Z, used
  99. embed // contains exported field
  100. }
  101. type Embed0 struct {
  102. Level1a int // overridden by Embed0a's Level1a with json tag
  103. Level1b int // used because Embed0a's Level1b is renamed
  104. Level1c int // used because Embed0a's Level1c is ignored
  105. Level1d int // annihilated by Embed0a's Level1d
  106. Level1e int `json:"x"` // annihilated by Embed0a.Level1e
  107. }
  108. type Embed0a struct {
  109. Level1a int `json:"Level1a,omitempty"`
  110. Level1b int `json:"LEVEL1B,omitempty"`
  111. Level1c int `json:"-"`
  112. Level1d int // annihilated by Embed0's Level1d
  113. Level1f int `json:"x"` // annihilated by Embed0's Level1e
  114. }
  115. type Embed0b Embed0
  116. type Embed0c Embed0
  117. type Embed0p struct {
  118. image.Point
  119. }
  120. type Embed0q struct {
  121. Point
  122. }
  123. type embed struct {
  124. Q int
  125. }
  126. type Loop struct {
  127. Loop1 int `json:",omitempty"`
  128. Loop2 int `json:",omitempty"`
  129. *Loop
  130. }
  131. // From reflect test:
  132. // The X in S6 and S7 annihilate, but they also block the X in S8.S9.
  133. type S5 struct {
  134. S6
  135. S7
  136. S8
  137. }
  138. type S6 struct {
  139. X int
  140. }
  141. type S7 S6
  142. type S8 struct {
  143. S9
  144. }
  145. type S9 struct {
  146. X int
  147. Y int
  148. }
  149. // From reflect test:
  150. // The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9.
  151. type S10 struct {
  152. S11
  153. S12
  154. S13
  155. }
  156. type S11 struct {
  157. S6
  158. }
  159. type S12 struct {
  160. S6
  161. }
  162. type S13 struct {
  163. S8
  164. }
  165. type unmarshalTest struct {
  166. in string
  167. ptr interface{}
  168. out interface{}
  169. err error
  170. useNumber bool
  171. }
  172. type Ambig struct {
  173. // Given "hello", the first match should win.
  174. First int `json:"HELLO"`
  175. Second int `json:"Hello"`
  176. }
  177. type XYZ struct {
  178. X interface{}
  179. Y interface{}
  180. Z interface{}
  181. }
  182. func sliceAddr(x []int) *[]int { return &x }
  183. func mapAddr(x map[string]int) *map[string]int { return &x }
  184. var unmarshalTests = []unmarshalTest{
  185. // basic types
  186. {in: `true`, ptr: new(bool), out: true},
  187. {in: `1`, ptr: new(int), out: 1},
  188. {in: `1.2`, ptr: new(float64), out: 1.2},
  189. {in: `-5`, ptr: new(int16), out: int16(-5)},
  190. {in: `2`, ptr: new(Number), out: Number("2"), useNumber: true},
  191. {in: `2`, ptr: new(Number), out: Number("2")},
  192. {in: `2`, ptr: new(interface{}), out: float64(2.0)},
  193. {in: `2`, ptr: new(interface{}), out: Number("2"), useNumber: true},
  194. {in: `"a\u1234"`, ptr: new(string), out: "a\u1234"},
  195. {in: `"http:\/\/"`, ptr: new(string), out: "http://"},
  196. {in: `"g-clef: \uD834\uDD1E"`, ptr: new(string), out: "g-clef: \U0001D11E"},
  197. {in: `"invalid: \uD834x\uDD1E"`, ptr: new(string), out: "invalid: \uFFFDx\uFFFD"},
  198. {in: "null", ptr: new(interface{}), out: nil},
  199. {in: `{"X": [1,2,3], "Y": 4}`, ptr: new(T), out: T{Y: 4}, err: &UnmarshalTypeError{"array", reflect.TypeOf(""), 7}},
  200. {in: `{"x": 1}`, ptr: new(tx), out: tx{}},
  201. {in: `{"F1":1,"F2":2,"F3":3}`, ptr: new(V), out: V{F1: float64(1), F2: int32(2), F3: Number("3")}},
  202. {in: `{"F1":1,"F2":2,"F3":3}`, ptr: new(V), out: V{F1: Number("1"), F2: int32(2), F3: Number("3")}, useNumber: true},
  203. {in: `{"k1":1,"k2":"s","k3":[1,2.0,3e-3],"k4":{"kk1":"s","kk2":2}}`, ptr: new(interface{}), out: ifaceNumAsFloat64},
  204. {in: `{"k1":1,"k2":"s","k3":[1,2.0,3e-3],"k4":{"kk1":"s","kk2":2}}`, ptr: new(interface{}), out: ifaceNumAsNumber, useNumber: true},
  205. // raw values with whitespace
  206. {in: "\n true ", ptr: new(bool), out: true},
  207. {in: "\t 1 ", ptr: new(int), out: 1},
  208. {in: "\r 1.2 ", ptr: new(float64), out: 1.2},
  209. {in: "\t -5 \n", ptr: new(int16), out: int16(-5)},
  210. {in: "\t \"a\\u1234\" \n", ptr: new(string), out: "a\u1234"},
  211. // Z has a "-" tag.
  212. {in: `{"Y": 1, "Z": 2}`, ptr: new(T), out: T{Y: 1}},
  213. {in: `{"alpha": "abc", "alphabet": "xyz"}`, ptr: new(U), out: U{Alphabet: "abc"}},
  214. {in: `{"alpha": "abc"}`, ptr: new(U), out: U{Alphabet: "abc"}},
  215. {in: `{"alphabet": "xyz"}`, ptr: new(U), out: U{}},
  216. // syntax errors
  217. {in: `{"X": "foo", "Y"}`, err: &SyntaxError{"invalid character '}' after object key", 17}},
  218. {in: `[1, 2, 3+]`, err: &SyntaxError{"invalid character '+' after array element", 9}},
  219. {in: `{"X":12x}`, err: &SyntaxError{"invalid character 'x' after object key:value pair", 8}, useNumber: true},
  220. // raw value errors
  221. {in: "\x01 42", err: &SyntaxError{"invalid character '\\x01' looking for beginning of value", 1}},
  222. {in: " 42 \x01", err: &SyntaxError{"invalid character '\\x01' after top-level value", 5}},
  223. {in: "\x01 true", err: &SyntaxError{"invalid character '\\x01' looking for beginning of value", 1}},
  224. {in: " false \x01", err: &SyntaxError{"invalid character '\\x01' after top-level value", 8}},
  225. {in: "\x01 1.2", err: &SyntaxError{"invalid character '\\x01' looking for beginning of value", 1}},
  226. {in: " 3.4 \x01", err: &SyntaxError{"invalid character '\\x01' after top-level value", 6}},
  227. {in: "\x01 \"string\"", err: &SyntaxError{"invalid character '\\x01' looking for beginning of value", 1}},
  228. {in: " \"string\" \x01", err: &SyntaxError{"invalid character '\\x01' after top-level value", 11}},
  229. // array tests
  230. {in: `[1, 2, 3]`, ptr: new([3]int), out: [3]int{1, 2, 3}},
  231. {in: `[1, 2, 3]`, ptr: new([1]int), out: [1]int{1}},
  232. {in: `[1, 2, 3]`, ptr: new([5]int), out: [5]int{1, 2, 3, 0, 0}},
  233. // empty array to interface test
  234. {in: `[]`, ptr: new([]interface{}), out: []interface{}{}},
  235. {in: `null`, ptr: new([]interface{}), out: []interface{}(nil)},
  236. {in: `{"T":[]}`, ptr: new(map[string]interface{}), out: map[string]interface{}{"T": []interface{}{}}},
  237. {in: `{"T":null}`, ptr: new(map[string]interface{}), out: map[string]interface{}{"T": interface{}(nil)}},
  238. // composite tests
  239. {in: allValueIndent, ptr: new(All), out: allValue},
  240. {in: allValueCompact, ptr: new(All), out: allValue},
  241. {in: allValueIndent, ptr: new(*All), out: &allValue},
  242. {in: allValueCompact, ptr: new(*All), out: &allValue},
  243. {in: pallValueIndent, ptr: new(All), out: pallValue},
  244. {in: pallValueCompact, ptr: new(All), out: pallValue},
  245. {in: pallValueIndent, ptr: new(*All), out: &pallValue},
  246. {in: pallValueCompact, ptr: new(*All), out: &pallValue},
  247. // unmarshal interface test
  248. {in: `{"T":false}`, ptr: &um0, out: umtrue}, // use "false" so test will fail if custom unmarshaler is not called
  249. {in: `{"T":false}`, ptr: &ump, out: &umtrue},
  250. {in: `[{"T":false}]`, ptr: &umslice, out: umslice},
  251. {in: `[{"T":false}]`, ptr: &umslicep, out: &umslice},
  252. {in: `{"M":{"T":false}}`, ptr: &umstruct, out: umstruct},
  253. // UnmarshalText interface test
  254. {in: `"X"`, ptr: &um0T, out: umtrueT}, // use "false" so test will fail if custom unmarshaler is not called
  255. {in: `"X"`, ptr: &umpT, out: &umtrueT},
  256. {in: `["X"]`, ptr: &umsliceT, out: umsliceT},
  257. {in: `["X"]`, ptr: &umslicepT, out: &umsliceT},
  258. {in: `{"M":"X"}`, ptr: &umstructT, out: umstructT},
  259. // Overwriting of data.
  260. // This is different from package xml, but it's what we've always done.
  261. // Now documented and tested.
  262. {in: `[2]`, ptr: sliceAddr([]int{1}), out: []int{2}},
  263. {in: `{"key": 2}`, ptr: mapAddr(map[string]int{"old": 0, "key": 1}), out: map[string]int{"key": 2}},
  264. {
  265. in: `{
  266. "Level0": 1,
  267. "Level1b": 2,
  268. "Level1c": 3,
  269. "x": 4,
  270. "Level1a": 5,
  271. "LEVEL1B": 6,
  272. "e": {
  273. "Level1a": 8,
  274. "Level1b": 9,
  275. "Level1c": 10,
  276. "Level1d": 11,
  277. "x": 12
  278. },
  279. "Loop1": 13,
  280. "Loop2": 14,
  281. "X": 15,
  282. "Y": 16,
  283. "Z": 17,
  284. "Q": 18
  285. }`,
  286. ptr: new(Top),
  287. out: Top{
  288. Level0: 1,
  289. Embed0: Embed0{
  290. Level1b: 2,
  291. Level1c: 3,
  292. },
  293. Embed0a: &Embed0a{
  294. Level1a: 5,
  295. Level1b: 6,
  296. },
  297. Embed0b: &Embed0b{
  298. Level1a: 8,
  299. Level1b: 9,
  300. Level1c: 10,
  301. Level1d: 11,
  302. Level1e: 12,
  303. },
  304. Loop: Loop{
  305. Loop1: 13,
  306. Loop2: 14,
  307. },
  308. Embed0p: Embed0p{
  309. Point: image.Point{X: 15, Y: 16},
  310. },
  311. Embed0q: Embed0q{
  312. Point: Point{Z: 17},
  313. },
  314. embed: embed{
  315. Q: 18,
  316. },
  317. },
  318. },
  319. {
  320. in: `{"hello": 1}`,
  321. ptr: new(Ambig),
  322. out: Ambig{First: 1},
  323. },
  324. {
  325. in: `{"X": 1,"Y":2}`,
  326. ptr: new(S5),
  327. out: S5{S8: S8{S9: S9{Y: 2}}},
  328. },
  329. {
  330. in: `{"X": 1,"Y":2}`,
  331. ptr: new(S10),
  332. out: S10{S13: S13{S8: S8{S9: S9{Y: 2}}}},
  333. },
  334. // invalid UTF-8 is coerced to valid UTF-8.
  335. {
  336. in: "\"hello\xffworld\"",
  337. ptr: new(string),
  338. out: "hello\ufffdworld",
  339. },
  340. {
  341. in: "\"hello\xc2\xc2world\"",
  342. ptr: new(string),
  343. out: "hello\ufffd\ufffdworld",
  344. },
  345. {
  346. in: "\"hello\xc2\xffworld\"",
  347. ptr: new(string),
  348. out: "hello\ufffd\ufffdworld",
  349. },
  350. {
  351. in: "\"hello\\ud800world\"",
  352. ptr: new(string),
  353. out: "hello\ufffdworld",
  354. },
  355. {
  356. in: "\"hello\\ud800\\ud800world\"",
  357. ptr: new(string),
  358. out: "hello\ufffd\ufffdworld",
  359. },
  360. {
  361. in: "\"hello\\ud800\\ud800world\"",
  362. ptr: new(string),
  363. out: "hello\ufffd\ufffdworld",
  364. },
  365. {
  366. in: "\"hello\xed\xa0\x80\xed\xb0\x80world\"",
  367. ptr: new(string),
  368. out: "hello\ufffd\ufffd\ufffd\ufffd\ufffd\ufffdworld",
  369. },
  370. // issue 8305
  371. {
  372. in: `{"2009-11-10T23:00:00Z": "hello world"}`,
  373. ptr: &map[time.Time]string{},
  374. err: &UnmarshalTypeError{"object", reflect.TypeOf(map[time.Time]string{}), 1},
  375. },
  376. }
  377. func TestMarshal(t *testing.T) {
  378. b, err := Marshal(allValue)
  379. if err != nil {
  380. t.Fatalf("Marshal allValue: %v", err)
  381. }
  382. if string(b) != allValueCompact {
  383. t.Errorf("Marshal allValueCompact")
  384. diff(t, b, []byte(allValueCompact))
  385. return
  386. }
  387. b, err = Marshal(pallValue)
  388. if err != nil {
  389. t.Fatalf("Marshal pallValue: %v", err)
  390. }
  391. if string(b) != pallValueCompact {
  392. t.Errorf("Marshal pallValueCompact")
  393. diff(t, b, []byte(pallValueCompact))
  394. return
  395. }
  396. }
  397. var badUTF8 = []struct {
  398. in, out string
  399. }{
  400. {"hello\xffworld", `"hello\ufffdworld"`},
  401. {"", `""`},
  402. {"\xff", `"\ufffd"`},
  403. {"\xff\xff", `"\ufffd\ufffd"`},
  404. {"a\xffb", `"a\ufffdb"`},
  405. {"\xe6\x97\xa5\xe6\x9c\xac\xff\xaa\x9e", `"日本\ufffd\ufffd\ufffd"`},
  406. }
  407. func TestMarshalBadUTF8(t *testing.T) {
  408. for _, tt := range badUTF8 {
  409. b, err := Marshal(tt.in)
  410. if string(b) != tt.out || err != nil {
  411. t.Errorf("Marshal(%q) = %#q, %v, want %#q, nil", tt.in, b, err, tt.out)
  412. }
  413. }
  414. }
  415. func TestMarshalNumberZeroVal(t *testing.T) {
  416. var n Number
  417. out, err := Marshal(n)
  418. if err != nil {
  419. t.Fatal(err)
  420. }
  421. outStr := string(out)
  422. if outStr != "0" {
  423. t.Fatalf("Invalid zero val for Number: %q", outStr)
  424. }
  425. }
  426. func TestMarshalEmbeds(t *testing.T) {
  427. top := &Top{
  428. Level0: 1,
  429. Embed0: Embed0{
  430. Level1b: 2,
  431. Level1c: 3,
  432. },
  433. Embed0a: &Embed0a{
  434. Level1a: 5,
  435. Level1b: 6,
  436. },
  437. Embed0b: &Embed0b{
  438. Level1a: 8,
  439. Level1b: 9,
  440. Level1c: 10,
  441. Level1d: 11,
  442. Level1e: 12,
  443. },
  444. Loop: Loop{
  445. Loop1: 13,
  446. Loop2: 14,
  447. },
  448. Embed0p: Embed0p{
  449. Point: image.Point{X: 15, Y: 16},
  450. },
  451. Embed0q: Embed0q{
  452. Point: Point{Z: 17},
  453. },
  454. embed: embed{
  455. Q: 18,
  456. },
  457. }
  458. b, err := Marshal(top)
  459. if err != nil {
  460. t.Fatal(err)
  461. }
  462. want := "{\"Level0\":1,\"Level1b\":2,\"Level1c\":3,\"Level1a\":5,\"LEVEL1B\":6,\"e\":{\"Level1a\":8,\"Level1b\":9,\"Level1c\":10,\"Level1d\":11,\"x\":12},\"Loop1\":13,\"Loop2\":14,\"X\":15,\"Y\":16,\"Z\":17,\"Q\":18}"
  463. if string(b) != want {
  464. t.Errorf("Wrong marshal result.\n got: %q\nwant: %q", b, want)
  465. }
  466. }
  467. func TestUnmarshal(t *testing.T) {
  468. for i, tt := range unmarshalTests {
  469. var scan scanner
  470. in := []byte(tt.in)
  471. if err := checkValid(in, &scan); err != nil {
  472. if !reflect.DeepEqual(err, tt.err) {
  473. t.Errorf("#%d: checkValid: %#v", i, err)
  474. continue
  475. }
  476. }
  477. if tt.ptr == nil {
  478. continue
  479. }
  480. // v = new(right-type)
  481. v := reflect.New(reflect.TypeOf(tt.ptr).Elem())
  482. dec := NewDecoder(bytes.NewReader(in))
  483. if tt.useNumber {
  484. dec.UseNumber()
  485. }
  486. if err := dec.Decode(v.Interface()); !reflect.DeepEqual(err, tt.err) {
  487. t.Errorf("#%d: %v, want %v", i, err, tt.err)
  488. continue
  489. } else if err != nil {
  490. continue
  491. }
  492. if !reflect.DeepEqual(v.Elem().Interface(), tt.out) {
  493. t.Errorf("#%d: mismatch\nhave: %#+v\nwant: %#+v", i, v.Elem().Interface(), tt.out)
  494. data, _ := Marshal(v.Elem().Interface())
  495. println(string(data))
  496. data, _ = Marshal(tt.out)
  497. println(string(data))
  498. continue
  499. }
  500. // Check round trip.
  501. if tt.err == nil {
  502. enc, err := Marshal(v.Interface())
  503. if err != nil {
  504. t.Errorf("#%d: error re-marshaling: %v", i, err)
  505. continue
  506. }
  507. vv := reflect.New(reflect.TypeOf(tt.ptr).Elem())
  508. dec = NewDecoder(bytes.NewReader(enc))
  509. if tt.useNumber {
  510. dec.UseNumber()
  511. }
  512. if err := dec.Decode(vv.Interface()); err != nil {
  513. t.Errorf("#%d: error re-unmarshaling %#q: %v", i, enc, err)
  514. continue
  515. }
  516. if !reflect.DeepEqual(v.Elem().Interface(), vv.Elem().Interface()) {
  517. t.Errorf("#%d: mismatch\nhave: %#+v\nwant: %#+v", i, v.Elem().Interface(), vv.Elem().Interface())
  518. t.Errorf(" In: %q", strings.Map(noSpace, string(in)))
  519. t.Errorf("Marshal: %q", strings.Map(noSpace, string(enc)))
  520. continue
  521. }
  522. }
  523. }
  524. }
  525. func TestUnmarshalMarshal(t *testing.T) {
  526. initBig()
  527. var v interface{}
  528. if err := Unmarshal(jsonBig, &v); err != nil {
  529. t.Fatalf("Unmarshal: %v", err)
  530. }
  531. b, err := Marshal(v)
  532. if err != nil {
  533. t.Fatalf("Marshal: %v", err)
  534. }
  535. if !bytes.Equal(jsonBig, b) {
  536. t.Errorf("Marshal jsonBig")
  537. diff(t, b, jsonBig)
  538. return
  539. }
  540. }
  541. var numberTests = []struct {
  542. in string
  543. i int64
  544. intErr string
  545. f float64
  546. floatErr string
  547. }{
  548. {in: "-1.23e1", intErr: "strconv.ParseInt: parsing \"-1.23e1\": invalid syntax", f: -1.23e1},
  549. {in: "-12", i: -12, f: -12.0},
  550. {in: "1e1000", intErr: "strconv.ParseInt: parsing \"1e1000\": invalid syntax", floatErr: "strconv.ParseFloat: parsing \"1e1000\": value out of range"},
  551. }
  552. // Independent of Decode, basic coverage of the accessors in Number
  553. func TestNumberAccessors(t *testing.T) {
  554. for _, tt := range numberTests {
  555. n := Number(tt.in)
  556. if s := n.String(); s != tt.in {
  557. t.Errorf("Number(%q).String() is %q", tt.in, s)
  558. }
  559. if i, err := n.Int64(); err == nil && tt.intErr == "" && i != tt.i {
  560. t.Errorf("Number(%q).Int64() is %d", tt.in, i)
  561. } else if (err == nil && tt.intErr != "") || (err != nil && err.Error() != tt.intErr) {
  562. t.Errorf("Number(%q).Int64() wanted error %q but got: %v", tt.in, tt.intErr, err)
  563. }
  564. if f, err := n.Float64(); err == nil && tt.floatErr == "" && f != tt.f {
  565. t.Errorf("Number(%q).Float64() is %g", tt.in, f)
  566. } else if (err == nil && tt.floatErr != "") || (err != nil && err.Error() != tt.floatErr) {
  567. t.Errorf("Number(%q).Float64() wanted error %q but got: %v", tt.in, tt.floatErr, err)
  568. }
  569. }
  570. }
  571. func TestLargeByteSlice(t *testing.T) {
  572. s0 := make([]byte, 2000)
  573. for i := range s0 {
  574. s0[i] = byte(i)
  575. }
  576. b, err := Marshal(s0)
  577. if err != nil {
  578. t.Fatalf("Marshal: %v", err)
  579. }
  580. var s1 []byte
  581. if err := Unmarshal(b, &s1); err != nil {
  582. t.Fatalf("Unmarshal: %v", err)
  583. }
  584. if !bytes.Equal(s0, s1) {
  585. t.Errorf("Marshal large byte slice")
  586. diff(t, s0, s1)
  587. }
  588. }
  589. type Xint struct {
  590. X int
  591. }
  592. func TestUnmarshalInterface(t *testing.T) {
  593. var xint Xint
  594. var i interface{} = &xint
  595. if err := Unmarshal([]byte(`{"X":1}`), &i); err != nil {
  596. t.Fatalf("Unmarshal: %v", err)
  597. }
  598. if xint.X != 1 {
  599. t.Fatalf("Did not write to xint")
  600. }
  601. }
  602. func TestUnmarshalPtrPtr(t *testing.T) {
  603. var xint Xint
  604. pxint := &xint
  605. if err := Unmarshal([]byte(`{"X":1}`), &pxint); err != nil {
  606. t.Fatalf("Unmarshal: %v", err)
  607. }
  608. if xint.X != 1 {
  609. t.Fatalf("Did not write to xint")
  610. }
  611. }
  612. func TestEscape(t *testing.T) {
  613. const input = `"foobar"<html>` + " [\u2028 \u2029]"
  614. const expected = `"\"foobar\"\u003chtml\u003e [\u2028 \u2029]"`
  615. b, err := Marshal(input)
  616. if err != nil {
  617. t.Fatalf("Marshal error: %v", err)
  618. }
  619. if s := string(b); s != expected {
  620. t.Errorf("Encoding of [%s]:\n got [%s]\nwant [%s]", input, s, expected)
  621. }
  622. }
  623. // WrongString is a struct that's misusing the ,string modifier.
  624. type WrongString struct {
  625. Message string `json:"result,string"`
  626. }
  627. type wrongStringTest struct {
  628. in, err string
  629. }
  630. var wrongStringTests = []wrongStringTest{
  631. {`{"result":"x"}`, `json: invalid use of ,string struct tag, trying to unmarshal "x" into string`},
  632. {`{"result":"foo"}`, `json: invalid use of ,string struct tag, trying to unmarshal "foo" into string`},
  633. {`{"result":"123"}`, `json: invalid use of ,string struct tag, trying to unmarshal "123" into string`},
  634. {`{"result":123}`, `json: invalid use of ,string struct tag, trying to unmarshal unquoted value into string`},
  635. }
  636. // If people misuse the ,string modifier, the error message should be
  637. // helpful, telling the user that they're doing it wrong.
  638. func TestErrorMessageFromMisusedString(t *testing.T) {
  639. for n, tt := range wrongStringTests {
  640. r := strings.NewReader(tt.in)
  641. var s WrongString
  642. err := NewDecoder(r).Decode(&s)
  643. got := fmt.Sprintf("%v", err)
  644. if got != tt.err {
  645. t.Errorf("%d. got err = %q, want %q", n, got, tt.err)
  646. }
  647. }
  648. }
  649. func noSpace(c rune) rune {
  650. if isSpace(byte(c)) { //only used for ascii
  651. return -1
  652. }
  653. return c
  654. }
  655. type All struct {
  656. Bool bool
  657. Int int
  658. Int8 int8
  659. Int16 int16
  660. Int32 int32
  661. Int64 int64
  662. Uint uint
  663. Uint8 uint8
  664. Uint16 uint16
  665. Uint32 uint32
  666. Uint64 uint64
  667. Uintptr uintptr
  668. Float32 float32
  669. Float64 float64
  670. Foo string `json:"bar"`
  671. Foo2 string `json:"bar2,dummyopt"`
  672. IntStr int64 `json:",string"`
  673. PBool *bool
  674. PInt *int
  675. PInt8 *int8
  676. PInt16 *int16
  677. PInt32 *int32
  678. PInt64 *int64
  679. PUint *uint
  680. PUint8 *uint8
  681. PUint16 *uint16
  682. PUint32 *uint32
  683. PUint64 *uint64
  684. PUintptr *uintptr
  685. PFloat32 *float32
  686. PFloat64 *float64
  687. String string
  688. PString *string
  689. Map map[string]Small
  690. MapP map[string]*Small
  691. PMap *map[string]Small
  692. PMapP *map[string]*Small
  693. EmptyMap map[string]Small
  694. NilMap map[string]Small
  695. Slice []Small
  696. SliceP []*Small
  697. PSlice *[]Small
  698. PSliceP *[]*Small
  699. EmptySlice []Small
  700. NilSlice []Small
  701. StringSlice []string
  702. ByteSlice []byte
  703. Small Small
  704. PSmall *Small
  705. PPSmall **Small
  706. Interface interface{}
  707. PInterface *interface{}
  708. unexported int
  709. }
  710. type Small struct {
  711. Tag string
  712. }
  713. var allValue = All{
  714. Bool: true,
  715. Int: 2,
  716. Int8: 3,
  717. Int16: 4,
  718. Int32: 5,
  719. Int64: 6,
  720. Uint: 7,
  721. Uint8: 8,
  722. Uint16: 9,
  723. Uint32: 10,
  724. Uint64: 11,
  725. Uintptr: 12,
  726. Float32: 14.1,
  727. Float64: 15.1,
  728. Foo: "foo",
  729. Foo2: "foo2",
  730. IntStr: 42,
  731. String: "16",
  732. Map: map[string]Small{
  733. "17": {Tag: "tag17"},
  734. "18": {Tag: "tag18"},
  735. },
  736. MapP: map[string]*Small{
  737. "19": {Tag: "tag19"},
  738. "20": nil,
  739. },
  740. EmptyMap: map[string]Small{},
  741. Slice: []Small{{Tag: "tag20"}, {Tag: "tag21"}},
  742. SliceP: []*Small{{Tag: "tag22"}, nil, {Tag: "tag23"}},
  743. EmptySlice: []Small{},
  744. StringSlice: []string{"str24", "str25", "str26"},
  745. ByteSlice: []byte{27, 28, 29},
  746. Small: Small{Tag: "tag30"},
  747. PSmall: &Small{Tag: "tag31"},
  748. Interface: 5.2,
  749. }
  750. var pallValue = All{
  751. PBool: &allValue.Bool,
  752. PInt: &allValue.Int,
  753. PInt8: &allValue.Int8,
  754. PInt16: &allValue.Int16,
  755. PInt32: &allValue.Int32,
  756. PInt64: &allValue.Int64,
  757. PUint: &allValue.Uint,
  758. PUint8: &allValue.Uint8,
  759. PUint16: &allValue.Uint16,
  760. PUint32: &allValue.Uint32,
  761. PUint64: &allValue.Uint64,
  762. PUintptr: &allValue.Uintptr,
  763. PFloat32: &allValue.Float32,
  764. PFloat64: &allValue.Float64,
  765. PString: &allValue.String,
  766. PMap: &allValue.Map,
  767. PMapP: &allValue.MapP,
  768. PSlice: &allValue.Slice,
  769. PSliceP: &allValue.SliceP,
  770. PPSmall: &allValue.PSmall,
  771. PInterface: &allValue.Interface,
  772. }
  773. var allValueIndent = `{
  774. "Bool": true,
  775. "Int": 2,
  776. "Int8": 3,
  777. "Int16": 4,
  778. "Int32": 5,
  779. "Int64": 6,
  780. "Uint": 7,
  781. "Uint8": 8,
  782. "Uint16": 9,
  783. "Uint32": 10,
  784. "Uint64": 11,
  785. "Uintptr": 12,
  786. "Float32": 14.1,
  787. "Float64": 15.1,
  788. "bar": "foo",
  789. "bar2": "foo2",
  790. "IntStr": "42",
  791. "PBool": null,
  792. "PInt": null,
  793. "PInt8": null,
  794. "PInt16": null,
  795. "PInt32": null,
  796. "PInt64": null,
  797. "PUint": null,
  798. "PUint8": null,
  799. "PUint16": null,
  800. "PUint32": null,
  801. "PUint64": null,
  802. "PUintptr": null,
  803. "PFloat32": null,
  804. "PFloat64": null,
  805. "String": "16",
  806. "PString": null,
  807. "Map": {
  808. "17": {
  809. "Tag": "tag17"
  810. },
  811. "18": {
  812. "Tag": "tag18"
  813. }
  814. },
  815. "MapP": {
  816. "19": {
  817. "Tag": "tag19"
  818. },
  819. "20": null
  820. },
  821. "PMap": null,
  822. "PMapP": null,
  823. "EmptyMap": {},
  824. "NilMap": null,
  825. "Slice": [
  826. {
  827. "Tag": "tag20"
  828. },
  829. {
  830. "Tag": "tag21"
  831. }
  832. ],
  833. "SliceP": [
  834. {
  835. "Tag": "tag22"
  836. },
  837. null,
  838. {
  839. "Tag": "tag23"
  840. }
  841. ],
  842. "PSlice": null,
  843. "PSliceP": null,
  844. "EmptySlice": [],
  845. "NilSlice": null,
  846. "StringSlice": [
  847. "str24",
  848. "str25",
  849. "str26"
  850. ],
  851. "ByteSlice": "Gxwd",
  852. "Small": {
  853. "Tag": "tag30"
  854. },
  855. "PSmall": {
  856. "Tag": "tag31"
  857. },
  858. "PPSmall": null,
  859. "Interface": 5.2,
  860. "PInterface": null
  861. }`
  862. var allValueCompact = strings.Map(noSpace, allValueIndent)
  863. var pallValueIndent = `{
  864. "Bool": false,
  865. "Int": 0,
  866. "Int8": 0,
  867. "Int16": 0,
  868. "Int32": 0,
  869. "Int64": 0,
  870. "Uint": 0,
  871. "Uint8": 0,
  872. "Uint16": 0,
  873. "Uint32": 0,
  874. "Uint64": 0,
  875. "Uintptr": 0,
  876. "Float32": 0,
  877. "Float64": 0,
  878. "bar": "",
  879. "bar2": "",
  880. "IntStr": "0",
  881. "PBool": true,
  882. "PInt": 2,
  883. "PInt8": 3,
  884. "PInt16": 4,
  885. "PInt32": 5,
  886. "PInt64": 6,
  887. "PUint": 7,
  888. "PUint8": 8,
  889. "PUint16": 9,
  890. "PUint32": 10,
  891. "PUint64": 11,
  892. "PUintptr": 12,
  893. "PFloat32": 14.1,
  894. "PFloat64": 15.1,
  895. "String": "",
  896. "PString": "16",
  897. "Map": null,
  898. "MapP": null,
  899. "PMap": {
  900. "17": {
  901. "Tag": "tag17"
  902. },
  903. "18": {
  904. "Tag": "tag18"
  905. }
  906. },
  907. "PMapP": {
  908. "19": {
  909. "Tag": "tag19"
  910. },
  911. "20": null
  912. },
  913. "EmptyMap": null,
  914. "NilMap": null,
  915. "Slice": null,
  916. "SliceP": null,
  917. "PSlice": [
  918. {
  919. "Tag": "tag20"
  920. },
  921. {
  922. "Tag": "tag21"
  923. }
  924. ],
  925. "PSliceP": [
  926. {
  927. "Tag": "tag22"
  928. },
  929. null,
  930. {
  931. "Tag": "tag23"
  932. }
  933. ],
  934. "EmptySlice": null,
  935. "NilSlice": null,
  936. "StringSlice": null,
  937. "ByteSlice": null,
  938. "Small": {
  939. "Tag": ""
  940. },
  941. "PSmall": null,
  942. "PPSmall": {
  943. "Tag": "tag31"
  944. },
  945. "Interface": null,
  946. "PInterface": 5.2
  947. }`
  948. var pallValueCompact = strings.Map(noSpace, pallValueIndent)
  949. func TestRefUnmarshal(t *testing.T) {
  950. type S struct {
  951. // Ref is defined in encode_test.go.
  952. R0 Ref
  953. R1 *Ref
  954. R2 RefText
  955. R3 *RefText
  956. }
  957. want := S{
  958. R0: 12,
  959. R1: new(Ref),
  960. R2: 13,
  961. R3: new(RefText),
  962. }
  963. *want.R1 = 12
  964. *want.R3 = 13
  965. var got S
  966. if err := Unmarshal([]byte(`{"R0":"ref","R1":"ref","R2":"ref","R3":"ref"}`), &got); err != nil {
  967. t.Fatalf("Unmarshal: %v", err)
  968. }
  969. if !reflect.DeepEqual(got, want) {
  970. t.Errorf("got %+v, want %+v", got, want)
  971. }
  972. }
  973. // Test that the empty string doesn't panic decoding when ,string is specified
  974. // Issue 3450
  975. func TestEmptyString(t *testing.T) {
  976. type T2 struct {
  977. Number1 int `json:",string"`
  978. Number2 int `json:",string"`
  979. }
  980. data := `{"Number1":"1", "Number2":""}`
  981. dec := NewDecoder(strings.NewReader(data))
  982. var t2 T2
  983. err := dec.Decode(&t2)
  984. if err == nil {
  985. t.Fatal("Decode: did not return error")
  986. }
  987. if t2.Number1 != 1 {
  988. t.Fatal("Decode: did not set Number1")
  989. }
  990. }
  991. // Test that a null for ,string is not replaced with the previous quoted string (issue 7046).
  992. // It should also not be an error (issue 2540, issue 8587).
  993. func TestNullString(t *testing.T) {
  994. type T struct {
  995. A int `json:",string"`
  996. B int `json:",string"`
  997. C *int `json:",string"`
  998. }
  999. data := []byte(`{"A": "1", "B": null, "C": null}`)
  1000. var s T
  1001. s.B = 1
  1002. s.C = new(int)
  1003. *s.C = 2
  1004. err := Unmarshal(data, &s)
  1005. if err != nil {
  1006. t.Fatalf("Unmarshal: %v", err)
  1007. }
  1008. if s.B != 1 || s.C != nil {
  1009. t.Fatalf("after Unmarshal, s.B=%d, s.C=%p, want 1, nil", s.B, s.C)
  1010. }
  1011. }
  1012. func intp(x int) *int {
  1013. p := new(int)
  1014. *p = x
  1015. return p
  1016. }
  1017. func intpp(x *int) **int {
  1018. pp := new(*int)
  1019. *pp = x
  1020. return pp
  1021. }
  1022. var interfaceSetTests = []struct {
  1023. pre interface{}
  1024. json string
  1025. post interface{}
  1026. }{
  1027. {"foo", `"bar"`, "bar"},
  1028. {"foo", `2`, 2.0},
  1029. {"foo", `true`, true},
  1030. {"foo", `null`, nil},
  1031. {nil, `null`, nil},
  1032. {new(int), `null`, nil},
  1033. {(*int)(nil), `null`, nil},
  1034. {new(*int), `null`, new(*int)},
  1035. {(**int)(nil), `null`, nil},
  1036. {intp(1), `null`, nil},
  1037. {intpp(nil), `null`, intpp(nil)},
  1038. {intpp(intp(1)), `null`, intpp(nil)},
  1039. }
  1040. func TestInterfaceSet(t *testing.T) {
  1041. for _, tt := range interfaceSetTests {
  1042. b := struct{ X interface{} }{tt.pre}
  1043. blob := `{"X":` + tt.json + `}`
  1044. if err := Unmarshal([]byte(blob), &b); err != nil {
  1045. t.Errorf("Unmarshal %#q: %v", blob, err)
  1046. continue
  1047. }
  1048. if !reflect.DeepEqual(b.X, tt.post) {
  1049. t.Errorf("Unmarshal %#q into %#v: X=%#v, want %#v", blob, tt.pre, b.X, tt.post)
  1050. }
  1051. }
  1052. }
  1053. // JSON null values should be ignored for primitives and string values instead of resulting in an error.
  1054. // Issue 2540
  1055. func TestUnmarshalNulls(t *testing.T) {
  1056. jsonData := []byte(`{
  1057. "Bool" : null,
  1058. "Int" : null,
  1059. "Int8" : null,
  1060. "Int16" : null,
  1061. "Int32" : null,
  1062. "Int64" : null,
  1063. "Uint" : null,
  1064. "Uint8" : null,
  1065. "Uint16" : null,
  1066. "Uint32" : null,
  1067. "Uint64" : null,
  1068. "Float32" : null,
  1069. "Float64" : null,
  1070. "String" : null}`)
  1071. nulls := All{
  1072. Bool: true,
  1073. Int: 2,
  1074. Int8: 3,
  1075. Int16: 4,
  1076. Int32: 5,
  1077. Int64: 6,
  1078. Uint: 7,
  1079. Uint8: 8,
  1080. Uint16: 9,
  1081. Uint32: 10,
  1082. Uint64: 11,
  1083. Float32: 12.1,
  1084. Float64: 13.1,
  1085. String: "14"}
  1086. err := Unmarshal(jsonData, &nulls)
  1087. if err != nil {
  1088. t.Errorf("Unmarshal of null values failed: %v", err)
  1089. }
  1090. if !nulls.Bool || nulls.Int != 2 || nulls.Int8 != 3 || nulls.Int16 != 4 || nulls.Int32 != 5 || nulls.Int64 != 6 ||
  1091. nulls.Uint != 7 || nulls.Uint8 != 8 || nulls.Uint16 != 9 || nulls.Uint32 != 10 || nulls.Uint64 != 11 ||
  1092. nulls.Float32 != 12.1 || nulls.Float64 != 13.1 || nulls.String != "14" {
  1093. t.Errorf("Unmarshal of null values affected primitives")
  1094. }
  1095. }
  1096. func TestStringKind(t *testing.T) {
  1097. type stringKind string
  1098. var m1, m2 map[stringKind]int
  1099. m1 = map[stringKind]int{
  1100. "foo": 42,
  1101. }
  1102. data, err := Marshal(m1)
  1103. if err != nil {
  1104. t.Errorf("Unexpected error marshaling: %v", err)
  1105. }
  1106. err = Unmarshal(data, &m2)
  1107. if err != nil {
  1108. t.Errorf("Unexpected error unmarshaling: %v", err)
  1109. }
  1110. if !reflect.DeepEqual(m1, m2) {
  1111. t.Error("Items should be equal after encoding and then decoding")
  1112. }
  1113. }
  1114. // Custom types with []byte as underlying type could not be marshalled
  1115. // and then unmarshalled.
  1116. // Issue 8962.
  1117. func TestByteKind(t *testing.T) {
  1118. type byteKind []byte
  1119. a := byteKind("hello")
  1120. data, err := Marshal(a)
  1121. if err != nil {
  1122. t.Error(err)
  1123. }
  1124. var b byteKind
  1125. err = Unmarshal(data, &b)
  1126. if err != nil {
  1127. t.Fatal(err)
  1128. }
  1129. if !reflect.DeepEqual(a, b) {
  1130. t.Errorf("expected %v == %v", a, b)
  1131. }
  1132. }
  1133. // The fix for issue 8962 introduced a regression.
  1134. // Issue 12921.
  1135. func TestSliceOfCustomByte(t *testing.T) {
  1136. type Uint8 uint8
  1137. a := []Uint8("hello")
  1138. data, err := Marshal(a)
  1139. if err != nil {
  1140. t.Fatal(err)
  1141. }
  1142. var b []Uint8
  1143. err = Unmarshal(data, &b)
  1144. if err != nil {
  1145. t.Fatal(err)
  1146. }
  1147. if !reflect.DeepEqual(a, b) {
  1148. t.Fatal("expected %v == %v", a, b)
  1149. }
  1150. }
  1151. var decodeTypeErrorTests = []struct {
  1152. dest interface{}
  1153. src string
  1154. }{
  1155. {new(string), `{"user": "name"}`}, // issue 4628.
  1156. {new(error), `{}`}, // issue 4222
  1157. {new(error), `[]`},
  1158. {new(error), `""`},
  1159. {new(error), `123`},
  1160. {new(error), `true`},
  1161. }
  1162. func TestUnmarshalTypeError(t *testing.T) {
  1163. for _, item := range decodeTypeErrorTests {
  1164. err := Unmarshal([]byte(item.src), item.dest)
  1165. if _, ok := err.(*UnmarshalTypeError); !ok {
  1166. t.Errorf("expected type error for Unmarshal(%q, type %T): got %T",
  1167. item.src, item.dest, err)
  1168. }
  1169. }
  1170. }
  1171. var unmarshalSyntaxTests = []string{
  1172. "tru",
  1173. "fals",
  1174. "nul",
  1175. "123e",
  1176. `"hello`,
  1177. `[1,2,3`,
  1178. `{"key":1`,
  1179. `{"key":1,`,
  1180. }
  1181. func TestUnmarshalSyntax(t *testing.T) {
  1182. var x interface{}
  1183. for _, src := range unmarshalSyntaxTests {
  1184. err := Unmarshal([]byte(src), &x)
  1185. if _, ok := err.(*SyntaxError); !ok {
  1186. t.Errorf("expected syntax error for Unmarshal(%q): got %T", src, err)
  1187. }
  1188. }
  1189. }
  1190. // Test handling of unexported fields that should be ignored.
  1191. // Issue 4660
  1192. type unexportedFields struct {
  1193. Name string
  1194. m map[string]interface{} `json:"-"`
  1195. m2 map[string]interface{} `json:"abcd"`
  1196. }
  1197. func TestUnmarshalUnexported(t *testing.T) {
  1198. input := `{"Name": "Bob", "m": {"x": 123}, "m2": {"y": 456}, "abcd": {"z": 789}}`
  1199. want := &unexportedFields{Name: "Bob"}
  1200. out := &unexportedFields{}
  1201. err := Unmarshal([]byte(input), out)
  1202. if err != nil {
  1203. t.Errorf("got error %v, expected nil", err)
  1204. }
  1205. if !reflect.DeepEqual(out, want) {
  1206. t.Errorf("got %q, want %q", out, want)
  1207. }
  1208. }
  1209. // Time3339 is a time.Time which encodes to and from JSON
  1210. // as an RFC 3339 time in UTC.
  1211. type Time3339 time.Time
  1212. func (t *Time3339) UnmarshalJSON(b []byte) error {
  1213. if len(b) < 2 || b[0] != '"' || b[len(b)-1] != '"' {
  1214. return fmt.Errorf("types: failed to unmarshal non-string value %q as an RFC 3339 time", b)
  1215. }
  1216. tm, err := time.Parse(time.RFC3339, string(b[1:len(b)-1]))
  1217. if err != nil {
  1218. return err
  1219. }
  1220. *t = Time3339(tm)
  1221. return nil
  1222. }
  1223. func TestUnmarshalJSONLiteralError(t *testing.T) {
  1224. var t3 Time3339
  1225. err := Unmarshal([]byte(`"0000-00-00T00:00:00Z"`), &t3)
  1226. if err == nil {
  1227. t.Fatalf("expected error; got time %v", time.Time(t3))
  1228. }
  1229. if !strings.Contains(err.Error(), "range") {
  1230. t.Errorf("got err = %v; want out of range error", err)
  1231. }
  1232. }
  1233. // Test that extra object elements in an array do not result in a
  1234. // "data changing underfoot" error.
  1235. // Issue 3717
  1236. func TestSkipArrayObjects(t *testing.T) {
  1237. json := `[{}]`
  1238. var dest [0]interface{}
  1239. err := Unmarshal([]byte(json), &dest)
  1240. if err != nil {
  1241. t.Errorf("got error %q, want nil", err)
  1242. }
  1243. }
  1244. // Test semantics of pre-filled struct fields and pre-filled map fields.
  1245. // Issue 4900.
  1246. func TestPrefilled(t *testing.T) {
  1247. ptrToMap := func(m map[string]interface{}) *map[string]interface{} { return &m }
  1248. // Values here change, cannot reuse table across runs.
  1249. var prefillTests = []struct {
  1250. in string
  1251. ptr interface{}
  1252. out interface{}
  1253. }{
  1254. {
  1255. in: `{"X": 1, "Y": 2}`,
  1256. ptr: &XYZ{X: float32(3), Y: int16(4), Z: 1.5},
  1257. out: &XYZ{X: float64(1), Y: float64(2), Z: 1.5},
  1258. },
  1259. {
  1260. in: `{"X": 1, "Y": 2}`,
  1261. ptr: ptrToMap(map[string]interface{}{"X": float32(3), "Y": int16(4), "Z": 1.5}),
  1262. out: ptrToMap(map[string]interface{}{"X": float64(1), "Y": float64(2), "Z": 1.5}),
  1263. },
  1264. }
  1265. for _, tt := range prefillTests {
  1266. ptrstr := fmt.Sprintf("%v", tt.ptr)
  1267. err := Unmarshal([]byte(tt.in), tt.ptr) // tt.ptr edited here
  1268. if err != nil {
  1269. t.Errorf("Unmarshal: %v", err)
  1270. }
  1271. if !reflect.DeepEqual(tt.ptr, tt.out) {
  1272. t.Errorf("Unmarshal(%#q, %s): have %v, want %v", tt.in, ptrstr, tt.ptr, tt.out)
  1273. }
  1274. }
  1275. }
  1276. var invalidUnmarshalTests = []struct {
  1277. v interface{}
  1278. want string
  1279. }{
  1280. {nil, "json: Unmarshal(nil)"},
  1281. {struct{}{}, "json: Unmarshal(non-pointer struct {})"},
  1282. {(*int)(nil), "json: Unmarshal(nil *int)"},
  1283. }
  1284. func TestInvalidUnmarshal(t *testing.T) {
  1285. buf := []byte(`{"a":"1"}`)
  1286. for _, tt := range invalidUnmarshalTests {
  1287. err := Unmarshal(buf, tt.v)
  1288. if err == nil {
  1289. t.Errorf("Unmarshal expecting error, got nil")
  1290. continue
  1291. }
  1292. if got := err.Error(); got != tt.want {
  1293. t.Errorf("Unmarshal = %q; want %q", got, tt.want)
  1294. }
  1295. }
  1296. }
  1297. var invalidUnmarshalTextTests = []struct {
  1298. v interface{}
  1299. want string
  1300. }{
  1301. {nil, "json: Unmarshal(nil)"},
  1302. {struct{}{}, "json: Unmarshal(non-pointer struct {})"},
  1303. {(*int)(nil), "json: Unmarshal(nil *int)"},
  1304. {new(net.IP), "json: cannot unmarshal string into Go value of type *net.IP"},
  1305. }
  1306. func TestInvalidUnmarshalText(t *testing.T) {
  1307. buf := []byte(`123`)
  1308. for _, tt := range invalidUnmarshalTextTests {
  1309. err := Unmarshal(buf, tt.v)
  1310. if err == nil {
  1311. t.Errorf("Unmarshal expecting error, got nil")
  1312. continue
  1313. }
  1314. if got := err.Error(); got != tt.want {
  1315. t.Errorf("Unmarshal = %q; want %q", got, tt.want)
  1316. }
  1317. }
  1318. }
  1319. // Test that string option is ignored for invalid types.
  1320. // Issue 9812.
  1321. func TestInvalidStringOption(t *testing.T) {
  1322. num := 0
  1323. item := struct {
  1324. T time.Time `json:",string"`
  1325. M map[string]string `json:",string"`
  1326. S []string `json:",string"`
  1327. A [1]string `json:",string"`
  1328. I interface{} `json:",string"`
  1329. P *int `json:",string"`
  1330. }{M: make(map[string]string), S: make([]string, 0), I: num, P: &num}
  1331. data, err := Marshal(item)
  1332. if err != nil {
  1333. t.Fatalf("Marshal: %v", err)
  1334. }
  1335. err = Unmarshal(data, &item)
  1336. if err != nil {
  1337. t.Fatalf("Unmarshal: %v", err)
  1338. }
  1339. }