Debian Codegraph @

libgo/go/encoding/xml/marshal_test.go

raw
1 // Copyright 2011 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
5 package xml
6
7 import (
8 "bytes"
9 "errors"
10 "fmt"
11 "io"
12 "reflect"
13 "strconv"
14 "strings"
15 "sync"
16 "testing"
17 "time"
18 )
19
20 type DriveType int
21
22 const (
23 HyperDrive DriveType = iota
24 ImprobabilityDrive
25 )
26
27 type Passenger struct {
28 Name []string `xml:"name"`
29 Weight float32 `xml:"weight"`
30 }
31
32 type Ship struct {
33 XMLName struct{} `xml:"spaceship"`
34
35 Name string `xml:"name,attr"`
36 Pilot string `xml:"pilot,attr"`
37 Drive DriveType `xml:"drive"`
38 Age uint `xml:"age"`
39 Passenger []*Passenger `xml:"passenger"`
40 secret string
41 }
42
43 type NamedType string
44
45 type Port struct {
46 XMLName struct{} `xml:"port"`
47 Type string `xml:"type,attr,omitempty"`
48 Comment string `xml:",comment"`
49 Number string `xml:",chardata"`
50 }
51
52 type Domain struct {
53 XMLName struct{} `xml:"domain"`
54 Country string `xml:",attr,omitempty"`
55 Name []byte `xml:",chardata"`
56 Comment []byte `xml:",comment"`
57 }
58
59 type Book struct {
60 XMLName struct{} `xml:"book"`
61 Title string `xml:",chardata"`
62 }
63
64 type Event struct {
65 XMLName struct{} `xml:"event"`
66 Year int `xml:",chardata"`
67 }
68
69 type Movie struct {
70 XMLName struct{} `xml:"movie"`
71 Length uint `xml:",chardata"`
72 }
73
74 type Pi struct {
75 XMLName struct{} `xml:"pi"`
76 Approximation float32 `xml:",chardata"`
77 }
78
79 type Universe struct {
80 XMLName struct{} `xml:"universe"`
81 Visible float64 `xml:",chardata"`
82 }
83
84 type Particle struct {
85 XMLName struct{} `xml:"particle"`
86 HasMass bool `xml:",chardata"`
87 }
88
89 type Departure struct {
90 XMLName struct{} `xml:"departure"`
91 When time.Time `xml:",chardata"`
92 }
93
94 type SecretAgent struct {
95 XMLName struct{} `xml:"agent"`
96 Handle string `xml:"handle,attr"`
97 Identity string
98 Obfuscate string `xml:",innerxml"`
99 }
100
101 type NestedItems struct {
102 XMLName struct{} `xml:"result"`
103 Items []string `xml:">item"`
104 Item1 []string `xml:"Items>item1"`
105 }
106
107 type NestedOrder struct {
108 XMLName struct{} `xml:"result"`
109 Field1 string `xml:"parent>c"`
110 Field2 string `xml:"parent>b"`
111 Field3 string `xml:"parent>a"`
112 }
113
114 type MixedNested struct {
115 XMLName struct{} `xml:"result"`
116 A string `xml:"parent1>a"`
117 B string `xml:"b"`
118 C string `xml:"parent1>parent2>c"`
119 D string `xml:"parent1>d"`
120 }
121
122 type NilTest struct {
123 A any `xml:"parent1>parent2>a"`
124 B any `xml:"parent1>b"`
125 C any `xml:"parent1>parent2>c"`
126 }
127
128 type Service struct {
129 XMLName struct{} `xml:"service"`
130 Domain *Domain `xml:"host>domain"`
131 Port *Port `xml:"host>port"`
132 Extra1 any
133 Extra2 any `xml:"host>extra2"`
134 }
135
136 var nilStruct *Ship
137
138 type EmbedA struct {
139 EmbedC
140 EmbedB EmbedB
141 FieldA string
142 embedD
143 }
144
145 type EmbedB struct {
146 FieldB string
147 *EmbedC
148 }
149
150 type EmbedC struct {
151 FieldA1 string `xml:"FieldA>A1"`
152 FieldA2 string `xml:"FieldA>A2"`
153 FieldB string
154 FieldC string
155 }
156
157 type embedD struct {
158 fieldD string
159 FieldE string // Promoted and visible when embedD is embedded.
160 }
161
162 type NameCasing struct {
163 XMLName struct{} `xml:"casing"`
164 Xy string
165 XY string
166 XyA string `xml:"Xy,attr"`
167 XYA string `xml:"XY,attr"`
168 }
169
170 type NamePrecedence struct {
171 XMLName Name `xml:"Parent"`
172 FromTag XMLNameWithoutTag `xml:"InTag"`
173 FromNameVal XMLNameWithoutTag
174 FromNameTag XMLNameWithTag
175 InFieldName string
176 }
177
178 type XMLNameWithTag struct {
179 XMLName Name `xml:"InXMLNameTag"`
180 Value string `xml:",chardata"`
181 }
182
183 type XMLNameWithoutTag struct {
184 XMLName Name
185 Value string `xml:",chardata"`
186 }
187
188 type NameInField struct {
189 Foo Name `xml:"ns foo"`
190 }
191
192 type AttrTest struct {
193 Int int `xml:",attr"`
194 Named int `xml:"int,attr"`
195 Float float64 `xml:",attr"`
196 Uint8 uint8 `xml:",attr"`
197 Bool bool `xml:",attr"`
198 Str string `xml:",attr"`
199 Bytes []byte `xml:",attr"`
200 }
201
202 type AttrsTest struct {
203 Attrs []Attr `xml:",any,attr"`
204 Int int `xml:",attr"`
205 Named int `xml:"int,attr"`
206 Float float64 `xml:",attr"`
207 Uint8 uint8 `xml:",attr"`
208 Bool bool `xml:",attr"`
209 Str string `xml:",attr"`
210 Bytes []byte `xml:",attr"`
211 }
212
213 type OmitAttrTest struct {
214 Int int `xml:",attr,omitempty"`
215 Named int `xml:"int,attr,omitempty"`
216 Float float64 `xml:",attr,omitempty"`
217 Uint8 uint8 `xml:",attr,omitempty"`
218 Bool bool `xml:",attr,omitempty"`
219 Str string `xml:",attr,omitempty"`
220 Bytes []byte `xml:",attr,omitempty"`
221 PStr *string `xml:",attr,omitempty"`
222 }
223
224 type OmitFieldTest struct {
225 Int int `xml:",omitempty"`
226 Named int `xml:"int,omitempty"`
227 Float float64 `xml:",omitempty"`
228 Uint8 uint8 `xml:",omitempty"`
229 Bool bool `xml:",omitempty"`
230 Str string `xml:",omitempty"`
231 Bytes []byte `xml:",omitempty"`
232 PStr *string `xml:",omitempty"`
233 Ptr *PresenceTest `xml:",omitempty"`
234 }
235
236 type AnyTest struct {
237 XMLName struct{} `xml:"a"`
238 Nested string `xml:"nested>value"`
239 AnyField AnyHolder `xml:",any"`
240 }
241
242 type AnyOmitTest struct {
243 XMLName struct{} `xml:"a"`
244 Nested string `xml:"nested>value"`
245 AnyField *AnyHolder `xml:",any,omitempty"`
246 }
247
248 type AnySliceTest struct {
249 XMLName struct{} `xml:"a"`
250 Nested string `xml:"nested>value"`
251 AnyField []AnyHolder `xml:",any"`
252 }
253
254 type AnyHolder struct {
255 XMLName Name
256 XML string `xml:",innerxml"`
257 }
258
259 type RecurseA struct {
260 A string
261 B *RecurseB
262 }
263
264 type RecurseB struct {
265 A *RecurseA
266 B string
267 }
268
269 type PresenceTest struct {
270 Exists *struct{}
271 }
272
273 type IgnoreTest struct {
274 PublicSecret string `xml:"-"`
275 }
276
277 type MyBytes []byte
278
279 type Data struct {
280 Bytes []byte
281 Attr []byte `xml:",attr"`
282 Custom MyBytes
283 }
284
285 type Plain struct {
286 V any
287 }
288
289 type MyInt int
290
291 type EmbedInt struct {
292 MyInt
293 }
294
295 type Strings struct {
296 X []string `xml:"A>B,omitempty"`
297 }
298
299 type PointerFieldsTest struct {
300 XMLName Name `xml:"dummy"`
301 Name *string `xml:"name,attr"`
302 Age *uint `xml:"age,attr"`
303 Empty *string `xml:"empty,attr"`
304 Contents *string `xml:",chardata"`
305 }
306
307 type ChardataEmptyTest struct {
308 XMLName Name `xml:"test"`
309 Contents *string `xml:",chardata"`
310 }
311
312 type PointerAnonFields struct {
313 *MyInt
314 *NamedType
315 }
316
317 type MyMarshalerTest struct {
318 }
319
320 var _ Marshaler = (*MyMarshalerTest)(nil)
321
322 func (m *MyMarshalerTest) MarshalXML(e *Encoder, start StartElement) error {
323 e.EncodeToken(start)
324 e.EncodeToken(CharData([]byte("hello world")))
325 e.EncodeToken(EndElement{start.Name})
326 return nil
327 }
328
329 type MyMarshalerAttrTest struct {
330 }
331
332 var _ MarshalerAttr = (*MyMarshalerAttrTest)(nil)
333
334 func (m *MyMarshalerAttrTest) MarshalXMLAttr(name Name) (Attr, error) {
335 return Attr{name, "hello world"}, nil
336 }
337
338 func (m *MyMarshalerAttrTest) UnmarshalXMLAttr(attr Attr) error {
339 return nil
340 }
341
342 type MarshalerStruct struct {
343 Foo MyMarshalerAttrTest `xml:",attr"`
344 }
345
346 type InnerStruct struct {
347 XMLName Name `xml:"testns outer"`
348 }
349
350 type OuterStruct struct {
351 InnerStruct
352 IntAttr int `xml:"int,attr"`
353 }
354
355 type OuterNamedStruct struct {
356 InnerStruct
357 XMLName Name `xml:"outerns test"`
358 IntAttr int `xml:"int,attr"`
359 }
360
361 type OuterNamedOrderedStruct struct {
362 XMLName Name `xml:"outerns test"`
363 InnerStruct
364 IntAttr int `xml:"int,attr"`
365 }
366
367 type OuterOuterStruct struct {
368 OuterStruct
369 }
370
371 type NestedAndChardata struct {
372 AB []string `xml:"A>B"`
373 Chardata string `xml:",chardata"`
374 }
375
376 type NestedAndComment struct {
377 AB []string `xml:"A>B"`
378 Comment string `xml:",comment"`
379 }
380
381 type CDataTest struct {
382 Chardata string `xml:",cdata"`
383 }
384
385 type NestedAndCData struct {
386 AB []string `xml:"A>B"`
387 CDATA string `xml:",cdata"`
388 }
389
390 func ifaceptr(x any) any {
391 return &x
392 }
393
394 func stringptr(x string) *string {
395 return &x
396 }
397
398 type T1 struct{}
399 type T2 struct{}
400
401 type IndirComment struct {
402 T1 T1
403 Comment *string `xml:",comment"`
404 T2 T2
405 }
406
407 type DirectComment struct {
408 T1 T1
409 Comment string `xml:",comment"`
410 T2 T2
411 }
412
413 type IfaceComment struct {
414 T1 T1
415 Comment any `xml:",comment"`
416 T2 T2
417 }
418
419 type IndirChardata struct {
420 T1 T1
421 Chardata *string `xml:",chardata"`
422 T2 T2
423 }
424
425 type DirectChardata struct {
426 T1 T1
427 Chardata string `xml:",chardata"`
428 T2 T2
429 }
430
431 type IfaceChardata struct {
432 T1 T1
433 Chardata any `xml:",chardata"`
434 T2 T2
435 }
436
437 type IndirCDATA struct {
438 T1 T1
439 CDATA *string `xml:",cdata"`
440 T2 T2
441 }
442
443 type DirectCDATA struct {
444 T1 T1
445 CDATA string `xml:",cdata"`
446 T2 T2
447 }
448
449 type IfaceCDATA struct {
450 T1 T1
451 CDATA any `xml:",cdata"`
452 T2 T2
453 }
454
455 type IndirInnerXML struct {
456 T1 T1
457 InnerXML *string `xml:",innerxml"`
458 T2 T2
459 }
460
461 type DirectInnerXML struct {
462 T1 T1
463 InnerXML string `xml:",innerxml"`
464 T2 T2
465 }
466
467 type IfaceInnerXML struct {
468 T1 T1
469 InnerXML any `xml:",innerxml"`
470 T2 T2
471 }
472
473 type IndirElement struct {
474 T1 T1
475 Element *string
476 T2 T2
477 }
478
479 type DirectElement struct {
480 T1 T1
481 Element string
482 T2 T2
483 }
484
485 type IfaceElement struct {
486 T1 T1
487 Element any
488 T2 T2
489 }
490
491 type IndirOmitEmpty struct {
492 T1 T1
493 OmitEmpty *string `xml:",omitempty"`
494 T2 T2
495 }
496
497 type DirectOmitEmpty struct {
498 T1 T1
499 OmitEmpty string `xml:",omitempty"`
500 T2 T2
501 }
502
503 type IfaceOmitEmpty struct {
504 T1 T1
505 OmitEmpty any `xml:",omitempty"`
506 T2 T2
507 }
508
509 type IndirAny struct {
510 T1 T1
511 Any *string `xml:",any"`
512 T2 T2
513 }
514
515 type DirectAny struct {
516 T1 T1
517 Any string `xml:",any"`
518 T2 T2
519 }
520
521 type IfaceAny struct {
522 T1 T1
523 Any any `xml:",any"`
524 T2 T2
525 }
526
527 /* FIXME: Commented out for gofrontend.
528
529 type Generic[T any] struct {
530 X T
531 }
532
533 */
534
535 var (
536 nameAttr = "Sarah"
537 ageAttr = uint(12)
538 contentsAttr = "lorem ipsum"
539 empty = ""
540 )
541
542 // Unless explicitly stated as such (or *Plain), all of the
543 // tests below are two-way tests. When introducing new tests,
544 // please try to make them two-way as well to ensure that
545 // marshaling and unmarshaling are as symmetrical as feasible.
546 var marshalTests = []struct {
547 Value any
548 ExpectXML string
549 MarshalOnly bool
550 MarshalError string
551 UnmarshalOnly bool
552 UnmarshalError string
553 }{
554 // Test nil marshals to nothing
555 {Value: nil, ExpectXML: ``, MarshalOnly: true},
556 {Value: nilStruct, ExpectXML: ``, MarshalOnly: true},
557
558 // Test value types
559 {Value: &Plain{true}, ExpectXML: `<Plain><V>true</V></Plain>`},
560 {Value: &Plain{false}, ExpectXML: `<Plain><V>false</V></Plain>`},
561 {Value: &Plain{int(42)}, ExpectXML: `<Plain><V>42</V></Plain>`},
562 {Value: &Plain{int8(42)}, ExpectXML: `<Plain><V>42</V></Plain>`},
563 {Value: &Plain{int16(42)}, ExpectXML: `<Plain><V>42</V></Plain>`},
564 {Value: &Plain{int32(42)}, ExpectXML: `<Plain><V>42</V></Plain>`},
565 {Value: &Plain{uint(42)}, ExpectXML: `<Plain><V>42</V></Plain>`},
566 {Value: &Plain{uint8(42)}, ExpectXML: `<Plain><V>42</V></Plain>`},
567 {Value: &Plain{uint16(42)}, ExpectXML: `<Plain><V>42</V></Plain>`},
568 {Value: &Plain{uint32(42)}, ExpectXML: `<Plain><V>42</V></Plain>`},
569 {Value: &Plain{float32(1.25)}, ExpectXML: `<Plain><V>1.25</V></Plain>`},
570 {Value: &Plain{float64(1.25)}, ExpectXML: `<Plain><V>1.25</V></Plain>`},
571 {Value: &Plain{uintptr(0xFFDD)}, ExpectXML: `<Plain><V>65501</V></Plain>`},
572 {Value: &Plain{"gopher"}, ExpectXML: `<Plain><V>gopher</V></Plain>`},
573 {Value: &Plain{[]byte("gopher")}, ExpectXML: `<Plain><V>gopher</V></Plain>`},
574 {Value: &Plain{"</>"}, ExpectXML: `<Plain><V>&lt;/&gt;</V></Plain>`},
575 {Value: &Plain{[]byte("</>")}, ExpectXML: `<Plain><V>&lt;/&gt;</V></Plain>`},
576 {Value: &Plain{[3]byte{'<', '/', '>'}}, ExpectXML: `<Plain><V>&lt;/&gt;</V></Plain>`},
577 {Value: &Plain{NamedType("potato")}, ExpectXML: `<Plain><V>potato</V></Plain>`},
578 {Value: &Plain{[]int{1, 2, 3}}, ExpectXML: `<Plain><V>1</V><V>2</V><V>3</V></Plain>`},
579 {Value: &Plain{[3]int{1, 2, 3}}, ExpectXML: `<Plain><V>1</V><V>2</V><V>3</V></Plain>`},
580 {Value: ifaceptr(true), MarshalOnly: true, ExpectXML: `<bool>true</bool>`},
581
582 // Test time.
583 {
584 Value: &Plain{time.Unix(1e9, 123456789).UTC()},
585 ExpectXML: `<Plain><V>2001-09-09T01:46:40.123456789Z</V></Plain>`,
586 },
587
588 // A pointer to struct{} may be used to test for an element's presence.
589 {
590 Value: &PresenceTest{new(struct{})},
591 ExpectXML: `<PresenceTest><Exists></Exists></PresenceTest>`,
592 },
593 {
594 Value: &PresenceTest{},
595 ExpectXML: `<PresenceTest></PresenceTest>`,
596 },
597
598 // A []byte field is only nil if the element was not found.
599 {
600 Value: &Data{},
601 ExpectXML: `<Data></Data>`,
602 UnmarshalOnly: true,
603 },
604 {
605 Value: &Data{Bytes: []byte{}, Custom: MyBytes{}, Attr: []byte{}},
606 ExpectXML: `<Data Attr=""><Bytes></Bytes><Custom></Custom></Data>`,
607 UnmarshalOnly: true,
608 },
609
610 // Check that []byte works, including named []byte types.
611 {
612 Value: &Data{Bytes: []byte("ab"), Custom: MyBytes("cd"), Attr: []byte{'v'}},
613 ExpectXML: `<Data Attr="v"><Bytes>ab</Bytes><Custom>cd</Custom></Data>`,
614 },
615
616 // Test innerxml
617 {
618 Value: &SecretAgent{
619 Handle: "007",
620 Identity: "James Bond",
621 Obfuscate: "<redacted/>",
622 },
623 ExpectXML: `<agent handle="007"><Identity>James Bond</Identity><redacted/></agent>`,
624 MarshalOnly: true,
625 },
626 {
627 Value: &SecretAgent{
628 Handle: "007",
629 Identity: "James Bond",
630 Obfuscate: "<Identity>James Bond</Identity><redacted/>",
631 },
632 ExpectXML: `<agent handle="007"><Identity>James Bond</Identity><redacted/></agent>`,
633 UnmarshalOnly: true,
634 },
635
636 // Test structs
637 {Value: &Port{Type: "ssl", Number: "443"}, ExpectXML: `<port type="ssl">443</port>`},
638 {Value: &Port{Number: "443"}, ExpectXML: `<port>443</port>`},
639 {Value: &Port{Type: "<unix>"}, ExpectXML: `<port type="&lt;unix&gt;"></port>`},
640 {Value: &Port{Number: "443", Comment: "https"}, ExpectXML: `<port><!--https-->443</port>`},
641 {Value: &Port{Number: "443", Comment: "add space-"}, ExpectXML: `<port><!--add space- -->443</port>`, MarshalOnly: true},
642 {Value: &Domain{Name: []byte("google.com&friends")}, ExpectXML: `<domain>google.com&amp;friends</domain>`},
643 {Value: &Domain{Name: []byte("google.com"), Comment: []byte(" &friends ")}, ExpectXML: `<domain>google.com<!-- &friends --></domain>`},
644 {Value: &Book{Title: "Pride & Prejudice"}, ExpectXML: `<book>Pride &amp; Prejudice</book>`},
645 {Value: &Event{Year: -3114}, ExpectXML: `<event>-3114</event>`},
646 {Value: &Movie{Length: 13440}, ExpectXML: `<movie>13440</movie>`},
647 {Value: &Pi{Approximation: 3.14159265}, ExpectXML: `<pi>3.1415927</pi>`},
648 {Value: &Universe{Visible: 9.3e13}, ExpectXML: `<universe>9.3e+13</universe>`},
649 {Value: &Particle{HasMass: true}, ExpectXML: `<particle>true</particle>`},
650 {Value: &Departure{When: ParseTime("2013-01-09T00:15:00-09:00")}, ExpectXML: `<departure>2013-01-09T00:15:00-09:00</departure>`},
651 {Value: atomValue, ExpectXML: atomXML},
652 // {Value: &Generic[int]{1}, ExpectXML: `<Generic><X>1</X></Generic>`},
653 {
654 Value: &Ship{
655 Name: "Heart of Gold",
656 Pilot: "Computer",
657 Age: 1,
658 Drive: ImprobabilityDrive,
659 Passenger: []*Passenger{
660 {
661 Name: []string{"Zaphod", "Beeblebrox"},
662 Weight: 7.25,
663 },
664 {
665 Name: []string{"Trisha", "McMillen"},
666 Weight: 5.5,
667 },
668 {
669 Name: []string{"Ford", "Prefect"},
670 Weight: 7,
671 },
672 {
673 Name: []string{"Arthur", "Dent"},
674 Weight: 6.75,
675 },
676 },
677 },
678 ExpectXML: `<spaceship name="Heart of Gold" pilot="Computer">` +
679 `<drive>` + strconv.Itoa(int(ImprobabilityDrive)) + `</drive>` +
680 `<age>1</age>` +
681 `<passenger>` +
682 `<name>Zaphod</name>` +
683 `<name>Beeblebrox</name>` +
684 `<weight>7.25</weight>` +
685 `</passenger>` +
686 `<passenger>` +
687 `<name>Trisha</name>` +
688 `<name>McMillen</name>` +
689 `<weight>5.5</weight>` +
690 `</passenger>` +
691 `<passenger>` +
692 `<name>Ford</name>` +
693 `<name>Prefect</name>` +
694 `<weight>7</weight>` +
695 `</passenger>` +
696 `<passenger>` +
697 `<name>Arthur</name>` +
698 `<name>Dent</name>` +
699 `<weight>6.75</weight>` +
700 `</passenger>` +
701 `</spaceship>`,
702 },
703
704 // Test a>b
705 {
706 Value: &NestedItems{Items: nil, Item1: nil},
707 ExpectXML: `<result>` +
708 `<Items>` +
709 `</Items>` +
710 `</result>`,
711 },
712 {
713 Value: &NestedItems{Items: []string{}, Item1: []string{}},
714 ExpectXML: `<result>` +
715 `<Items>` +
716 `</Items>` +
717 `</result>`,
718 MarshalOnly: true,
719 },
720 {
721 Value: &NestedItems{Items: nil, Item1: []string{"A"}},
722 ExpectXML: `<result>` +
723 `<Items>` +
724 `<item1>A</item1>` +
725 `</Items>` +
726 `</result>`,
727 },
728 {
729 Value: &NestedItems{Items: []string{"A", "B"}, Item1: nil},
730 ExpectXML: `<result>` +
731 `<Items>` +
732 `<item>A</item>` +
733 `<item>B</item>` +
734 `</Items>` +
735 `</result>`,
736 },
737 {
738 Value: &NestedItems{Items: []string{"A", "B"}, Item1: []string{"C"}},
739 ExpectXML: `<result>` +
740 `<Items>` +
741 `<item>A</item>` +
742 `<item>B</item>` +
743 `<item1>C</item1>` +
744 `</Items>` +
745 `</result>`,
746 },
747 {
748 Value: &NestedOrder{Field1: "C", Field2: "B", Field3: "A"},
749 ExpectXML: `<result>` +
750 `<parent>` +
751 `<c>C</c>` +
752 `<b>B</b>` +
753 `<a>A</a>` +
754 `</parent>` +
755 `</result>`,
756 },
757 {
758 Value: &NilTest{A: "A", B: nil, C: "C"},
759 ExpectXML: `<NilTest>` +
760 `<parent1>` +
761 `<parent2><a>A</a></parent2>` +
762 `<parent2><c>C</c></parent2>` +
763 `</parent1>` +
764 `</NilTest>`,
765 MarshalOnly: true, // Uses interface{}
766 },
767 {
768 Value: &MixedNested{A: "A", B: "B", C: "C", D: "D"},
769 ExpectXML: `<result>` +
770 `<parent1><a>A</a></parent1>` +
771 `<b>B</b>` +
772 `<parent1>` +
773 `<parent2><c>C</c></parent2>` +
774 `<d>D</d>` +
775 `</parent1>` +
776 `</result>`,
777 },
778 {
779 Value: &Service{Port: &Port{Number: "80"}},
780 ExpectXML: `<service><host><port>80</port></host></service>`,
781 },
782 {
783 Value: &Service{},
784 ExpectXML: `<service></service>`,
785 },
786 {
787 Value: &Service{Port: &Port{Number: "80"}, Extra1: "A", Extra2: "B"},
788 ExpectXML: `<service>` +
789 `<host><port>80</port></host>` +
790 `<Extra1>A</Extra1>` +
791 `<host><extra2>B</extra2></host>` +
792 `</service>`,
793 MarshalOnly: true,
794 },
795 {
796 Value: &Service{Port: &Port{Number: "80"}, Extra2: "example"},
797 ExpectXML: `<service>` +
798 `<host><port>80</port></host>` +
799 `<host><extra2>example</extra2></host>` +
800 `</service>`,
801 MarshalOnly: true,
802 },
803 {
804 Value: &struct {
805 XMLName struct{} `xml:"space top"`
806 A string `xml:"x>a"`
807 B string `xml:"x>b"`
808 C string `xml:"space x>c"`
809 C1 string `xml:"space1 x>c"`
810 D1 string `xml:"space1 x>d"`
811 }{
812 A: "a",
813 B: "b",
814 C: "c",
815 C1: "c1",
816 D1: "d1",
817 },
818 ExpectXML: `<top xmlns="space">` +
819 `<x><a>a</a><b>b</b><c xmlns="space">c</c>` +
820 `<c xmlns="space1">c1</c>` +
821 `<d xmlns="space1">d1</d>` +
822 `</x>` +
823 `</top>`,
824 },
825 {
826 Value: &struct {
827 XMLName Name
828 A string `xml:"x>a"`
829 B string `xml:"x>b"`
830 C string `xml:"space x>c"`
831 C1 string `xml:"space1 x>c"`
832 D1 string `xml:"space1 x>d"`
833 }{
834 XMLName: Name{
835 Space: "space0",
836 Local: "top",
837 },
838 A: "a",
839 B: "b",
840 C: "c",
841 C1: "c1",
842 D1: "d1",
843 },
844 ExpectXML: `<top xmlns="space0">` +
845 `<x><a>a</a><b>b</b>` +
846 `<c xmlns="space">c</c>` +
847 `<c xmlns="space1">c1</c>` +
848 `<d xmlns="space1">d1</d>` +
849 `</x>` +
850 `</top>`,
851 },
852 {
853 Value: &struct {
854 XMLName struct{} `xml:"top"`
855 B string `xml:"space x>b"`
856 B1 string `xml:"space1 x>b"`
857 }{
858 B: "b",
859 B1: "b1",
860 },
861 ExpectXML: `<top>` +
862 `<x><b xmlns="space">b</b>` +
863 `<b xmlns="space1">b1</b></x>` +
864 `</top>`,
865 },
866
867 // Test struct embedding
868 {
869 Value: &EmbedA{
870 EmbedC: EmbedC{
871 FieldA1: "", // Shadowed by A.A
872 FieldA2: "", // Shadowed by A.A
873 FieldB: "A.C.B",
874 FieldC: "A.C.C",
875 },
876 EmbedB: EmbedB{
877 FieldB: "A.B.B",
878 EmbedC: &EmbedC{
879 FieldA1: "A.B.C.A1",
880 FieldA2: "A.B.C.A2",
881 FieldB: "", // Shadowed by A.B.B
882 FieldC: "A.B.C.C",
883 },
884 },
885 FieldA: "A.A",
886 embedD: embedD{
887 FieldE: "A.D.E",
888 },
889 },
890 ExpectXML: `<EmbedA>` +
891 `<FieldB>A.C.B</FieldB>` +
892 `<FieldC>A.C.C</FieldC>` +
893 `<EmbedB>` +
894 `<FieldB>A.B.B</FieldB>` +
895 `<FieldA>` +
896 `<A1>A.B.C.A1</A1>` +
897 `<A2>A.B.C.A2</A2>` +
898 `</FieldA>` +
899 `<FieldC>A.B.C.C</FieldC>` +
900 `</EmbedB>` +
901 `<FieldA>A.A</FieldA>` +
902 `<FieldE>A.D.E</FieldE>` +
903 `</EmbedA>`,
904 },
905
906 // Anonymous struct pointer field which is nil
907 {
908 Value: &EmbedB{},
909 ExpectXML: `<EmbedB><FieldB></FieldB></EmbedB>`,
910 },
911
912 // Other kinds of nil anonymous fields
913 {
914 Value: &PointerAnonFields{},
915 ExpectXML: `<PointerAnonFields></PointerAnonFields>`,
916 },
917
918 // Test that name casing matters
919 {
920 Value: &NameCasing{Xy: "mixed", XY: "upper", XyA: "mixedA", XYA: "upperA"},
921 ExpectXML: `<casing Xy="mixedA" XY="upperA"><Xy>mixed</Xy><XY>upper</XY></casing>`,
922 },
923
924 // Test the order in which the XML element name is chosen
925 {
926 Value: &NamePrecedence{
927 FromTag: XMLNameWithoutTag{Value: "A"},
928 FromNameVal: XMLNameWithoutTag{XMLName: Name{Local: "InXMLName"}, Value: "B"},
929 FromNameTag: XMLNameWithTag{Value: "C"},
930 InFieldName: "D",
931 },
932 ExpectXML: `<Parent>` +
933 `<InTag>A</InTag>` +
934 `<InXMLName>B</InXMLName>` +
935 `<InXMLNameTag>C</InXMLNameTag>` +
936 `<InFieldName>D</InFieldName>` +
937 `</Parent>`,
938 MarshalOnly: true,
939 },
940 {
941 Value: &NamePrecedence{
942 XMLName: Name{Local: "Parent"},
943 FromTag: XMLNameWithoutTag{XMLName: Name{Local: "InTag"}, Value: "A"},
944 FromNameVal: XMLNameWithoutTag{XMLName: Name{Local: "FromNameVal"}, Value: "B"},
945 FromNameTag: XMLNameWithTag{XMLName: Name{Local: "InXMLNameTag"}, Value: "C"},
946 InFieldName: "D",
947 },
948 ExpectXML: `<Parent>` +
949 `<InTag>A</InTag>` +
950 `<FromNameVal>B</FromNameVal>` +
951 `<InXMLNameTag>C</InXMLNameTag>` +
952 `<InFieldName>D</InFieldName>` +
953 `</Parent>`,
954 UnmarshalOnly: true,
955 },
956
957 // xml.Name works in a plain field as well.
958 {
959 Value: &NameInField{Name{Space: "ns", Local: "foo"}},
960 ExpectXML: `<NameInField><foo xmlns="ns"></foo></NameInField>`,
961 },
962 {
963 Value: &NameInField{Name{Space: "ns", Local: "foo"}},
964 ExpectXML: `<NameInField><foo xmlns="ns"><ignore></ignore></foo></NameInField>`,
965 UnmarshalOnly: true,
966 },
967
968 // Marshaling zero xml.Name uses the tag or field name.
969 {
970 Value: &NameInField{},
971 ExpectXML: `<NameInField><foo xmlns="ns"></foo></NameInField>`,
972 MarshalOnly: true,
973 },
974
975 // Test attributes
976 {
977 Value: &AttrTest{
978 Int: 8,
979 Named: 9,
980 Float: 23.5,
981 Uint8: 255,
982 Bool: true,
983 Str: "str",
984 Bytes: []byte("byt"),
985 },
986 ExpectXML: `<AttrTest Int="8" int="9" Float="23.5" Uint8="255"` +
987 ` Bool="true" Str="str" Bytes="byt"></AttrTest>`,
988 },
989 {
990 Value: &AttrTest{Bytes: []byte{}},
991 ExpectXML: `<AttrTest Int="0" int="0" Float="0" Uint8="0"` +
992 ` Bool="false" Str="" Bytes=""></AttrTest>`,
993 },
994 {
995 Value: &AttrsTest{
996 Attrs: []Attr{
997 {Name: Name{Local: "Answer"}, Value: "42"},
998 {Name: Name{Local: "Int"}, Value: "8"},
999 {Name: Name{Local: "int"}, Value: "9"},
1000 {Name: Name{Local: "Float"}, Value: "23.5"},
1001 {Name: Name{Local: "Uint8"}, Value: "255"},
1002 {Name: Name{Local: "Bool"}, Value: "true"},
1003 {Name: Name{Local: "Str"}, Value: "str"},
1004 {Name: Name{Local: "Bytes"}, Value: "byt"},
1005 },
1006 },
1007 ExpectXML: `<AttrsTest Answer="42" Int="8" int="9" Float="23.5" Uint8="255" Bool="true" Str="str" Bytes="byt" Int="0" int="0" Float="0" Uint8="0" Bool="false" Str="" Bytes=""></AttrsTest>`,
1008 MarshalOnly: true,
1009 },
1010 {
1011 Value: &AttrsTest{
1012 Attrs: []Attr{
1013 {Name: Name{Local: "Answer"}, Value: "42"},
1014 },
1015 Int: 8,
1016 Named: 9,
1017 Float: 23.5,
1018 Uint8: 255,
1019 Bool: true,
1020 Str: "str",
1021 Bytes: []byte("byt"),
1022 },
1023 ExpectXML: `<AttrsTest Answer="42" Int="8" int="9" Float="23.5" Uint8="255" Bool="true" Str="str" Bytes="byt"></AttrsTest>`,
1024 },
1025 {
1026 Value: &AttrsTest{
1027 Attrs: []Attr{
1028 {Name: Name{Local: "Int"}, Value: "0"},
1029 {Name: Name{Local: "int"}, Value: "0"},
1030 {Name: Name{Local: "Float"}, Value: "0"},
1031 {Name: Name{Local: "Uint8"}, Value: "0"},
1032 {Name: Name{Local: "Bool"}, Value: "false"},
1033 {Name: Name{Local: "Str"}},
1034 {Name: Name{Local: "Bytes"}},
1035 },
1036 Bytes: []byte{},
1037 },
1038 ExpectXML: `<AttrsTest Int="0" int="0" Float="0" Uint8="0" Bool="false" Str="" Bytes="" Int="0" int="0" Float="0" Uint8="0" Bool="false" Str="" Bytes=""></AttrsTest>`,
1039 MarshalOnly: true,
1040 },
1041 {
1042 Value: &OmitAttrTest{
1043 Int: 8,
1044 Named: 9,
1045 Float: 23.5,
1046 Uint8: 255,
1047 Bool: true,
1048 Str: "str",
1049 Bytes: []byte("byt"),
1050 PStr: &empty,
1051 },
1052 ExpectXML: `<OmitAttrTest Int="8" int="9" Float="23.5" Uint8="255"` +
1053 ` Bool="true" Str="str" Bytes="byt" PStr=""></OmitAttrTest>`,
1054 },
1055 {
1056 Value: &OmitAttrTest{},
1057 ExpectXML: `<OmitAttrTest></OmitAttrTest>`,
1058 },
1059
1060 // pointer fields
1061 {
1062 Value: &PointerFieldsTest{Name: &nameAttr, Age: &ageAttr, Contents: &contentsAttr},
1063 ExpectXML: `<dummy name="Sarah" age="12">lorem ipsum</dummy>`,
1064 MarshalOnly: true,
1065 },
1066
1067 // empty chardata pointer field
1068 {
1069 Value: &ChardataEmptyTest{},
1070 ExpectXML: `<test></test>`,
1071 MarshalOnly: true,
1072 },
1073
1074 // omitempty on fields
1075 {
1076 Value: &OmitFieldTest{
1077 Int: 8,
1078 Named: 9,
1079 Float: 23.5,
1080 Uint8: 255,
1081 Bool: true,
1082 Str: "str",
1083 Bytes: []byte("byt"),
1084 PStr: &empty,
1085 Ptr: &PresenceTest{},
1086 },
1087 ExpectXML: `<OmitFieldTest>` +
1088 `<Int>8</Int>` +
1089 `<int>9</int>` +
1090 `<Float>23.5</Float>` +
1091 `<Uint8>255</Uint8>` +
1092 `<Bool>true</Bool>` +
1093 `<Str>str</Str>` +
1094 `<Bytes>byt</Bytes>` +
1095 `<PStr></PStr>` +
1096 `<Ptr></Ptr>` +
1097 `</OmitFieldTest>`,
1098 },
1099 {
1100 Value: &OmitFieldTest{},
1101 ExpectXML: `<OmitFieldTest></OmitFieldTest>`,
1102 },
1103
1104 // Test ",any"
1105 {
1106 ExpectXML: `<a><nested><value>known</value></nested><other><sub>unknown</sub></other></a>`,
1107 Value: &AnyTest{
1108 Nested: "known",
1109 AnyField: AnyHolder{
1110 XMLName: Name{Local: "other"},
1111 XML: "<sub>unknown</sub>",
1112 },
1113 },
1114 },
1115 {
1116 Value: &AnyTest{Nested: "known",
1117 AnyField: AnyHolder{
1118 XML: "<unknown/>",
1119 XMLName: Name{Local: "AnyField"},
1120 },
1121 },
1122 ExpectXML: `<a><nested><value>known</value></nested><AnyField><unknown/></AnyField></a>`,
1123 },
1124 {
1125 ExpectXML: `<a><nested><value>b</value></nested></a>`,
1126 Value: &AnyOmitTest{
1127 Nested: "b",
1128 },
1129 },
1130 {
1131 ExpectXML: `<a><nested><value>b</value></nested><c><d>e</d></c><g xmlns="f"><h>i</h></g></a>`,
1132 Value: &AnySliceTest{
1133 Nested: "b",
1134 AnyField: []AnyHolder{
1135 {
1136 XMLName: Name{Local: "c"},
1137 XML: "<d>e</d>",
1138 },
1139 {
1140 XMLName: Name{Space: "f", Local: "g"},
1141 XML: "<h>i</h>",
1142 },
1143 },
1144 },
1145 },
1146 {
1147 ExpectXML: `<a><nested><value>b</value></nested></a>`,
1148 Value: &AnySliceTest{
1149 Nested: "b",
1150 },
1151 },
1152
1153 // Test recursive types.
1154 {
1155 Value: &RecurseA{
1156 A: "a1",
1157 B: &RecurseB{
1158 A: &RecurseA{"a2", nil},
1159 B: "b1",
1160 },
1161 },
1162 ExpectXML: `<RecurseA><A>a1</A><B><A><A>a2</A></A><B>b1</B></B></RecurseA>`,
1163 },
1164
1165 // Test ignoring fields via "-" tag
1166 {
1167 ExpectXML: `<IgnoreTest></IgnoreTest>`,
1168 Value: &IgnoreTest{},
1169 },
1170 {
1171 ExpectXML: `<IgnoreTest></IgnoreTest>`,
1172 Value: &IgnoreTest{PublicSecret: "can't tell"},
1173 MarshalOnly: true,
1174 },
1175 {
1176 ExpectXML: `<IgnoreTest><PublicSecret>ignore me</PublicSecret></IgnoreTest>`,
1177 Value: &IgnoreTest{},
1178 UnmarshalOnly: true,
1179 },
1180
1181 // Test escaping.
1182 {
1183 ExpectXML: `<a><nested><value>dquote: &#34;; squote: &#39;; ampersand: &amp;; less: &lt;; greater: &gt;;</value></nested><empty></empty></a>`,
1184 Value: &AnyTest{
1185 Nested: `dquote: "; squote: '; ampersand: &; less: <; greater: >;`,
1186 AnyField: AnyHolder{XMLName: Name{Local: "empty"}},
1187 },
1188 },
1189 {
1190 ExpectXML: `<a><nested><value>newline: &#xA;; cr: &#xD;; tab: &#x9;;</value></nested><AnyField></AnyField></a>`,
1191 Value: &AnyTest{
1192 Nested: "newline: \n; cr: \r; tab: \t;",
1193 AnyField: AnyHolder{XMLName: Name{Local: "AnyField"}},
1194 },
1195 },
1196 {
1197 ExpectXML: "<a><nested><value>1\r2\r\n3\n\r4\n5</value></nested></a>",
1198 Value: &AnyTest{
1199 Nested: "1\n2\n3\n\n4\n5",
1200 },
1201 UnmarshalOnly: true,
1202 },
1203 {
1204 ExpectXML: `<EmbedInt><MyInt>42</MyInt></EmbedInt>`,
1205 Value: &EmbedInt{
1206 MyInt: 42,
1207 },
1208 },
1209 // Test outputting CDATA-wrapped text.
1210 {
1211 ExpectXML: `<CDataTest></CDataTest>`,
1212 Value: &CDataTest{},
1213 },
1214 {
1215 ExpectXML: `<CDataTest><![CDATA[http://example.com/tests/1?foo=1&bar=baz]]></CDataTest>`,
1216 Value: &CDataTest{
1217 Chardata: "http://example.com/tests/1?foo=1&bar=baz",
1218 },
1219 },
1220 {
1221 ExpectXML: `<CDataTest><![CDATA[Literal <![CDATA[Nested]]]]><![CDATA[>!]]></CDataTest>`,
1222 Value: &CDataTest{
1223 Chardata: "Literal <![CDATA[Nested]]>!",
1224 },
1225 },
1226 {
1227 ExpectXML: `<CDataTest><![CDATA[<![CDATA[Nested]]]]><![CDATA[> Literal!]]></CDataTest>`,
1228 Value: &CDataTest{
1229 Chardata: "<![CDATA[Nested]]> Literal!",
1230 },
1231 },
1232 {
1233 ExpectXML: `<CDataTest><![CDATA[<![CDATA[Nested]]]]><![CDATA[> Literal! <![CDATA[Nested]]]]><![CDATA[> Literal!]]></CDataTest>`,
1234 Value: &CDataTest{
1235 Chardata: "<![CDATA[Nested]]> Literal! <![CDATA[Nested]]> Literal!",
1236 },
1237 },
1238 {
1239 ExpectXML: `<CDataTest><![CDATA[<![CDATA[<![CDATA[Nested]]]]><![CDATA[>]]]]><![CDATA[>]]></CDataTest>`,
1240 Value: &CDataTest{
1241 Chardata: "<![CDATA[<![CDATA[Nested]]>]]>",
1242 },
1243 },
1244
1245 // Test omitempty with parent chain; see golang.org/issue/4168.
1246 {
1247 ExpectXML: `<Strings><A></A></Strings>`,
1248 Value: &Strings{},
1249 },
1250 // Custom marshalers.
1251 {
1252 ExpectXML: `<MyMarshalerTest>hello world</MyMarshalerTest>`,
1253 Value: &MyMarshalerTest{},
1254 },
1255 {
1256 ExpectXML: `<MarshalerStruct Foo="hello world"></MarshalerStruct>`,
1257 Value: &MarshalerStruct{},
1258 },
1259 {
1260 ExpectXML: `<outer xmlns="testns" int="10"></outer>`,
1261 Value: &OuterStruct{IntAttr: 10},
1262 },
1263 {
1264 ExpectXML: `<test xmlns="outerns" int="10"></test>`,
1265 Value: &OuterNamedStruct{XMLName: Name{Space: "outerns", Local: "test"}, IntAttr: 10},
1266 },
1267 {
1268 ExpectXML: `<test xmlns="outerns" int="10"></test>`,
1269 Value: &OuterNamedOrderedStruct{XMLName: Name{Space: "outerns", Local: "test"}, IntAttr: 10},
1270 },
1271 {
1272 ExpectXML: `<outer xmlns="testns" int="10"></outer>`,
1273 Value: &OuterOuterStruct{OuterStruct{IntAttr: 10}},
1274 },
1275 {
1276 ExpectXML: `<NestedAndChardata><A><B></B><B></B></A>test</NestedAndChardata>`,
1277 Value: &NestedAndChardata{AB: make([]string, 2), Chardata: "test"},
1278 },
1279 {
1280 ExpectXML: `<NestedAndComment><A><B></B><B></B></A><!--test--></NestedAndComment>`,
1281 Value: &NestedAndComment{AB: make([]string, 2), Comment: "test"},
1282 },
1283 {
1284 ExpectXML: `<NestedAndCData><A><B></B><B></B></A><![CDATA[test]]></NestedAndCData>`,
1285 Value: &NestedAndCData{AB: make([]string, 2), CDATA: "test"},
1286 },
1287 // Test pointer indirection in various kinds of fields.
1288 // https://golang.org/issue/19063
1289 {
1290 ExpectXML: `<IndirComment><T1></T1><!--hi--><T2></T2></IndirComment>`,
1291 Value: &IndirComment{Comment: stringptr("hi")},
1292 MarshalOnly: true,
1293 },
1294 {
1295 ExpectXML: `<IndirComment><T1></T1><T2></T2></IndirComment>`,
1296 Value: &IndirComment{Comment: stringptr("")},
1297 MarshalOnly: true,
1298 },
1299 {
1300 ExpectXML: `<IndirComment><T1></T1><T2></T2></IndirComment>`,
1301 Value: &IndirComment{Comment: nil},
1302 MarshalError: "xml: bad type for comment field of xml.IndirComment",
1303 },
1304 {
1305 ExpectXML: `<IndirComment><T1></T1><!--hi--><T2></T2></IndirComment>`,
1306 Value: &IndirComment{Comment: nil},
1307 UnmarshalOnly: true,
1308 },
1309 {
1310 ExpectXML: `<IfaceComment><T1></T1><!--hi--><T2></T2></IfaceComment>`,
1311 Value: &IfaceComment{Comment: "hi"},
1312 MarshalOnly: true,
1313 },
1314 {
1315 ExpectXML: `<IfaceComment><T1></T1><!--hi--><T2></T2></IfaceComment>`,
1316 Value: &IfaceComment{Comment: nil},
1317 UnmarshalOnly: true,
1318 },
1319 {
1320 ExpectXML: `<IfaceComment><T1></T1><T2></T2></IfaceComment>`,
1321 Value: &IfaceComment{Comment: nil},
1322 MarshalError: "xml: bad type for comment field of xml.IfaceComment",
1323 },
1324 {
1325 ExpectXML: `<IfaceComment><T1></T1><T2></T2></IfaceComment>`,
1326 Value: &IfaceComment{Comment: nil},
1327 UnmarshalOnly: true,
1328 },
1329 {
1330 ExpectXML: `<DirectComment><T1></T1><!--hi--><T2></T2></DirectComment>`,
1331 Value: &DirectComment{Comment: string("hi")},
1332 },
1333 {
1334 ExpectXML: `<DirectComment><T1></T1><T2></T2></DirectComment>`,
1335 Value: &DirectComment{Comment: string("")},
1336 },
1337 {
1338 ExpectXML: `<IndirChardata><T1></T1>hi<T2></T2></IndirChardata>`,
1339 Value: &IndirChardata{Chardata: stringptr("hi")},
1340 },
1341 {
1342 ExpectXML: `<IndirChardata><T1></T1><![CDATA[hi]]><T2></T2></IndirChardata>`,
1343 Value: &IndirChardata{Chardata: stringptr("hi")},
1344 UnmarshalOnly: true, // marshals without CDATA
1345 },
1346 {
1347 ExpectXML: `<IndirChardata><T1></T1><T2></T2></IndirChardata>`,
1348 Value: &IndirChardata{Chardata: stringptr("")},
1349 },
1350 {
1351 ExpectXML: `<IndirChardata><T1></T1><T2></T2></IndirChardata>`,
1352 Value: &IndirChardata{Chardata: nil},
1353 MarshalOnly: true, // unmarshal leaves Chardata=stringptr("")
1354 },
1355 {
1356 ExpectXML: `<IfaceChardata><T1></T1>hi<T2></T2></IfaceChardata>`,
1357 Value: &IfaceChardata{Chardata: string("hi")},
1358 UnmarshalError: "cannot unmarshal into interface {}",
1359 },
1360 {
1361 ExpectXML: `<IfaceChardata><T1></T1><![CDATA[hi]]><T2></T2></IfaceChardata>`,
1362 Value: &IfaceChardata{Chardata: string("hi")},
1363 UnmarshalOnly: true, // marshals without CDATA
1364 UnmarshalError: "cannot unmarshal into interface {}",
1365 },
1366 {
1367 ExpectXML: `<IfaceChardata><T1></T1><T2></T2></IfaceChardata>`,
1368 Value: &IfaceChardata{Chardata: string("")},
1369 UnmarshalError: "cannot unmarshal into interface {}",
1370 },
1371 {
1372 ExpectXML: `<IfaceChardata><T1></T1><T2></T2></IfaceChardata>`,
1373 Value: &IfaceChardata{Chardata: nil},
1374 UnmarshalError: "cannot unmarshal into interface {}",
1375 },
1376 {
1377 ExpectXML: `<DirectChardata><T1></T1>hi<T2></T2></DirectChardata>`,
1378 Value: &DirectChardata{Chardata: string("hi")},
1379 },
1380 {
1381 ExpectXML: `<DirectChardata><T1></T1><![CDATA[hi]]><T2></T2></DirectChardata>`,
1382 Value: &DirectChardata{Chardata: string("hi")},
1383 UnmarshalOnly: true, // marshals without CDATA
1384 },
1385 {
1386 ExpectXML: `<DirectChardata><T1></T1><T2></T2></DirectChardata>`,
1387 Value: &DirectChardata{Chardata: string("")},
1388 },
1389 {
1390 ExpectXML: `<IndirCDATA><T1></T1><![CDATA[hi]]><T2></T2></IndirCDATA>`,
1391 Value: &IndirCDATA{CDATA: stringptr("hi")},
1392 },
1393 {
1394 ExpectXML: `<IndirCDATA><T1></T1>hi<T2></T2></IndirCDATA>`,
1395 Value: &IndirCDATA{CDATA: stringptr("hi")},
1396 UnmarshalOnly: true, // marshals with CDATA
1397 },
1398 {
1399 ExpectXML: `<IndirCDATA><T1></T1><T2></T2></IndirCDATA>`,
1400 Value: &IndirCDATA{CDATA: stringptr("")},
1401 },
1402 {
1403 ExpectXML: `<IndirCDATA><T1></T1><T2></T2></IndirCDATA>`,
1404 Value: &IndirCDATA{CDATA: nil},
1405 MarshalOnly: true, // unmarshal leaves CDATA=stringptr("")
1406 },
1407 {
1408 ExpectXML: `<IfaceCDATA><T1></T1><![CDATA[hi]]><T2></T2></IfaceCDATA>`,
1409 Value: &IfaceCDATA{CDATA: string("hi")},
1410 UnmarshalError: "cannot unmarshal into interface {}",
1411 },
1412 {
1413 ExpectXML: `<IfaceCDATA><T1></T1>hi<T2></T2></IfaceCDATA>`,
1414 Value: &IfaceCDATA{CDATA: string("hi")},
1415 UnmarshalOnly: true, // marshals with CDATA
1416 UnmarshalError: "cannot unmarshal into interface {}",
1417 },
1418 {
1419 ExpectXML: `<IfaceCDATA><T1></T1><T2></T2></IfaceCDATA>`,
1420 Value: &IfaceCDATA{CDATA: string("")},
1421 UnmarshalError: "cannot unmarshal into interface {}",
1422 },
1423 {
1424 ExpectXML: `<IfaceCDATA><T1></T1><T2></T2></IfaceCDATA>`,
1425 Value: &IfaceCDATA{CDATA: nil},
1426 UnmarshalError: "cannot unmarshal into interface {}",
1427 },
1428 {
1429 ExpectXML: `<DirectCDATA><T1></T1><![CDATA[hi]]><T2></T2></DirectCDATA>`,
1430 Value: &DirectCDATA{CDATA: string("hi")},
1431 },
1432 {
1433 ExpectXML: `<DirectCDATA><T1></T1>hi<T2></T2></DirectCDATA>`,
1434 Value: &DirectCDATA{CDATA: string("hi")},
1435 UnmarshalOnly: true, // marshals with CDATA
1436 },
1437 {
1438 ExpectXML: `<DirectCDATA><T1></T1><T2></T2></DirectCDATA>`,
1439 Value: &DirectCDATA{CDATA: string("")},
1440 },
1441 {
1442 ExpectXML: `<IndirInnerXML><T1></T1><hi/><T2></T2></IndirInnerXML>`,
1443 Value: &IndirInnerXML{InnerXML: stringptr("<hi/>")},
1444 MarshalOnly: true,
1445 },
1446 {
1447 ExpectXML: `<IndirInnerXML><T1></T1><T2></T2></IndirInnerXML>`,
1448 Value: &IndirInnerXML{InnerXML: stringptr("")},
1449 MarshalOnly: true,
1450 },
1451 {
1452 ExpectXML: `<IndirInnerXML><T1></T1><T2></T2></IndirInnerXML>`,
1453 Value: &IndirInnerXML{InnerXML: nil},
1454 },
1455 {
1456 ExpectXML: `<IndirInnerXML><T1></T1><hi/><T2></T2></IndirInnerXML>`,
1457 Value: &IndirInnerXML{InnerXML: nil},
1458 UnmarshalOnly: true,
1459 },
1460 {
1461 ExpectXML: `<IfaceInnerXML><T1></T1><hi/><T2></T2></IfaceInnerXML>`,
1462 Value: &IfaceInnerXML{InnerXML: "<hi/>"},
1463 MarshalOnly: true,
1464 },
1465 {
1466 ExpectXML: `<IfaceInnerXML><T1></T1><hi/><T2></T2></IfaceInnerXML>`,
1467 Value: &IfaceInnerXML{InnerXML: nil},
1468 UnmarshalOnly: true,
1469 },
1470 {
1471 ExpectXML: `<IfaceInnerXML><T1></T1><T2></T2></IfaceInnerXML>`,
1472 Value: &IfaceInnerXML{InnerXML: nil},
1473 },
1474 {
1475 ExpectXML: `<IfaceInnerXML><T1></T1><T2></T2></IfaceInnerXML>`,
1476 Value: &IfaceInnerXML{InnerXML: nil},
1477 UnmarshalOnly: true,
1478 },
1479 {
1480 ExpectXML: `<DirectInnerXML><T1></T1><hi/><T2></T2></DirectInnerXML>`,
1481 Value: &DirectInnerXML{InnerXML: string("<hi/>")},
1482 MarshalOnly: true,
1483 },
1484 {
1485 ExpectXML: `<DirectInnerXML><T1></T1><hi/><T2></T2></DirectInnerXML>`,
1486 Value: &DirectInnerXML{InnerXML: string("<T1></T1><hi/><T2></T2>")},
1487 UnmarshalOnly: true,
1488 },
1489 {
1490 ExpectXML: `<DirectInnerXML><T1></T1><T2></T2></DirectInnerXML>`,
1491 Value: &DirectInnerXML{InnerXML: string("")},
1492 MarshalOnly: true,
1493 },
1494 {
1495 ExpectXML: `<DirectInnerXML><T1></T1><T2></T2></DirectInnerXML>`,
1496 Value: &DirectInnerXML{InnerXML: string("<T1></T1><T2></T2>")},
1497 UnmarshalOnly: true,
1498 },
1499 {
1500 ExpectXML: `<IndirElement><T1></T1><Element>hi</Element><T2></T2></IndirElement>`,
1501 Value: &IndirElement{Element: stringptr("hi")},
1502 },
1503 {
1504 ExpectXML: `<IndirElement><T1></T1><Element></Element><T2></T2></IndirElement>`,
1505 Value: &IndirElement{Element: stringptr("")},
1506 },
1507 {
1508 ExpectXML: `<IndirElement><T1></T1><T2></T2></IndirElement>`,
1509 Value: &IndirElement{Element: nil},
1510 },
1511 {
1512 ExpectXML: `<IfaceElement><T1></T1><Element>hi</Element><T2></T2></IfaceElement>`,
1513 Value: &IfaceElement{Element: "hi"},
1514 MarshalOnly: true,
1515 },
1516 {
1517 ExpectXML: `<IfaceElement><T1></T1><Element>hi</Element><T2></T2></IfaceElement>`,
1518 Value: &IfaceElement{Element: nil},
1519 UnmarshalOnly: true,
1520 },
1521 {
1522 ExpectXML: `<IfaceElement><T1></T1><T2></T2></IfaceElement>`,
1523 Value: &IfaceElement{Element: nil},
1524 },
1525 {
1526 ExpectXML: `<IfaceElement><T1></T1><T2></T2></IfaceElement>`,
1527 Value: &IfaceElement{Element: nil},
1528 UnmarshalOnly: true,
1529 },
1530 {
1531 ExpectXML: `<DirectElement><T1></T1><Element>hi</Element><T2></T2></DirectElement>`,
1532 Value: &DirectElement{Element: string("hi")},
1533 },
1534 {
1535 ExpectXML: `<DirectElement><T1></T1><Element></Element><T2></T2></DirectElement>`,
1536 Value: &DirectElement{Element: string("")},
1537 },
1538 {
1539 ExpectXML: `<IndirOmitEmpty><T1></T1><OmitEmpty>hi</OmitEmpty><T2></T2></IndirOmitEmpty>`,
1540 Value: &IndirOmitEmpty{OmitEmpty: stringptr("hi")},
1541 },
1542 {
1543 // Note: Changed in Go 1.8 to include <OmitEmpty> element (because x.OmitEmpty != nil).
1544 ExpectXML: `<IndirOmitEmpty><T1></T1><OmitEmpty></OmitEmpty><T2></T2></IndirOmitEmpty>`,
1545 Value: &IndirOmitEmpty{OmitEmpty: stringptr("")},
1546 MarshalOnly: true,
1547 },
1548 {
1549 ExpectXML: `<IndirOmitEmpty><T1></T1><OmitEmpty></OmitEmpty><T2></T2></IndirOmitEmpty>`,
1550 Value: &IndirOmitEmpty{OmitEmpty: stringptr("")},
1551 UnmarshalOnly: true,
1552 },
1553 {
1554 ExpectXML: `<IndirOmitEmpty><T1></T1><T2></T2></IndirOmitEmpty>`,
1555 Value: &IndirOmitEmpty{OmitEmpty: nil},
1556 },
1557 {
1558 ExpectXML: `<IfaceOmitEmpty><T1></T1><OmitEmpty>hi</OmitEmpty><T2></T2></IfaceOmitEmpty>`,
1559 Value: &IfaceOmitEmpty{OmitEmpty: "hi"},
1560 MarshalOnly: true,
1561 },
1562 {
1563 ExpectXML: `<IfaceOmitEmpty><T1></T1><OmitEmpty>hi</OmitEmpty><T2></T2></IfaceOmitEmpty>`,
1564 Value: &IfaceOmitEmpty{OmitEmpty: nil},
1565 UnmarshalOnly: true,
1566 },
1567 {
1568 ExpectXML: `<IfaceOmitEmpty><T1></T1><T2></T2></IfaceOmitEmpty>`,
1569 Value: &IfaceOmitEmpty{OmitEmpty: nil},
1570 },
1571 {
1572 ExpectXML: `<IfaceOmitEmpty><T1></T1><T2></T2></IfaceOmitEmpty>`,
1573 Value: &IfaceOmitEmpty{OmitEmpty: nil},
1574 UnmarshalOnly: true,
1575 },
1576 {
1577 ExpectXML: `<DirectOmitEmpty><T1></T1><OmitEmpty>hi</OmitEmpty><T2></T2></DirectOmitEmpty>`,
1578 Value: &DirectOmitEmpty{OmitEmpty: string("hi")},
1579 },
1580 {
1581 ExpectXML: `<DirectOmitEmpty><T1></T1><T2></T2></DirectOmitEmpty>`,
1582 Value: &DirectOmitEmpty{OmitEmpty: string("")},
1583 },
1584 {
1585 ExpectXML: `<IndirAny><T1></T1><Any>hi</Any><T2></T2></IndirAny>`,
1586 Value: &IndirAny{Any: stringptr("hi")},
1587 },
1588 {
1589 ExpectXML: `<IndirAny><T1></T1><Any></Any><T2></T2></IndirAny>`,
1590 Value: &IndirAny{Any: stringptr("")},
1591 },
1592 {
1593 ExpectXML: `<IndirAny><T1></T1><T2></T2></IndirAny>`,
1594 Value: &IndirAny{Any: nil},
1595 },
1596 {
1597 ExpectXML: `<IfaceAny><T1></T1><Any>hi</Any><T2></T2></IfaceAny>`,
1598 Value: &IfaceAny{Any: "hi"},
1599 MarshalOnly: true,
1600 },
1601 {
1602 ExpectXML: `<IfaceAny><T1></T1><Any>hi</Any><T2></T2></IfaceAny>`,
1603 Value: &IfaceAny{Any: nil},
1604 UnmarshalOnly: true,
1605 },
1606 {
1607 ExpectXML: `<IfaceAny><T1></T1><T2></T2></IfaceAny>`,
1608 Value: &IfaceAny{Any: nil},
1609 },
1610 {
1611 ExpectXML: `<IfaceAny><T1></T1><T2></T2></IfaceAny>`,
1612 Value: &IfaceAny{Any: nil},
1613 UnmarshalOnly: true,
1614 },
1615 {
1616 ExpectXML: `<DirectAny><T1></T1><Any>hi</Any><T2></T2></DirectAny>`,
1617 Value: &DirectAny{Any: string("hi")},
1618 },
1619 {
1620 ExpectXML: `<DirectAny><T1></T1><Any></Any><T2></T2></DirectAny>`,
1621 Value: &DirectAny{Any: string("")},
1622 },
1623 {
1624 ExpectXML: `<IndirFoo><T1></T1><Foo>hi</Foo><T2></T2></IndirFoo>`,
1625 Value: &IndirAny{Any: stringptr("hi")},
1626 UnmarshalOnly: true,
1627 },
1628 {
1629 ExpectXML: `<IndirFoo><T1></T1><Foo></Foo><T2></T2></IndirFoo>`,
1630 Value: &IndirAny{Any: stringptr("")},
1631 UnmarshalOnly: true,
1632 },
1633 {
1634 ExpectXML: `<IndirFoo><T1></T1><T2></T2></IndirFoo>`,
1635 Value: &IndirAny{Any: nil},
1636 UnmarshalOnly: true,
1637 },
1638 {
1639 ExpectXML: `<IfaceFoo><T1></T1><Foo>hi</Foo><T2></T2></IfaceFoo>`,
1640 Value: &IfaceAny{Any: nil},
1641 UnmarshalOnly: true,
1642 },
1643 {
1644 ExpectXML: `<IfaceFoo><T1></T1><T2></T2></IfaceFoo>`,
1645 Value: &IfaceAny{Any: nil},
1646 UnmarshalOnly: true,
1647 },
1648 {
1649 ExpectXML: `<IfaceFoo><T1></T1><T2></T2></IfaceFoo>`,
1650 Value: &IfaceAny{Any: nil},
1651 UnmarshalOnly: true,
1652 },
1653 {
1654 ExpectXML: `<DirectFoo><T1></T1><Foo>hi</Foo><T2></T2></DirectFoo>`,
1655 Value: &DirectAny{Any: string("hi")},
1656 UnmarshalOnly: true,
1657 },
1658 {
1659 ExpectXML: `<DirectFoo><T1></T1><Foo></Foo><T2></T2></DirectFoo>`,
1660 Value: &DirectAny{Any: string("")},
1661 UnmarshalOnly: true,
1662 },
1663 }
1664
1665 func TestMarshal(t *testing.T) {
1666 for idx, test := range marshalTests {
1667 if test.UnmarshalOnly {
1668 continue
1669 }
1670
1671 t.Run(fmt.Sprintf("%d", idx), func(t *testing.T) {
1672 data, err := Marshal(test.Value)
1673 if err != nil {
1674 if test.MarshalError == "" {
1675 t.Errorf("marshal(%#v): %s", test.Value, err)
1676 return
1677 }
1678 if !strings.Contains(err.Error(), test.MarshalError) {
1679 t.Errorf("marshal(%#v): %s, want %q", test.Value, err, test.MarshalError)
1680 }
1681 return
1682 }
1683 if test.MarshalError != "" {
1684 t.Errorf("Marshal succeeded, want error %q", test.MarshalError)
1685 return
1686 }
1687 if got, want := string(data), test.ExpectXML; got != want {
1688 if strings.Contains(want, "\n") {
1689 t.Errorf("marshal(%#v):\nHAVE:\n%s\nWANT:\n%s", test.Value, got, want)
1690 } else {
1691 t.Errorf("marshal(%#v):\nhave %#q\nwant %#q", test.Value, got, want)
1692 }
1693 }
1694 })
1695 }
1696 }
1697
1698 type AttrParent struct {
1699 X string `xml:"X>Y,attr"`
1700 }
1701
1702 type BadAttr struct {
1703 Name map[string]string `xml:"name,attr"`
1704 }
1705
1706 var marshalErrorTests = []struct {
1707 Value any
1708 Err string
1709 Kind reflect.Kind
1710 }{
1711 {
1712 Value: make(chan bool),
1713 Err: "xml: unsupported type: chan bool",
1714 Kind: reflect.Chan,
1715 },
1716 {
1717 Value: map[string]string{
1718 "question": "What do you get when you multiply six by nine?",
1719 "answer": "42",
1720 },
1721 Err: "xml: unsupported type: map[string]string",
1722 Kind: reflect.Map,
1723 },
1724 {
1725 Value: map[*Ship]bool{nil: false},
1726 Err: "xml: unsupported type: map[*xml.Ship]bool",
1727 Kind: reflect.Map,
1728 },
1729 {
1730 Value: &Domain{Comment: []byte("f--bar")},
1731 Err: `xml: comments must not contain "--"`,
1732 },
1733 // Reject parent chain with attr, never worked; see golang.org/issue/5033.
1734 {
1735 Value: &AttrParent{},
1736 Err: `xml: X>Y chain not valid with attr flag`,
1737 },
1738 {
1739 Value: BadAttr{map[string]string{"X": "Y"}},
1740 Err: `xml: unsupported type: map[string]string`,
1741 },
1742 }
1743
1744 var marshalIndentTests = []struct {
1745 Value any
1746 Prefix string
1747 Indent string
1748 ExpectXML string
1749 }{
1750 {
1751 Value: &SecretAgent{
1752 Handle: "007",
1753 Identity: "James Bond",
1754 Obfuscate: "<redacted/>",
1755 },
1756 Prefix: "",
1757 Indent: "\t",
1758 ExpectXML: fmt.Sprintf("<agent handle=\"007\">\n\t<Identity>James Bond</Identity><redacted/>\n</agent>"),
1759 },
1760 }
1761
1762 func TestMarshalErrors(t *testing.T) {
1763 for idx, test := range marshalErrorTests {
1764 data, err := Marshal(test.Value)
1765 if err == nil {
1766 t.Errorf("#%d: marshal(%#v) = [success] %q, want error %v", idx, test.Value, data, test.Err)
1767 continue
1768 }
1769 if err.Error() != test.Err {
1770 t.Errorf("#%d: marshal(%#v) = [error] %v, want %v", idx, test.Value, err, test.Err)
1771 }
1772 if test.Kind != reflect.Invalid {
1773 if kind := err.(*UnsupportedTypeError).Type.Kind(); kind != test.Kind {
1774 t.Errorf("#%d: marshal(%#v) = [error kind] %s, want %s", idx, test.Value, kind, test.Kind)
1775 }
1776 }
1777 }
1778 }
1779
1780 // Do invertibility testing on the various structures that we test
1781 func TestUnmarshal(t *testing.T) {
1782 for i, test := range marshalTests {
1783 if test.MarshalOnly {
1784 continue
1785 }
1786 if _, ok := test.Value.(*Plain); ok {
1787 continue
1788 }
1789 if test.ExpectXML == `<top>`+
1790 `<x><b xmlns="space">b</b>`+
1791 `<b xmlns="space1">b1</b></x>`+
1792 `</top>` {
1793 // TODO(rogpeppe): re-enable this test in
1794 // https://go-review.googlesource.com/#/c/5910/
1795 continue
1796 }
1797
1798 vt := reflect.TypeOf(test.Value)
1799 dest := reflect.New(vt.Elem()).Interface()
1800 err := Unmarshal([]byte(test.ExpectXML), dest)
1801
1802 t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
1803 switch fix := dest.(type) {
1804 case *Feed:
1805 fix.Author.InnerXML = ""
1806 for i := range fix.Entry {
1807 fix.Entry[i].Author.InnerXML = ""
1808 }
1809 }
1810
1811 if err != nil {
1812 if test.UnmarshalError == "" {
1813 t.Errorf("unmarshal(%#v): %s", test.ExpectXML, err)
1814 return
1815 }
1816 if !strings.Contains(err.Error(), test.UnmarshalError) {
1817 t.Errorf("unmarshal(%#v): %s, want %q", test.ExpectXML, err, test.UnmarshalError)
1818 }
1819 return
1820 }
1821 if got, want := dest, test.Value; !reflect.DeepEqual(got, want) {
1822 t.Errorf("unmarshal(%q):\nhave %#v\nwant %#v", test.ExpectXML, got, want)
1823 }
1824 })
1825 }
1826 }
1827
1828 func TestMarshalIndent(t *testing.T) {
1829 for i, test := range marshalIndentTests {
1830 data, err := MarshalIndent(test.Value, test.Prefix, test.Indent)
1831 if err != nil {
1832 t.Errorf("#%d: Error: %s", i, err)
1833 continue
1834 }
1835 if got, want := string(data), test.ExpectXML; got != want {
1836 t.Errorf("#%d: MarshalIndent:\nGot:%s\nWant:\n%s", i, got, want)
1837 }
1838 }
1839 }
1840
1841 type limitedBytesWriter struct {
1842 w io.Writer
1843 remain int // until writes fail
1844 }
1845
1846 func (lw *limitedBytesWriter) Write(p []byte) (n int, err error) {
1847 if lw.remain <= 0 {
1848 println("error")
1849 return 0, errors.New("write limit hit")
1850 }
1851 if len(p) > lw.remain {
1852 p = p[:lw.remain]
1853 n, _ = lw.w.Write(p)
1854 lw.remain = 0
1855 return n, errors.New("write limit hit")
1856 }
1857 n, err = lw.w.Write(p)
1858 lw.remain -= n
1859 return n, err
1860 }
1861
1862 func TestMarshalWriteErrors(t *testing.T) {
1863 var buf bytes.Buffer
1864 const writeCap = 1024
1865 w := &limitedBytesWriter{&buf, writeCap}
1866 enc := NewEncoder(w)
1867 var err error
1868 var i int
1869 const n = 4000
1870 for i = 1; i <= n; i++ {
1871 err = enc.Encode(&Passenger{
1872 Name: []string{"Alice", "Bob"},
1873 Weight: 5,
1874 })
1875 if err != nil {
1876 break
1877 }
1878 }
1879 if err == nil {
1880 t.Error("expected an error")
1881 }
1882 if i == n {
1883 t.Errorf("expected to fail before the end")
1884 }
1885 if buf.Len() != writeCap {
1886 t.Errorf("buf.Len() = %d; want %d", buf.Len(), writeCap)
1887 }
1888 }
1889
1890 func TestMarshalWriteIOErrors(t *testing.T) {
1891 enc := NewEncoder(errWriter{})
1892
1893 expectErr := "unwritable"
1894 err := enc.Encode(&Passenger{})
1895 if err == nil || err.Error() != expectErr {
1896 t.Errorf("EscapeTest = [error] %v, want %v", err, expectErr)
1897 }
1898 }
1899
1900 func TestMarshalFlush(t *testing.T) {
1901 var buf bytes.Buffer
1902 enc := NewEncoder(&buf)
1903 if err := enc.EncodeToken(CharData("hello world")); err != nil {
1904 t.Fatalf("enc.EncodeToken: %v", err)
1905 }
1906 if buf.Len() > 0 {
1907 t.Fatalf("enc.EncodeToken caused actual write: %q", buf.Bytes())
1908 }
1909 if err := enc.Flush(); err != nil {
1910 t.Fatalf("enc.Flush: %v", err)
1911 }
1912 if buf.String() != "hello world" {
1913 t.Fatalf("after enc.Flush, buf.String() = %q, want %q", buf.String(), "hello world")
1914 }
1915 }
1916
1917 func BenchmarkMarshal(b *testing.B) {
1918 b.ReportAllocs()
1919 b.RunParallel(func(pb *testing.PB) {
1920 for pb.Next() {
1921 Marshal(atomValue)
1922 }
1923 })
1924 }
1925
1926 func BenchmarkUnmarshal(b *testing.B) {
1927 b.ReportAllocs()
1928 xml := []byte(atomXML)
1929 b.RunParallel(func(pb *testing.PB) {
1930 for pb.Next() {
1931 Unmarshal(xml, &Feed{})
1932 }
1933 })
1934 }
1935
1936 // golang.org/issue/6556
1937 func TestStructPointerMarshal(t *testing.T) {
1938 type A struct {
1939 XMLName string `xml:"a"`
1940 B []any
1941 }
1942 type C struct {
1943 XMLName Name
1944 Value string `xml:"value"`
1945 }
1946
1947 a := new(A)
1948 a.B = append(a.B, &C{
1949 XMLName: Name{Local: "c"},
1950 Value: "x",
1951 })
1952
1953 b, err := Marshal(a)
1954 if err != nil {
1955 t.Fatal(err)
1956 }
1957 if x := string(b); x != "<a><c><value>x</value></c></a>" {
1958 t.Fatal(x)
1959 }
1960 var v A
1961 err = Unmarshal(b, &v)
1962 if err != nil {
1963 t.Fatal(err)
1964 }
1965 }
1966
1967 var encodeTokenTests = []struct {
1968 desc string
1969 toks []Token
1970 want string
1971 err string
1972 }{{
1973 desc: "start element with name space",
1974 toks: []Token{
1975 StartElement{Name{"space", "local"}, nil},
1976 },
1977 want: `<local xmlns="space">`,
1978 }, {
1979 desc: "start element with no name",
1980 toks: []Token{
1981 StartElement{Name{"space", ""}, nil},
1982 },
1983 err: "xml: start tag with no name",
1984 }, {
1985 desc: "end element with no name",
1986 toks: []Token{
1987 EndElement{Name{"space", ""}},
1988 },
1989 err: "xml: end tag with no name",
1990 }, {
1991 desc: "char data",
1992 toks: []Token{
1993 CharData("foo"),
1994 },
1995 want: `foo`,
1996 }, {
1997 desc: "char data with escaped chars",
1998 toks: []Token{
1999 CharData(" \t\n"),
2000 },
2001 want: " &#x9;\n",
2002 }, {
2003 desc: "comment",
2004 toks: []Token{
2005 Comment("foo"),
2006 },
2007 want: `<!--foo-->`,
2008 }, {
2009 desc: "comment with invalid content",
2010 toks: []Token{
2011 Comment("foo-->"),
2012 },
2013 err: "xml: EncodeToken of Comment containing --> marker",
2014 }, {
2015 desc: "proc instruction",
2016 toks: []Token{
2017 ProcInst{"Target", []byte("Instruction")},
2018 },
2019 want: `<?Target Instruction?>`,
2020 }, {
2021 desc: "proc instruction with empty target",
2022 toks: []Token{
2023 ProcInst{"", []byte("Instruction")},
2024 },
2025 err: "xml: EncodeToken of ProcInst with invalid Target",
2026 }, {
2027 desc: "proc instruction with bad content",
2028 toks: []Token{
2029 ProcInst{"", []byte("Instruction?>")},
2030 },
2031 err: "xml: EncodeToken of ProcInst with invalid Target",
2032 }, {
2033 desc: "directive",
2034 toks: []Token{
2035 Directive("foo"),
2036 },
2037 want: `<!foo>`,
2038 }, {
2039 desc: "more complex directive",
2040 toks: []Token{
2041 Directive("DOCTYPE doc [ <!ELEMENT doc '>'> <!-- com>ment --> ]"),
2042 },
2043 want: `<!DOCTYPE doc [ <!ELEMENT doc '>'> <!-- com>ment --> ]>`,
2044 }, {
2045 desc: "directive instruction with bad name",
2046 toks: []Token{
2047 Directive("foo>"),
2048 },
2049 err: "xml: EncodeToken of Directive containing wrong < or > markers",
2050 }, {
2051 desc: "end tag without start tag",
2052 toks: []Token{
2053 EndElement{Name{"foo", "bar"}},
2054 },
2055 err: "xml: end tag </bar> without start tag",
2056 }, {
2057 desc: "mismatching end tag local name",
2058 toks: []Token{
2059 StartElement{Name{"", "foo"}, nil},
2060 EndElement{Name{"", "bar"}},
2061 },
2062 err: "xml: end tag </bar> does not match start tag <foo>",
2063 want: `<foo>`,
2064 }, {
2065 desc: "mismatching end tag namespace",
2066 toks: []Token{
2067 StartElement{Name{"space", "foo"}, nil},
2068 EndElement{Name{"another", "foo"}},
2069 },
2070 err: "xml: end tag </foo> in namespace another does not match start tag <foo> in namespace space",
2071 want: `<foo xmlns="space">`,
2072 }, {
2073 desc: "start element with explicit namespace",
2074 toks: []Token{
2075 StartElement{Name{"space", "local"}, []Attr{
2076 {Name{"xmlns", "x"}, "space"},
2077 {Name{"space", "foo"}, "value"},
2078 }},
2079 },
2080 want: `<local xmlns="space" xmlns:_xmlns="xmlns" _xmlns:x="space" xmlns:space="space" space:foo="value">`,
2081 }, {
2082 desc: "start element with explicit namespace and colliding prefix",
2083 toks: []Token{
2084 StartElement{Name{"space", "local"}, []Attr{
2085 {Name{"xmlns", "x"}, "space"},
2086 {Name{"space", "foo"}, "value"},
2087 {Name{"x", "bar"}, "other"},
2088 }},
2089 },
2090 want: `<local xmlns="space" xmlns:_xmlns="xmlns" _xmlns:x="space" xmlns:space="space" space:foo="value" xmlns:x="x" x:bar="other">`,
2091 }, {
2092 desc: "start element using previously defined namespace",
2093 toks: []Token{
2094 StartElement{Name{"", "local"}, []Attr{
2095 {Name{"xmlns", "x"}, "space"},
2096 }},
2097 StartElement{Name{"space", "foo"}, []Attr{
2098 {Name{"space", "x"}, "y"},
2099 }},
2100 },
2101 want: `<local xmlns:_xmlns="xmlns" _xmlns:x="space"><foo xmlns="space" xmlns:space="space" space:x="y">`,
2102 }, {
2103 desc: "nested name space with same prefix",
2104 toks: []Token{
2105 StartElement{Name{"", "foo"}, []Attr{
2106 {Name{"xmlns", "x"}, "space1"},
2107 }},
2108 StartElement{Name{"", "foo"}, []Attr{
2109 {Name{"xmlns", "x"}, "space2"},
2110 }},
2111 StartElement{Name{"", "foo"}, []Attr{
2112 {Name{"space1", "a"}, "space1 value"},
2113 {Name{"space2", "b"}, "space2 value"},
2114 }},
2115 EndElement{Name{"", "foo"}},
2116 EndElement{Name{"", "foo"}},
2117 StartElement{Name{"", "foo"}, []Attr{
2118 {Name{"space1", "a"}, "space1 value"},
2119 {Name{"space2", "b"}, "space2 value"},
2120 }},
2121 },
2122 want: `<foo xmlns:_xmlns="xmlns" _xmlns:x="space1"><foo _xmlns:x="space2"><foo xmlns:space1="space1" space1:a="space1 value" xmlns:space2="space2" space2:b="space2 value"></foo></foo><foo xmlns:space1="space1" space1:a="space1 value" xmlns:space2="space2" space2:b="space2 value">`,
2123 }, {
2124 desc: "start element defining several prefixes for the same name space",
2125 toks: []Token{
2126 StartElement{Name{"space", "foo"}, []Attr{
2127 {Name{"xmlns", "a"}, "space"},
2128 {Name{"xmlns", "b"}, "space"},
2129 {Name{"space", "x"}, "value"},
2130 }},
2131 },
2132 want: `<foo xmlns="space" xmlns:_xmlns="xmlns" _xmlns:a="space" _xmlns:b="space" xmlns:space="space" space:x="value">`,
2133 }, {
2134 desc: "nested element redefines name space",
2135 toks: []Token{
2136 StartElement{Name{"", "foo"}, []Attr{
2137 {Name{"xmlns", "x"}, "space"},
2138 }},
2139 StartElement{Name{"space", "foo"}, []Attr{
2140 {Name{"xmlns", "y"}, "space"},
2141 {Name{"space", "a"}, "value"},
2142 }},
2143 },
2144 want: `<foo xmlns:_xmlns="xmlns" _xmlns:x="space"><foo xmlns="space" _xmlns:y="space" xmlns:space="space" space:a="value">`,
2145 }, {
2146 desc: "nested element creates alias for default name space",
2147 toks: []Token{
2148 StartElement{Name{"space", "foo"}, []Attr{
2149 {Name{"", "xmlns"}, "space"},
2150 }},
2151 StartElement{Name{"space", "foo"}, []Attr{
2152 {Name{"xmlns", "y"}, "space"},
2153 {Name{"space", "a"}, "value"},
2154 }},
2155 },
2156 want: `<foo xmlns="space" xmlns="space"><foo xmlns="space" xmlns:_xmlns="xmlns" _xmlns:y="space" xmlns:space="space" space:a="value">`,
2157 }, {
2158 desc: "nested element defines default name space with existing prefix",
2159 toks: []Token{
2160 StartElement{Name{"", "foo"}, []Attr{
2161 {Name{"xmlns", "x"}, "space"},
2162 }},
2163 StartElement{Name{"space", "foo"}, []Attr{
2164 {Name{"", "xmlns"}, "space"},
2165 {Name{"space", "a"}, "value"},
2166 }},
2167 },
2168 want: `<foo xmlns:_xmlns="xmlns" _xmlns:x="space"><foo xmlns="space" xmlns="space" xmlns:space="space" space:a="value">`,
2169 }, {
2170 desc: "nested element uses empty attribute name space when default ns defined",
2171 toks: []Token{
2172 StartElement{Name{"space", "foo"}, []Attr{
2173 {Name{"", "xmlns"}, "space"},
2174 }},
2175 StartElement{Name{"space", "foo"}, []Attr{
2176 {Name{"", "attr"}, "value"},
2177 }},
2178 },
2179 want: `<foo xmlns="space" xmlns="space"><foo xmlns="space" attr="value">`,
2180 }, {
2181 desc: "redefine xmlns",
2182 toks: []Token{
2183 StartElement{Name{"", "foo"}, []Attr{
2184 {Name{"foo", "xmlns"}, "space"},
2185 }},
2186 },
2187 want: `<foo xmlns:foo="foo" foo:xmlns="space">`,
2188 }, {
2189 desc: "xmlns with explicit name space #1",
2190 toks: []Token{
2191 StartElement{Name{"space", "foo"}, []Attr{
2192 {Name{"xml", "xmlns"}, "space"},
2193 }},
2194 },
2195 want: `<foo xmlns="space" xmlns:_xml="xml" _xml:xmlns="space">`,
2196 }, {
2197 desc: "xmlns with explicit name space #2",
2198 toks: []Token{
2199 StartElement{Name{"space", "foo"}, []Attr{
2200 {Name{xmlURL, "xmlns"}, "space"},
2201 }},
2202 },
2203 want: `<foo xmlns="space" xml:xmlns="space">`,
2204 }, {
2205 desc: "empty name space declaration is ignored",
2206 toks: []Token{
2207 StartElement{Name{"", "foo"}, []Attr{
2208 {Name{"xmlns", "foo"}, ""},
2209 }},
2210 },
2211 want: `<foo xmlns:_xmlns="xmlns" _xmlns:foo="">`,
2212 }, {
2213 desc: "attribute with no name is ignored",
2214 toks: []Token{
2215 StartElement{Name{"", "foo"}, []Attr{
2216 {Name{"", ""}, "value"},
2217 }},
2218 },
2219 want: `<foo>`,
2220 }, {
2221 desc: "namespace URL with non-valid name",
2222 toks: []Token{
2223 StartElement{Name{"/34", "foo"}, []Attr{
2224 {Name{"/34", "x"}, "value"},
2225 }},
2226 },
2227 want: `<foo xmlns="/34" xmlns:_="/34" _:x="value">`,
2228 }, {
2229 desc: "nested element resets default namespace to empty",
2230 toks: []Token{
2231 StartElement{Name{"space", "foo"}, []Attr{
2232 {Name{"", "xmlns"}, "space"},
2233 }},
2234 StartElement{Name{"", "foo"}, []Attr{
2235 {Name{"", "xmlns"}, ""},
2236 {Name{"", "x"}, "value"},
2237 {Name{"space", "x"}, "value"},
2238 }},
2239 },
2240 want: `<foo xmlns="space" xmlns="space"><foo xmlns="" x="value" xmlns:space="space" space:x="value">`,
2241 }, {
2242 desc: "nested element requires empty default name space",
2243 toks: []Token{
2244 StartElement{Name{"space", "foo"}, []Attr{
2245 {Name{"", "xmlns"}, "space"},
2246 }},
2247 StartElement{Name{"", "foo"}, nil},
2248 },
2249 want: `<foo xmlns="space" xmlns="space"><foo>`,
2250 }, {
2251 desc: "attribute uses name space from xmlns",
2252 toks: []Token{
2253 StartElement{Name{"some/space", "foo"}, []Attr{
2254 {Name{"", "attr"}, "value"},
2255 {Name{"some/space", "other"}, "other value"},
2256 }},
2257 },
2258 want: `<foo xmlns="some/space" attr="value" xmlns:space="some/space" space:other="other value">`,
2259 }, {
2260 desc: "default name space should not be used by attributes",
2261 toks: []Token{
2262 StartElement{Name{"space", "foo"}, []Attr{
2263 {Name{"", "xmlns"}, "space"},
2264 {Name{"xmlns", "bar"}, "space"},
2265 {Name{"space", "baz"}, "foo"},
2266 }},
2267 StartElement{Name{"space", "baz"}, nil},
2268 EndElement{Name{"space", "baz"}},
2269 EndElement{Name{"space", "foo"}},
2270 },
2271 want: `<foo xmlns="space" xmlns="space" xmlns:_xmlns="xmlns" _xmlns:bar="space" xmlns:space="space" space:baz="foo"><baz xmlns="space"></baz></foo>`,
2272 }, {
2273 desc: "default name space not used by attributes, not explicitly defined",
2274 toks: []Token{
2275 StartElement{Name{"space", "foo"}, []Attr{
2276 {Name{"", "xmlns"}, "space"},
2277 {Name{"space", "baz"}, "foo"},
2278 }},
2279 StartElement{Name{"space", "baz"}, nil},
2280 EndElement{Name{"space", "baz"}},
2281 EndElement{Name{"space", "foo"}},
2282 },
2283 want: `<foo xmlns="space" xmlns="space" xmlns:space="space" space:baz="foo"><baz xmlns="space"></baz></foo>`,
2284 }, {
2285 desc: "impossible xmlns declaration",
2286 toks: []Token{
2287 StartElement{Name{"", "foo"}, []Attr{
2288 {Name{"", "xmlns"}, "space"},
2289 }},
2290 StartElement{Name{"space", "bar"}, []Attr{
2291 {Name{"space", "attr"}, "value"},
2292 }},
2293 },
2294 want: `<foo xmlns="space"><bar xmlns="space" xmlns:space="space" space:attr="value">`,
2295 }, {
2296 desc: "reserved namespace prefix -- all lower case",
2297 toks: []Token{
2298 StartElement{Name{"", "foo"}, []Attr{
2299 {Name{"http://www.w3.org/2001/xmlSchema-instance", "nil"}, "true"},
2300 }},
2301 },
2302 want: `<foo xmlns:_xmlSchema-instance="http://www.w3.org/2001/xmlSchema-instance" _xmlSchema-instance:nil="true">`,
2303 }, {
2304 desc: "reserved namespace prefix -- all upper case",
2305 toks: []Token{
2306 StartElement{Name{"", "foo"}, []Attr{
2307 {Name{"http://www.w3.org/2001/XMLSchema-instance", "nil"}, "true"},
2308 }},
2309 },
2310 want: `<foo xmlns:_XMLSchema-instance="http://www.w3.org/2001/XMLSchema-instance" _XMLSchema-instance:nil="true">`,
2311 }, {
2312 desc: "reserved namespace prefix -- all mixed case",
2313 toks: []Token{
2314 StartElement{Name{"", "foo"}, []Attr{
2315 {Name{"http://www.w3.org/2001/XmLSchema-instance", "nil"}, "true"},
2316 }},
2317 },
2318 want: `<foo xmlns:_XmLSchema-instance="http://www.w3.org/2001/XmLSchema-instance" _XmLSchema-instance:nil="true">`,
2319 }}
2320
2321 func TestEncodeToken(t *testing.T) {
2322 loop:
2323 for i, tt := range encodeTokenTests {
2324 var buf bytes.Buffer
2325 enc := NewEncoder(&buf)
2326 var err error
2327 for j, tok := range tt.toks {
2328 err = enc.EncodeToken(tok)
2329 if err != nil && j < len(tt.toks)-1 {
2330 t.Errorf("#%d %s token #%d: %v", i, tt.desc, j, err)
2331 continue loop
2332 }
2333 }
2334 errorf := func(f string, a ...any) {
2335 t.Errorf("#%d %s token #%d:%s", i, tt.desc, len(tt.toks)-1, fmt.Sprintf(f, a...))
2336 }
2337 switch {
2338 case tt.err != "" && err == nil:
2339 errorf(" expected error; got none")
2340 continue
2341 case tt.err == "" && err != nil:
2342 errorf(" got error: %v", err)
2343 continue
2344 case tt.err != "" && err != nil && tt.err != err.Error():
2345 errorf(" error mismatch; got %v, want %v", err, tt.err)
2346 continue
2347 }
2348 if err := enc.Flush(); err != nil {
2349 errorf(" %v", err)
2350 continue
2351 }
2352 if got := buf.String(); got != tt.want {
2353 errorf("\ngot %v\nwant %v", got, tt.want)
2354 continue
2355 }
2356 }
2357 }
2358
2359 func TestProcInstEncodeToken(t *testing.T) {
2360 var buf bytes.Buffer
2361 enc := NewEncoder(&buf)
2362
2363 if err := enc.EncodeToken(ProcInst{"xml", []byte("Instruction")}); err != nil {
2364 t.Fatalf("enc.EncodeToken: expected to be able to encode xml target ProcInst as first token, %s", err)
2365 }
2366
2367 if err := enc.EncodeToken(ProcInst{"Target", []byte("Instruction")}); err != nil {
2368 t.Fatalf("enc.EncodeToken: expected to be able to add non-xml target ProcInst")
2369 }
2370
2371 if err := enc.EncodeToken(ProcInst{"xml", []byte("Instruction")}); err == nil {
2372 t.Fatalf("enc.EncodeToken: expected to not be allowed to encode xml target ProcInst when not first token")
2373 }
2374 }
2375
2376 func TestDecodeEncode(t *testing.T) {
2377 var in, out bytes.Buffer
2378 in.WriteString(`<?xml version="1.0" encoding="UTF-8"?>
2379 <?Target Instruction?>
2380 <root>
2381 </root>
2382 `)
2383 dec := NewDecoder(&in)
2384 enc := NewEncoder(&out)
2385 for tok, err := dec.Token(); err == nil; tok, err = dec.Token() {
2386 err = enc.EncodeToken(tok)
2387 if err != nil {
2388 t.Fatalf("enc.EncodeToken: Unable to encode token (%#v), %v", tok, err)
2389 }
2390 }
2391 }
2392
2393 // Issue 9796. Used to fail with GORACE="halt_on_error=1" -race.
2394 func TestRace9796(t *testing.T) {
2395 type A struct{}
2396 type B struct {
2397 C []A `xml:"X>Y"`
2398 }
2399 var wg sync.WaitGroup
2400 for i := 0; i < 2; i++ {
2401 wg.Add(1)
2402 go func() {
2403 Marshal(B{[]A{{}}})
2404 wg.Done()
2405 }()
2406 }
2407 wg.Wait()
2408 }
2409
2410 func TestIsValidDirective(t *testing.T) {
2411 testOK := []string{
2412 "<>",
2413 "< < > >",
2414 "<!DOCTYPE '<' '>' '>' <!--nothing-->>",
2415 "<!DOCTYPE doc [ <!ELEMENT doc ANY> <!ELEMENT doc ANY> ]>",
2416 "<!DOCTYPE doc [ <!ELEMENT doc \"ANY> '<' <!E\" LEMENT '>' doc ANY> ]>",
2417 "<!DOCTYPE doc <!-- just>>>> a < comment --> [ <!ITEM anything> ] >",
2418 }
2419 testKO := []string{
2420 "<",
2421 ">",
2422 "<!--",
2423 "-->",
2424 "< > > < < >",
2425 "<!dummy <!-- > -->",
2426 "<!DOCTYPE doc '>",
2427 "<!DOCTYPE doc '>'",
2428 "<!DOCTYPE doc <!--comment>",
2429 }
2430 for _, s := range testOK {
2431 if !isValidDirective(Directive(s)) {
2432 t.Errorf("Directive %q is expected to be valid", s)
2433 }
2434 }
2435 for _, s := range testKO {
2436 if isValidDirective(Directive(s)) {
2437 t.Errorf("Directive %q is expected to be invalid", s)
2438 }
2439 }
2440 }
2441
2442 // Issue 11719. EncodeToken used to silently eat tokens with an invalid type.
2443 func TestSimpleUseOfEncodeToken(t *testing.T) {
2444 var buf bytes.Buffer
2445 enc := NewEncoder(&buf)
2446 if err := enc.EncodeToken(&StartElement{Name: Name{"", "object1"}}); err == nil {
2447 t.Errorf("enc.EncodeToken: pointer type should be rejected")
2448 }
2449 if err := enc.EncodeToken(&EndElement{Name: Name{"", "object1"}}); err == nil {
2450 t.Errorf("enc.EncodeToken: pointer type should be rejected")
2451 }
2452 if err := enc.EncodeToken(StartElement{Name: Name{"", "object2"}}); err != nil {
2453 t.Errorf("enc.EncodeToken: StartElement %s", err)
2454 }
2455 if err := enc.EncodeToken(EndElement{Name: Name{"", "object2"}}); err != nil {
2456 t.Errorf("enc.EncodeToken: EndElement %s", err)
2457 }
2458 if err := enc.EncodeToken(Universe{}); err == nil {
2459 t.Errorf("enc.EncodeToken: invalid type not caught")
2460 }
2461 if err := enc.Flush(); err != nil {
2462 t.Errorf("enc.Flush: %s", err)
2463 }
2464 if buf.Len() == 0 {
2465 t.Errorf("enc.EncodeToken: empty buffer")
2466 }
2467 want := "<object2></object2>"
2468 if buf.String() != want {
2469 t.Errorf("enc.EncodeToken: expected %q; got %q", want, buf.String())
2470 }
2471 }
2472
2473 // Issue 16158. Decoder.unmarshalAttr ignores the return value of copyValue.
2474 func TestIssue16158(t *testing.T) {
2475 const data = `<foo b="HELLOWORLD"></foo>`
2476 err := Unmarshal([]byte(data), &struct {
2477 B byte `xml:"b,attr,omitempty"`
2478 }{})
2479 if err == nil {
2480 t.Errorf("Unmarshal: expected error, got nil")
2481 }
2482 }
2483
2484 // Issue 20953. Crash on invalid XMLName attribute.
2485
2486 type InvalidXMLName struct {
2487 XMLName Name `xml:"error"`
2488 Type struct {
2489 XMLName Name `xml:"type,attr"`
2490 }
2491 }
2492
2493 func TestInvalidXMLName(t *testing.T) {
2494 var buf bytes.Buffer
2495 enc := NewEncoder(&buf)
2496 if err := enc.Encode(InvalidXMLName{}); err == nil {
2497 t.Error("unexpected success")
2498 } else if want := "invalid tag"; !strings.Contains(err.Error(), want) {
2499 t.Errorf("error %q does not contain %q", err, want)
2500 }
2501 }
2502
2503 // Issue 50164. Crash on zero value XML attribute.
2504 type LayerOne struct {
2505 XMLName Name `xml:"l1"`
2506
2507 Value *float64 `xml:"value,omitempty"`
2508 *LayerTwo `xml:",omitempty"`
2509 }
2510
2511 type LayerTwo struct {
2512 ValueTwo *int `xml:"value_two,attr,omitempty"`
2513 }
2514
2515 func TestMarshalZeroValue(t *testing.T) {
2516 proofXml := `<l1><value>1.2345</value></l1>`
2517 var l1 LayerOne
2518 err := Unmarshal([]byte(proofXml), &l1)
2519 if err != nil {
2520 t.Fatalf("unmarshal XML error: %v", err)
2521 }
2522 want := float64(1.2345)
2523 got := *l1.Value
2524 if got != want {
2525 t.Fatalf("unexpected unmarshal result, want %f but got %f", want, got)
2526 }
2527
2528 // Marshal again (or Encode again)
2529 // In issue 50164, here `Marshal(l1)` will panic because of the zero value of xml attribute ValueTwo `value_two`.
2530 anotherXML, err := Marshal(l1)
2531 if err != nil {
2532 t.Fatalf("marshal XML error: %v", err)
2533 }
2534 if string(anotherXML) != proofXml {
2535 t.Fatalf("unexpected unmarshal result, want %q but got %q", proofXml, anotherXML)
2536 }
2537 }