decode_test.go 24 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111
  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. // Single document with garbage following it.
  576. {
  577. "---\nhello\n...\n}not yaml",
  578. "hello",
  579. },
  580. }
  581. type M map[interface{}]interface{}
  582. type inlineB struct {
  583. B int
  584. inlineC `yaml:",inline"`
  585. }
  586. type inlineC struct {
  587. C int
  588. }
  589. func (s *S) TestUnmarshal(c *C) {
  590. for i, item := range unmarshalTests {
  591. c.Logf("test %d: %q", i, item.data)
  592. t := reflect.ValueOf(item.value).Type()
  593. value := reflect.New(t)
  594. err := yaml.Unmarshal([]byte(item.data), value.Interface())
  595. if _, ok := err.(*yaml.TypeError); !ok {
  596. c.Assert(err, IsNil)
  597. }
  598. c.Assert(value.Elem().Interface(), DeepEquals, item.value)
  599. }
  600. }
  601. func (s *S) TestDecoderSingleDocument(c *C) {
  602. // Test that Decoder.Decode works as expected on
  603. // all the unmarshal tests.
  604. for i, item := range unmarshalTests {
  605. c.Logf("test %d: %q", i, item.data)
  606. if item.data == "" {
  607. // Behaviour differs when there's no YAML.
  608. continue
  609. }
  610. t := reflect.ValueOf(item.value).Type()
  611. value := reflect.New(t)
  612. err := yaml.NewDecoder(strings.NewReader(item.data)).Decode(value.Interface())
  613. if _, ok := err.(*yaml.TypeError); !ok {
  614. c.Assert(err, IsNil)
  615. }
  616. c.Assert(value.Elem().Interface(), DeepEquals, item.value)
  617. }
  618. }
  619. var decoderTests = []struct {
  620. data string
  621. values []interface{}
  622. }{{
  623. "",
  624. nil,
  625. }, {
  626. "a: b",
  627. []interface{}{
  628. map[interface{}]interface{}{"a": "b"},
  629. },
  630. }, {
  631. "---\na: b\n...\n",
  632. []interface{}{
  633. map[interface{}]interface{}{"a": "b"},
  634. },
  635. }, {
  636. "---\n'hello'\n...\n---\ngoodbye\n...\n",
  637. []interface{}{
  638. "hello",
  639. "goodbye",
  640. },
  641. }}
  642. func (s *S) TestDecoder(c *C) {
  643. for i, item := range decoderTests {
  644. c.Logf("test %d: %q", i, item.data)
  645. var values []interface{}
  646. dec := yaml.NewDecoder(strings.NewReader(item.data))
  647. for {
  648. var value interface{}
  649. err := dec.Decode(&value)
  650. if err == io.EOF {
  651. break
  652. }
  653. c.Assert(err, IsNil)
  654. values = append(values, value)
  655. }
  656. c.Assert(values, DeepEquals, item.values)
  657. }
  658. }
  659. type errReader struct{}
  660. func (errReader) Read([]byte) (int, error) {
  661. return 0, errors.New("some read error")
  662. }
  663. func (s *S) TestDecoderReadError(c *C) {
  664. err := yaml.NewDecoder(errReader{}).Decode(&struct{}{})
  665. c.Assert(err, ErrorMatches, `yaml: input error: some read error`)
  666. }
  667. func (s *S) TestUnmarshalNaN(c *C) {
  668. value := map[string]interface{}{}
  669. err := yaml.Unmarshal([]byte("notanum: .NaN"), &value)
  670. c.Assert(err, IsNil)
  671. c.Assert(math.IsNaN(value["notanum"].(float64)), Equals, true)
  672. }
  673. var unmarshalErrorTests = []struct {
  674. data, error string
  675. }{
  676. {"v: !!float 'error'", "yaml: cannot decode !!str `error` as a !!float"},
  677. {"v: [A,", "yaml: line 1: did not find expected node content"},
  678. {"v:\n- [A,", "yaml: line 2: did not find expected node content"},
  679. {"a: *b\n", "yaml: unknown anchor 'b' referenced"},
  680. {"a: &a\n b: *a\n", "yaml: anchor 'a' value contains itself"},
  681. {"value: -", "yaml: block sequence entries are not allowed in this context"},
  682. {"a: !!binary ==", "yaml: !!binary value contains invalid base64 data"},
  683. {"{[.]}", `yaml: invalid map key: \[\]interface \{\}\{"\."\}`},
  684. {"{{.}}", `yaml: invalid map key: map\[interface\ \{\}\]interface \{\}\{".":interface \{\}\(nil\)\}`},
  685. {"b: *a\na: &a {c: 1}", `yaml: unknown anchor 'a' referenced`},
  686. {"%TAG !%79! tag:yaml.org,2002:\n---\nv: !%79!int '1'", "yaml: did not find expected whitespace"},
  687. }
  688. func (s *S) TestUnmarshalErrors(c *C) {
  689. for i, item := range unmarshalErrorTests {
  690. c.Logf("test %d: %q", i, item.data)
  691. var value interface{}
  692. err := yaml.Unmarshal([]byte(item.data), &value)
  693. c.Assert(err, ErrorMatches, item.error, Commentf("Partial unmarshal: %#v", value))
  694. }
  695. }
  696. func (s *S) TestDecoderErrors(c *C) {
  697. for _, item := range unmarshalErrorTests {
  698. var value interface{}
  699. err := yaml.NewDecoder(strings.NewReader(item.data)).Decode(&value)
  700. c.Assert(err, ErrorMatches, item.error, Commentf("Partial unmarshal: %#v", value))
  701. }
  702. }
  703. var unmarshalerTests = []struct {
  704. data, tag string
  705. value interface{}
  706. }{
  707. {"_: {hi: there}", "!!map", map[interface{}]interface{}{"hi": "there"}},
  708. {"_: [1,A]", "!!seq", []interface{}{1, "A"}},
  709. {"_: 10", "!!int", 10},
  710. {"_: null", "!!null", nil},
  711. {`_: BAR!`, "!!str", "BAR!"},
  712. {`_: "BAR!"`, "!!str", "BAR!"},
  713. {"_: !!foo 'BAR!'", "!!foo", "BAR!"},
  714. {`_: ""`, "!!str", ""},
  715. }
  716. var unmarshalerResult = map[int]error{}
  717. type unmarshalerType struct {
  718. value interface{}
  719. }
  720. func (o *unmarshalerType) UnmarshalYAML(unmarshal func(v interface{}) error) error {
  721. if err := unmarshal(&o.value); err != nil {
  722. return err
  723. }
  724. if i, ok := o.value.(int); ok {
  725. if result, ok := unmarshalerResult[i]; ok {
  726. return result
  727. }
  728. }
  729. return nil
  730. }
  731. type unmarshalerPointer struct {
  732. Field *unmarshalerType "_"
  733. }
  734. type unmarshalerValue struct {
  735. Field unmarshalerType "_"
  736. }
  737. func (s *S) TestUnmarshalerPointerField(c *C) {
  738. for _, item := range unmarshalerTests {
  739. obj := &unmarshalerPointer{}
  740. err := yaml.Unmarshal([]byte(item.data), obj)
  741. c.Assert(err, IsNil)
  742. if item.value == nil {
  743. c.Assert(obj.Field, IsNil)
  744. } else {
  745. c.Assert(obj.Field, NotNil, Commentf("Pointer not initialized (%#v)", item.value))
  746. c.Assert(obj.Field.value, DeepEquals, item.value)
  747. }
  748. }
  749. }
  750. func (s *S) TestUnmarshalerValueField(c *C) {
  751. for _, item := range unmarshalerTests {
  752. obj := &unmarshalerValue{}
  753. err := yaml.Unmarshal([]byte(item.data), obj)
  754. c.Assert(err, IsNil)
  755. c.Assert(obj.Field, NotNil, Commentf("Pointer not initialized (%#v)", item.value))
  756. c.Assert(obj.Field.value, DeepEquals, item.value)
  757. }
  758. }
  759. func (s *S) TestUnmarshalerWholeDocument(c *C) {
  760. obj := &unmarshalerType{}
  761. err := yaml.Unmarshal([]byte(unmarshalerTests[0].data), obj)
  762. c.Assert(err, IsNil)
  763. value, ok := obj.value.(map[interface{}]interface{})
  764. c.Assert(ok, Equals, true, Commentf("value: %#v", obj.value))
  765. c.Assert(value["_"], DeepEquals, unmarshalerTests[0].value)
  766. }
  767. func (s *S) TestUnmarshalerTypeError(c *C) {
  768. unmarshalerResult[2] = &yaml.TypeError{[]string{"foo"}}
  769. unmarshalerResult[4] = &yaml.TypeError{[]string{"bar"}}
  770. defer func() {
  771. delete(unmarshalerResult, 2)
  772. delete(unmarshalerResult, 4)
  773. }()
  774. type T struct {
  775. Before int
  776. After int
  777. M map[string]*unmarshalerType
  778. }
  779. var v T
  780. data := `{before: A, m: {abc: 1, def: 2, ghi: 3, jkl: 4}, after: B}`
  781. err := yaml.Unmarshal([]byte(data), &v)
  782. c.Assert(err, ErrorMatches, ""+
  783. "yaml: unmarshal errors:\n"+
  784. " line 1: cannot unmarshal !!str `A` into int\n"+
  785. " foo\n"+
  786. " bar\n"+
  787. " line 1: cannot unmarshal !!str `B` into int")
  788. c.Assert(v.M["abc"], NotNil)
  789. c.Assert(v.M["def"], IsNil)
  790. c.Assert(v.M["ghi"], NotNil)
  791. c.Assert(v.M["jkl"], IsNil)
  792. c.Assert(v.M["abc"].value, Equals, 1)
  793. c.Assert(v.M["ghi"].value, Equals, 3)
  794. }
  795. type proxyTypeError struct{}
  796. func (v *proxyTypeError) UnmarshalYAML(unmarshal func(interface{}) error) error {
  797. var s string
  798. var a int32
  799. var b int64
  800. if err := unmarshal(&s); err != nil {
  801. panic(err)
  802. }
  803. if s == "a" {
  804. if err := unmarshal(&b); err == nil {
  805. panic("should have failed")
  806. }
  807. return unmarshal(&a)
  808. }
  809. if err := unmarshal(&a); err == nil {
  810. panic("should have failed")
  811. }
  812. return unmarshal(&b)
  813. }
  814. func (s *S) TestUnmarshalerTypeErrorProxying(c *C) {
  815. type T struct {
  816. Before int
  817. After int
  818. M map[string]*proxyTypeError
  819. }
  820. var v T
  821. data := `{before: A, m: {abc: a, def: b}, after: B}`
  822. err := yaml.Unmarshal([]byte(data), &v)
  823. c.Assert(err, ErrorMatches, ""+
  824. "yaml: unmarshal errors:\n"+
  825. " line 1: cannot unmarshal !!str `A` into int\n"+
  826. " line 1: cannot unmarshal !!str `a` into int32\n"+
  827. " line 1: cannot unmarshal !!str `b` into int64\n"+
  828. " line 1: cannot unmarshal !!str `B` into int")
  829. }
  830. type failingUnmarshaler struct{}
  831. var failingErr = errors.New("failingErr")
  832. func (ft *failingUnmarshaler) UnmarshalYAML(unmarshal func(interface{}) error) error {
  833. return failingErr
  834. }
  835. func (s *S) TestUnmarshalerError(c *C) {
  836. err := yaml.Unmarshal([]byte("a: b"), &failingUnmarshaler{})
  837. c.Assert(err, Equals, failingErr)
  838. }
  839. type sliceUnmarshaler []int
  840. func (su *sliceUnmarshaler) UnmarshalYAML(unmarshal func(interface{}) error) error {
  841. var slice []int
  842. err := unmarshal(&slice)
  843. if err == nil {
  844. *su = slice
  845. return nil
  846. }
  847. var intVal int
  848. err = unmarshal(&intVal)
  849. if err == nil {
  850. *su = []int{intVal}
  851. return nil
  852. }
  853. return err
  854. }
  855. func (s *S) TestUnmarshalerRetry(c *C) {
  856. var su sliceUnmarshaler
  857. err := yaml.Unmarshal([]byte("[1, 2, 3]"), &su)
  858. c.Assert(err, IsNil)
  859. c.Assert(su, DeepEquals, sliceUnmarshaler([]int{1, 2, 3}))
  860. err = yaml.Unmarshal([]byte("1"), &su)
  861. c.Assert(err, IsNil)
  862. c.Assert(su, DeepEquals, sliceUnmarshaler([]int{1}))
  863. }
  864. // From http://yaml.org/type/merge.html
  865. var mergeTests = `
  866. anchors:
  867. list:
  868. - &CENTER { "x": 1, "y": 2 }
  869. - &LEFT { "x": 0, "y": 2 }
  870. - &BIG { "r": 10 }
  871. - &SMALL { "r": 1 }
  872. # All the following maps are equal:
  873. plain:
  874. # Explicit keys
  875. "x": 1
  876. "y": 2
  877. "r": 10
  878. label: center/big
  879. mergeOne:
  880. # Merge one map
  881. << : *CENTER
  882. "r": 10
  883. label: center/big
  884. mergeMultiple:
  885. # Merge multiple maps
  886. << : [ *CENTER, *BIG ]
  887. label: center/big
  888. override:
  889. # Override
  890. << : [ *BIG, *LEFT, *SMALL ]
  891. "x": 1
  892. label: center/big
  893. shortTag:
  894. # Explicit short merge tag
  895. !!merge "<<" : [ *CENTER, *BIG ]
  896. label: center/big
  897. longTag:
  898. # Explicit merge long tag
  899. !<tag:yaml.org,2002:merge> "<<" : [ *CENTER, *BIG ]
  900. label: center/big
  901. inlineMap:
  902. # Inlined map
  903. << : {"x": 1, "y": 2, "r": 10}
  904. label: center/big
  905. inlineSequenceMap:
  906. # Inlined map in sequence
  907. << : [ *CENTER, {"r": 10} ]
  908. label: center/big
  909. `
  910. func (s *S) TestMerge(c *C) {
  911. var want = map[interface{}]interface{}{
  912. "x": 1,
  913. "y": 2,
  914. "r": 10,
  915. "label": "center/big",
  916. }
  917. var m map[interface{}]interface{}
  918. err := yaml.Unmarshal([]byte(mergeTests), &m)
  919. c.Assert(err, IsNil)
  920. for name, test := range m {
  921. if name == "anchors" {
  922. continue
  923. }
  924. c.Assert(test, DeepEquals, want, Commentf("test %q failed", name))
  925. }
  926. }
  927. func (s *S) TestMergeStruct(c *C) {
  928. type Data struct {
  929. X, Y, R int
  930. Label string
  931. }
  932. want := Data{1, 2, 10, "center/big"}
  933. var m map[string]Data
  934. err := yaml.Unmarshal([]byte(mergeTests), &m)
  935. c.Assert(err, IsNil)
  936. for name, test := range m {
  937. if name == "anchors" {
  938. continue
  939. }
  940. c.Assert(test, Equals, want, Commentf("test %q failed", name))
  941. }
  942. }
  943. var unmarshalNullTests = []func() interface{}{
  944. func() interface{} { var v interface{}; v = "v"; return &v },
  945. func() interface{} { var s = "s"; return &s },
  946. func() interface{} { var s = "s"; sptr := &s; return &sptr },
  947. func() interface{} { var i = 1; return &i },
  948. func() interface{} { var i = 1; iptr := &i; return &iptr },
  949. func() interface{} { m := map[string]int{"s": 1}; return &m },
  950. func() interface{} { m := map[string]int{"s": 1}; return m },
  951. }
  952. func (s *S) TestUnmarshalNull(c *C) {
  953. for _, test := range unmarshalNullTests {
  954. item := test()
  955. zero := reflect.Zero(reflect.TypeOf(item).Elem()).Interface()
  956. err := yaml.Unmarshal([]byte("null"), item)
  957. c.Assert(err, IsNil)
  958. if reflect.TypeOf(item).Kind() == reflect.Map {
  959. c.Assert(reflect.ValueOf(item).Interface(), DeepEquals, reflect.MakeMap(reflect.TypeOf(item)).Interface())
  960. } else {
  961. c.Assert(reflect.ValueOf(item).Elem().Interface(), DeepEquals, zero)
  962. }
  963. }
  964. }
  965. func (s *S) TestUnmarshalSliceOnPreset(c *C) {
  966. // Issue #48.
  967. v := struct{ A []int }{[]int{1}}
  968. yaml.Unmarshal([]byte("a: [2]"), &v)
  969. c.Assert(v.A, DeepEquals, []int{2})
  970. }
  971. func (s *S) TestUnmarshalStrict(c *C) {
  972. v := struct{ A, B int }{}
  973. err := yaml.UnmarshalStrict([]byte("a: 1\nb: 2"), &v)
  974. c.Check(err, IsNil)
  975. err = yaml.Unmarshal([]byte("a: 1\nb: 2\nc: 3"), &v)
  976. c.Check(err, IsNil)
  977. err = yaml.UnmarshalStrict([]byte("a: 1\nb: 2\nc: 3"), &v)
  978. c.Check(err, ErrorMatches, "yaml: unmarshal errors:\n line 3: field c not found in struct struct { A int; B int }")
  979. }
  980. //var data []byte
  981. //func init() {
  982. // var err error
  983. // data, err = ioutil.ReadFile("/tmp/file.yaml")
  984. // if err != nil {
  985. // panic(err)
  986. // }
  987. //}
  988. //
  989. //func (s *S) BenchmarkUnmarshal(c *C) {
  990. // var err error
  991. // for i := 0; i < c.N; i++ {
  992. // var v map[string]interface{}
  993. // err = yaml.Unmarshal(data, &v)
  994. // }
  995. // if err != nil {
  996. // panic(err)
  997. // }
  998. //}
  999. //
  1000. //func (s *S) BenchmarkMarshal(c *C) {
  1001. // var v map[string]interface{}
  1002. // yaml.Unmarshal(data, &v)
  1003. // c.ResetTimer()
  1004. // for i := 0; i < c.N; i++ {
  1005. // yaml.Marshal(&v)
  1006. // }
  1007. //}