decode_test.go 24 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106
  1. package yaml_test
  2. import (
  3. "errors"
  4. "io"
  5. "math"
  6. "net"
  7. "reflect"
  8. "strings"
  9. "time"
  10. . "gopkg.in/check.v1"
  11. "gopkg.in/yaml.v2"
  12. )
  13. var unmarshalIntTest = 123
  14. var unmarshalTests = []struct {
  15. data string
  16. value interface{}
  17. }{
  18. {
  19. "",
  20. (*struct{})(nil),
  21. },
  22. {
  23. "{}", &struct{}{},
  24. }, {
  25. "v: hi",
  26. map[string]string{"v": "hi"},
  27. }, {
  28. "v: hi", map[string]interface{}{"v": "hi"},
  29. }, {
  30. "v: true",
  31. map[string]string{"v": "true"},
  32. }, {
  33. "v: true",
  34. map[string]interface{}{"v": true},
  35. }, {
  36. "v: 10",
  37. map[string]interface{}{"v": 10},
  38. }, {
  39. "v: 0b10",
  40. map[string]interface{}{"v": 2},
  41. }, {
  42. "v: 0xA",
  43. map[string]interface{}{"v": 10},
  44. }, {
  45. "v: 4294967296",
  46. map[string]int64{"v": 4294967296},
  47. }, {
  48. "v: 0.1",
  49. map[string]interface{}{"v": 0.1},
  50. }, {
  51. "v: .1",
  52. map[string]interface{}{"v": 0.1},
  53. }, {
  54. "v: .Inf",
  55. map[string]interface{}{"v": math.Inf(+1)},
  56. }, {
  57. "v: -.Inf",
  58. map[string]interface{}{"v": math.Inf(-1)},
  59. }, {
  60. "v: -10",
  61. map[string]interface{}{"v": -10},
  62. }, {
  63. "v: -.1",
  64. map[string]interface{}{"v": -0.1},
  65. },
  66. // Simple values.
  67. {
  68. "123",
  69. &unmarshalIntTest,
  70. },
  71. // Floats from spec
  72. {
  73. "canonical: 6.8523e+5",
  74. map[string]interface{}{"canonical": 6.8523e+5},
  75. }, {
  76. "expo: 685.230_15e+03",
  77. map[string]interface{}{"expo": 685.23015e+03},
  78. }, {
  79. "fixed: 685_230.15",
  80. map[string]interface{}{"fixed": 685230.15},
  81. }, {
  82. "neginf: -.inf",
  83. map[string]interface{}{"neginf": math.Inf(-1)},
  84. }, {
  85. "fixed: 685_230.15",
  86. map[string]float64{"fixed": 685230.15},
  87. },
  88. //{"sexa: 190:20:30.15", map[string]interface{}{"sexa": 0}}, // Unsupported
  89. //{"notanum: .NaN", map[string]interface{}{"notanum": math.NaN()}}, // Equality of NaN fails.
  90. // Bools from spec
  91. {
  92. "canonical: y",
  93. map[string]interface{}{"canonical": true},
  94. }, {
  95. "answer: NO",
  96. map[string]interface{}{"answer": false},
  97. }, {
  98. "logical: True",
  99. map[string]interface{}{"logical": true},
  100. }, {
  101. "option: on",
  102. map[string]interface{}{"option": true},
  103. }, {
  104. "option: on",
  105. map[string]bool{"option": true},
  106. },
  107. // Ints from spec
  108. {
  109. "canonical: 685230",
  110. map[string]interface{}{"canonical": 685230},
  111. }, {
  112. "decimal: +685_230",
  113. map[string]interface{}{"decimal": 685230},
  114. }, {
  115. "octal: 02472256",
  116. map[string]interface{}{"octal": 685230},
  117. }, {
  118. "hexa: 0x_0A_74_AE",
  119. map[string]interface{}{"hexa": 685230},
  120. }, {
  121. "bin: 0b1010_0111_0100_1010_1110",
  122. map[string]interface{}{"bin": 685230},
  123. }, {
  124. "bin: -0b101010",
  125. map[string]interface{}{"bin": -42},
  126. }, {
  127. "decimal: +685_230",
  128. map[string]int{"decimal": 685230},
  129. },
  130. //{"sexa: 190:20:30", map[string]interface{}{"sexa": 0}}, // Unsupported
  131. // Nulls from spec
  132. {
  133. "empty:",
  134. map[string]interface{}{"empty": nil},
  135. }, {
  136. "canonical: ~",
  137. map[string]interface{}{"canonical": nil},
  138. }, {
  139. "english: null",
  140. map[string]interface{}{"english": nil},
  141. }, {
  142. "~: null key",
  143. map[interface{}]string{nil: "null key"},
  144. }, {
  145. "empty:",
  146. map[string]*bool{"empty": nil},
  147. },
  148. // Flow sequence
  149. {
  150. "seq: [A,B]",
  151. map[string]interface{}{"seq": []interface{}{"A", "B"}},
  152. }, {
  153. "seq: [A,B,C,]",
  154. map[string][]string{"seq": []string{"A", "B", "C"}},
  155. }, {
  156. "seq: [A,1,C]",
  157. map[string][]string{"seq": []string{"A", "1", "C"}},
  158. }, {
  159. "seq: [A,1,C]",
  160. map[string][]int{"seq": []int{1}},
  161. }, {
  162. "seq: [A,1,C]",
  163. map[string]interface{}{"seq": []interface{}{"A", 1, "C"}},
  164. },
  165. // Block sequence
  166. {
  167. "seq:\n - A\n - B",
  168. map[string]interface{}{"seq": []interface{}{"A", "B"}},
  169. }, {
  170. "seq:\n - A\n - B\n - C",
  171. map[string][]string{"seq": []string{"A", "B", "C"}},
  172. }, {
  173. "seq:\n - A\n - 1\n - C",
  174. map[string][]string{"seq": []string{"A", "1", "C"}},
  175. }, {
  176. "seq:\n - A\n - 1\n - C",
  177. map[string][]int{"seq": []int{1}},
  178. }, {
  179. "seq:\n - A\n - 1\n - C",
  180. map[string]interface{}{"seq": []interface{}{"A", 1, "C"}},
  181. },
  182. // Literal block scalar
  183. {
  184. "scalar: | # Comment\n\n literal\n\n \ttext\n\n",
  185. map[string]string{"scalar": "\nliteral\n\n\ttext\n"},
  186. },
  187. // Folded block scalar
  188. {
  189. "scalar: > # Comment\n\n folded\n line\n \n next\n line\n * one\n * two\n\n last\n line\n\n",
  190. map[string]string{"scalar": "\nfolded line\nnext line\n * one\n * two\n\nlast line\n"},
  191. },
  192. // Map inside interface with no type hints.
  193. {
  194. "a: {b: c}",
  195. map[interface{}]interface{}{"a": map[interface{}]interface{}{"b": "c"}},
  196. },
  197. // Structs and type conversions.
  198. {
  199. "hello: world",
  200. &struct{ Hello string }{"world"},
  201. }, {
  202. "a: {b: c}",
  203. &struct{ A struct{ B string } }{struct{ B string }{"c"}},
  204. }, {
  205. "a: {b: c}",
  206. &struct{ A *struct{ B string } }{&struct{ B string }{"c"}},
  207. }, {
  208. "a: {b: c}",
  209. &struct{ A map[string]string }{map[string]string{"b": "c"}},
  210. }, {
  211. "a: {b: c}",
  212. &struct{ A *map[string]string }{&map[string]string{"b": "c"}},
  213. }, {
  214. "a:",
  215. &struct{ A map[string]string }{},
  216. }, {
  217. "a: 1",
  218. &struct{ A int }{1},
  219. }, {
  220. "a: 1",
  221. &struct{ A float64 }{1},
  222. }, {
  223. "a: 1.0",
  224. &struct{ A int }{1},
  225. }, {
  226. "a: 1.0",
  227. &struct{ A uint }{1},
  228. }, {
  229. "a: [1, 2]",
  230. &struct{ A []int }{[]int{1, 2}},
  231. }, {
  232. "a: 1",
  233. &struct{ B int }{0},
  234. }, {
  235. "a: 1",
  236. &struct {
  237. B int "a"
  238. }{1},
  239. }, {
  240. "a: y",
  241. &struct{ A bool }{true},
  242. },
  243. // Some cross type conversions
  244. {
  245. "v: 42",
  246. map[string]uint{"v": 42},
  247. }, {
  248. "v: -42",
  249. map[string]uint{},
  250. }, {
  251. "v: 4294967296",
  252. map[string]uint64{"v": 4294967296},
  253. }, {
  254. "v: -4294967296",
  255. map[string]uint64{},
  256. },
  257. // int
  258. {
  259. "int_max: 2147483647",
  260. map[string]int{"int_max": math.MaxInt32},
  261. },
  262. {
  263. "int_min: -2147483648",
  264. map[string]int{"int_min": math.MinInt32},
  265. },
  266. {
  267. "int_overflow: 9223372036854775808", // math.MaxInt64 + 1
  268. map[string]int{},
  269. },
  270. // int64
  271. {
  272. "int64_max: 9223372036854775807",
  273. map[string]int64{"int64_max": math.MaxInt64},
  274. },
  275. {
  276. "int64_max_base2: 0b111111111111111111111111111111111111111111111111111111111111111",
  277. map[string]int64{"int64_max_base2": math.MaxInt64},
  278. },
  279. {
  280. "int64_min: -9223372036854775808",
  281. map[string]int64{"int64_min": math.MinInt64},
  282. },
  283. {
  284. "int64_neg_base2: -0b111111111111111111111111111111111111111111111111111111111111111",
  285. map[string]int64{"int64_neg_base2": -math.MaxInt64},
  286. },
  287. {
  288. "int64_overflow: 9223372036854775808", // math.MaxInt64 + 1
  289. map[string]int64{},
  290. },
  291. // uint
  292. {
  293. "uint_min: 0",
  294. map[string]uint{"uint_min": 0},
  295. },
  296. {
  297. "uint_max: 4294967295",
  298. map[string]uint{"uint_max": math.MaxUint32},
  299. },
  300. {
  301. "uint_underflow: -1",
  302. map[string]uint{},
  303. },
  304. // uint64
  305. {
  306. "uint64_min: 0",
  307. map[string]uint{"uint64_min": 0},
  308. },
  309. {
  310. "uint64_max: 18446744073709551615",
  311. map[string]uint64{"uint64_max": math.MaxUint64},
  312. },
  313. {
  314. "uint64_max_base2: 0b1111111111111111111111111111111111111111111111111111111111111111",
  315. map[string]uint64{"uint64_max_base2": math.MaxUint64},
  316. },
  317. {
  318. "uint64_maxint64: 9223372036854775807",
  319. map[string]uint64{"uint64_maxint64": math.MaxInt64},
  320. },
  321. {
  322. "uint64_underflow: -1",
  323. map[string]uint64{},
  324. },
  325. // float32
  326. {
  327. "float32_max: 3.40282346638528859811704183484516925440e+38",
  328. map[string]float32{"float32_max": math.MaxFloat32},
  329. },
  330. {
  331. "float32_nonzero: 1.401298464324817070923729583289916131280e-45",
  332. map[string]float32{"float32_nonzero": math.SmallestNonzeroFloat32},
  333. },
  334. {
  335. "float32_maxuint64: 18446744073709551615",
  336. map[string]float32{"float32_maxuint64": float32(math.MaxUint64)},
  337. },
  338. {
  339. "float32_maxuint64+1: 18446744073709551616",
  340. map[string]float32{"float32_maxuint64+1": float32(math.MaxUint64 + 1)},
  341. },
  342. // float64
  343. {
  344. "float64_max: 1.797693134862315708145274237317043567981e+308",
  345. map[string]float64{"float64_max": math.MaxFloat64},
  346. },
  347. {
  348. "float64_nonzero: 4.940656458412465441765687928682213723651e-324",
  349. map[string]float64{"float64_nonzero": math.SmallestNonzeroFloat64},
  350. },
  351. {
  352. "float64_maxuint64: 18446744073709551615",
  353. map[string]float64{"float64_maxuint64": float64(math.MaxUint64)},
  354. },
  355. {
  356. "float64_maxuint64+1: 18446744073709551616",
  357. map[string]float64{"float64_maxuint64+1": float64(math.MaxUint64 + 1)},
  358. },
  359. // Overflow cases.
  360. {
  361. "v: 4294967297",
  362. map[string]int32{},
  363. }, {
  364. "v: 128",
  365. map[string]int8{},
  366. },
  367. // Quoted values.
  368. {
  369. "'1': '\"2\"'",
  370. map[interface{}]interface{}{"1": "\"2\""},
  371. }, {
  372. "v:\n- A\n- 'B\n\n C'\n",
  373. map[string][]string{"v": []string{"A", "B\nC"}},
  374. },
  375. // Explicit tags.
  376. {
  377. "v: !!float '1.1'",
  378. map[string]interface{}{"v": 1.1},
  379. }, {
  380. "v: !!null ''",
  381. map[string]interface{}{"v": nil},
  382. }, {
  383. "%TAG !y! tag:yaml.org,2002:\n---\nv: !y!int '1'",
  384. map[string]interface{}{"v": 1},
  385. },
  386. // Non-specific tag (Issue #75)
  387. {
  388. "v: ! test",
  389. map[string]interface{}{"v": "test"},
  390. },
  391. // Anchors and aliases.
  392. {
  393. "a: &x 1\nb: &y 2\nc: *x\nd: *y\n",
  394. &struct{ A, B, C, D int }{1, 2, 1, 2},
  395. }, {
  396. "a: &a {c: 1}\nb: *a",
  397. &struct {
  398. A, B struct {
  399. C int
  400. }
  401. }{struct{ C int }{1}, struct{ C int }{1}},
  402. }, {
  403. "a: &a [1, 2]\nb: *a",
  404. &struct{ B []int }{[]int{1, 2}},
  405. },
  406. // Bug #1133337
  407. {
  408. "foo: ''",
  409. map[string]*string{"foo": new(string)},
  410. }, {
  411. "foo: null",
  412. map[string]*string{"foo": nil},
  413. }, {
  414. "foo: null",
  415. map[string]string{"foo": ""},
  416. }, {
  417. "foo: null",
  418. map[string]interface{}{"foo": nil},
  419. },
  420. // Support for ~
  421. {
  422. "foo: ~",
  423. map[string]*string{"foo": nil},
  424. }, {
  425. "foo: ~",
  426. map[string]string{"foo": ""},
  427. }, {
  428. "foo: ~",
  429. map[string]interface{}{"foo": nil},
  430. },
  431. // Ignored field
  432. {
  433. "a: 1\nb: 2\n",
  434. &struct {
  435. A int
  436. B int "-"
  437. }{1, 0},
  438. },
  439. // Bug #1191981
  440. {
  441. "" +
  442. "%YAML 1.1\n" +
  443. "--- !!str\n" +
  444. `"Generic line break (no glyph)\n\` + "\n" +
  445. ` Generic line break (glyphed)\n\` + "\n" +
  446. ` Line separator\u2028\` + "\n" +
  447. ` Paragraph separator\u2029"` + "\n",
  448. "" +
  449. "Generic line break (no glyph)\n" +
  450. "Generic line break (glyphed)\n" +
  451. "Line separator\u2028Paragraph separator\u2029",
  452. },
  453. // Struct inlining
  454. {
  455. "a: 1\nb: 2\nc: 3\n",
  456. &struct {
  457. A int
  458. C inlineB `yaml:",inline"`
  459. }{1, inlineB{2, inlineC{3}}},
  460. },
  461. // Map inlining
  462. {
  463. "a: 1\nb: 2\nc: 3\n",
  464. &struct {
  465. A int
  466. C map[string]int `yaml:",inline"`
  467. }{1, map[string]int{"b": 2, "c": 3}},
  468. },
  469. // bug 1243827
  470. {
  471. "a: -b_c",
  472. map[string]interface{}{"a": "-b_c"},
  473. },
  474. {
  475. "a: +b_c",
  476. map[string]interface{}{"a": "+b_c"},
  477. },
  478. {
  479. "a: 50cent_of_dollar",
  480. map[string]interface{}{"a": "50cent_of_dollar"},
  481. },
  482. // Duration
  483. {
  484. "a: 3s",
  485. map[string]time.Duration{"a": 3 * time.Second},
  486. },
  487. // Issue #24.
  488. {
  489. "a: <foo>",
  490. map[string]string{"a": "<foo>"},
  491. },
  492. // Base 60 floats are obsolete and unsupported.
  493. {
  494. "a: 1:1\n",
  495. map[string]string{"a": "1:1"},
  496. },
  497. // Binary data.
  498. {
  499. "a: !!binary gIGC\n",
  500. map[string]string{"a": "\x80\x81\x82"},
  501. }, {
  502. "a: !!binary |\n " + strings.Repeat("kJCQ", 17) + "kJ\n CQ\n",
  503. map[string]string{"a": strings.Repeat("\x90", 54)},
  504. }, {
  505. "a: !!binary |\n " + strings.Repeat("A", 70) + "\n ==\n",
  506. map[string]string{"a": strings.Repeat("\x00", 52)},
  507. },
  508. // Ordered maps.
  509. {
  510. "{b: 2, a: 1, d: 4, c: 3, sub: {e: 5}}",
  511. &yaml.MapSlice{{"b", 2}, {"a", 1}, {"d", 4}, {"c", 3}, {"sub", yaml.MapSlice{{"e", 5}}}},
  512. },
  513. // Issue #39.
  514. {
  515. "a:\n b:\n c: d\n",
  516. map[string]struct{ B interface{} }{"a": {map[interface{}]interface{}{"c": "d"}}},
  517. },
  518. // Custom map type.
  519. {
  520. "a: {b: c}",
  521. M{"a": M{"b": "c"}},
  522. },
  523. // Support encoding.TextUnmarshaler.
  524. {
  525. "a: 1.2.3.4\n",
  526. map[string]net.IP{"a": net.IPv4(1, 2, 3, 4)},
  527. },
  528. {
  529. "a: 2015-02-24T18:19:39Z\n",
  530. map[string]time.Time{"a": time.Unix(1424801979, 0).In(time.UTC)},
  531. },
  532. // Encode empty lists as zero-length slices.
  533. {
  534. "a: []",
  535. &struct{ A []int }{[]int{}},
  536. },
  537. // UTF-16-LE
  538. {
  539. "\xff\xfe\xf1\x00o\x00\xf1\x00o\x00:\x00 \x00v\x00e\x00r\x00y\x00 \x00y\x00e\x00s\x00\n\x00",
  540. M{"ñoño": "very yes"},
  541. },
  542. // UTF-16-LE with surrogate.
  543. {
  544. "\xff\xfe\xf1\x00o\x00\xf1\x00o\x00:\x00 \x00v\x00e\x00r\x00y\x00 \x00y\x00e\x00s\x00 \x00=\xd8\xd4\xdf\n\x00",
  545. M{"ñoño": "very yes 🟔"},
  546. },
  547. // UTF-16-BE
  548. {
  549. "\xfe\xff\x00\xf1\x00o\x00\xf1\x00o\x00:\x00 \x00v\x00e\x00r\x00y\x00 \x00y\x00e\x00s\x00\n",
  550. M{"ñoño": "very yes"},
  551. },
  552. // UTF-16-BE with surrogate.
  553. {
  554. "\xfe\xff\x00\xf1\x00o\x00\xf1\x00o\x00:\x00 \x00v\x00e\x00r\x00y\x00 \x00y\x00e\x00s\x00 \xd8=\xdf\xd4\x00\n",
  555. M{"ñoño": "very yes 🟔"},
  556. },
  557. // YAML Float regex shouldn't match this
  558. {
  559. "a: 123456e1\n",
  560. M{"a": "123456e1"},
  561. }, {
  562. "a: 123456E1\n",
  563. M{"a": "123456E1"},
  564. },
  565. // yaml-test-suite 3GZX: Spec Example 7.1. Alias Nodes
  566. {
  567. "First occurrence: &anchor Foo\nSecond occurrence: *anchor\nOverride anchor: &anchor Bar\nReuse anchor: *anchor\n",
  568. map[interface{}]interface{}{
  569. "Reuse anchor": "Bar",
  570. "First occurrence": "Foo",
  571. "Second occurrence": "Foo",
  572. "Override anchor": "Bar",
  573. },
  574. },
  575. }
  576. type M map[interface{}]interface{}
  577. type inlineB struct {
  578. B int
  579. inlineC `yaml:",inline"`
  580. }
  581. type inlineC struct {
  582. C int
  583. }
  584. func (s *S) TestUnmarshal(c *C) {
  585. for i, item := range unmarshalTests {
  586. c.Logf("test %d: %q", i, item.data)
  587. t := reflect.ValueOf(item.value).Type()
  588. value := reflect.New(t)
  589. err := yaml.Unmarshal([]byte(item.data), value.Interface())
  590. if _, ok := err.(*yaml.TypeError); !ok {
  591. c.Assert(err, IsNil)
  592. }
  593. c.Assert(value.Elem().Interface(), DeepEquals, item.value)
  594. }
  595. }
  596. func (s *S) TestDecoderSingleDocument(c *C) {
  597. // Test that Decoder.Decode works as expected on
  598. // all the unmarshal tests.
  599. for i, item := range unmarshalTests {
  600. c.Logf("test %d: %q", i, item.data)
  601. if item.data == "" {
  602. // Behaviour differs when there's no YAML.
  603. continue
  604. }
  605. t := reflect.ValueOf(item.value).Type()
  606. value := reflect.New(t)
  607. err := yaml.NewDecoder(strings.NewReader(item.data)).Decode(value.Interface())
  608. if _, ok := err.(*yaml.TypeError); !ok {
  609. c.Assert(err, IsNil)
  610. }
  611. c.Assert(value.Elem().Interface(), DeepEquals, item.value)
  612. }
  613. }
  614. var decoderTests = []struct {
  615. data string
  616. values []interface{}
  617. }{{
  618. "",
  619. nil,
  620. }, {
  621. "a: b",
  622. []interface{}{
  623. map[interface{}]interface{}{"a": "b"},
  624. },
  625. }, {
  626. "---\na: b\n...\n",
  627. []interface{}{
  628. map[interface{}]interface{}{"a": "b"},
  629. },
  630. }, {
  631. "---\n'hello'\n...\n---\ngoodbye\n...\n",
  632. []interface{}{
  633. "hello",
  634. "goodbye",
  635. },
  636. }}
  637. func (s *S) TestDecoder(c *C) {
  638. for i, item := range decoderTests {
  639. c.Logf("test %d: %q", i, item.data)
  640. var values []interface{}
  641. dec := yaml.NewDecoder(strings.NewReader(item.data))
  642. for {
  643. var value interface{}
  644. err := dec.Decode(&value)
  645. if err == io.EOF {
  646. break
  647. }
  648. c.Assert(err, IsNil)
  649. values = append(values, value)
  650. }
  651. c.Assert(values, DeepEquals, item.values)
  652. }
  653. }
  654. type errReader struct{}
  655. func (errReader) Read([]byte) (int, error) {
  656. return 0, errors.New("some read error")
  657. }
  658. func (s *S) TestDecoderReadError(c *C) {
  659. err := yaml.NewDecoder(errReader{}).Decode(&struct{}{})
  660. c.Assert(err, ErrorMatches, `yaml: input error: some read error`)
  661. }
  662. func (s *S) TestUnmarshalNaN(c *C) {
  663. value := map[string]interface{}{}
  664. err := yaml.Unmarshal([]byte("notanum: .NaN"), &value)
  665. c.Assert(err, IsNil)
  666. c.Assert(math.IsNaN(value["notanum"].(float64)), Equals, true)
  667. }
  668. var unmarshalErrorTests = []struct {
  669. data, error string
  670. }{
  671. {"v: !!float 'error'", "yaml: cannot decode !!str `error` as a !!float"},
  672. {"v: [A,", "yaml: line 1: did not find expected node content"},
  673. {"v:\n- [A,", "yaml: line 2: did not find expected node content"},
  674. {"a: *b\n", "yaml: unknown anchor 'b' referenced"},
  675. {"a: &a\n b: *a\n", "yaml: anchor 'a' value contains itself"},
  676. {"value: -", "yaml: block sequence entries are not allowed in this context"},
  677. {"a: !!binary ==", "yaml: !!binary value contains invalid base64 data"},
  678. {"{[.]}", `yaml: invalid map key: \[\]interface \{\}\{"\."\}`},
  679. {"{{.}}", `yaml: invalid map key: map\[interface\ \{\}\]interface \{\}\{".":interface \{\}\(nil\)\}`},
  680. {"b: *a\na: &a {c: 1}", `yaml: unknown anchor 'a' referenced`},
  681. {"%TAG !%79! tag:yaml.org,2002:\n---\nv: !%79!int '1'", "yaml: did not find expected whitespace"},
  682. }
  683. func (s *S) TestUnmarshalErrors(c *C) {
  684. for i, item := range unmarshalErrorTests {
  685. c.Logf("test %d: %q", i, item.data)
  686. var value interface{}
  687. err := yaml.Unmarshal([]byte(item.data), &value)
  688. c.Assert(err, ErrorMatches, item.error, Commentf("Partial unmarshal: %#v", value))
  689. }
  690. }
  691. func (s *S) TestDecoderErrors(c *C) {
  692. for _, item := range unmarshalErrorTests {
  693. var value interface{}
  694. err := yaml.NewDecoder(strings.NewReader(item.data)).Decode(&value)
  695. c.Assert(err, ErrorMatches, item.error, Commentf("Partial unmarshal: %#v", value))
  696. }
  697. }
  698. var unmarshalerTests = []struct {
  699. data, tag string
  700. value interface{}
  701. }{
  702. {"_: {hi: there}", "!!map", map[interface{}]interface{}{"hi": "there"}},
  703. {"_: [1,A]", "!!seq", []interface{}{1, "A"}},
  704. {"_: 10", "!!int", 10},
  705. {"_: null", "!!null", nil},
  706. {`_: BAR!`, "!!str", "BAR!"},
  707. {`_: "BAR!"`, "!!str", "BAR!"},
  708. {"_: !!foo 'BAR!'", "!!foo", "BAR!"},
  709. {`_: ""`, "!!str", ""},
  710. }
  711. var unmarshalerResult = map[int]error{}
  712. type unmarshalerType struct {
  713. value interface{}
  714. }
  715. func (o *unmarshalerType) UnmarshalYAML(unmarshal func(v interface{}) error) error {
  716. if err := unmarshal(&o.value); err != nil {
  717. return err
  718. }
  719. if i, ok := o.value.(int); ok {
  720. if result, ok := unmarshalerResult[i]; ok {
  721. return result
  722. }
  723. }
  724. return nil
  725. }
  726. type unmarshalerPointer struct {
  727. Field *unmarshalerType "_"
  728. }
  729. type unmarshalerValue struct {
  730. Field unmarshalerType "_"
  731. }
  732. func (s *S) TestUnmarshalerPointerField(c *C) {
  733. for _, item := range unmarshalerTests {
  734. obj := &unmarshalerPointer{}
  735. err := yaml.Unmarshal([]byte(item.data), obj)
  736. c.Assert(err, IsNil)
  737. if item.value == nil {
  738. c.Assert(obj.Field, IsNil)
  739. } else {
  740. c.Assert(obj.Field, NotNil, Commentf("Pointer not initialized (%#v)", item.value))
  741. c.Assert(obj.Field.value, DeepEquals, item.value)
  742. }
  743. }
  744. }
  745. func (s *S) TestUnmarshalerValueField(c *C) {
  746. for _, item := range unmarshalerTests {
  747. obj := &unmarshalerValue{}
  748. err := yaml.Unmarshal([]byte(item.data), obj)
  749. c.Assert(err, IsNil)
  750. c.Assert(obj.Field, NotNil, Commentf("Pointer not initialized (%#v)", item.value))
  751. c.Assert(obj.Field.value, DeepEquals, item.value)
  752. }
  753. }
  754. func (s *S) TestUnmarshalerWholeDocument(c *C) {
  755. obj := &unmarshalerType{}
  756. err := yaml.Unmarshal([]byte(unmarshalerTests[0].data), obj)
  757. c.Assert(err, IsNil)
  758. value, ok := obj.value.(map[interface{}]interface{})
  759. c.Assert(ok, Equals, true, Commentf("value: %#v", obj.value))
  760. c.Assert(value["_"], DeepEquals, unmarshalerTests[0].value)
  761. }
  762. func (s *S) TestUnmarshalerTypeError(c *C) {
  763. unmarshalerResult[2] = &yaml.TypeError{[]string{"foo"}}
  764. unmarshalerResult[4] = &yaml.TypeError{[]string{"bar"}}
  765. defer func() {
  766. delete(unmarshalerResult, 2)
  767. delete(unmarshalerResult, 4)
  768. }()
  769. type T struct {
  770. Before int
  771. After int
  772. M map[string]*unmarshalerType
  773. }
  774. var v T
  775. data := `{before: A, m: {abc: 1, def: 2, ghi: 3, jkl: 4}, after: B}`
  776. err := yaml.Unmarshal([]byte(data), &v)
  777. c.Assert(err, ErrorMatches, ""+
  778. "yaml: unmarshal errors:\n"+
  779. " line 1: cannot unmarshal !!str `A` into int\n"+
  780. " foo\n"+
  781. " bar\n"+
  782. " line 1: cannot unmarshal !!str `B` into int")
  783. c.Assert(v.M["abc"], NotNil)
  784. c.Assert(v.M["def"], IsNil)
  785. c.Assert(v.M["ghi"], NotNil)
  786. c.Assert(v.M["jkl"], IsNil)
  787. c.Assert(v.M["abc"].value, Equals, 1)
  788. c.Assert(v.M["ghi"].value, Equals, 3)
  789. }
  790. type proxyTypeError struct{}
  791. func (v *proxyTypeError) UnmarshalYAML(unmarshal func(interface{}) error) error {
  792. var s string
  793. var a int32
  794. var b int64
  795. if err := unmarshal(&s); err != nil {
  796. panic(err)
  797. }
  798. if s == "a" {
  799. if err := unmarshal(&b); err == nil {
  800. panic("should have failed")
  801. }
  802. return unmarshal(&a)
  803. }
  804. if err := unmarshal(&a); err == nil {
  805. panic("should have failed")
  806. }
  807. return unmarshal(&b)
  808. }
  809. func (s *S) TestUnmarshalerTypeErrorProxying(c *C) {
  810. type T struct {
  811. Before int
  812. After int
  813. M map[string]*proxyTypeError
  814. }
  815. var v T
  816. data := `{before: A, m: {abc: a, def: b}, after: B}`
  817. err := yaml.Unmarshal([]byte(data), &v)
  818. c.Assert(err, ErrorMatches, ""+
  819. "yaml: unmarshal errors:\n"+
  820. " line 1: cannot unmarshal !!str `A` into int\n"+
  821. " line 1: cannot unmarshal !!str `a` into int32\n"+
  822. " line 1: cannot unmarshal !!str `b` into int64\n"+
  823. " line 1: cannot unmarshal !!str `B` into int")
  824. }
  825. type failingUnmarshaler struct{}
  826. var failingErr = errors.New("failingErr")
  827. func (ft *failingUnmarshaler) UnmarshalYAML(unmarshal func(interface{}) error) error {
  828. return failingErr
  829. }
  830. func (s *S) TestUnmarshalerError(c *C) {
  831. err := yaml.Unmarshal([]byte("a: b"), &failingUnmarshaler{})
  832. c.Assert(err, Equals, failingErr)
  833. }
  834. type sliceUnmarshaler []int
  835. func (su *sliceUnmarshaler) UnmarshalYAML(unmarshal func(interface{}) error) error {
  836. var slice []int
  837. err := unmarshal(&slice)
  838. if err == nil {
  839. *su = slice
  840. return nil
  841. }
  842. var intVal int
  843. err = unmarshal(&intVal)
  844. if err == nil {
  845. *su = []int{intVal}
  846. return nil
  847. }
  848. return err
  849. }
  850. func (s *S) TestUnmarshalerRetry(c *C) {
  851. var su sliceUnmarshaler
  852. err := yaml.Unmarshal([]byte("[1, 2, 3]"), &su)
  853. c.Assert(err, IsNil)
  854. c.Assert(su, DeepEquals, sliceUnmarshaler([]int{1, 2, 3}))
  855. err = yaml.Unmarshal([]byte("1"), &su)
  856. c.Assert(err, IsNil)
  857. c.Assert(su, DeepEquals, sliceUnmarshaler([]int{1}))
  858. }
  859. // From http://yaml.org/type/merge.html
  860. var mergeTests = `
  861. anchors:
  862. list:
  863. - &CENTER { "x": 1, "y": 2 }
  864. - &LEFT { "x": 0, "y": 2 }
  865. - &BIG { "r": 10 }
  866. - &SMALL { "r": 1 }
  867. # All the following maps are equal:
  868. plain:
  869. # Explicit keys
  870. "x": 1
  871. "y": 2
  872. "r": 10
  873. label: center/big
  874. mergeOne:
  875. # Merge one map
  876. << : *CENTER
  877. "r": 10
  878. label: center/big
  879. mergeMultiple:
  880. # Merge multiple maps
  881. << : [ *CENTER, *BIG ]
  882. label: center/big
  883. override:
  884. # Override
  885. << : [ *BIG, *LEFT, *SMALL ]
  886. "x": 1
  887. label: center/big
  888. shortTag:
  889. # Explicit short merge tag
  890. !!merge "<<" : [ *CENTER, *BIG ]
  891. label: center/big
  892. longTag:
  893. # Explicit merge long tag
  894. !<tag:yaml.org,2002:merge> "<<" : [ *CENTER, *BIG ]
  895. label: center/big
  896. inlineMap:
  897. # Inlined map
  898. << : {"x": 1, "y": 2, "r": 10}
  899. label: center/big
  900. inlineSequenceMap:
  901. # Inlined map in sequence
  902. << : [ *CENTER, {"r": 10} ]
  903. label: center/big
  904. `
  905. func (s *S) TestMerge(c *C) {
  906. var want = map[interface{}]interface{}{
  907. "x": 1,
  908. "y": 2,
  909. "r": 10,
  910. "label": "center/big",
  911. }
  912. var m map[interface{}]interface{}
  913. err := yaml.Unmarshal([]byte(mergeTests), &m)
  914. c.Assert(err, IsNil)
  915. for name, test := range m {
  916. if name == "anchors" {
  917. continue
  918. }
  919. c.Assert(test, DeepEquals, want, Commentf("test %q failed", name))
  920. }
  921. }
  922. func (s *S) TestMergeStruct(c *C) {
  923. type Data struct {
  924. X, Y, R int
  925. Label string
  926. }
  927. want := Data{1, 2, 10, "center/big"}
  928. var m map[string]Data
  929. err := yaml.Unmarshal([]byte(mergeTests), &m)
  930. c.Assert(err, IsNil)
  931. for name, test := range m {
  932. if name == "anchors" {
  933. continue
  934. }
  935. c.Assert(test, Equals, want, Commentf("test %q failed", name))
  936. }
  937. }
  938. var unmarshalNullTests = []func() interface{}{
  939. func() interface{} { var v interface{}; v = "v"; return &v },
  940. func() interface{} { var s = "s"; return &s },
  941. func() interface{} { var s = "s"; sptr := &s; return &sptr },
  942. func() interface{} { var i = 1; return &i },
  943. func() interface{} { var i = 1; iptr := &i; return &iptr },
  944. func() interface{} { m := map[string]int{"s": 1}; return &m },
  945. func() interface{} { m := map[string]int{"s": 1}; return m },
  946. }
  947. func (s *S) TestUnmarshalNull(c *C) {
  948. for _, test := range unmarshalNullTests {
  949. item := test()
  950. zero := reflect.Zero(reflect.TypeOf(item).Elem()).Interface()
  951. err := yaml.Unmarshal([]byte("null"), item)
  952. c.Assert(err, IsNil)
  953. if reflect.TypeOf(item).Kind() == reflect.Map {
  954. c.Assert(reflect.ValueOf(item).Interface(), DeepEquals, reflect.MakeMap(reflect.TypeOf(item)).Interface())
  955. } else {
  956. c.Assert(reflect.ValueOf(item).Elem().Interface(), DeepEquals, zero)
  957. }
  958. }
  959. }
  960. func (s *S) TestUnmarshalSliceOnPreset(c *C) {
  961. // Issue #48.
  962. v := struct{ A []int }{[]int{1}}
  963. yaml.Unmarshal([]byte("a: [2]"), &v)
  964. c.Assert(v.A, DeepEquals, []int{2})
  965. }
  966. func (s *S) TestUnmarshalStrict(c *C) {
  967. v := struct{ A, B int }{}
  968. err := yaml.UnmarshalStrict([]byte("a: 1\nb: 2"), &v)
  969. c.Check(err, IsNil)
  970. err = yaml.Unmarshal([]byte("a: 1\nb: 2\nc: 3"), &v)
  971. c.Check(err, IsNil)
  972. err = yaml.UnmarshalStrict([]byte("a: 1\nb: 2\nc: 3"), &v)
  973. c.Check(err, ErrorMatches, "yaml: unmarshal errors:\n line 3: field c not found in struct struct { A int; B int }")
  974. }
  975. //var data []byte
  976. //func init() {
  977. // var err error
  978. // data, err = ioutil.ReadFile("/tmp/file.yaml")
  979. // if err != nil {
  980. // panic(err)
  981. // }
  982. //}
  983. //
  984. //func (s *S) BenchmarkUnmarshal(c *C) {
  985. // var err error
  986. // for i := 0; i < c.N; i++ {
  987. // var v map[string]interface{}
  988. // err = yaml.Unmarshal(data, &v)
  989. // }
  990. // if err != nil {
  991. // panic(err)
  992. // }
  993. //}
  994. //
  995. //func (s *S) BenchmarkMarshal(c *C) {
  996. // var v map[string]interface{}
  997. // yaml.Unmarshal(data, &v)
  998. // c.ResetTimer()
  999. // for i := 0; i < c.N; i++ {
  1000. // yaml.Marshal(&v)
  1001. // }
  1002. //}