encode_test.go 11 KB

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