decode_test.go 35 KB

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