encode_test.go 11 KB

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