decode_test.go 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505
  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{},
  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{},
  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. // Comment scan exhausting the input buffer (issue #469).
  724. {
  725. "true\n#" + strings.Repeat(" ", 512*3),
  726. "true",
  727. },
  728. {
  729. "true #" + strings.Repeat(" ", 512*3),
  730. "true",
  731. },
  732. }
  733. type M map[string]interface{}
  734. type inlineB struct {
  735. B int
  736. inlineC `yaml:",inline"`
  737. }
  738. type inlineC struct {
  739. C int
  740. }
  741. type inlineD struct {
  742. C *inlineC `yaml:",inline"`
  743. D int
  744. }
  745. func (s *S) TestUnmarshal(c *C) {
  746. for i, item := range unmarshalTests {
  747. c.Logf("test %d: %q", i, item.data)
  748. t := reflect.ValueOf(item.value).Type()
  749. value := reflect.New(t)
  750. err := yaml.Unmarshal([]byte(item.data), value.Interface())
  751. if _, ok := err.(*yaml.TypeError); !ok {
  752. c.Assert(err, IsNil)
  753. }
  754. c.Assert(value.Elem().Interface(), DeepEquals, item.value, Commentf("error: %v", err))
  755. }
  756. }
  757. func (s *S) TestUnmarshalFullTimestamp(c *C) {
  758. // Full timestamp in same format as encoded. This is confirmed to be
  759. // properly decoded by Python as a timestamp as well.
  760. var str = "2015-02-24T18:19:39.123456789-03:00"
  761. var t interface{}
  762. err := yaml.Unmarshal([]byte(str), &t)
  763. c.Assert(err, IsNil)
  764. c.Assert(t, Equals, time.Date(2015, 2, 24, 18, 19, 39, 123456789, t.(time.Time).Location()))
  765. c.Assert(t.(time.Time).In(time.UTC), Equals, time.Date(2015, 2, 24, 21, 19, 39, 123456789, time.UTC))
  766. }
  767. func (s *S) TestDecoderSingleDocument(c *C) {
  768. // Test that Decoder.Decode works as expected on
  769. // all the unmarshal tests.
  770. for i, item := range unmarshalTests {
  771. c.Logf("test %d: %q", i, item.data)
  772. if item.data == "" {
  773. // Behaviour differs when there's no YAML.
  774. continue
  775. }
  776. t := reflect.ValueOf(item.value).Type()
  777. value := reflect.New(t)
  778. err := yaml.NewDecoder(strings.NewReader(item.data)).Decode(value.Interface())
  779. if _, ok := err.(*yaml.TypeError); !ok {
  780. c.Assert(err, IsNil)
  781. }
  782. c.Assert(value.Elem().Interface(), DeepEquals, item.value)
  783. }
  784. }
  785. var decoderTests = []struct {
  786. data string
  787. values []interface{}
  788. }{{
  789. "",
  790. nil,
  791. }, {
  792. "a: b",
  793. []interface{}{
  794. map[string]interface{}{"a": "b"},
  795. },
  796. }, {
  797. "---\na: b\n...\n",
  798. []interface{}{
  799. map[string]interface{}{"a": "b"},
  800. },
  801. }, {
  802. "---\n'hello'\n...\n---\ngoodbye\n...\n",
  803. []interface{}{
  804. "hello",
  805. "goodbye",
  806. },
  807. }}
  808. func (s *S) TestDecoder(c *C) {
  809. for i, item := range decoderTests {
  810. c.Logf("test %d: %q", i, item.data)
  811. var values []interface{}
  812. dec := yaml.NewDecoder(strings.NewReader(item.data))
  813. for {
  814. var value interface{}
  815. err := dec.Decode(&value)
  816. if err == io.EOF {
  817. break
  818. }
  819. c.Assert(err, IsNil)
  820. values = append(values, value)
  821. }
  822. c.Assert(values, DeepEquals, item.values)
  823. }
  824. }
  825. type errReader struct{}
  826. func (errReader) Read([]byte) (int, error) {
  827. return 0, errors.New("some read error")
  828. }
  829. func (s *S) TestDecoderReadError(c *C) {
  830. err := yaml.NewDecoder(errReader{}).Decode(&struct{}{})
  831. c.Assert(err, ErrorMatches, `yaml: input error: some read error`)
  832. }
  833. func (s *S) TestUnmarshalNaN(c *C) {
  834. value := map[string]interface{}{}
  835. err := yaml.Unmarshal([]byte("notanum: .NaN"), &value)
  836. c.Assert(err, IsNil)
  837. c.Assert(math.IsNaN(value["notanum"].(float64)), Equals, true)
  838. }
  839. func (s *S) TestUnmarshalDurationInt(c *C) {
  840. // Don't accept plain ints as durations as it's unclear (issue #200).
  841. var d time.Duration
  842. err := yaml.Unmarshal([]byte("123"), &d)
  843. c.Assert(err, ErrorMatches, "(?s).* line 1: cannot unmarshal !!int `123` into time.Duration")
  844. }
  845. var unmarshalErrorTests = []struct {
  846. data, error string
  847. }{
  848. {"v: !!float 'error'", "yaml: cannot decode !!str `error` as a !!float"},
  849. {"v: [A,", "yaml: line 1: did not find expected node content"},
  850. {"v:\n- [A,", "yaml: line 2: did not find expected node content"},
  851. {"a:\n- b: *,", "yaml: line 2: did not find expected alphabetic or numeric character"},
  852. {"a: *b\n", "yaml: unknown anchor 'b' referenced"},
  853. {"a: &a\n b: *a\n", "yaml: anchor 'a' value contains itself"},
  854. {"value: -", "yaml: block sequence entries are not allowed in this context"},
  855. {"a: !!binary ==", "yaml: !!binary value contains invalid base64 data"},
  856. {"{[.]}", `yaml: invalid map key: \[\]interface \{\}\{"\."\}`},
  857. {"{{.}}", `yaml: invalid map key: map\[interface\ \{\}\]interface \{\}\{".":interface \{\}\(nil\)\}`},
  858. {"b: *a\na: &a {c: 1}", `yaml: unknown anchor 'a' referenced`},
  859. {"%TAG !%79! tag:yaml.org,2002:\n---\nv: !%79!int '1'", "yaml: did not find expected whitespace"},
  860. {
  861. "a: &a [00,00,00,00,00,00,00,00,00]\n" +
  862. "b: &b [*a,*a,*a,*a,*a,*a,*a,*a,*a]\n" +
  863. "c: &c [*b,*b,*b,*b,*b,*b,*b,*b,*b]\n" +
  864. "d: &d [*c,*c,*c,*c,*c,*c,*c,*c,*c]\n" +
  865. "e: &e [*d,*d,*d,*d,*d,*d,*d,*d,*d]\n" +
  866. "f: &f [*e,*e,*e,*e,*e,*e,*e,*e,*e]\n" +
  867. "g: &g [*f,*f,*f,*f,*f,*f,*f,*f,*f]\n" +
  868. "h: &h [*g,*g,*g,*g,*g,*g,*g,*g,*g]\n" +
  869. "i: &i [*h,*h,*h,*h,*h,*h,*h,*h,*h]\n",
  870. "yaml: document contains excessive aliasing",
  871. },
  872. }
  873. func (s *S) TestUnmarshalErrors(c *C) {
  874. for i, item := range unmarshalErrorTests {
  875. c.Logf("test %d: %q", i, item.data)
  876. var value interface{}
  877. err := yaml.Unmarshal([]byte(item.data), &value)
  878. c.Assert(err, ErrorMatches, item.error, Commentf("Partial unmarshal: %#v", value))
  879. }
  880. }
  881. func (s *S) TestDecoderErrors(c *C) {
  882. for _, item := range unmarshalErrorTests {
  883. var value interface{}
  884. err := yaml.NewDecoder(strings.NewReader(item.data)).Decode(&value)
  885. c.Assert(err, ErrorMatches, item.error, Commentf("Partial unmarshal: %#v", value))
  886. }
  887. }
  888. var unmarshalerTests = []struct {
  889. data, tag string
  890. value interface{}
  891. }{
  892. {"_: {hi: there}", "!!map", map[string]interface{}{"hi": "there"}},
  893. {"_: [1,A]", "!!seq", []interface{}{1, "A"}},
  894. {"_: 10", "!!int", 10},
  895. {"_: null", "!!null", nil},
  896. {`_: BAR!`, "!!str", "BAR!"},
  897. {`_: "BAR!"`, "!!str", "BAR!"},
  898. {"_: !!foo 'BAR!'", "!!foo", "BAR!"},
  899. {`_: ""`, "!!str", ""},
  900. }
  901. var unmarshalerResult = map[int]error{}
  902. type unmarshalerType struct {
  903. value interface{}
  904. }
  905. func (o *unmarshalerType) UnmarshalYAML(value *yaml.Node) error {
  906. if err := value.Decode(&o.value); err != nil {
  907. return err
  908. }
  909. if i, ok := o.value.(int); ok {
  910. if result, ok := unmarshalerResult[i]; ok {
  911. return result
  912. }
  913. }
  914. return nil
  915. }
  916. type unmarshalerPointer struct {
  917. Field *unmarshalerType "_"
  918. }
  919. type unmarshalerValue struct {
  920. Field unmarshalerType "_"
  921. }
  922. type unmarshalerInlined struct {
  923. Field *unmarshalerType "_"
  924. Inlined unmarshalerType `yaml:",inline"`
  925. }
  926. type unmarshalerInlinedTwice struct {
  927. InlinedTwice unmarshalerInlined `yaml:",inline"`
  928. }
  929. type obsoleteUnmarshalerType struct {
  930. value interface{}
  931. }
  932. func (o *obsoleteUnmarshalerType) UnmarshalYAML(unmarshal func(v interface{}) error) error {
  933. if err := unmarshal(&o.value); err != nil {
  934. return err
  935. }
  936. if i, ok := o.value.(int); ok {
  937. if result, ok := unmarshalerResult[i]; ok {
  938. return result
  939. }
  940. }
  941. return nil
  942. }
  943. type obsoleteUnmarshalerPointer struct {
  944. Field *obsoleteUnmarshalerType "_"
  945. }
  946. type obsoleteUnmarshalerValue struct {
  947. Field obsoleteUnmarshalerType "_"
  948. }
  949. func (s *S) TestUnmarshalerPointerField(c *C) {
  950. for _, item := range unmarshalerTests {
  951. obj := &unmarshalerPointer{}
  952. err := yaml.Unmarshal([]byte(item.data), obj)
  953. c.Assert(err, IsNil)
  954. if item.value == nil {
  955. c.Assert(obj.Field, IsNil)
  956. } else {
  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. for _, item := range unmarshalerTests {
  962. obj := &obsoleteUnmarshalerPointer{}
  963. err := yaml.Unmarshal([]byte(item.data), obj)
  964. c.Assert(err, IsNil)
  965. if item.value == nil {
  966. c.Assert(obj.Field, IsNil)
  967. } else {
  968. c.Assert(obj.Field, NotNil, Commentf("Pointer not initialized (%#v)", item.value))
  969. c.Assert(obj.Field.value, DeepEquals, item.value)
  970. }
  971. }
  972. }
  973. func (s *S) TestUnmarshalerValueField(c *C) {
  974. for _, item := range unmarshalerTests {
  975. obj := &obsoleteUnmarshalerValue{}
  976. err := yaml.Unmarshal([]byte(item.data), obj)
  977. c.Assert(err, IsNil)
  978. c.Assert(obj.Field, NotNil, Commentf("Pointer not initialized (%#v)", item.value))
  979. c.Assert(obj.Field.value, DeepEquals, item.value)
  980. }
  981. }
  982. func (s *S) TestUnmarshalerInlinedField(c *C) {
  983. obj := &unmarshalerInlined{}
  984. err := yaml.Unmarshal([]byte("_: a\ninlined: b\n"), obj)
  985. c.Assert(err, IsNil)
  986. c.Assert(obj.Field, DeepEquals, &unmarshalerType{"a"})
  987. c.Assert(obj.Inlined, DeepEquals, unmarshalerType{map[string]interface{}{"_": "a", "inlined": "b"}})
  988. twc := &unmarshalerInlinedTwice{}
  989. err = yaml.Unmarshal([]byte("_: a\ninlined: b\n"), twc)
  990. c.Assert(err, IsNil)
  991. c.Assert(twc.InlinedTwice.Field, DeepEquals, &unmarshalerType{"a"})
  992. c.Assert(twc.InlinedTwice.Inlined, DeepEquals, unmarshalerType{map[string]interface{}{"_": "a", "inlined": "b"}})
  993. }
  994. func (s *S) TestUnmarshalerWholeDocument(c *C) {
  995. obj := &obsoleteUnmarshalerType{}
  996. err := yaml.Unmarshal([]byte(unmarshalerTests[0].data), obj)
  997. c.Assert(err, IsNil)
  998. value, ok := obj.value.(map[interface{}]interface{})
  999. c.Assert(ok, Equals, true, Commentf("value: %#v", obj.value))
  1000. c.Assert(value["_"], DeepEquals, unmarshalerTests[0].value)
  1001. }
  1002. func (s *S) TestUnmarshalerTypeError(c *C) {
  1003. unmarshalerResult[2] = &yaml.TypeError{[]string{"foo"}}
  1004. unmarshalerResult[4] = &yaml.TypeError{[]string{"bar"}}
  1005. defer func() {
  1006. delete(unmarshalerResult, 2)
  1007. delete(unmarshalerResult, 4)
  1008. }()
  1009. type T struct {
  1010. Before int
  1011. After int
  1012. M map[string]*obsoleteUnmarshalerType
  1013. }
  1014. var v T
  1015. data := `{before: A, m: {abc: 1, def: 2, ghi: 3, jkl: 4}, after: B}`
  1016. err := yaml.Unmarshal([]byte(data), &v)
  1017. c.Assert(err, ErrorMatches, ""+
  1018. "yaml: unmarshal errors:\n"+
  1019. " line 1: cannot unmarshal !!str `A` into int\n"+
  1020. " foo\n"+
  1021. " bar\n"+
  1022. " line 1: cannot unmarshal !!str `B` into int")
  1023. c.Assert(v.M["abc"], NotNil)
  1024. c.Assert(v.M["def"], IsNil)
  1025. c.Assert(v.M["ghi"], NotNil)
  1026. c.Assert(v.M["jkl"], IsNil)
  1027. c.Assert(v.M["abc"].value, Equals, 1)
  1028. c.Assert(v.M["ghi"].value, Equals, 3)
  1029. }
  1030. type proxyTypeError struct{}
  1031. func (v *proxyTypeError) UnmarshalYAML(unmarshal func(interface{}) error) error {
  1032. var s string
  1033. var a int32
  1034. var b int64
  1035. if err := unmarshal(&s); err != nil {
  1036. panic(err)
  1037. }
  1038. if s == "a" {
  1039. if err := unmarshal(&b); err == nil {
  1040. panic("should have failed")
  1041. }
  1042. return unmarshal(&a)
  1043. }
  1044. if err := unmarshal(&a); err == nil {
  1045. panic("should have failed")
  1046. }
  1047. return unmarshal(&b)
  1048. }
  1049. func (s *S) TestUnmarshalerTypeErrorProxying(c *C) {
  1050. type T struct {
  1051. Before int
  1052. After int
  1053. M map[string]*proxyTypeError
  1054. }
  1055. var v T
  1056. data := `{before: A, m: {abc: a, def: b}, after: B}`
  1057. err := yaml.Unmarshal([]byte(data), &v)
  1058. c.Assert(err, ErrorMatches, ""+
  1059. "yaml: unmarshal errors:\n"+
  1060. " line 1: cannot unmarshal !!str `A` into int\n"+
  1061. " line 1: cannot unmarshal !!str `a` into int32\n"+
  1062. " line 1: cannot unmarshal !!str `b` into int64\n"+
  1063. " line 1: cannot unmarshal !!str `B` into int")
  1064. }
  1065. type failingUnmarshaler struct{}
  1066. var failingErr = errors.New("failingErr")
  1067. func (ft *failingUnmarshaler) UnmarshalYAML(unmarshal func(interface{}) error) error {
  1068. return failingErr
  1069. }
  1070. func (s *S) TestUnmarshalerError(c *C) {
  1071. err := yaml.Unmarshal([]byte("a: b"), &failingUnmarshaler{})
  1072. c.Assert(err, Equals, failingErr)
  1073. }
  1074. type sliceUnmarshaler []int
  1075. func (su *sliceUnmarshaler) UnmarshalYAML(unmarshal func(interface{}) error) error {
  1076. var slice []int
  1077. err := unmarshal(&slice)
  1078. if err == nil {
  1079. *su = slice
  1080. return nil
  1081. }
  1082. var intVal int
  1083. err = unmarshal(&intVal)
  1084. if err == nil {
  1085. *su = []int{intVal}
  1086. return nil
  1087. }
  1088. return err
  1089. }
  1090. func (s *S) TestUnmarshalerRetry(c *C) {
  1091. var su sliceUnmarshaler
  1092. err := yaml.Unmarshal([]byte("[1, 2, 3]"), &su)
  1093. c.Assert(err, IsNil)
  1094. c.Assert(su, DeepEquals, sliceUnmarshaler([]int{1, 2, 3}))
  1095. err = yaml.Unmarshal([]byte("1"), &su)
  1096. c.Assert(err, IsNil)
  1097. c.Assert(su, DeepEquals, sliceUnmarshaler([]int{1}))
  1098. }
  1099. // From http://yaml.org/type/merge.html
  1100. var mergeTests = `
  1101. anchors:
  1102. list:
  1103. - &CENTER { "x": 1, "y": 2 }
  1104. - &LEFT { "x": 0, "y": 2 }
  1105. - &BIG { "r": 10 }
  1106. - &SMALL { "r": 1 }
  1107. # All the following maps are equal:
  1108. plain:
  1109. # Explicit keys
  1110. "x": 1
  1111. "y": 2
  1112. "r": 10
  1113. label: center/big
  1114. mergeOne:
  1115. # Merge one map
  1116. << : *CENTER
  1117. "r": 10
  1118. label: center/big
  1119. mergeMultiple:
  1120. # Merge multiple maps
  1121. << : [ *CENTER, *BIG ]
  1122. label: center/big
  1123. override:
  1124. # Override
  1125. << : [ *BIG, *LEFT, *SMALL ]
  1126. "x": 1
  1127. label: center/big
  1128. shortTag:
  1129. # Explicit short merge tag
  1130. !!merge "<<" : [ *CENTER, *BIG ]
  1131. label: center/big
  1132. longTag:
  1133. # Explicit merge long tag
  1134. !<tag:yaml.org,2002:merge> "<<" : [ *CENTER, *BIG ]
  1135. label: center/big
  1136. inlineMap:
  1137. # Inlined map
  1138. << : {"x": 1, "y": 2, "r": 10}
  1139. label: center/big
  1140. inlineSequenceMap:
  1141. # Inlined map in sequence
  1142. << : [ *CENTER, {"r": 10} ]
  1143. label: center/big
  1144. `
  1145. func (s *S) TestMerge(c *C) {
  1146. var want = map[interface{}]interface{}{
  1147. "x": 1,
  1148. "y": 2,
  1149. "r": 10,
  1150. "label": "center/big",
  1151. }
  1152. var m map[interface{}]interface{}
  1153. err := yaml.Unmarshal([]byte(mergeTests), &m)
  1154. c.Assert(err, IsNil)
  1155. for name, test := range m {
  1156. if name == "anchors" {
  1157. continue
  1158. }
  1159. c.Assert(test, DeepEquals, want, Commentf("test %q failed", name))
  1160. }
  1161. }
  1162. func (s *S) TestMergeStruct(c *C) {
  1163. type Data struct {
  1164. X, Y, R int
  1165. Label string
  1166. }
  1167. want := Data{1, 2, 10, "center/big"}
  1168. var m map[string]Data
  1169. err := yaml.Unmarshal([]byte(mergeTests), &m)
  1170. c.Assert(err, IsNil)
  1171. for name, test := range m {
  1172. if name == "anchors" {
  1173. continue
  1174. }
  1175. c.Assert(test, Equals, want, Commentf("test %q failed", name))
  1176. }
  1177. }
  1178. var unmarshalNullTests = []func() interface{}{
  1179. func() interface{} { var v interface{}; v = "v"; return &v },
  1180. func() interface{} { var s = "s"; return &s },
  1181. func() interface{} { var s = "s"; sptr := &s; return &sptr },
  1182. func() interface{} { var i = 1; return &i },
  1183. func() interface{} { var i = 1; iptr := &i; return &iptr },
  1184. func() interface{} { m := map[string]int{"s": 1}; return &m },
  1185. func() interface{} { m := map[string]int{"s": 1}; return m },
  1186. }
  1187. func (s *S) TestUnmarshalNull(c *C) {
  1188. for _, test := range unmarshalNullTests {
  1189. pristine := test()
  1190. decoded := test()
  1191. zero := reflect.Zero(reflect.TypeOf(decoded).Elem()).Interface()
  1192. err := yaml.Unmarshal([]byte("null"), decoded)
  1193. c.Assert(err, IsNil)
  1194. switch pristine.(type) {
  1195. case *interface{}, **string, **int, *map[string]int:
  1196. c.Assert(reflect.ValueOf(decoded).Elem().Interface(), DeepEquals, zero)
  1197. default:
  1198. c.Assert(reflect.ValueOf(decoded).Interface(), DeepEquals, pristine)
  1199. }
  1200. }
  1201. }
  1202. func (s *S) TestUnmarshalPreservesData(c *C) {
  1203. var v struct {
  1204. A, B int
  1205. C int `yaml:"-"`
  1206. }
  1207. v.A = 42
  1208. v.C = 88
  1209. err := yaml.Unmarshal([]byte("---"), &v)
  1210. c.Assert(err, IsNil)
  1211. c.Assert(v.A, Equals, 42)
  1212. c.Assert(v.B, Equals, 0)
  1213. c.Assert(v.C, Equals, 88)
  1214. err = yaml.Unmarshal([]byte("b: 21\nc: 99"), &v)
  1215. c.Assert(err, IsNil)
  1216. c.Assert(v.A, Equals, 42)
  1217. c.Assert(v.B, Equals, 21)
  1218. c.Assert(v.C, Equals, 88)
  1219. }
  1220. func (s *S) TestUnmarshalSliceOnPreset(c *C) {
  1221. // Issue #48.
  1222. v := struct{ A []int }{[]int{1}}
  1223. yaml.Unmarshal([]byte("a: [2]"), &v)
  1224. c.Assert(v.A, DeepEquals, []int{2})
  1225. }
  1226. var unmarshalStrictTests = []struct {
  1227. known bool
  1228. unique bool
  1229. data string
  1230. value interface{}
  1231. error string
  1232. }{{
  1233. known: true,
  1234. data: "a: 1\nc: 2\n",
  1235. value: struct{ A, B int }{A: 1},
  1236. error: `yaml: unmarshal errors:\n line 2: field c not found in type struct { A int; B int }`,
  1237. }, {
  1238. unique: true,
  1239. data: "a: 1\nb: 2\na: 3\n",
  1240. value: struct{ A, B int }{A: 3, B: 2},
  1241. error: `yaml: unmarshal errors:\n line 3: mapping key "a" already defined at line 1`,
  1242. }, {
  1243. unique: true,
  1244. data: "c: 3\na: 1\nb: 2\nc: 4\n",
  1245. value: struct {
  1246. A int
  1247. inlineB `yaml:",inline"`
  1248. }{
  1249. A: 1,
  1250. inlineB: inlineB{
  1251. B: 2,
  1252. inlineC: inlineC{
  1253. C: 4,
  1254. },
  1255. },
  1256. },
  1257. error: `yaml: unmarshal errors:\n line 4: mapping key "c" already defined at line 1`,
  1258. }, {
  1259. unique: true,
  1260. data: "c: 0\na: 1\nb: 2\nc: 1\n",
  1261. value: struct {
  1262. A int
  1263. inlineB `yaml:",inline"`
  1264. }{
  1265. A: 1,
  1266. inlineB: inlineB{
  1267. B: 2,
  1268. inlineC: inlineC{
  1269. C: 1,
  1270. },
  1271. },
  1272. },
  1273. error: `yaml: unmarshal errors:\n line 4: mapping key "c" already defined at line 1`,
  1274. }, {
  1275. unique: true,
  1276. data: "c: 1\na: 1\nb: 2\nc: 3\n",
  1277. value: struct {
  1278. A int
  1279. M map[string]interface{} `yaml:",inline"`
  1280. }{
  1281. A: 1,
  1282. M: map[string]interface{}{
  1283. "b": 2,
  1284. "c": 3,
  1285. },
  1286. },
  1287. error: `yaml: unmarshal errors:\n line 4: mapping key "c" already defined at line 1`,
  1288. }, {
  1289. unique: true,
  1290. data: "a: 1\n9: 2\nnull: 3\n9: 4",
  1291. value: map[interface{}]interface{}{
  1292. "a": 1,
  1293. nil: 3,
  1294. 9: 4,
  1295. },
  1296. error: `yaml: unmarshal errors:\n line 4: mapping key "9" already defined at line 2`,
  1297. }}
  1298. func (s *S) TestUnmarshalKnownFields(c *C) {
  1299. for i, item := range unmarshalStrictTests {
  1300. c.Logf("test %d: %q", i, item.data)
  1301. // First test that normal Unmarshal unmarshals to the expected value.
  1302. if !item.unique {
  1303. t := reflect.ValueOf(item.value).Type()
  1304. value := reflect.New(t)
  1305. err := yaml.Unmarshal([]byte(item.data), value.Interface())
  1306. c.Assert(err, Equals, nil)
  1307. c.Assert(value.Elem().Interface(), DeepEquals, item.value)
  1308. }
  1309. // Then test that it fails on the same thing with KnownFields on.
  1310. t := reflect.ValueOf(item.value).Type()
  1311. value := reflect.New(t)
  1312. dec := yaml.NewDecoder(bytes.NewBuffer([]byte(item.data)))
  1313. dec.KnownFields(item.known)
  1314. err := dec.Decode(value.Interface())
  1315. c.Assert(err, ErrorMatches, item.error)
  1316. }
  1317. }
  1318. type textUnmarshaler struct {
  1319. S string
  1320. }
  1321. func (t *textUnmarshaler) UnmarshalText(s []byte) error {
  1322. t.S = string(s)
  1323. return nil
  1324. }
  1325. func (s *S) TestFuzzCrashers(c *C) {
  1326. cases := []string{
  1327. // runtime error: index out of range
  1328. "\"\\0\\\r\n",
  1329. // should not happen
  1330. " 0: [\n] 0",
  1331. "? ? \"\n\" 0",
  1332. " - {\n000}0",
  1333. "0:\n 0: [0\n] 0",
  1334. " - \"\n000\"0",
  1335. " - \"\n000\"\"",
  1336. "0:\n - {\n000}0",
  1337. "0:\n - \"\n000\"0",
  1338. "0:\n - \"\n000\"\"",
  1339. // runtime error: index out of range
  1340. " \ufeff\n",
  1341. "? \ufeff\n",
  1342. "? \ufeff:\n",
  1343. "0: \ufeff\n",
  1344. "? \ufeff: \ufeff\n",
  1345. }
  1346. for _, data := range cases {
  1347. var v interface{}
  1348. _ = yaml.Unmarshal([]byte(data), &v)
  1349. }
  1350. }
  1351. //var data []byte
  1352. //func init() {
  1353. // var err error
  1354. // data, err = ioutil.ReadFile("/tmp/file.yaml")
  1355. // if err != nil {
  1356. // panic(err)
  1357. // }
  1358. //}
  1359. //
  1360. //func (s *S) BenchmarkUnmarshal(c *C) {
  1361. // var err error
  1362. // for i := 0; i < c.N; i++ {
  1363. // var v map[string]interface{}
  1364. // err = yaml.Unmarshal(data, &v)
  1365. // }
  1366. // if err != nil {
  1367. // panic(err)
  1368. // }
  1369. //}
  1370. //
  1371. //func (s *S) BenchmarkMarshal(c *C) {
  1372. // var v map[string]interface{}
  1373. // yaml.Unmarshal(data, &v)
  1374. // c.ResetTimer()
  1375. // for i := 0; i < c.N; i++ {
  1376. // yaml.Marshal(&v)
  1377. // }
  1378. //}