encode_test.go 11 KB

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