encode_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  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: !!timestamp 2018-01-09T10:40:47Z\nt4: !!timestamp 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: !!timestamp 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: !!timestamp 2015-02-24T18:19:39Z\n",
  320. },
  321. // Ensure timestamp-like strings are quoted.
  322. {
  323. map[string]string{"a": "2015-02-24T18:19:39Z"},
  324. "a: \"2015-02-24T18:19:39Z\"\n",
  325. },
  326. // Ensure strings containing ": " are quoted (reported as PR #43, but not reproducible).
  327. {
  328. map[string]string{"a": "b: c"},
  329. "a: 'b: c'\n",
  330. },
  331. // Containing hash mark ('#') in string should be quoted
  332. {
  333. map[string]string{"a": "Hello #comment"},
  334. "a: 'Hello #comment'\n",
  335. },
  336. {
  337. map[string]string{"a": "你好 #comment"},
  338. "a: '你好 #comment'\n",
  339. },
  340. }
  341. func (s *S) TestMarshal(c *C) {
  342. defer os.Setenv("TZ", os.Getenv("TZ"))
  343. os.Setenv("TZ", "UTC")
  344. for i, item := range marshalTests {
  345. c.Logf("test %d: %q", i, item.data)
  346. data, err := yaml.Marshal(item.value)
  347. c.Assert(err, IsNil)
  348. c.Assert(string(data), Equals, item.data)
  349. }
  350. }
  351. func (s *S) TestEncoderSingleDocument(c *C) {
  352. for i, item := range marshalTests {
  353. c.Logf("test %d. %q", i, item.data)
  354. var buf bytes.Buffer
  355. enc := yaml.NewEncoder(&buf)
  356. err := enc.Encode(item.value)
  357. c.Assert(err, Equals, nil)
  358. err = enc.Close()
  359. c.Assert(err, Equals, nil)
  360. c.Assert(buf.String(), Equals, item.data)
  361. }
  362. }
  363. func (s *S) TestEncoderMultipleDocuments(c *C) {
  364. var buf bytes.Buffer
  365. enc := yaml.NewEncoder(&buf)
  366. err := enc.Encode(map[string]string{"a": "b"})
  367. c.Assert(err, Equals, nil)
  368. err = enc.Encode(map[string]string{"c": "d"})
  369. c.Assert(err, Equals, nil)
  370. err = enc.Close()
  371. c.Assert(err, Equals, nil)
  372. c.Assert(buf.String(), Equals, "a: b\n---\nc: d\n")
  373. }
  374. func (s *S) TestEncoderWriteError(c *C) {
  375. enc := yaml.NewEncoder(errorWriter{})
  376. err := enc.Encode(map[string]string{"a": "b"})
  377. c.Assert(err, ErrorMatches, `yaml: write error: some write error`) // Data not flushed yet
  378. }
  379. type errorWriter struct{}
  380. func (errorWriter) Write([]byte) (int, error) {
  381. return 0, fmt.Errorf("some write error")
  382. }
  383. var marshalErrorTests = []struct {
  384. value interface{}
  385. error string
  386. panic string
  387. }{{
  388. value: &struct {
  389. B int
  390. inlineB ",inline"
  391. }{1, inlineB{2, inlineC{3}}},
  392. panic: `Duplicated key 'b' in struct struct \{ B int; .*`,
  393. }, {
  394. value: &struct {
  395. A int
  396. B map[string]int ",inline"
  397. }{1, map[string]int{"a": 2}},
  398. panic: `Can't have key "a" in inlined map; conflicts with struct field`,
  399. }}
  400. func (s *S) TestMarshalErrors(c *C) {
  401. for _, item := range marshalErrorTests {
  402. if item.panic != "" {
  403. c.Assert(func() { yaml.Marshal(item.value) }, PanicMatches, item.panic)
  404. } else {
  405. _, err := yaml.Marshal(item.value)
  406. c.Assert(err, ErrorMatches, item.error)
  407. }
  408. }
  409. }
  410. func (s *S) TestMarshalTypeCache(c *C) {
  411. var data []byte
  412. var err error
  413. func() {
  414. type T struct{ A int }
  415. data, err = yaml.Marshal(&T{})
  416. c.Assert(err, IsNil)
  417. }()
  418. func() {
  419. type T struct{ B int }
  420. data, err = yaml.Marshal(&T{})
  421. c.Assert(err, IsNil)
  422. }()
  423. c.Assert(string(data), Equals, "b: 0\n")
  424. }
  425. var marshalerTests = []struct {
  426. data string
  427. value interface{}
  428. }{
  429. {"_:\n hi: there\n", map[interface{}]interface{}{"hi": "there"}},
  430. {"_:\n- 1\n- A\n", []interface{}{1, "A"}},
  431. {"_: 10\n", 10},
  432. {"_: null\n", nil},
  433. {"_: BAR!\n", "BAR!"},
  434. }
  435. type marshalerType struct {
  436. value interface{}
  437. }
  438. func (o marshalerType) MarshalText() ([]byte, error) {
  439. panic("MarshalText called on type with MarshalYAML")
  440. }
  441. func (o marshalerType) MarshalYAML() (interface{}, error) {
  442. return o.value, nil
  443. }
  444. type marshalerValue struct {
  445. Field marshalerType "_"
  446. }
  447. func (s *S) TestMarshaler(c *C) {
  448. for _, item := range marshalerTests {
  449. obj := &marshalerValue{}
  450. obj.Field.value = item.value
  451. data, err := yaml.Marshal(obj)
  452. c.Assert(err, IsNil)
  453. c.Assert(string(data), Equals, string(item.data))
  454. }
  455. }
  456. func (s *S) TestMarshalerWholeDocument(c *C) {
  457. obj := &marshalerType{}
  458. obj.value = map[string]string{"hello": "world!"}
  459. data, err := yaml.Marshal(obj)
  460. c.Assert(err, IsNil)
  461. c.Assert(string(data), Equals, "hello: world!\n")
  462. }
  463. type failingMarshaler struct{}
  464. func (ft *failingMarshaler) MarshalYAML() (interface{}, error) {
  465. return nil, failingErr
  466. }
  467. func (s *S) TestMarshalerError(c *C) {
  468. _, err := yaml.Marshal(&failingMarshaler{})
  469. c.Assert(err, Equals, failingErr)
  470. }
  471. func (s *S) TestSortedOutput(c *C) {
  472. order := []interface{}{
  473. false,
  474. true,
  475. 1,
  476. uint(1),
  477. 1.0,
  478. 1.1,
  479. 1.2,
  480. 2,
  481. uint(2),
  482. 2.0,
  483. 2.1,
  484. "",
  485. ".1",
  486. ".2",
  487. ".a",
  488. "1",
  489. "2",
  490. "a!10",
  491. "a/0001",
  492. "a/002",
  493. "a/3",
  494. "a/10",
  495. "a/11",
  496. "a/0012",
  497. "a/100",
  498. "a~10",
  499. "ab/1",
  500. "b/1",
  501. "b/01",
  502. "b/2",
  503. "b/02",
  504. "b/3",
  505. "b/03",
  506. "b1",
  507. "b01",
  508. "b3",
  509. "c2.10",
  510. "c10.2",
  511. "d1",
  512. "d7",
  513. "d7abc",
  514. "d12",
  515. "d12a",
  516. }
  517. m := make(map[interface{}]int)
  518. for _, k := range order {
  519. m[k] = 1
  520. }
  521. data, err := yaml.Marshal(m)
  522. c.Assert(err, IsNil)
  523. out := "\n" + string(data)
  524. last := 0
  525. for i, k := range order {
  526. repr := fmt.Sprint(k)
  527. if s, ok := k.(string); ok {
  528. if _, err = strconv.ParseFloat(repr, 32); s == "" || err == nil {
  529. repr = `"` + repr + `"`
  530. }
  531. }
  532. index := strings.Index(out, "\n"+repr+":")
  533. if index == -1 {
  534. c.Fatalf("%#v is not in the output: %#v", k, out)
  535. }
  536. if index < last {
  537. c.Fatalf("%#v was generated before %#v: %q", k, order[i-1], out)
  538. }
  539. last = index
  540. }
  541. }
  542. func newTime(t time.Time) *time.Time {
  543. return &t
  544. }