decode_test.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461
  1. //
  2. // Copyright (c) 2011-2019 Canonical Ltd
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. package yaml_test
  16. import (
  17. "bytes"
  18. "errors"
  19. "io"
  20. "math"
  21. "reflect"
  22. "strings"
  23. "time"
  24. . "gopkg.in/check.v1"
  25. "gopkg.in/yaml.v3"
  26. )
  27. var unmarshalIntTest = 123
  28. var unmarshalTests = []struct {
  29. data string
  30. value interface{}
  31. }{
  32. {
  33. "",
  34. (*struct{})(nil),
  35. },
  36. {
  37. "{}", &struct{}{},
  38. }, {
  39. "v: hi",
  40. map[string]string{"v": "hi"},
  41. }, {
  42. "v: hi", map[string]interface{}{"v": "hi"},
  43. }, {
  44. "v: true",
  45. map[string]string{"v": "true"},
  46. }, {
  47. "v: true",
  48. map[string]interface{}{"v": true},
  49. }, {
  50. "v: 10",
  51. map[string]interface{}{"v": 10},
  52. }, {
  53. "v: 0b10",
  54. map[string]interface{}{"v": 2},
  55. }, {
  56. "v: 0xA",
  57. map[string]interface{}{"v": 10},
  58. }, {
  59. "v: 4294967296",
  60. map[string]int64{"v": 4294967296},
  61. }, {
  62. "v: 0.1",
  63. map[string]interface{}{"v": 0.1},
  64. }, {
  65. "v: .1",
  66. map[string]interface{}{"v": 0.1},
  67. }, {
  68. "v: .Inf",
  69. map[string]interface{}{"v": math.Inf(+1)},
  70. }, {
  71. "v: -.Inf",
  72. map[string]interface{}{"v": math.Inf(-1)},
  73. }, {
  74. "v: -10",
  75. map[string]interface{}{"v": -10},
  76. }, {
  77. "v: -.1",
  78. map[string]interface{}{"v": -0.1},
  79. },
  80. // Simple values.
  81. {
  82. "123",
  83. &unmarshalIntTest,
  84. },
  85. // Floats from spec
  86. {
  87. "canonical: 6.8523e+5",
  88. map[string]interface{}{"canonical": 6.8523e+5},
  89. }, {
  90. "expo: 685.230_15e+03",
  91. map[string]interface{}{"expo": 685.23015e+03},
  92. }, {
  93. "fixed: 685_230.15",
  94. map[string]interface{}{"fixed": 685230.15},
  95. }, {
  96. "neginf: -.inf",
  97. map[string]interface{}{"neginf": math.Inf(-1)},
  98. }, {
  99. "fixed: 685_230.15",
  100. map[string]float64{"fixed": 685230.15},
  101. },
  102. //{"sexa: 190:20:30.15", map[string]interface{}{"sexa": 0}}, // Unsupported
  103. //{"notanum: .NaN", map[string]interface{}{"notanum": math.NaN()}}, // Equality of NaN fails.
  104. // Bools are per 1.2 spec.
  105. {
  106. "canonical: true",
  107. map[string]interface{}{"canonical": true},
  108. },
  109. // For backwards compatibility with 1.1, decoding old strings into typed values still works.
  110. {
  111. "option: on",
  112. map[string]bool{"option": true},
  113. }, {
  114. "option: y",
  115. map[string]bool{"option": true},
  116. }, {
  117. "option: Off",
  118. map[string]bool{"option": false},
  119. }, {
  120. "option: No",
  121. map[string]bool{"option": false},
  122. }, {
  123. "option: other",
  124. map[string]bool{},
  125. },
  126. // Ints from spec
  127. {
  128. "canonical: 685230",
  129. map[string]interface{}{"canonical": 685230},
  130. }, {
  131. "decimal: +685_230",
  132. map[string]interface{}{"decimal": 685230},
  133. }, {
  134. "octal: 02472256",
  135. map[string]interface{}{"octal": 685230},
  136. }, {
  137. "octal: -02472256",
  138. map[string]interface{}{"octal": -685230},
  139. }, {
  140. "octal: 0o2472256",
  141. map[string]interface{}{"octal": 685230},
  142. }, {
  143. "octal: -0o2472256",
  144. map[string]interface{}{"octal": -685230},
  145. }, {
  146. "hexa: 0x_0A_74_AE",
  147. map[string]interface{}{"hexa": 685230},
  148. }, {
  149. "bin: 0b1010_0111_0100_1010_1110",
  150. map[string]interface{}{"bin": 685230},
  151. }, {
  152. "bin: -0b101010",
  153. map[string]interface{}{"bin": -42},
  154. }, {
  155. "bin: -0b1000000000000000000000000000000000000000000000000000000000000000",
  156. map[string]interface{}{"bin": -9223372036854775808},
  157. }, {
  158. "decimal: +685_230",
  159. map[string]int{"decimal": 685230},
  160. },
  161. //{"sexa: 190:20:30", map[string]interface{}{"sexa": 0}}, // Unsupported
  162. // Nulls from spec
  163. {
  164. "empty:",
  165. map[string]interface{}{"empty": nil},
  166. }, {
  167. "canonical: ~",
  168. map[string]interface{}{"canonical": nil},
  169. }, {
  170. "english: null",
  171. map[string]interface{}{"english": nil},
  172. }, {
  173. "~: null key",
  174. map[interface{}]string{nil: "null key"},
  175. }, {
  176. "empty:",
  177. map[string]*bool{"empty": nil},
  178. },
  179. // Flow sequence
  180. {
  181. "seq: [A,B]",
  182. map[string]interface{}{"seq": []interface{}{"A", "B"}},
  183. }, {
  184. "seq: [A,B,C,]",
  185. map[string][]string{"seq": []string{"A", "B", "C"}},
  186. }, {
  187. "seq: [A,1,C]",
  188. map[string][]string{"seq": []string{"A", "1", "C"}},
  189. }, {
  190. "seq: [A,1,C]",
  191. map[string][]int{"seq": []int{1}},
  192. }, {
  193. "seq: [A,1,C]",
  194. map[string]interface{}{"seq": []interface{}{"A", 1, "C"}},
  195. },
  196. // Block sequence
  197. {
  198. "seq:\n - A\n - B",
  199. map[string]interface{}{"seq": []interface{}{"A", "B"}},
  200. }, {
  201. "seq:\n - A\n - B\n - C",
  202. map[string][]string{"seq": []string{"A", "B", "C"}},
  203. }, {
  204. "seq:\n - A\n - 1\n - C",
  205. map[string][]string{"seq": []string{"A", "1", "C"}},
  206. }, {
  207. "seq:\n - A\n - 1\n - C",
  208. map[string][]int{"seq": []int{1}},
  209. }, {
  210. "seq:\n - A\n - 1\n - C",
  211. map[string]interface{}{"seq": []interface{}{"A", 1, "C"}},
  212. },
  213. // Literal block scalar
  214. {
  215. "scalar: | # Comment\n\n literal\n\n \ttext\n\n",
  216. map[string]string{"scalar": "\nliteral\n\n\ttext\n"},
  217. },
  218. // Folded block scalar
  219. {
  220. "scalar: > # Comment\n\n folded\n line\n \n next\n line\n * one\n * two\n\n last\n line\n\n",
  221. map[string]string{"scalar": "\nfolded line\nnext line\n * one\n * two\n\nlast line\n"},
  222. },
  223. // Map inside interface with no type hints.
  224. {
  225. "a: {b: c}",
  226. map[interface{}]interface{}{"a": map[string]interface{}{"b": "c"}},
  227. },
  228. // Non-string map inside interface with no type hints.
  229. {
  230. "a: {b: c, 1: d}",
  231. map[interface{}]interface{}{"a": map[interface{}]interface{}{"b": "c", 1: "d"}},
  232. },
  233. // Structs and type conversions.
  234. {
  235. "hello: world",
  236. &struct{ Hello string }{"world"},
  237. }, {
  238. "a: {b: c}",
  239. &struct{ A struct{ B string } }{struct{ B string }{"c"}},
  240. }, {
  241. "a: {b: c}",
  242. &struct{ A *struct{ B string } }{&struct{ B string }{"c"}},
  243. }, {
  244. "a: 'null'",
  245. &struct{ A *unmarshalerType }{&unmarshalerType{"null"}},
  246. }, {
  247. "a: {b: c}",
  248. &struct{ A map[string]string }{map[string]string{"b": "c"}},
  249. }, {
  250. "a: {b: c}",
  251. &struct{ A *map[string]string }{&map[string]string{"b": "c"}},
  252. }, {
  253. "a:",
  254. &struct{ A map[string]string }{},
  255. }, {
  256. "a: 1",
  257. &struct{ A int }{1},
  258. }, {
  259. "a: 1",
  260. &struct{ A float64 }{1},
  261. }, {
  262. "a: 1.0",
  263. &struct{ A int }{1},
  264. }, {
  265. "a: 1.0",
  266. &struct{ A uint }{1},
  267. }, {
  268. "a: [1, 2]",
  269. &struct{ A []int }{[]int{1, 2}},
  270. }, {
  271. "a: [1, 2]",
  272. &struct{ A [2]int }{[2]int{1, 2}},
  273. }, {
  274. "a: 1",
  275. &struct{ B int }{0},
  276. }, {
  277. "a: 1",
  278. &struct {
  279. B int "a"
  280. }{1},
  281. }, {
  282. // Some limited backwards compatibility with the 1.1 spec.
  283. "a: YES",
  284. &struct{ A bool }{true},
  285. },
  286. // Some cross type conversions
  287. {
  288. "v: 42",
  289. map[string]uint{"v": 42},
  290. }, {
  291. "v: -42",
  292. map[string]uint{},
  293. }, {
  294. "v: 4294967296",
  295. map[string]uint64{"v": 4294967296},
  296. }, {
  297. "v: -4294967296",
  298. map[string]uint64{},
  299. },
  300. // int
  301. {
  302. "int_max: 2147483647",
  303. map[string]int{"int_max": math.MaxInt32},
  304. },
  305. {
  306. "int_min: -2147483648",
  307. map[string]int{"int_min": math.MinInt32},
  308. },
  309. {
  310. "int_overflow: 9223372036854775808", // math.MaxInt64 + 1
  311. map[string]int{},
  312. },
  313. // int64
  314. {
  315. "int64_max: 9223372036854775807",
  316. map[string]int64{"int64_max": math.MaxInt64},
  317. },
  318. {
  319. "int64_max_base2: 0b111111111111111111111111111111111111111111111111111111111111111",
  320. map[string]int64{"int64_max_base2": math.MaxInt64},
  321. },
  322. {
  323. "int64_min: -9223372036854775808",
  324. map[string]int64{"int64_min": math.MinInt64},
  325. },
  326. {
  327. "int64_neg_base2: -0b111111111111111111111111111111111111111111111111111111111111111",
  328. map[string]int64{"int64_neg_base2": -math.MaxInt64},
  329. },
  330. {
  331. "int64_overflow: 9223372036854775808", // math.MaxInt64 + 1
  332. map[string]int64{},
  333. },
  334. // uint
  335. {
  336. "uint_min: 0",
  337. map[string]uint{"uint_min": 0},
  338. },
  339. {
  340. "uint_max: 4294967295",
  341. map[string]uint{"uint_max": math.MaxUint32},
  342. },
  343. {
  344. "uint_underflow: -1",
  345. map[string]uint{},
  346. },
  347. // uint64
  348. {
  349. "uint64_min: 0",
  350. map[string]uint{"uint64_min": 0},
  351. },
  352. {
  353. "uint64_max: 18446744073709551615",
  354. map[string]uint64{"uint64_max": math.MaxUint64},
  355. },
  356. {
  357. "uint64_max_base2: 0b1111111111111111111111111111111111111111111111111111111111111111",
  358. map[string]uint64{"uint64_max_base2": math.MaxUint64},
  359. },
  360. {
  361. "uint64_maxint64: 9223372036854775807",
  362. map[string]uint64{"uint64_maxint64": math.MaxInt64},
  363. },
  364. {
  365. "uint64_underflow: -1",
  366. map[string]uint64{},
  367. },
  368. // float32
  369. {
  370. "float32_max: 3.40282346638528859811704183484516925440e+38",
  371. map[string]float32{"float32_max": math.MaxFloat32},
  372. },
  373. {
  374. "float32_nonzero: 1.401298464324817070923729583289916131280e-45",
  375. map[string]float32{"float32_nonzero": math.SmallestNonzeroFloat32},
  376. },
  377. {
  378. "float32_maxuint64: 18446744073709551615",
  379. map[string]float32{"float32_maxuint64": float32(math.MaxUint64)},
  380. },
  381. {
  382. "float32_maxuint64+1: 18446744073709551616",
  383. map[string]float32{"float32_maxuint64+1": float32(math.MaxUint64 + 1)},
  384. },
  385. // float64
  386. {
  387. "float64_max: 1.797693134862315708145274237317043567981e+308",
  388. map[string]float64{"float64_max": math.MaxFloat64},
  389. },
  390. {
  391. "float64_nonzero: 4.940656458412465441765687928682213723651e-324",
  392. map[string]float64{"float64_nonzero": math.SmallestNonzeroFloat64},
  393. },
  394. {
  395. "float64_maxuint64: 18446744073709551615",
  396. map[string]float64{"float64_maxuint64": float64(math.MaxUint64)},
  397. },
  398. {
  399. "float64_maxuint64+1: 18446744073709551616",
  400. map[string]float64{"float64_maxuint64+1": float64(math.MaxUint64 + 1)},
  401. },
  402. // Overflow cases.
  403. {
  404. "v: 4294967297",
  405. map[string]int32{},
  406. }, {
  407. "v: 128",
  408. map[string]int8{},
  409. },
  410. // Quoted values.
  411. {
  412. "'1': '\"2\"'",
  413. map[interface{}]interface{}{"1": "\"2\""},
  414. }, {
  415. "v:\n- A\n- 'B\n\n C'\n",
  416. map[string][]string{"v": []string{"A", "B\nC"}},
  417. },
  418. // Explicit tags.
  419. {
  420. "v: !!float '1.1'",
  421. map[string]interface{}{"v": 1.1},
  422. }, {
  423. "v: !!float 0",
  424. map[string]interface{}{"v": float64(0)},
  425. }, {
  426. "v: !!float -1",
  427. map[string]interface{}{"v": float64(-1)},
  428. }, {
  429. "v: !!null ''",
  430. map[string]interface{}{"v": nil},
  431. }, {
  432. "%TAG !y! tag:yaml.org,2002:\n---\nv: !y!int '1'",
  433. map[string]interface{}{"v": 1},
  434. },
  435. // Non-specific tag (Issue #75)
  436. {
  437. "v: ! test",
  438. map[string]interface{}{"v": "test"},
  439. },
  440. // Anchors and aliases.
  441. {
  442. "a: &x 1\nb: &y 2\nc: *x\nd: *y\n",
  443. &struct{ A, B, C, D int }{1, 2, 1, 2},
  444. }, {
  445. "a: &a {c: 1}\nb: *a",
  446. &struct {
  447. A, B struct {
  448. C int
  449. }
  450. }{struct{ C int }{1}, struct{ C int }{1}},
  451. }, {
  452. "a: &a [1, 2]\nb: *a",
  453. &struct{ B []int }{[]int{1, 2}},
  454. },
  455. // Bug #1133337
  456. {
  457. "foo: ''",
  458. map[string]*string{"foo": new(string)},
  459. }, {
  460. "foo: null",
  461. map[string]*string{"foo": nil},
  462. }, {
  463. "foo: null",
  464. map[string]string{"foo": ""},
  465. }, {
  466. "foo: null",
  467. map[string]interface{}{"foo": nil},
  468. },
  469. // Support for ~
  470. {
  471. "foo: ~",
  472. map[string]*string{"foo": nil},
  473. }, {
  474. "foo: ~",
  475. map[string]string{"foo": ""},
  476. }, {
  477. "foo: ~",
  478. map[string]interface{}{"foo": nil},
  479. },
  480. // Ignored field
  481. {
  482. "a: 1\nb: 2\n",
  483. &struct {
  484. A int
  485. B int "-"
  486. }{1, 0},
  487. },
  488. // Bug #1191981
  489. {
  490. "" +
  491. "%YAML 1.1\n" +
  492. "--- !!str\n" +
  493. `"Generic line break (no glyph)\n\` + "\n" +
  494. ` Generic line break (glyphed)\n\` + "\n" +
  495. ` Line separator\u2028\` + "\n" +
  496. ` Paragraph separator\u2029"` + "\n",
  497. "" +
  498. "Generic line break (no glyph)\n" +
  499. "Generic line break (glyphed)\n" +
  500. "Line separator\u2028Paragraph separator\u2029",
  501. },
  502. // Struct inlining
  503. {
  504. "a: 1\nb: 2\nc: 3\n",
  505. &struct {
  506. A int
  507. C inlineB `yaml:",inline"`
  508. }{1, inlineB{2, inlineC{3}}},
  509. },
  510. // Struct inlining as a pointer.
  511. {
  512. "a: 1\nb: 2\nc: 3\n",
  513. &struct {
  514. A int
  515. C *inlineB `yaml:",inline"`
  516. }{1, &inlineB{2, inlineC{3}}},
  517. }, {
  518. "a: 1\n",
  519. &struct {
  520. A int
  521. C *inlineB `yaml:",inline"`
  522. }{1, nil},
  523. }, {
  524. "a: 1\nc: 3\nd: 4\n",
  525. &struct {
  526. A int
  527. C *inlineD `yaml:",inline"`
  528. }{1, &inlineD{&inlineC{3}, 4}},
  529. },
  530. // Map inlining
  531. {
  532. "a: 1\nb: 2\nc: 3\n",
  533. &struct {
  534. A int
  535. C map[string]int `yaml:",inline"`
  536. }{1, map[string]int{"b": 2, "c": 3}},
  537. },
  538. // bug 1243827
  539. {
  540. "a: -b_c",
  541. map[string]interface{}{"a": "-b_c"},
  542. },
  543. {
  544. "a: +b_c",
  545. map[string]interface{}{"a": "+b_c"},
  546. },
  547. {
  548. "a: 50cent_of_dollar",
  549. map[string]interface{}{"a": "50cent_of_dollar"},
  550. },
  551. // issue #295 (allow scalars with colons in flow mappings and sequences)
  552. {
  553. "a: {b: https://github.com/go-yaml/yaml}",
  554. map[string]interface{}{"a": map[string]interface{}{
  555. "b": "https://github.com/go-yaml/yaml",
  556. }},
  557. },
  558. {
  559. "a: [https://github.com/go-yaml/yaml]",
  560. map[string]interface{}{"a": []interface{}{"https://github.com/go-yaml/yaml"}},
  561. },
  562. // Duration
  563. {
  564. "a: 3s",
  565. map[string]time.Duration{"a": 3 * time.Second},
  566. },
  567. // Issue #24.
  568. {
  569. "a: <foo>",
  570. map[string]string{"a": "<foo>"},
  571. },
  572. // Base 60 floats are obsolete and unsupported.
  573. {
  574. "a: 1:1\n",
  575. map[string]string{"a": "1:1"},
  576. },
  577. // Binary data.
  578. {
  579. "a: !!binary gIGC\n",
  580. map[string]string{"a": "\x80\x81\x82"},
  581. }, {
  582. "a: !!binary |\n " + strings.Repeat("kJCQ", 17) + "kJ\n CQ\n",
  583. map[string]string{"a": strings.Repeat("\x90", 54)},
  584. }, {
  585. "a: !!binary |\n " + strings.Repeat("A", 70) + "\n ==\n",
  586. map[string]string{"a": strings.Repeat("\x00", 52)},
  587. },
  588. // Issue #39.
  589. {
  590. "a:\n b:\n c: d\n",
  591. map[string]struct{ B interface{} }{"a": {map[string]interface{}{"c": "d"}}},
  592. },
  593. // Custom map type.
  594. {
  595. "a: {b: c}",
  596. M{"a": M{"b": "c"}},
  597. },
  598. // Support encoding.TextUnmarshaler.
  599. {
  600. "a: 1.2.3.4\n",
  601. map[string]textUnmarshaler{"a": textUnmarshaler{S: "1.2.3.4"}},
  602. },
  603. {
  604. "a: 2015-02-24T18:19:39Z\n",
  605. map[string]textUnmarshaler{"a": textUnmarshaler{"2015-02-24T18:19:39Z"}},
  606. },
  607. // Timestamps
  608. {
  609. // Date only.
  610. "a: 2015-01-01\n",
  611. map[string]time.Time{"a": time.Date(2015, 1, 1, 0, 0, 0, 0, time.UTC)},
  612. },
  613. {
  614. // RFC3339
  615. "a: 2015-02-24T18:19:39.12Z\n",
  616. map[string]time.Time{"a": time.Date(2015, 2, 24, 18, 19, 39, .12e9, time.UTC)},
  617. },
  618. {
  619. // RFC3339 with short dates.
  620. "a: 2015-2-3T3:4:5Z",
  621. map[string]time.Time{"a": time.Date(2015, 2, 3, 3, 4, 5, 0, time.UTC)},
  622. },
  623. {
  624. // ISO8601 lower case t
  625. "a: 2015-02-24t18:19:39Z\n",
  626. map[string]time.Time{"a": time.Date(2015, 2, 24, 18, 19, 39, 0, time.UTC)},
  627. },
  628. {
  629. // space separate, no time zone
  630. "a: 2015-02-24 18:19:39\n",
  631. map[string]time.Time{"a": time.Date(2015, 2, 24, 18, 19, 39, 0, time.UTC)},
  632. },
  633. // Some cases not currently handled. Uncomment these when
  634. // the code is fixed.
  635. // {
  636. // // space separated with time zone
  637. // "a: 2001-12-14 21:59:43.10 -5",
  638. // map[string]interface{}{"a": time.Date(2001, 12, 14, 21, 59, 43, .1e9, time.UTC)},
  639. // },
  640. // {
  641. // // arbitrary whitespace between fields
  642. // "a: 2001-12-14 \t\t \t21:59:43.10 \t Z",
  643. // map[string]interface{}{"a": time.Date(2001, 12, 14, 21, 59, 43, .1e9, time.UTC)},
  644. // },
  645. {
  646. // explicit string tag
  647. "a: !!str 2015-01-01",
  648. map[string]interface{}{"a": "2015-01-01"},
  649. },
  650. {
  651. // explicit timestamp tag on quoted string
  652. "a: !!timestamp \"2015-01-01\"",
  653. map[string]time.Time{"a": time.Date(2015, 1, 1, 0, 0, 0, 0, time.UTC)},
  654. },
  655. {
  656. // explicit timestamp tag on unquoted string
  657. "a: !!timestamp 2015-01-01",
  658. map[string]time.Time{"a": time.Date(2015, 1, 1, 0, 0, 0, 0, time.UTC)},
  659. },
  660. {
  661. // quoted string that's a valid timestamp
  662. "a: \"2015-01-01\"",
  663. map[string]interface{}{"a": "2015-01-01"},
  664. },
  665. {
  666. // explicit timestamp tag into interface.
  667. "a: !!timestamp \"2015-01-01\"",
  668. map[string]interface{}{"a": time.Date(2015, 1, 1, 0, 0, 0, 0, time.UTC)},
  669. },
  670. {
  671. // implicit timestamp tag into interface.
  672. "a: 2015-01-01",
  673. map[string]interface{}{"a": time.Date(2015, 1, 1, 0, 0, 0, 0, time.UTC)},
  674. },
  675. // Encode empty lists as zero-length slices.
  676. {
  677. "a: []",
  678. &struct{ A []int }{[]int{}},
  679. },
  680. // UTF-16-LE
  681. {
  682. "\xff\xfe\xf1\x00o\x00\xf1\x00o\x00:\x00 \x00v\x00e\x00r\x00y\x00 \x00y\x00e\x00s\x00\n\x00",
  683. M{"ñoño": "very yes"},
  684. },
  685. // UTF-16-LE with surrogate.
  686. {
  687. "\xff\xfe\xf1\x00o\x00\xf1\x00o\x00:\x00 \x00v\x00e\x00r\x00y\x00 \x00y\x00e\x00s\x00 \x00=\xd8\xd4\xdf\n\x00",
  688. M{"ñoño": "very yes 🟔"},
  689. },
  690. // UTF-16-BE
  691. {
  692. "\xfe\xff\x00\xf1\x00o\x00\xf1\x00o\x00:\x00 \x00v\x00e\x00r\x00y\x00 \x00y\x00e\x00s\x00\n",
  693. M{"ñoño": "very yes"},
  694. },
  695. // UTF-16-BE with surrogate.
  696. {
  697. "\xfe\xff\x00\xf1\x00o\x00\xf1\x00o\x00:\x00 \x00v\x00e\x00r\x00y\x00 \x00y\x00e\x00s\x00 \xd8=\xdf\xd4\x00\n",
  698. M{"ñoño": "very yes 🟔"},
  699. },
  700. // This *is* in fact a float number, per the spec. #171 was a mistake.
  701. {
  702. "a: 123456e1\n",
  703. M{"a": 123456e1},
  704. }, {
  705. "a: 123456E1\n",
  706. M{"a": 123456E1},
  707. },
  708. // yaml-test-suite 3GZX: Spec Example 7.1. Alias Nodes
  709. {
  710. "First occurrence: &anchor Foo\nSecond occurrence: *anchor\nOverride anchor: &anchor Bar\nReuse anchor: *anchor\n",
  711. map[string]interface{}{
  712. "First occurrence": "Foo",
  713. "Second occurrence": "Foo",
  714. "Override anchor": "Bar",
  715. "Reuse anchor": "Bar",
  716. },
  717. },
  718. // Single document with garbage following it.
  719. {
  720. "---\nhello\n...\n}not yaml",
  721. "hello",
  722. },
  723. }
  724. type M map[string]interface{}
  725. type inlineB struct {
  726. B int
  727. inlineC `yaml:",inline"`
  728. }
  729. type inlineC struct {
  730. C int
  731. }
  732. type inlineD struct {
  733. C *inlineC `yaml:",inline"`
  734. D int
  735. }
  736. func (s *S) TestUnmarshal(c *C) {
  737. for i, item := range unmarshalTests {
  738. c.Logf("test %d: %q", i, item.data)
  739. t := reflect.ValueOf(item.value).Type()
  740. value := reflect.New(t)
  741. err := yaml.Unmarshal([]byte(item.data), value.Interface())
  742. if _, ok := err.(*yaml.TypeError); !ok {
  743. c.Assert(err, IsNil)
  744. }
  745. c.Assert(value.Elem().Interface(), DeepEquals, item.value, Commentf("error: %v", err))
  746. }
  747. }
  748. func (s *S) TestUnmarshalFullTimestamp(c *C) {
  749. // Full timestamp in same format as encoded. This is confirmed to be
  750. // properly decoded by Python as a timestamp as well.
  751. var str = "2015-02-24T18:19:39.123456789-03:00"
  752. var t interface{}
  753. err := yaml.Unmarshal([]byte(str), &t)
  754. c.Assert(err, IsNil)
  755. c.Assert(t, Equals, time.Date(2015, 2, 24, 18, 19, 39, 123456789, t.(time.Time).Location()))
  756. c.Assert(t.(time.Time).In(time.UTC), Equals, time.Date(2015, 2, 24, 21, 19, 39, 123456789, time.UTC))
  757. }
  758. func (s *S) TestDecoderSingleDocument(c *C) {
  759. // Test that Decoder.Decode works as expected on
  760. // all the unmarshal tests.
  761. for i, item := range unmarshalTests {
  762. c.Logf("test %d: %q", i, item.data)
  763. if item.data == "" {
  764. // Behaviour differs when there's no YAML.
  765. continue
  766. }
  767. t := reflect.ValueOf(item.value).Type()
  768. value := reflect.New(t)
  769. err := yaml.NewDecoder(strings.NewReader(item.data)).Decode(value.Interface())
  770. if _, ok := err.(*yaml.TypeError); !ok {
  771. c.Assert(err, IsNil)
  772. }
  773. c.Assert(value.Elem().Interface(), DeepEquals, item.value)
  774. }
  775. }
  776. var decoderTests = []struct {
  777. data string
  778. values []interface{}
  779. }{{
  780. "",
  781. nil,
  782. }, {
  783. "a: b",
  784. []interface{}{
  785. map[string]interface{}{"a": "b"},
  786. },
  787. }, {
  788. "---\na: b\n...\n",
  789. []interface{}{
  790. map[string]interface{}{"a": "b"},
  791. },
  792. }, {
  793. "---\n'hello'\n...\n---\ngoodbye\n...\n",
  794. []interface{}{
  795. "hello",
  796. "goodbye",
  797. },
  798. }}
  799. func (s *S) TestDecoder(c *C) {
  800. for i, item := range decoderTests {
  801. c.Logf("test %d: %q", i, item.data)
  802. var values []interface{}
  803. dec := yaml.NewDecoder(strings.NewReader(item.data))
  804. for {
  805. var value interface{}
  806. err := dec.Decode(&value)
  807. if err == io.EOF {
  808. break
  809. }
  810. c.Assert(err, IsNil)
  811. values = append(values, value)
  812. }
  813. c.Assert(values, DeepEquals, item.values)
  814. }
  815. }
  816. type errReader struct{}
  817. func (errReader) Read([]byte) (int, error) {
  818. return 0, errors.New("some read error")
  819. }
  820. func (s *S) TestDecoderReadError(c *C) {
  821. err := yaml.NewDecoder(errReader{}).Decode(&struct{}{})
  822. c.Assert(err, ErrorMatches, `yaml: input error: some read error`)
  823. }
  824. func (s *S) TestUnmarshalNaN(c *C) {
  825. value := map[string]interface{}{}
  826. err := yaml.Unmarshal([]byte("notanum: .NaN"), &value)
  827. c.Assert(err, IsNil)
  828. c.Assert(math.IsNaN(value["notanum"].(float64)), Equals, true)
  829. }
  830. func (s *S) TestUnmarshalDurationInt(c *C) {
  831. // Don't accept plain ints as durations as it's unclear (issue #200).
  832. var d time.Duration
  833. err := yaml.Unmarshal([]byte("123"), &d)
  834. c.Assert(err, ErrorMatches, "(?s).* line 1: cannot unmarshal !!int `123` into time.Duration")
  835. }
  836. var unmarshalErrorTests = []struct {
  837. data, error string
  838. }{
  839. {"v: !!float 'error'", "yaml: cannot decode !!str `error` as a !!float"},
  840. {"v: [A,", "yaml: line 1: did not find expected node content"},
  841. {"v:\n- [A,", "yaml: line 2: did not find expected node content"},
  842. {"a:\n- b: *,", "yaml: line 2: did not find expected alphabetic or numeric character"},
  843. {"a: *b\n", "yaml: unknown anchor 'b' referenced"},
  844. {"a: &a\n b: *a\n", "yaml: anchor 'a' value contains itself"},
  845. {"value: -", "yaml: block sequence entries are not allowed in this context"},
  846. {"a: !!binary ==", "yaml: !!binary value contains invalid base64 data"},
  847. {"{[.]}", `yaml: invalid map key: \[\]interface \{\}\{"\."\}`},
  848. {"{{.}}", `yaml: invalid map key: map\[interface\ \{\}\]interface \{\}\{".":interface \{\}\(nil\)\}`},
  849. {"b: *a\na: &a {c: 1}", `yaml: unknown anchor 'a' referenced`},
  850. {"%TAG !%79! tag:yaml.org,2002:\n---\nv: !%79!int '1'", "yaml: did not find expected whitespace"},
  851. }
  852. func (s *S) TestUnmarshalErrors(c *C) {
  853. for i, item := range unmarshalErrorTests {
  854. c.Logf("test %d: %q", i, item.data)
  855. var value interface{}
  856. err := yaml.Unmarshal([]byte(item.data), &value)
  857. c.Assert(err, ErrorMatches, item.error, Commentf("Partial unmarshal: %#v", value))
  858. }
  859. }
  860. func (s *S) TestDecoderErrors(c *C) {
  861. for _, item := range unmarshalErrorTests {
  862. var value interface{}
  863. err := yaml.NewDecoder(strings.NewReader(item.data)).Decode(&value)
  864. c.Assert(err, ErrorMatches, item.error, Commentf("Partial unmarshal: %#v", value))
  865. }
  866. }
  867. var unmarshalerTests = []struct {
  868. data, tag string
  869. value interface{}
  870. }{
  871. {"_: {hi: there}", "!!map", map[string]interface{}{"hi": "there"}},
  872. {"_: [1,A]", "!!seq", []interface{}{1, "A"}},
  873. {"_: 10", "!!int", 10},
  874. {"_: null", "!!null", nil},
  875. {`_: BAR!`, "!!str", "BAR!"},
  876. {`_: "BAR!"`, "!!str", "BAR!"},
  877. {"_: !!foo 'BAR!'", "!!foo", "BAR!"},
  878. {`_: ""`, "!!str", ""},
  879. }
  880. var unmarshalerResult = map[int]error{}
  881. type unmarshalerType struct {
  882. value interface{}
  883. }
  884. func (o *unmarshalerType) UnmarshalYAML(value *yaml.Node) error {
  885. if err := value.Decode(&o.value); err != nil {
  886. return err
  887. }
  888. if i, ok := o.value.(int); ok {
  889. if result, ok := unmarshalerResult[i]; ok {
  890. return result
  891. }
  892. }
  893. return nil
  894. }
  895. type unmarshalerPointer struct {
  896. Field *unmarshalerType "_"
  897. }
  898. type unmarshalerValue struct {
  899. Field unmarshalerType "_"
  900. }
  901. type unmarshalerInlined struct {
  902. Field *unmarshalerType "_"
  903. Inlined unmarshalerType `yaml:",inline"`
  904. }
  905. type unmarshalerInlinedTwice struct {
  906. InlinedTwice unmarshalerInlined `yaml:",inline"`
  907. }
  908. type obsoleteUnmarshalerType struct {
  909. value interface{}
  910. }
  911. func (o *obsoleteUnmarshalerType) UnmarshalYAML(unmarshal func(v interface{}) error) error {
  912. if err := unmarshal(&o.value); err != nil {
  913. return err
  914. }
  915. if i, ok := o.value.(int); ok {
  916. if result, ok := unmarshalerResult[i]; ok {
  917. return result
  918. }
  919. }
  920. return nil
  921. }
  922. type obsoleteUnmarshalerPointer struct {
  923. Field *obsoleteUnmarshalerType "_"
  924. }
  925. type obsoleteUnmarshalerValue struct {
  926. Field obsoleteUnmarshalerType "_"
  927. }
  928. func (s *S) TestUnmarshalerPointerField(c *C) {
  929. for _, item := range unmarshalerTests {
  930. obj := &unmarshalerPointer{}
  931. err := yaml.Unmarshal([]byte(item.data), obj)
  932. c.Assert(err, IsNil)
  933. if item.value == nil {
  934. c.Assert(obj.Field, IsNil)
  935. } else {
  936. c.Assert(obj.Field, NotNil, Commentf("Pointer not initialized (%#v)", item.value))
  937. c.Assert(obj.Field.value, DeepEquals, item.value)
  938. }
  939. }
  940. for _, item := range unmarshalerTests {
  941. obj := &obsoleteUnmarshalerPointer{}
  942. err := yaml.Unmarshal([]byte(item.data), obj)
  943. c.Assert(err, IsNil)
  944. if item.value == nil {
  945. c.Assert(obj.Field, IsNil)
  946. } else {
  947. c.Assert(obj.Field, NotNil, Commentf("Pointer not initialized (%#v)", item.value))
  948. c.Assert(obj.Field.value, DeepEquals, item.value)
  949. }
  950. }
  951. }
  952. func (s *S) TestUnmarshalerValueField(c *C) {
  953. for _, item := range unmarshalerTests {
  954. obj := &obsoleteUnmarshalerValue{}
  955. err := yaml.Unmarshal([]byte(item.data), obj)
  956. c.Assert(err, IsNil)
  957. c.Assert(obj.Field, NotNil, Commentf("Pointer not initialized (%#v)", item.value))
  958. c.Assert(obj.Field.value, DeepEquals, item.value)
  959. }
  960. }
  961. func (s *S) TestUnmarshalerInlinedField(c *C) {
  962. obj := &unmarshalerInlined{}
  963. err := yaml.Unmarshal([]byte("_: a\ninlined: b\n"), obj)
  964. c.Assert(err, IsNil)
  965. c.Assert(obj.Field, DeepEquals, &unmarshalerType{"a"})
  966. c.Assert(obj.Inlined, DeepEquals, unmarshalerType{map[string]interface{}{"_": "a", "inlined": "b"}})
  967. twc := &unmarshalerInlinedTwice{}
  968. err = yaml.Unmarshal([]byte("_: a\ninlined: b\n"), twc)
  969. c.Assert(err, IsNil)
  970. c.Assert(twc.InlinedTwice.Field, DeepEquals, &unmarshalerType{"a"})
  971. c.Assert(twc.InlinedTwice.Inlined, DeepEquals, unmarshalerType{map[string]interface{}{"_": "a", "inlined": "b"}})
  972. }
  973. func (s *S) TestUnmarshalerWholeDocument(c *C) {
  974. obj := &obsoleteUnmarshalerType{}
  975. err := yaml.Unmarshal([]byte(unmarshalerTests[0].data), obj)
  976. c.Assert(err, IsNil)
  977. value, ok := obj.value.(map[interface{}]interface{})
  978. c.Assert(ok, Equals, true, Commentf("value: %#v", obj.value))
  979. c.Assert(value["_"], DeepEquals, unmarshalerTests[0].value)
  980. }
  981. func (s *S) TestUnmarshalerTypeError(c *C) {
  982. unmarshalerResult[2] = &yaml.TypeError{[]string{"foo"}}
  983. unmarshalerResult[4] = &yaml.TypeError{[]string{"bar"}}
  984. defer func() {
  985. delete(unmarshalerResult, 2)
  986. delete(unmarshalerResult, 4)
  987. }()
  988. type T struct {
  989. Before int
  990. After int
  991. M map[string]*obsoleteUnmarshalerType
  992. }
  993. var v T
  994. data := `{before: A, m: {abc: 1, def: 2, ghi: 3, jkl: 4}, after: B}`
  995. err := yaml.Unmarshal([]byte(data), &v)
  996. c.Assert(err, ErrorMatches, ""+
  997. "yaml: unmarshal errors:\n"+
  998. " line 1: cannot unmarshal !!str `A` into int\n"+
  999. " foo\n"+
  1000. " bar\n"+
  1001. " line 1: cannot unmarshal !!str `B` into int")
  1002. c.Assert(v.M["abc"], NotNil)
  1003. c.Assert(v.M["def"], IsNil)
  1004. c.Assert(v.M["ghi"], NotNil)
  1005. c.Assert(v.M["jkl"], IsNil)
  1006. c.Assert(v.M["abc"].value, Equals, 1)
  1007. c.Assert(v.M["ghi"].value, Equals, 3)
  1008. }
  1009. type proxyTypeError struct{}
  1010. func (v *proxyTypeError) UnmarshalYAML(unmarshal func(interface{}) error) error {
  1011. var s string
  1012. var a int32
  1013. var b int64
  1014. if err := unmarshal(&s); err != nil {
  1015. panic(err)
  1016. }
  1017. if s == "a" {
  1018. if err := unmarshal(&b); err == nil {
  1019. panic("should have failed")
  1020. }
  1021. return unmarshal(&a)
  1022. }
  1023. if err := unmarshal(&a); err == nil {
  1024. panic("should have failed")
  1025. }
  1026. return unmarshal(&b)
  1027. }
  1028. func (s *S) TestUnmarshalerTypeErrorProxying(c *C) {
  1029. type T struct {
  1030. Before int
  1031. After int
  1032. M map[string]*proxyTypeError
  1033. }
  1034. var v T
  1035. data := `{before: A, m: {abc: a, def: b}, after: B}`
  1036. err := yaml.Unmarshal([]byte(data), &v)
  1037. c.Assert(err, ErrorMatches, ""+
  1038. "yaml: unmarshal errors:\n"+
  1039. " line 1: cannot unmarshal !!str `A` into int\n"+
  1040. " line 1: cannot unmarshal !!str `a` into int32\n"+
  1041. " line 1: cannot unmarshal !!str `b` into int64\n"+
  1042. " line 1: cannot unmarshal !!str `B` into int")
  1043. }
  1044. type failingUnmarshaler struct{}
  1045. var failingErr = errors.New("failingErr")
  1046. func (ft *failingUnmarshaler) UnmarshalYAML(unmarshal func(interface{}) error) error {
  1047. return failingErr
  1048. }
  1049. func (s *S) TestUnmarshalerError(c *C) {
  1050. err := yaml.Unmarshal([]byte("a: b"), &failingUnmarshaler{})
  1051. c.Assert(err, Equals, failingErr)
  1052. }
  1053. type sliceUnmarshaler []int
  1054. func (su *sliceUnmarshaler) UnmarshalYAML(unmarshal func(interface{}) error) error {
  1055. var slice []int
  1056. err := unmarshal(&slice)
  1057. if err == nil {
  1058. *su = slice
  1059. return nil
  1060. }
  1061. var intVal int
  1062. err = unmarshal(&intVal)
  1063. if err == nil {
  1064. *su = []int{intVal}
  1065. return nil
  1066. }
  1067. return err
  1068. }
  1069. func (s *S) TestUnmarshalerRetry(c *C) {
  1070. var su sliceUnmarshaler
  1071. err := yaml.Unmarshal([]byte("[1, 2, 3]"), &su)
  1072. c.Assert(err, IsNil)
  1073. c.Assert(su, DeepEquals, sliceUnmarshaler([]int{1, 2, 3}))
  1074. err = yaml.Unmarshal([]byte("1"), &su)
  1075. c.Assert(err, IsNil)
  1076. c.Assert(su, DeepEquals, sliceUnmarshaler([]int{1}))
  1077. }
  1078. // From http://yaml.org/type/merge.html
  1079. var mergeTests = `
  1080. anchors:
  1081. list:
  1082. - &CENTER { "x": 1, "y": 2 }
  1083. - &LEFT { "x": 0, "y": 2 }
  1084. - &BIG { "r": 10 }
  1085. - &SMALL { "r": 1 }
  1086. # All the following maps are equal:
  1087. plain:
  1088. # Explicit keys
  1089. "x": 1
  1090. "y": 2
  1091. "r": 10
  1092. label: center/big
  1093. mergeOne:
  1094. # Merge one map
  1095. << : *CENTER
  1096. "r": 10
  1097. label: center/big
  1098. mergeMultiple:
  1099. # Merge multiple maps
  1100. << : [ *CENTER, *BIG ]
  1101. label: center/big
  1102. override:
  1103. # Override
  1104. << : [ *BIG, *LEFT, *SMALL ]
  1105. "x": 1
  1106. label: center/big
  1107. shortTag:
  1108. # Explicit short merge tag
  1109. !!merge "<<" : [ *CENTER, *BIG ]
  1110. label: center/big
  1111. longTag:
  1112. # Explicit merge long tag
  1113. !<tag:yaml.org,2002:merge> "<<" : [ *CENTER, *BIG ]
  1114. label: center/big
  1115. inlineMap:
  1116. # Inlined map
  1117. << : {"x": 1, "y": 2, "r": 10}
  1118. label: center/big
  1119. inlineSequenceMap:
  1120. # Inlined map in sequence
  1121. << : [ *CENTER, {"r": 10} ]
  1122. label: center/big
  1123. `
  1124. func (s *S) TestMerge(c *C) {
  1125. var want = map[interface{}]interface{}{
  1126. "x": 1,
  1127. "y": 2,
  1128. "r": 10,
  1129. "label": "center/big",
  1130. }
  1131. var m map[interface{}]interface{}
  1132. err := yaml.Unmarshal([]byte(mergeTests), &m)
  1133. c.Assert(err, IsNil)
  1134. for name, test := range m {
  1135. if name == "anchors" {
  1136. continue
  1137. }
  1138. c.Assert(test, DeepEquals, want, Commentf("test %q failed", name))
  1139. }
  1140. }
  1141. func (s *S) TestMergeStruct(c *C) {
  1142. type Data struct {
  1143. X, Y, R int
  1144. Label string
  1145. }
  1146. want := Data{1, 2, 10, "center/big"}
  1147. var m map[string]Data
  1148. err := yaml.Unmarshal([]byte(mergeTests), &m)
  1149. c.Assert(err, IsNil)
  1150. for name, test := range m {
  1151. if name == "anchors" {
  1152. continue
  1153. }
  1154. c.Assert(test, Equals, want, Commentf("test %q failed", name))
  1155. }
  1156. }
  1157. var unmarshalNullTests = []func() interface{}{
  1158. func() interface{} { var v interface{}; v = "v"; return &v },
  1159. func() interface{} { var s = "s"; return &s },
  1160. func() interface{} { var s = "s"; sptr := &s; return &sptr },
  1161. func() interface{} { var i = 1; return &i },
  1162. func() interface{} { var i = 1; iptr := &i; return &iptr },
  1163. func() interface{} { m := map[string]int{"s": 1}; return &m },
  1164. func() interface{} { m := map[string]int{"s": 1}; return m },
  1165. }
  1166. func (s *S) TestUnmarshalNull(c *C) {
  1167. for _, test := range unmarshalNullTests {
  1168. item := test()
  1169. zero := reflect.Zero(reflect.TypeOf(item).Elem()).Interface()
  1170. err := yaml.Unmarshal([]byte("null"), item)
  1171. c.Assert(err, IsNil)
  1172. if reflect.TypeOf(item).Kind() == reflect.Map {
  1173. c.Assert(reflect.ValueOf(item).Interface(), DeepEquals, reflect.MakeMap(reflect.TypeOf(item)).Interface())
  1174. } else {
  1175. c.Assert(reflect.ValueOf(item).Elem().Interface(), DeepEquals, zero)
  1176. }
  1177. }
  1178. }
  1179. func (s *S) TestUnmarshalSliceOnPreset(c *C) {
  1180. // Issue #48.
  1181. v := struct{ A []int }{[]int{1}}
  1182. yaml.Unmarshal([]byte("a: [2]"), &v)
  1183. c.Assert(v.A, DeepEquals, []int{2})
  1184. }
  1185. var unmarshalStrictTests = []struct {
  1186. known bool
  1187. unique bool
  1188. data string
  1189. value interface{}
  1190. error string
  1191. }{{
  1192. known: true,
  1193. data: "a: 1\nc: 2\n",
  1194. value: struct{ A, B int }{A: 1},
  1195. error: `yaml: unmarshal errors:\n line 2: field c not found in type struct { A int; B int }`,
  1196. }, {
  1197. unique: true,
  1198. data: "a: 1\nb: 2\na: 3\n",
  1199. value: struct{ A, B int }{A: 3, B: 2},
  1200. error: `yaml: unmarshal errors:\n line 3: mapping key "a" already defined at line 1`,
  1201. }, {
  1202. unique: true,
  1203. data: "c: 3\na: 1\nb: 2\nc: 4\n",
  1204. value: struct {
  1205. A int
  1206. inlineB `yaml:",inline"`
  1207. }{
  1208. A: 1,
  1209. inlineB: inlineB{
  1210. B: 2,
  1211. inlineC: inlineC{
  1212. C: 4,
  1213. },
  1214. },
  1215. },
  1216. error: `yaml: unmarshal errors:\n line 4: mapping key "c" already defined at line 1`,
  1217. }, {
  1218. unique: true,
  1219. data: "c: 0\na: 1\nb: 2\nc: 1\n",
  1220. value: struct {
  1221. A int
  1222. inlineB `yaml:",inline"`
  1223. }{
  1224. A: 1,
  1225. inlineB: inlineB{
  1226. B: 2,
  1227. inlineC: inlineC{
  1228. C: 1,
  1229. },
  1230. },
  1231. },
  1232. error: `yaml: unmarshal errors:\n line 4: mapping key "c" already defined at line 1`,
  1233. }, {
  1234. unique: true,
  1235. data: "c: 1\na: 1\nb: 2\nc: 3\n",
  1236. value: struct {
  1237. A int
  1238. M map[string]interface{} `yaml:",inline"`
  1239. }{
  1240. A: 1,
  1241. M: map[string]interface{}{
  1242. "b": 2,
  1243. "c": 3,
  1244. },
  1245. },
  1246. error: `yaml: unmarshal errors:\n line 4: mapping key "c" already defined at line 1`,
  1247. }, {
  1248. unique: true,
  1249. data: "a: 1\n9: 2\nnull: 3\n9: 4",
  1250. value: map[interface{}]interface{}{
  1251. "a": 1,
  1252. nil: 3,
  1253. 9: 4,
  1254. },
  1255. error: `yaml: unmarshal errors:\n line 4: mapping key "9" already defined at line 2`,
  1256. }}
  1257. func (s *S) TestUnmarshalKnownFields(c *C) {
  1258. for i, item := range unmarshalStrictTests {
  1259. c.Logf("test %d: %q", i, item.data)
  1260. // First test that normal Unmarshal unmarshals to the expected value.
  1261. if !item.unique {
  1262. t := reflect.ValueOf(item.value).Type()
  1263. value := reflect.New(t)
  1264. err := yaml.Unmarshal([]byte(item.data), value.Interface())
  1265. c.Assert(err, Equals, nil)
  1266. c.Assert(value.Elem().Interface(), DeepEquals, item.value)
  1267. }
  1268. // Then test that it fails on the same thing with KnownFields on.
  1269. t := reflect.ValueOf(item.value).Type()
  1270. value := reflect.New(t)
  1271. dec := yaml.NewDecoder(bytes.NewBuffer([]byte(item.data)))
  1272. dec.KnownFields(item.known)
  1273. err := dec.Decode(value.Interface())
  1274. c.Assert(err, ErrorMatches, item.error)
  1275. }
  1276. }
  1277. type textUnmarshaler struct {
  1278. S string
  1279. }
  1280. func (t *textUnmarshaler) UnmarshalText(s []byte) error {
  1281. t.S = string(s)
  1282. return nil
  1283. }
  1284. func (s *S) TestFuzzCrashers(c *C) {
  1285. cases := []string{
  1286. // runtime error: index out of range
  1287. "\"\\0\\\r\n",
  1288. // should not happen
  1289. " 0: [\n] 0",
  1290. "? ? \"\n\" 0",
  1291. " - {\n000}0",
  1292. "0:\n 0: [0\n] 0",
  1293. " - \"\n000\"0",
  1294. " - \"\n000\"\"",
  1295. "0:\n - {\n000}0",
  1296. "0:\n - \"\n000\"0",
  1297. "0:\n - \"\n000\"\"",
  1298. // runtime error: index out of range
  1299. " \ufeff\n",
  1300. "? \ufeff\n",
  1301. "? \ufeff:\n",
  1302. "0: \ufeff\n",
  1303. "? \ufeff: \ufeff\n",
  1304. }
  1305. for _, data := range cases {
  1306. var v interface{}
  1307. _ = yaml.Unmarshal([]byte(data), &v)
  1308. }
  1309. }
  1310. //var data []byte
  1311. //func init() {
  1312. // var err error
  1313. // data, err = ioutil.ReadFile("/tmp/file.yaml")
  1314. // if err != nil {
  1315. // panic(err)
  1316. // }
  1317. //}
  1318. //
  1319. //func (s *S) BenchmarkUnmarshal(c *C) {
  1320. // var err error
  1321. // for i := 0; i < c.N; i++ {
  1322. // var v map[string]interface{}
  1323. // err = yaml.Unmarshal(data, &v)
  1324. // }
  1325. // if err != nil {
  1326. // panic(err)
  1327. // }
  1328. //}
  1329. //
  1330. //func (s *S) BenchmarkMarshal(c *C) {
  1331. // var v map[string]interface{}
  1332. // yaml.Unmarshal(data, &v)
  1333. // c.ResetTimer()
  1334. // for i := 0; i < c.N; i++ {
  1335. // yaml.Marshal(&v)
  1336. // }
  1337. //}