decode_test.go 31 KB

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