encode_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. package yaml_test
  2. import (
  3. "bytes"
  4. "fmt"
  5. "math"
  6. "strconv"
  7. "strings"
  8. "time"
  9. "net"
  10. "os"
  11. . "gopkg.in/check.v1"
  12. "gopkg.in/yaml.v2"
  13. )
  14. var marshalIntTest = 123
  15. var marshalTests = []struct {
  16. value interface{}
  17. data string
  18. }{
  19. {
  20. nil,
  21. "null\n",
  22. }, {
  23. (*marshalerType)(nil),
  24. "null\n",
  25. }, {
  26. &struct{}{},
  27. "{}\n",
  28. }, {
  29. map[string]string{"v": "hi"},
  30. "v: hi\n",
  31. }, {
  32. map[string]interface{}{"v": "hi"},
  33. "v: hi\n",
  34. }, {
  35. map[string]string{"v": "true"},
  36. "v: \"true\"\n",
  37. }, {
  38. map[string]string{"v": "false"},
  39. "v: \"false\"\n",
  40. }, {
  41. map[string]interface{}{"v": true},
  42. "v: true\n",
  43. }, {
  44. map[string]interface{}{"v": false},
  45. "v: false\n",
  46. }, {
  47. map[string]interface{}{"v": 10},
  48. "v: 10\n",
  49. }, {
  50. map[string]interface{}{"v": -10},
  51. "v: -10\n",
  52. }, {
  53. map[string]uint{"v": 42},
  54. "v: 42\n",
  55. }, {
  56. map[string]interface{}{"v": int64(4294967296)},
  57. "v: 4294967296\n",
  58. }, {
  59. map[string]int64{"v": int64(4294967296)},
  60. "v: 4294967296\n",
  61. }, {
  62. map[string]uint64{"v": 4294967296},
  63. "v: 4294967296\n",
  64. }, {
  65. map[string]interface{}{"v": "10"},
  66. "v: \"10\"\n",
  67. }, {
  68. map[string]interface{}{"v": 0.1},
  69. "v: 0.1\n",
  70. }, {
  71. map[string]interface{}{"v": float64(0.1)},
  72. "v: 0.1\n",
  73. }, {
  74. map[string]interface{}{"v": -0.1},
  75. "v: -0.1\n",
  76. }, {
  77. map[string]interface{}{"v": math.Inf(+1)},
  78. "v: .inf\n",
  79. }, {
  80. map[string]interface{}{"v": math.Inf(-1)},
  81. "v: -.inf\n",
  82. }, {
  83. map[string]interface{}{"v": math.NaN()},
  84. "v: .nan\n",
  85. }, {
  86. map[string]interface{}{"v": nil},
  87. "v: null\n",
  88. }, {
  89. map[string]interface{}{"v": ""},
  90. "v: \"\"\n",
  91. }, {
  92. map[string][]string{"v": []string{"A", "B"}},
  93. "v:\n- A\n- B\n",
  94. }, {
  95. map[string][]string{"v": []string{"A", "B\nC"}},
  96. "v:\n- A\n- |-\n B\n C\n",
  97. }, {
  98. map[string][]interface{}{"v": []interface{}{"A", 1, map[string][]int{"B": []int{2, 3}}}},
  99. "v:\n- A\n- 1\n- B:\n - 2\n - 3\n",
  100. }, {
  101. map[string]interface{}{"a": map[interface{}]interface{}{"b": "c"}},
  102. "a:\n b: c\n",
  103. }, {
  104. map[string]interface{}{"a": "-"},
  105. "a: '-'\n",
  106. },
  107. // Simple values.
  108. {
  109. &marshalIntTest,
  110. "123\n",
  111. },
  112. // Structures
  113. {
  114. &struct{ Hello string }{"world"},
  115. "hello: world\n",
  116. }, {
  117. &struct {
  118. A struct {
  119. B string
  120. }
  121. }{struct{ B string }{"c"}},
  122. "a:\n b: c\n",
  123. }, {
  124. &struct {
  125. A *struct {
  126. B string
  127. }
  128. }{&struct{ B string }{"c"}},
  129. "a:\n b: c\n",
  130. }, {
  131. &struct {
  132. A *struct {
  133. B string
  134. }
  135. }{},
  136. "a: null\n",
  137. }, {
  138. &struct{ A int }{1},
  139. "a: 1\n",
  140. }, {
  141. &struct{ A []int }{[]int{1, 2}},
  142. "a:\n- 1\n- 2\n",
  143. }, {
  144. &struct{ A [2]int }{[2]int{1, 2}},
  145. "a:\n- 1\n- 2\n",
  146. }, {
  147. &struct {
  148. B int "a"
  149. }{1},
  150. "a: 1\n",
  151. }, {
  152. &struct{ A bool }{true},
  153. "a: true\n",
  154. },
  155. // Conditional flag
  156. {
  157. &struct {
  158. A int "a,omitempty"
  159. B int "b,omitempty"
  160. }{1, 0},
  161. "a: 1\n",
  162. }, {
  163. &struct {
  164. A int "a,omitempty"
  165. B int "b,omitempty"
  166. }{0, 0},
  167. "{}\n",
  168. }, {
  169. &struct {
  170. A *struct{ X, y int } "a,omitempty,flow"
  171. }{&struct{ X, y int }{1, 2}},
  172. "a: {x: 1}\n",
  173. }, {
  174. &struct {
  175. A *struct{ X, y int } "a,omitempty,flow"
  176. }{nil},
  177. "{}\n",
  178. }, {
  179. &struct {
  180. A *struct{ X, y int } "a,omitempty,flow"
  181. }{&struct{ X, y int }{}},
  182. "a: {x: 0}\n",
  183. }, {
  184. &struct {
  185. A struct{ X, y int } "a,omitempty,flow"
  186. }{struct{ X, y int }{1, 2}},
  187. "a: {x: 1}\n",
  188. }, {
  189. &struct {
  190. A struct{ X, y int } "a,omitempty,flow"
  191. }{struct{ X, y int }{0, 1}},
  192. "{}\n",
  193. }, {
  194. &struct {
  195. A float64 "a,omitempty"
  196. B float64 "b,omitempty"
  197. }{1, 0},
  198. "a: 1\n",
  199. },
  200. {
  201. &struct {
  202. T1 time.Time "t1,omitempty"
  203. T2 time.Time "t2,omitempty"
  204. T3 *time.Time "t3,omitempty"
  205. T4 *time.Time "t4,omitempty"
  206. }{
  207. T2: time.Date(2018, 1, 9, 10, 40, 47, 0, time.UTC),
  208. T4: newTime(time.Date(2098, 1, 9, 10, 40, 47, 0, time.UTC)),
  209. },
  210. "t2: 2018-01-09T10:40:47Z\nt4: 2098-01-09T10:40:47Z\n",
  211. },
  212. // Nil interface that implements Marshaler.
  213. {
  214. map[string]yaml.Marshaler{
  215. "a": nil,
  216. },
  217. "a: null\n",
  218. },
  219. // Flow flag
  220. {
  221. &struct {
  222. A []int "a,flow"
  223. }{[]int{1, 2}},
  224. "a: [1, 2]\n",
  225. }, {
  226. &struct {
  227. A map[string]string "a,flow"
  228. }{map[string]string{"b": "c", "d": "e"}},
  229. "a: {b: c, d: e}\n",
  230. }, {
  231. &struct {
  232. A struct {
  233. B, D string
  234. } "a,flow"
  235. }{struct{ B, D string }{"c", "e"}},
  236. "a: {b: c, d: e}\n",
  237. },
  238. // Unexported field
  239. {
  240. &struct {
  241. u int
  242. A int
  243. }{0, 1},
  244. "a: 1\n",
  245. },
  246. // Ignored field
  247. {
  248. &struct {
  249. A int
  250. B int "-"
  251. }{1, 2},
  252. "a: 1\n",
  253. },
  254. // Struct inlining
  255. {
  256. &struct {
  257. A int
  258. C inlineB `yaml:",inline"`
  259. }{1, inlineB{2, inlineC{3}}},
  260. "a: 1\nb: 2\nc: 3\n",
  261. },
  262. // Map inlining
  263. {
  264. &struct {
  265. A int
  266. C map[string]int `yaml:",inline"`
  267. }{1, map[string]int{"b": 2, "c": 3}},
  268. "a: 1\nb: 2\nc: 3\n",
  269. },
  270. // Duration
  271. {
  272. map[string]time.Duration{"a": 3 * time.Second},
  273. "a: 3s\n",
  274. },
  275. // Issue #24: bug in map merging logic.
  276. {
  277. map[string]string{"a": "<foo>"},
  278. "a: <foo>\n",
  279. },
  280. // Issue #34: marshal unsupported base 60 floats quoted for compatibility
  281. // with old YAML 1.1 parsers.
  282. {
  283. map[string]string{"a": "1:1"},
  284. "a: \"1:1\"\n",
  285. },
  286. // Binary data.
  287. {
  288. map[string]string{"a": "\x00"},
  289. "a: \"\\0\"\n",
  290. }, {
  291. map[string]string{"a": "\x80\x81\x82"},
  292. "a: !!binary gIGC\n",
  293. }, {
  294. map[string]string{"a": strings.Repeat("\x90", 54)},
  295. "a: !!binary |\n " + strings.Repeat("kJCQ", 17) + "kJ\n CQ\n",
  296. },
  297. // Ordered maps.
  298. {
  299. &yaml.MapSlice{{"b", 2}, {"a", 1}, {"d", 4}, {"c", 3}, {"sub", yaml.MapSlice{{"e", 5}}}},
  300. "b: 2\na: 1\nd: 4\nc: 3\nsub:\n e: 5\n",
  301. },
  302. // Encode unicode as utf-8 rather than in escaped form.
  303. {
  304. map[string]string{"a": "你好"},
  305. "a: 你好\n",
  306. },
  307. // Support encoding.TextMarshaler.
  308. {
  309. map[string]net.IP{"a": net.IPv4(1, 2, 3, 4)},
  310. "a: 1.2.3.4\n",
  311. },
  312. // time.Time gets a timestamp tag.
  313. {
  314. map[string]time.Time{"a": time.Date(2015, 2, 24, 18, 19, 39, 0, time.UTC)},
  315. "a: 2015-02-24T18:19:39Z\n",
  316. },
  317. {
  318. map[string]*time.Time{"a": newTime(time.Date(2015, 2, 24, 18, 19, 39, 0, time.UTC))},
  319. "a: 2015-02-24T18:19:39Z\n",
  320. },
  321. {
  322. // This is confirmed to be properly decoded in Python (libyaml) without a timestamp tag.
  323. map[string]time.Time{"a": time.Date(2015, 2, 24, 18, 19, 39, 123456789, time.FixedZone("FOO", -3*60*60))},
  324. "a: 2015-02-24T18:19:39.123456789-03:00\n",
  325. },
  326. // Ensure timestamp-like strings are quoted.
  327. {
  328. map[string]string{"a": "2015-02-24T18:19:39Z"},
  329. "a: \"2015-02-24T18:19:39Z\"\n",
  330. },
  331. // Ensure strings containing ": " are quoted (reported as PR #43, but not reproducible).
  332. {
  333. map[string]string{"a": "b: c"},
  334. "a: 'b: c'\n",
  335. },
  336. // Containing hash mark ('#') in string should be quoted
  337. {
  338. map[string]string{"a": "Hello #comment"},
  339. "a: 'Hello #comment'\n",
  340. },
  341. {
  342. map[string]string{"a": "你好 #comment"},
  343. "a: '你好 #comment'\n",
  344. },
  345. }
  346. func (s *S) TestMarshal(c *C) {
  347. defer os.Setenv("TZ", os.Getenv("TZ"))
  348. os.Setenv("TZ", "UTC")
  349. for i, item := range marshalTests {
  350. c.Logf("test %d: %q", i, item.data)
  351. data, err := yaml.Marshal(item.value)
  352. c.Assert(err, IsNil)
  353. c.Assert(string(data), Equals, item.data)
  354. }
  355. }
  356. func (s *S) TestEncoderSingleDocument(c *C) {
  357. for i, item := range marshalTests {
  358. c.Logf("test %d. %q", i, item.data)
  359. var buf bytes.Buffer
  360. enc := yaml.NewEncoder(&buf)
  361. err := enc.Encode(item.value)
  362. c.Assert(err, Equals, nil)
  363. err = enc.Close()
  364. c.Assert(err, Equals, nil)
  365. c.Assert(buf.String(), Equals, item.data)
  366. }
  367. }
  368. func (s *S) TestEncoderMultipleDocuments(c *C) {
  369. var buf bytes.Buffer
  370. enc := yaml.NewEncoder(&buf)
  371. err := enc.Encode(map[string]string{"a": "b"})
  372. c.Assert(err, Equals, nil)
  373. err = enc.Encode(map[string]string{"c": "d"})
  374. c.Assert(err, Equals, nil)
  375. err = enc.Close()
  376. c.Assert(err, Equals, nil)
  377. c.Assert(buf.String(), Equals, "a: b\n---\nc: d\n")
  378. }
  379. func (s *S) TestEncoderWriteError(c *C) {
  380. enc := yaml.NewEncoder(errorWriter{})
  381. err := enc.Encode(map[string]string{"a": "b"})
  382. c.Assert(err, ErrorMatches, `yaml: write error: some write error`) // Data not flushed yet
  383. }
  384. type errorWriter struct{}
  385. func (errorWriter) Write([]byte) (int, error) {
  386. return 0, fmt.Errorf("some write error")
  387. }
  388. var marshalErrorTests = []struct {
  389. value interface{}
  390. error string
  391. panic string
  392. }{{
  393. value: &struct {
  394. B int
  395. inlineB ",inline"
  396. }{1, inlineB{2, inlineC{3}}},
  397. panic: `Duplicated key 'b' in struct struct \{ B int; .*`,
  398. }, {
  399. value: &struct {
  400. A int
  401. B map[string]int ",inline"
  402. }{1, map[string]int{"a": 2}},
  403. panic: `Can't have key "a" in inlined map; conflicts with struct field`,
  404. }}
  405. func (s *S) TestMarshalErrors(c *C) {
  406. for _, item := range marshalErrorTests {
  407. if item.panic != "" {
  408. c.Assert(func() { yaml.Marshal(item.value) }, PanicMatches, item.panic)
  409. } else {
  410. _, err := yaml.Marshal(item.value)
  411. c.Assert(err, ErrorMatches, item.error)
  412. }
  413. }
  414. }
  415. func (s *S) TestMarshalTypeCache(c *C) {
  416. var data []byte
  417. var err error
  418. func() {
  419. type T struct{ A int }
  420. data, err = yaml.Marshal(&T{})
  421. c.Assert(err, IsNil)
  422. }()
  423. func() {
  424. type T struct{ B int }
  425. data, err = yaml.Marshal(&T{})
  426. c.Assert(err, IsNil)
  427. }()
  428. c.Assert(string(data), Equals, "b: 0\n")
  429. }
  430. var marshalerTests = []struct {
  431. data string
  432. value interface{}
  433. }{
  434. {"_:\n hi: there\n", map[interface{}]interface{}{"hi": "there"}},
  435. {"_:\n- 1\n- A\n", []interface{}{1, "A"}},
  436. {"_: 10\n", 10},
  437. {"_: null\n", nil},
  438. {"_: BAR!\n", "BAR!"},
  439. }
  440. type marshalerType struct {
  441. value interface{}
  442. }
  443. func (o marshalerType) MarshalText() ([]byte, error) {
  444. panic("MarshalText called on type with MarshalYAML")
  445. }
  446. func (o marshalerType) MarshalYAML() (interface{}, error) {
  447. return o.value, nil
  448. }
  449. type marshalerValue struct {
  450. Field marshalerType "_"
  451. }
  452. func (s *S) TestMarshaler(c *C) {
  453. for _, item := range marshalerTests {
  454. obj := &marshalerValue{}
  455. obj.Field.value = item.value
  456. data, err := yaml.Marshal(obj)
  457. c.Assert(err, IsNil)
  458. c.Assert(string(data), Equals, string(item.data))
  459. }
  460. }
  461. func (s *S) TestMarshalerWholeDocument(c *C) {
  462. obj := &marshalerType{}
  463. obj.value = map[string]string{"hello": "world!"}
  464. data, err := yaml.Marshal(obj)
  465. c.Assert(err, IsNil)
  466. c.Assert(string(data), Equals, "hello: world!\n")
  467. }
  468. type failingMarshaler struct{}
  469. func (ft *failingMarshaler) MarshalYAML() (interface{}, error) {
  470. return nil, failingErr
  471. }
  472. func (s *S) TestMarshalerError(c *C) {
  473. _, err := yaml.Marshal(&failingMarshaler{})
  474. c.Assert(err, Equals, failingErr)
  475. }
  476. func (s *S) TestSortedOutput(c *C) {
  477. order := []interface{}{
  478. false,
  479. true,
  480. 1,
  481. uint(1),
  482. 1.0,
  483. 1.1,
  484. 1.2,
  485. 2,
  486. uint(2),
  487. 2.0,
  488. 2.1,
  489. "",
  490. ".1",
  491. ".2",
  492. ".a",
  493. "1",
  494. "2",
  495. "a!10",
  496. "a/0001",
  497. "a/002",
  498. "a/3",
  499. "a/10",
  500. "a/11",
  501. "a/0012",
  502. "a/100",
  503. "a~10",
  504. "ab/1",
  505. "b/1",
  506. "b/01",
  507. "b/2",
  508. "b/02",
  509. "b/3",
  510. "b/03",
  511. "b1",
  512. "b01",
  513. "b3",
  514. "c2.10",
  515. "c10.2",
  516. "d1",
  517. "d7",
  518. "d7abc",
  519. "d12",
  520. "d12a",
  521. }
  522. m := make(map[interface{}]int)
  523. for _, k := range order {
  524. m[k] = 1
  525. }
  526. data, err := yaml.Marshal(m)
  527. c.Assert(err, IsNil)
  528. out := "\n" + string(data)
  529. last := 0
  530. for i, k := range order {
  531. repr := fmt.Sprint(k)
  532. if s, ok := k.(string); ok {
  533. if _, err = strconv.ParseFloat(repr, 32); s == "" || err == nil {
  534. repr = `"` + repr + `"`
  535. }
  536. }
  537. index := strings.Index(out, "\n"+repr+":")
  538. if index == -1 {
  539. c.Fatalf("%#v is not in the output: %#v", k, out)
  540. }
  541. if index < last {
  542. c.Fatalf("%#v was generated before %#v: %q", k, order[i-1], out)
  543. }
  544. last = index
  545. }
  546. }
  547. func newTime(t time.Time) *time.Time {
  548. return &t
  549. }