Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 

745 rader
20 KiB

  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package xml
  5. import (
  6. "bytes"
  7. "fmt"
  8. "io"
  9. "reflect"
  10. "strings"
  11. "testing"
  12. "time"
  13. )
  14. // Stripped down Atom feed data structures.
  15. func TestUnmarshalFeed(t *testing.T) {
  16. var f Feed
  17. if err := Unmarshal([]byte(atomFeedString), &f); err != nil {
  18. t.Fatalf("Unmarshal: %s", err)
  19. }
  20. if !reflect.DeepEqual(f, atomFeed) {
  21. t.Fatalf("have %#v\nwant %#v", f, atomFeed)
  22. }
  23. }
  24. // hget http://codereview.appspot.com/rss/mine/rsc
  25. const atomFeedString = `
  26. <?xml version="1.0" encoding="utf-8"?>
  27. <feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en-us" updated="2009-10-04T01:35:58+00:00"><title>Code Review - My issues</title><link href="http://codereview.appspot.com/" rel="alternate"></link><link href="http://codereview.appspot.com/rss/mine/rsc" rel="self"></link><id>http://codereview.appspot.com/</id><author><name>rietveld&lt;&gt;</name></author><entry><title>rietveld: an attempt at pubsubhubbub
  28. </title><link href="http://codereview.appspot.com/126085" rel="alternate"></link><updated>2009-10-04T01:35:58+00:00</updated><author><name>email-address-removed</name></author><id>urn:md5:134d9179c41f806be79b3a5f7877d19a</id><summary type="html">
  29. An attempt at adding pubsubhubbub support to Rietveld.
  30. http://code.google.com/p/pubsubhubbub
  31. http://code.google.com/p/rietveld/issues/detail?id=155
  32. The server side of the protocol is trivial:
  33. 1. add a &amp;lt;link rel=&amp;quot;hub&amp;quot; href=&amp;quot;hub-server&amp;quot;&amp;gt; tag to all
  34. feeds that will be pubsubhubbubbed.
  35. 2. every time one of those feeds changes, tell the hub
  36. with a simple POST request.
  37. I have tested this by adding debug prints to a local hub
  38. server and checking that the server got the right publish
  39. requests.
  40. I can&amp;#39;t quite get the server to work, but I think the bug
  41. is not in my code. I think that the server expects to be
  42. able to grab the feed and see the feed&amp;#39;s actual URL in
  43. the link rel=&amp;quot;self&amp;quot;, but the default value for that drops
  44. the :port from the URL, and I cannot for the life of me
  45. figure out how to get the Atom generator deep inside
  46. django not to do that, or even where it is doing that,
  47. or even what code is running to generate the Atom feed.
  48. (I thought I knew but I added some assert False statements
  49. and it kept running!)
  50. Ignoring that particular problem, I would appreciate
  51. feedback on the right way to get the two values at
  52. the top of feeds.py marked NOTE(rsc).
  53. </summary></entry><entry><title>rietveld: correct tab handling
  54. </title><link href="http://codereview.appspot.com/124106" rel="alternate"></link><updated>2009-10-03T23:02:17+00:00</updated><author><name>email-address-removed</name></author><id>urn:md5:0a2a4f19bb815101f0ba2904aed7c35a</id><summary type="html">
  55. This fixes the buggy tab rendering that can be seen at
  56. http://codereview.appspot.com/116075/diff/1/2
  57. The fundamental problem was that the tab code was
  58. not being told what column the text began in, so it
  59. didn&amp;#39;t know where to put the tab stops. Another problem
  60. was that some of the code assumed that string byte
  61. offsets were the same as column offsets, which is only
  62. true if there are no tabs.
  63. In the process of fixing this, I cleaned up the arguments
  64. to Fold and ExpandTabs and renamed them Break and
  65. _ExpandTabs so that I could be sure that I found all the
  66. call sites. I also wanted to verify that ExpandTabs was
  67. not being used from outside intra_region_diff.py.
  68. </summary></entry></feed> `
  69. type Feed struct {
  70. XMLName Name `xml:"http://www.w3.org/2005/Atom feed"`
  71. Title string `xml:"title"`
  72. Id string `xml:"id"`
  73. Link []Link `xml:"link"`
  74. Updated time.Time `xml:"updated,attr"`
  75. Author Person `xml:"author"`
  76. Entry []Entry `xml:"entry"`
  77. }
  78. type Entry struct {
  79. Title string `xml:"title"`
  80. Id string `xml:"id"`
  81. Link []Link `xml:"link"`
  82. Updated time.Time `xml:"updated"`
  83. Author Person `xml:"author"`
  84. Summary Text `xml:"summary"`
  85. }
  86. type Link struct {
  87. Rel string `xml:"rel,attr,omitempty"`
  88. Href string `xml:"href,attr"`
  89. }
  90. type Person struct {
  91. Name string `xml:"name"`
  92. URI string `xml:"uri"`
  93. Email string `xml:"email"`
  94. InnerXML string `xml:",innerxml"`
  95. }
  96. type Text struct {
  97. Type string `xml:"type,attr,omitempty"`
  98. Body string `xml:",chardata"`
  99. }
  100. var atomFeed = Feed{
  101. XMLName: Name{"http://www.w3.org/2005/Atom", "feed"},
  102. Title: "Code Review - My issues",
  103. Link: []Link{
  104. {Rel: "alternate", Href: "http://codereview.appspot.com/"},
  105. {Rel: "self", Href: "http://codereview.appspot.com/rss/mine/rsc"},
  106. },
  107. Id: "http://codereview.appspot.com/",
  108. Updated: ParseTime("2009-10-04T01:35:58+00:00"),
  109. Author: Person{
  110. Name: "rietveld<>",
  111. InnerXML: "<name>rietveld&lt;&gt;</name>",
  112. },
  113. Entry: []Entry{
  114. {
  115. Title: "rietveld: an attempt at pubsubhubbub\n",
  116. Link: []Link{
  117. {Rel: "alternate", Href: "http://codereview.appspot.com/126085"},
  118. },
  119. Updated: ParseTime("2009-10-04T01:35:58+00:00"),
  120. Author: Person{
  121. Name: "email-address-removed",
  122. InnerXML: "<name>email-address-removed</name>",
  123. },
  124. Id: "urn:md5:134d9179c41f806be79b3a5f7877d19a",
  125. Summary: Text{
  126. Type: "html",
  127. Body: `
  128. An attempt at adding pubsubhubbub support to Rietveld.
  129. http://code.google.com/p/pubsubhubbub
  130. http://code.google.com/p/rietveld/issues/detail?id=155
  131. The server side of the protocol is trivial:
  132. 1. add a &lt;link rel=&quot;hub&quot; href=&quot;hub-server&quot;&gt; tag to all
  133. feeds that will be pubsubhubbubbed.
  134. 2. every time one of those feeds changes, tell the hub
  135. with a simple POST request.
  136. I have tested this by adding debug prints to a local hub
  137. server and checking that the server got the right publish
  138. requests.
  139. I can&#39;t quite get the server to work, but I think the bug
  140. is not in my code. I think that the server expects to be
  141. able to grab the feed and see the feed&#39;s actual URL in
  142. the link rel=&quot;self&quot;, but the default value for that drops
  143. the :port from the URL, and I cannot for the life of me
  144. figure out how to get the Atom generator deep inside
  145. django not to do that, or even where it is doing that,
  146. or even what code is running to generate the Atom feed.
  147. (I thought I knew but I added some assert False statements
  148. and it kept running!)
  149. Ignoring that particular problem, I would appreciate
  150. feedback on the right way to get the two values at
  151. the top of feeds.py marked NOTE(rsc).
  152. `,
  153. },
  154. },
  155. {
  156. Title: "rietveld: correct tab handling\n",
  157. Link: []Link{
  158. {Rel: "alternate", Href: "http://codereview.appspot.com/124106"},
  159. },
  160. Updated: ParseTime("2009-10-03T23:02:17+00:00"),
  161. Author: Person{
  162. Name: "email-address-removed",
  163. InnerXML: "<name>email-address-removed</name>",
  164. },
  165. Id: "urn:md5:0a2a4f19bb815101f0ba2904aed7c35a",
  166. Summary: Text{
  167. Type: "html",
  168. Body: `
  169. This fixes the buggy tab rendering that can be seen at
  170. http://codereview.appspot.com/116075/diff/1/2
  171. The fundamental problem was that the tab code was
  172. not being told what column the text began in, so it
  173. didn&#39;t know where to put the tab stops. Another problem
  174. was that some of the code assumed that string byte
  175. offsets were the same as column offsets, which is only
  176. true if there are no tabs.
  177. In the process of fixing this, I cleaned up the arguments
  178. to Fold and ExpandTabs and renamed them Break and
  179. _ExpandTabs so that I could be sure that I found all the
  180. call sites. I also wanted to verify that ExpandTabs was
  181. not being used from outside intra_region_diff.py.
  182. `,
  183. },
  184. },
  185. },
  186. }
  187. const pathTestString = `
  188. <Result>
  189. <Before>1</Before>
  190. <Items>
  191. <Item1>
  192. <Value>A</Value>
  193. </Item1>
  194. <Item2>
  195. <Value>B</Value>
  196. </Item2>
  197. <Item1>
  198. <Value>C</Value>
  199. <Value>D</Value>
  200. </Item1>
  201. <_>
  202. <Value>E</Value>
  203. </_>
  204. </Items>
  205. <After>2</After>
  206. </Result>
  207. `
  208. type PathTestItem struct {
  209. Value string
  210. }
  211. type PathTestA struct {
  212. Items []PathTestItem `xml:">Item1"`
  213. Before, After string
  214. }
  215. type PathTestB struct {
  216. Other []PathTestItem `xml:"Items>Item1"`
  217. Before, After string
  218. }
  219. type PathTestC struct {
  220. Values1 []string `xml:"Items>Item1>Value"`
  221. Values2 []string `xml:"Items>Item2>Value"`
  222. Before, After string
  223. }
  224. type PathTestSet struct {
  225. Item1 []PathTestItem
  226. }
  227. type PathTestD struct {
  228. Other PathTestSet `xml:"Items"`
  229. Before, After string
  230. }
  231. type PathTestE struct {
  232. Underline string `xml:"Items>_>Value"`
  233. Before, After string
  234. }
  235. var pathTests = []interface{}{
  236. &PathTestA{Items: []PathTestItem{{"A"}, {"D"}}, Before: "1", After: "2"},
  237. &PathTestB{Other: []PathTestItem{{"A"}, {"D"}}, Before: "1", After: "2"},
  238. &PathTestC{Values1: []string{"A", "C", "D"}, Values2: []string{"B"}, Before: "1", After: "2"},
  239. &PathTestD{Other: PathTestSet{Item1: []PathTestItem{{"A"}, {"D"}}}, Before: "1", After: "2"},
  240. &PathTestE{Underline: "E", Before: "1", After: "2"},
  241. }
  242. func TestUnmarshalPaths(t *testing.T) {
  243. for _, pt := range pathTests {
  244. v := reflect.New(reflect.TypeOf(pt).Elem()).Interface()
  245. if err := Unmarshal([]byte(pathTestString), v); err != nil {
  246. t.Fatalf("Unmarshal: %s", err)
  247. }
  248. if !reflect.DeepEqual(v, pt) {
  249. t.Fatalf("have %#v\nwant %#v", v, pt)
  250. }
  251. }
  252. }
  253. type BadPathTestA struct {
  254. First string `xml:"items>item1"`
  255. Other string `xml:"items>item2"`
  256. Second string `xml:"items"`
  257. }
  258. type BadPathTestB struct {
  259. Other string `xml:"items>item2>value"`
  260. First string `xml:"items>item1"`
  261. Second string `xml:"items>item1>value"`
  262. }
  263. type BadPathTestC struct {
  264. First string
  265. Second string `xml:"First"`
  266. }
  267. type BadPathTestD struct {
  268. BadPathEmbeddedA
  269. BadPathEmbeddedB
  270. }
  271. type BadPathEmbeddedA struct {
  272. First string
  273. }
  274. type BadPathEmbeddedB struct {
  275. Second string `xml:"First"`
  276. }
  277. var badPathTests = []struct {
  278. v, e interface{}
  279. }{
  280. {&BadPathTestA{}, &TagPathError{reflect.TypeOf(BadPathTestA{}), "First", "items>item1", "Second", "items"}},
  281. {&BadPathTestB{}, &TagPathError{reflect.TypeOf(BadPathTestB{}), "First", "items>item1", "Second", "items>item1>value"}},
  282. {&BadPathTestC{}, &TagPathError{reflect.TypeOf(BadPathTestC{}), "First", "", "Second", "First"}},
  283. {&BadPathTestD{}, &TagPathError{reflect.TypeOf(BadPathTestD{}), "First", "", "Second", "First"}},
  284. }
  285. func TestUnmarshalBadPaths(t *testing.T) {
  286. for _, tt := range badPathTests {
  287. err := Unmarshal([]byte(pathTestString), tt.v)
  288. if !reflect.DeepEqual(err, tt.e) {
  289. t.Fatalf("Unmarshal with %#v didn't fail properly:\nhave %#v,\nwant %#v", tt.v, err, tt.e)
  290. }
  291. }
  292. }
  293. const OK = "OK"
  294. const withoutNameTypeData = `
  295. <?xml version="1.0" charset="utf-8"?>
  296. <Test3 Attr="OK" />`
  297. type TestThree struct {
  298. XMLName Name `xml:"Test3"`
  299. Attr string `xml:",attr"`
  300. }
  301. func TestUnmarshalWithoutNameType(t *testing.T) {
  302. var x TestThree
  303. if err := Unmarshal([]byte(withoutNameTypeData), &x); err != nil {
  304. t.Fatalf("Unmarshal: %s", err)
  305. }
  306. if x.Attr != OK {
  307. t.Fatalf("have %v\nwant %v", x.Attr, OK)
  308. }
  309. }
  310. func TestUnmarshalAttr(t *testing.T) {
  311. type ParamVal struct {
  312. Int int `xml:"int,attr"`
  313. }
  314. type ParamPtr struct {
  315. Int *int `xml:"int,attr"`
  316. }
  317. type ParamStringPtr struct {
  318. Int *string `xml:"int,attr"`
  319. }
  320. x := []byte(`<Param int="1" />`)
  321. p1 := &ParamPtr{}
  322. if err := Unmarshal(x, p1); err != nil {
  323. t.Fatalf("Unmarshal: %s", err)
  324. }
  325. if p1.Int == nil {
  326. t.Fatalf("Unmarshal failed in to *int field")
  327. } else if *p1.Int != 1 {
  328. t.Fatalf("Unmarshal with %s failed:\nhave %#v,\n want %#v", x, p1.Int, 1)
  329. }
  330. p2 := &ParamVal{}
  331. if err := Unmarshal(x, p2); err != nil {
  332. t.Fatalf("Unmarshal: %s", err)
  333. }
  334. if p2.Int != 1 {
  335. t.Fatalf("Unmarshal with %s failed:\nhave %#v,\n want %#v", x, p2.Int, 1)
  336. }
  337. p3 := &ParamStringPtr{}
  338. if err := Unmarshal(x, p3); err != nil {
  339. t.Fatalf("Unmarshal: %s", err)
  340. }
  341. if p3.Int == nil {
  342. t.Fatalf("Unmarshal failed in to *string field")
  343. } else if *p3.Int != "1" {
  344. t.Fatalf("Unmarshal with %s failed:\nhave %#v,\n want %#v", x, p3.Int, 1)
  345. }
  346. }
  347. type Tables struct {
  348. HTable string `xml:"http://www.w3.org/TR/html4/ table"`
  349. FTable string `xml:"http://www.w3schools.com/furniture table"`
  350. }
  351. var tables = []struct {
  352. xml string
  353. tab Tables
  354. ns string
  355. }{
  356. {
  357. xml: `<Tables>` +
  358. `<table xmlns="http://www.w3.org/TR/html4/">hello</table>` +
  359. `<table xmlns="http://www.w3schools.com/furniture">world</table>` +
  360. `</Tables>`,
  361. tab: Tables{"hello", "world"},
  362. },
  363. {
  364. xml: `<Tables>` +
  365. `<table xmlns="http://www.w3schools.com/furniture">world</table>` +
  366. `<table xmlns="http://www.w3.org/TR/html4/">hello</table>` +
  367. `</Tables>`,
  368. tab: Tables{"hello", "world"},
  369. },
  370. {
  371. xml: `<Tables xmlns:f="http://www.w3schools.com/furniture" xmlns:h="http://www.w3.org/TR/html4/">` +
  372. `<f:table>world</f:table>` +
  373. `<h:table>hello</h:table>` +
  374. `</Tables>`,
  375. tab: Tables{"hello", "world"},
  376. },
  377. {
  378. xml: `<Tables>` +
  379. `<table>bogus</table>` +
  380. `</Tables>`,
  381. tab: Tables{},
  382. },
  383. {
  384. xml: `<Tables>` +
  385. `<table>only</table>` +
  386. `</Tables>`,
  387. tab: Tables{HTable: "only"},
  388. ns: "http://www.w3.org/TR/html4/",
  389. },
  390. {
  391. xml: `<Tables>` +
  392. `<table>only</table>` +
  393. `</Tables>`,
  394. tab: Tables{FTable: "only"},
  395. ns: "http://www.w3schools.com/furniture",
  396. },
  397. {
  398. xml: `<Tables>` +
  399. `<table>only</table>` +
  400. `</Tables>`,
  401. tab: Tables{},
  402. ns: "something else entirely",
  403. },
  404. }
  405. func TestUnmarshalNS(t *testing.T) {
  406. for i, tt := range tables {
  407. var dst Tables
  408. var err error
  409. if tt.ns != "" {
  410. d := NewDecoder(strings.NewReader(tt.xml))
  411. d.DefaultSpace = tt.ns
  412. err = d.Decode(&dst)
  413. } else {
  414. err = Unmarshal([]byte(tt.xml), &dst)
  415. }
  416. if err != nil {
  417. t.Errorf("#%d: Unmarshal: %v", i, err)
  418. continue
  419. }
  420. want := tt.tab
  421. if dst != want {
  422. t.Errorf("#%d: dst=%+v, want %+v", i, dst, want)
  423. }
  424. }
  425. }
  426. func TestRoundTrip(t *testing.T) {
  427. // From issue 7535
  428. const s = `<ex:element xmlns:ex="http://example.com/schema"></ex:element>`
  429. in := bytes.NewBufferString(s)
  430. for i := 0; i < 10; i++ {
  431. out := &bytes.Buffer{}
  432. d := NewDecoder(in)
  433. e := NewEncoder(out)
  434. for {
  435. t, err := d.Token()
  436. if err == io.EOF {
  437. break
  438. }
  439. if err != nil {
  440. fmt.Println("failed:", err)
  441. return
  442. }
  443. e.EncodeToken(t)
  444. }
  445. e.Flush()
  446. in = out
  447. }
  448. if got := in.String(); got != s {
  449. t.Errorf("have: %q\nwant: %q\n", got, s)
  450. }
  451. }
  452. func TestMarshalNS(t *testing.T) {
  453. dst := Tables{"hello", "world"}
  454. data, err := Marshal(&dst)
  455. if err != nil {
  456. t.Fatalf("Marshal: %v", err)
  457. }
  458. want := `<Tables><table xmlns="http://www.w3.org/TR/html4/">hello</table><table xmlns="http://www.w3schools.com/furniture">world</table></Tables>`
  459. str := string(data)
  460. if str != want {
  461. t.Errorf("have: %q\nwant: %q\n", str, want)
  462. }
  463. }
  464. type TableAttrs struct {
  465. TAttr TAttr
  466. }
  467. type TAttr struct {
  468. HTable string `xml:"http://www.w3.org/TR/html4/ table,attr"`
  469. FTable string `xml:"http://www.w3schools.com/furniture table,attr"`
  470. Lang string `xml:"http://www.w3.org/XML/1998/namespace lang,attr,omitempty"`
  471. Other1 string `xml:"http://golang.org/xml/ other,attr,omitempty"`
  472. Other2 string `xml:"http://golang.org/xmlfoo/ other,attr,omitempty"`
  473. Other3 string `xml:"http://golang.org/json/ other,attr,omitempty"`
  474. Other4 string `xml:"http://golang.org/2/json/ other,attr,omitempty"`
  475. }
  476. var tableAttrs = []struct {
  477. xml string
  478. tab TableAttrs
  479. ns string
  480. }{
  481. {
  482. xml: `<TableAttrs xmlns:f="http://www.w3schools.com/furniture" xmlns:h="http://www.w3.org/TR/html4/"><TAttr ` +
  483. `h:table="hello" f:table="world" ` +
  484. `/></TableAttrs>`,
  485. tab: TableAttrs{TAttr{HTable: "hello", FTable: "world"}},
  486. },
  487. {
  488. xml: `<TableAttrs><TAttr xmlns:f="http://www.w3schools.com/furniture" xmlns:h="http://www.w3.org/TR/html4/" ` +
  489. `h:table="hello" f:table="world" ` +
  490. `/></TableAttrs>`,
  491. tab: TableAttrs{TAttr{HTable: "hello", FTable: "world"}},
  492. },
  493. {
  494. xml: `<TableAttrs><TAttr ` +
  495. `h:table="hello" f:table="world" xmlns:f="http://www.w3schools.com/furniture" xmlns:h="http://www.w3.org/TR/html4/" ` +
  496. `/></TableAttrs>`,
  497. tab: TableAttrs{TAttr{HTable: "hello", FTable: "world"}},
  498. },
  499. {
  500. // Default space does not apply to attribute names.
  501. xml: `<TableAttrs xmlns="http://www.w3schools.com/furniture" xmlns:h="http://www.w3.org/TR/html4/"><TAttr ` +
  502. `h:table="hello" table="world" ` +
  503. `/></TableAttrs>`,
  504. tab: TableAttrs{TAttr{HTable: "hello", FTable: ""}},
  505. },
  506. {
  507. // Default space does not apply to attribute names.
  508. xml: `<TableAttrs xmlns:f="http://www.w3schools.com/furniture"><TAttr xmlns="http://www.w3.org/TR/html4/" ` +
  509. `table="hello" f:table="world" ` +
  510. `/></TableAttrs>`,
  511. tab: TableAttrs{TAttr{HTable: "", FTable: "world"}},
  512. },
  513. {
  514. xml: `<TableAttrs><TAttr ` +
  515. `table="bogus" ` +
  516. `/></TableAttrs>`,
  517. tab: TableAttrs{},
  518. },
  519. {
  520. // Default space does not apply to attribute names.
  521. xml: `<TableAttrs xmlns:h="http://www.w3.org/TR/html4/"><TAttr ` +
  522. `h:table="hello" table="world" ` +
  523. `/></TableAttrs>`,
  524. tab: TableAttrs{TAttr{HTable: "hello", FTable: ""}},
  525. ns: "http://www.w3schools.com/furniture",
  526. },
  527. {
  528. // Default space does not apply to attribute names.
  529. xml: `<TableAttrs xmlns:f="http://www.w3schools.com/furniture"><TAttr ` +
  530. `table="hello" f:table="world" ` +
  531. `/></TableAttrs>`,
  532. tab: TableAttrs{TAttr{HTable: "", FTable: "world"}},
  533. ns: "http://www.w3.org/TR/html4/",
  534. },
  535. {
  536. xml: `<TableAttrs><TAttr ` +
  537. `table="bogus" ` +
  538. `/></TableAttrs>`,
  539. tab: TableAttrs{},
  540. ns: "something else entirely",
  541. },
  542. }
  543. func TestUnmarshalNSAttr(t *testing.T) {
  544. for i, tt := range tableAttrs {
  545. var dst TableAttrs
  546. var err error
  547. if tt.ns != "" {
  548. d := NewDecoder(strings.NewReader(tt.xml))
  549. d.DefaultSpace = tt.ns
  550. err = d.Decode(&dst)
  551. } else {
  552. err = Unmarshal([]byte(tt.xml), &dst)
  553. }
  554. if err != nil {
  555. t.Errorf("#%d: Unmarshal: %v", i, err)
  556. continue
  557. }
  558. want := tt.tab
  559. if dst != want {
  560. t.Errorf("#%d: dst=%+v, want %+v", i, dst, want)
  561. }
  562. }
  563. }
  564. func TestMarshalNSAttr(t *testing.T) {
  565. src := TableAttrs{TAttr{"hello", "world", "en_US", "other1", "other2", "other3", "other4"}}
  566. data, err := Marshal(&src)
  567. if err != nil {
  568. t.Fatalf("Marshal: %v", err)
  569. }
  570. want := `<TableAttrs><TAttr xmlns:json_1="http://golang.org/2/json/" xmlns:json="http://golang.org/json/" xmlns:_xmlfoo="http://golang.org/xmlfoo/" xmlns:_xml="http://golang.org/xml/" xmlns:furniture="http://www.w3schools.com/furniture" xmlns:html4="http://www.w3.org/TR/html4/" html4:table="hello" furniture:table="world" xml:lang="en_US" _xml:other="other1" _xmlfoo:other="other2" json:other="other3" json_1:other="other4"></TAttr></TableAttrs>`
  571. str := string(data)
  572. if str != want {
  573. t.Errorf("Marshal:\nhave: %#q\nwant: %#q\n", str, want)
  574. }
  575. var dst TableAttrs
  576. if err := Unmarshal(data, &dst); err != nil {
  577. t.Errorf("Unmarshal: %v", err)
  578. }
  579. if dst != src {
  580. t.Errorf("Unmarshal = %q, want %q", dst, src)
  581. }
  582. }
  583. type MyCharData struct {
  584. body string
  585. }
  586. func (m *MyCharData) UnmarshalXML(d *Decoder, start StartElement) error {
  587. for {
  588. t, err := d.Token()
  589. if err == io.EOF { // found end of element
  590. break
  591. }
  592. if err != nil {
  593. return err
  594. }
  595. if char, ok := t.(CharData); ok {
  596. m.body += string(char)
  597. }
  598. }
  599. return nil
  600. }
  601. var _ Unmarshaler = (*MyCharData)(nil)
  602. func (m *MyCharData) UnmarshalXMLAttr(attr Attr) error {
  603. panic("must not call")
  604. }
  605. type MyAttr struct {
  606. attr string
  607. }
  608. func (m *MyAttr) UnmarshalXMLAttr(attr Attr) error {
  609. m.attr = attr.Value
  610. return nil
  611. }
  612. var _ UnmarshalerAttr = (*MyAttr)(nil)
  613. type MyStruct struct {
  614. Data *MyCharData
  615. Attr *MyAttr `xml:",attr"`
  616. Data2 MyCharData
  617. Attr2 MyAttr `xml:",attr"`
  618. }
  619. func TestUnmarshaler(t *testing.T) {
  620. xml := `<?xml version="1.0" encoding="utf-8"?>
  621. <MyStruct Attr="attr1" Attr2="attr2">
  622. <Data>hello <!-- comment -->world</Data>
  623. <Data2>howdy <!-- comment -->world</Data2>
  624. </MyStruct>
  625. `
  626. var m MyStruct
  627. if err := Unmarshal([]byte(xml), &m); err != nil {
  628. t.Fatal(err)
  629. }
  630. if m.Data == nil || m.Attr == nil || m.Data.body != "hello world" || m.Attr.attr != "attr1" || m.Data2.body != "howdy world" || m.Attr2.attr != "attr2" {
  631. t.Errorf("m=%#+v\n", m)
  632. }
  633. }
  634. type Pea struct {
  635. Cotelydon string
  636. }
  637. type Pod struct {
  638. Pea interface{} `xml:"Pea"`
  639. }
  640. // https://golang.org/issue/6836
  641. func TestUnmarshalIntoInterface(t *testing.T) {
  642. pod := new(Pod)
  643. pod.Pea = new(Pea)
  644. xml := `<Pod><Pea><Cotelydon>Green stuff</Cotelydon></Pea></Pod>`
  645. err := Unmarshal([]byte(xml), pod)
  646. if err != nil {
  647. t.Fatalf("failed to unmarshal %q: %v", xml, err)
  648. }
  649. pea, ok := pod.Pea.(*Pea)
  650. if !ok {
  651. t.Fatalf("unmarshalled into wrong type: have %T want *Pea", pod.Pea)
  652. }
  653. have, want := pea.Cotelydon, "Green stuff"
  654. if have != want {
  655. t.Errorf("failed to unmarshal into interface, have %q want %q", have, want)
  656. }
  657. }