Debian Codegraph @

etree_test.go

raw symbols SCIP
1 // Copyright 2015-2019 Brett Vickers.
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 etree
6
7 import (
8 "bytes"
9 "encoding/xml"
10 "errors"
11 "io"
12 "io/fs"
13 "math/rand"
14 "os"
15 "path"
16 "strings"
17 "testing"
18 )
19
20 func newDocumentFromString(t *testing.T, s string) *Document {
21 return newDocumentFromString2(t, s, ReadSettings{})
22 }
23
24 func newDocumentFromString2(t *testing.T, s string, settings ReadSettings) *Document {
25 t.Helper()
26 doc := NewDocument()
27 doc.ReadSettings = settings
28 err := doc.ReadFromString(s)
29 if err != nil {
30 t.Fatal("etree: failed to parse document")
31 }
32 return doc
33 }
34
35 func checkStrEq(t *testing.T, got, want string) {
36 t.Helper()
37 if got != want {
38 t.Errorf("etree: unexpected result.\nGot:\n%s\nWanted:\n%s\n", got, want)
39 }
40 }
41
42 func checkStrBinaryEq(t *testing.T, got, want string) {
43 t.Helper()
44 if got != want {
45 t.Errorf("etree: unexpected result.\nGot:\n%v\nWanted:\n%v\n", []byte(got), []byte(want))
46 }
47 }
48
49 func checkIntEq(t *testing.T, got, want int) {
50 t.Helper()
51 if got != want {
52 t.Errorf("etree: unexpected integer. Got: %d. Wanted: %d\n", got, want)
53 }
54 }
55
56 func checkBoolEq(t *testing.T, got, want bool) {
57 t.Helper()
58 if got != want {
59 t.Errorf("etree: unexpected boolean. Got: %v. Wanted: %v\n", got, want)
60 }
61 }
62
63 func checkElementEq(t *testing.T, got, want *Element) {
64 t.Helper()
65 if got != want {
66 t.Errorf("etree: unexpected element. Got: %v. Wanted: %v.\n", got, want)
67 }
68 }
69
70 func checkDocEq(t *testing.T, doc *Document, expected string) {
71 t.Helper()
72 doc.Indent(NoIndent)
73 s, err := doc.WriteToString()
74 if err != nil {
75 t.Error("etree: failed to serialize document")
76 }
77 if s != expected {
78 t.Errorf("etree: unexpected document.\nGot:\n%s\nWanted:\n%s\n", s, expected)
79 }
80 }
81
82 func checkIndexes(t *testing.T, e *Element) {
83 t.Helper()
84 for i := 0; i < len(e.Child); i++ {
85 c := e.Child[i]
86 if c.Index() != i {
87 t.Errorf("Child index mismatch. Got %d, expected %d.", c.Index(), i)
88 }
89 if ce, ok := c.(*Element); ok {
90 checkIndexes(t, ce)
91 }
92 }
93 }
94
95 func TestDocument(t *testing.T) {
96 // Create a document
97 doc := NewDocument()
98 doc.CreateProcInst("xml", `version="1.0" encoding="UTF-8"`)
99 doc.CreateProcInst("xml-stylesheet", `type="text/xsl" href="style.xsl"`)
100 store := doc.CreateElement("store")
101 store.CreateAttr("xmlns:t", "urn:books-com:titles")
102 store.CreateDirective("Directive")
103 store.CreateComment("This is a comment")
104 book := store.CreateElement("book")
105 book.CreateAttr("lang", "fr")
106 book.CreateAttr("lang", "en")
107 title := book.CreateElement("t:title")
108 title.SetText("Nicholas Nickleby")
109 title.SetText("Great Expectations")
110 author := book.CreateElement("author")
111 author.CreateCharData("Charles Dickens")
112 review := book.CreateElement("review")
113 review.CreateCData("<<< Will be replaced")
114 review.SetCData(">>> Excellent book")
115 doc.IndentTabs()
116
117 checkIndexes(t, &doc.Element)
118
119 // Serialize the document to a string
120 s, err := doc.WriteToString()
121 if err != nil {
122 t.Error("etree: failed to serialize document")
123 }
124
125 // Make sure the serialized XML matches expectation.
126 expected := `<?xml version="1.0" encoding="UTF-8"?>
127 <?xml-stylesheet type="text/xsl" href="style.xsl"?>
128 <store xmlns:t="urn:books-com:titles">
129 <!Directive>
130 <!--This is a comment-->
131 <book lang="en">
132 <t:title>Great Expectations</t:title>
133 <author>Charles Dickens</author>
134 <review><![CDATA[>>> Excellent book]]></review>
135 </book>
136 </store>
137 `
138 checkStrEq(t, s, expected)
139
140 // Test the structure of the XML
141 if doc.Root() != store {
142 t.Error("etree: root mismatch")
143 }
144 if len(store.ChildElements()) != 1 || len(store.Child) != 7 {
145 t.Error("etree: incorrect tree structure")
146 }
147 if len(book.ChildElements()) != 3 || len(book.Attr) != 1 || len(book.Child) != 7 {
148 t.Error("etree: incorrect tree structure")
149 }
150 if len(title.ChildElements()) != 0 || len(title.Child) != 1 || len(title.Attr) != 0 {
151 t.Error("etree: incorrect tree structure")
152 }
153 if len(author.ChildElements()) != 0 || len(author.Child) != 1 || len(author.Attr) != 0 {
154 t.Error("etree: incorrect tree structure")
155 }
156 if len(review.ChildElements()) != 0 || len(review.Child) != 1 || len(review.Attr) != 0 {
157 t.Error("etree: incorrect tree structure")
158 }
159 if book.parent != store || store.parent != &doc.Element || doc.parent != nil {
160 t.Error("etree: incorrect tree structure")
161 }
162 if title.parent != book || author.parent != book {
163 t.Error("etree: incorrect tree structure")
164 }
165
166 // Perform some basic queries on the document
167 elements := doc.SelectElements("store")
168 if len(elements) != 1 || elements[0] != store {
169 t.Error("etree: incorrect SelectElements result")
170 }
171 element := doc.SelectElement("store")
172 if element != store {
173 t.Error("etree: incorrect SelectElement result")
174 }
175 elements = store.SelectElements("book")
176 if len(elements) != 1 || elements[0] != book {
177 t.Error("etree: incorrect SelectElements result")
178 }
179 element = store.SelectElement("book")
180 if element != book {
181 t.Error("etree: incorrect SelectElement result")
182 }
183 attr := book.SelectAttr("lang")
184 if attr == nil || attr.Key != "lang" || attr.Value != "en" {
185 t.Error("etree: incorrect SelectAttr result")
186 }
187 if book.SelectAttrValue("lang", "unknown") != "en" {
188 t.Error("etree: incorrect SelectAttrValue result")
189 }
190 if book.SelectAttrValue("t:missing", "unknown") != "unknown" {
191 t.Error("etree: incorrect SelectAttrValue result")
192 }
193 attr = book.RemoveAttr("lang")
194 if attr.Value != "en" {
195 t.Error("etree: incorrect RemoveAttr result")
196 }
197 book.CreateAttr("lang", "de")
198 attr = book.RemoveAttr("lang")
199 if attr.Value != "de" {
200 t.Error("etree: incorrect RemoveAttr result")
201 }
202 element = book.SelectElement("t:title")
203 if element != title || element.Text() != "Great Expectations" || len(element.Attr) != 0 {
204 t.Error("etree: incorrect SelectElement result")
205 }
206 element = book.SelectElement("title")
207 if element != title {
208 t.Error("etree: incorrect SelectElement result")
209 }
210 element = book.SelectElement("p:title")
211 if element != nil {
212 t.Error("etree: incorrect SelectElement result")
213 }
214 element = book.RemoveChildAt(title.Index()).(*Element)
215 if element != title {
216 t.Error("etree: incorrect RemoveElement result")
217 }
218 element = book.SelectElement("title")
219 if element != nil {
220 t.Error("etree: incorrect SelectElement result")
221 }
222 element = book.SelectElement("review")
223 if element != review || element.Text() != ">>> Excellent book" || len(element.Attr) != 0 {
224 t.Error("etree: incorrect SelectElement result")
225 }
226 }
227
228 func TestSelectElementsSeq(t *testing.T) {
229 doc := NewDocument()
230 store := doc.CreateElement("store")
231 book1 := store.CreateElement("book")
232 book1.CreateAttr("id", "1")
233 book2 := store.CreateElement("book")
234 book2.CreateAttr("id", "2")
235 other := store.CreateElement("other")
236 other.CreateAttr("id", "3")
237 book3 := store.CreateElement("book")
238 book3.CreateAttr("id", "4")
239
240 expectedBooks := store.SelectElements("book")
241 if len(expectedBooks) != 3 {
242 t.Error("etree: setup error - expected 3 books")
243 }
244
245 var iterBooks []*Element
246 for book := range store.SelectElementsSeq("book") {
247 iterBooks = append(iterBooks, book)
248 }
249
250 if len(iterBooks) != len(expectedBooks) {
251 t.Errorf("etree: SelectElementsSeq returned %d elements, expected %d", len(iterBooks), len(expectedBooks))
252 }
253
254 for i, book := range iterBooks {
255 if book != expectedBooks[i] {
256 t.Errorf("etree: SelectElementsSeq element %d mismatch", i)
257 }
258 if book.SelectAttrValue("id", "") == "" {
259 t.Errorf("etree: SelectElementsSeq element %d missing id attribute", i)
260 }
261 }
262
263 count := 0
264 for book := range store.SelectElementsSeq("book") {
265 count++
266 if count == 2 {
267 break
268 }
269 _ = book
270 }
271 if count != 2 {
272 t.Errorf("etree: early termination failed, got %d iterations", count)
273 }
274
275 nonExistentCount := 0
276 for range store.SelectElementsSeq("nonexistent") {
277 nonExistentCount++
278 }
279 if nonExistentCount != 0 {
280 t.Errorf("etree: SelectElementsSeq found %d non-existent elements", nonExistentCount)
281 }
282 }
283
284 func TestFindElementsSeq(t *testing.T) {
285 doc := NewDocument()
286 store := doc.CreateElement("store")
287
288 book1 := store.CreateElement("book")
289 book1.CreateAttr("category", "fiction")
290 title1 := book1.CreateElement("title")
291 title1.SetText("Book One")
292 author1 := book1.CreateElement("author")
293 author1.SetText("Author A")
294
295 book2 := store.CreateElement("book")
296 book2.CreateAttr("category", "nonfiction")
297 title2 := book2.CreateElement("title")
298 title2.SetText("Book Two")
299 author2 := book2.CreateElement("author")
300 author2.SetText("Author B")
301
302 magazine := store.CreateElement("magazine")
303 magazine.CreateAttr("category", "tech")
304 magTitle := magazine.CreateElement("title")
305 magTitle.SetText("Tech Magazine")
306
307 section := store.CreateElement("section")
308 section.CreateAttr("name", "classics")
309 book3 := section.CreateElement("book")
310 book3.CreateAttr("category", "classic")
311 title3 := book3.CreateElement("title")
312 title3.SetText("Classic Book")
313
314 testCases := []struct {
315 name string
316 path string
317 }{
318 {"direct children", "book"},
319 {"all descendants", "//book"},
320 {"all titles", "//title"},
321 {"books with specific category", "book[@category='fiction']"},
322 {"nested path", "section/book"},
323 {"all elements", "//*"},
324 {"specific attribute", "//book[@category='classic']"},
325 }
326
327 for _, tc := range testCases {
328 t.Run(tc.name, func(t *testing.T) {
329 expected := store.FindElements(tc.path)
330
331 var iterResults []*Element
332 for elem := range store.FindElementsSeq(tc.path) {
333 iterResults = append(iterResults, elem)
334 }
335
336 if len(iterResults) != len(expected) {
337 t.Errorf("FindElementsSeq returned %d elements, expected %d for path %s",
338 len(iterResults), len(expected), tc.path)
339 }
340
341 expectedMap := make(map[*Element]bool)
342 for _, e := range expected {
343 expectedMap[e] = true
344 }
345
346 for _, e := range iterResults {
347 if !expectedMap[e] {
348 t.Errorf("FindElementsSeq returned unexpected element for path %s", tc.path)
349 }
350 }
351 })
352 }
353
354 t.Run("early termination", func(t *testing.T) {
355 count := 0
356 for elem := range store.FindElementsSeq("//title") {
357 count++
358 if count == 2 {
359 break
360 }
361 _ = elem
362 }
363 if count != 2 {
364 t.Errorf("Early termination failed, got %d iterations", count)
365 }
366 })
367
368 t.Run("compiled path", func(t *testing.T) {
369 path := MustCompilePath("//book")
370 expected := store.FindElementsPath(path)
371
372 var iterResults []*Element
373 for elem := range store.FindElementsPathSeq(path) {
374 iterResults = append(iterResults, elem)
375 }
376
377 if len(iterResults) != len(expected) {
378 t.Errorf("FindElementsPathSeq returned %d elements, expected %d",
379 len(iterResults), len(expected))
380 }
381 })
382
383 t.Run("empty results", func(t *testing.T) {
384 count := 0
385 for range store.FindElementsSeq("//nonexistent") {
386 count++
387 }
388 if count != 0 {
389 t.Errorf("FindElementsSeq found %d non-existent elements", count)
390 }
391 })
392 }
393
394 func TestImbalancedXML(t *testing.T) {
395 cases := []string{
396 `<test>`,
397 `</test>`,
398 `<test></test2>`,
399 `<doc xmlns:p="xyz"><p:test></test></doc>`,
400 `<doc xmlns:p="xyz"><test></p:test></doc>`,
401 `<test>malformed`,
402 `malformed</test>`,
403 `<test><test></test>`,
404 `<test></test></test>`,
405 `<test><test></test></test2>`,
406 `<test><test2></test></test2>`,
407 }
408 for _, c := range cases {
409 doc := NewDocument()
410 err := doc.ReadFromString(c)
411 if err == nil {
412 t.Errorf("etree: imbalanced XML should have failed:\n%s", c)
413 }
414 }
415 }
416
417 func TestDocumentCharsetReader(t *testing.T) {
418 s := `<?xml version="1.0" encoding="lowercase"?>
419 <Store>
420 <Book Lang="en">
421 <Title>Great Expectations</Title>
422 <Author>Charles Dickens</Author>
423 </Book>
424 </Store>`
425
426 doc := newDocumentFromString2(t, s, ReadSettings{
427 CharsetReader: func(label string, input io.Reader) (io.Reader, error) {
428 if label == "lowercase" {
429 return &lowercaseCharsetReader{input}, nil
430 }
431 return nil, errors.New("unknown charset")
432 },
433 })
434
435 cases := []struct {
436 path string
437 text string
438 }{
439 {"/store/book/title", "great expectations"},
440 {"/store/book/author", "charles dickens"},
441 }
442 for _, c := range cases {
443 e := doc.FindElement(c.path)
444 if e == nil {
445 t.Errorf("etree: failed to find element '%s'", c.path)
446 } else if e.Text() != c.text {
447 t.Errorf("etree: expected path '%s' to contain '%s', got '%s'", c.path, c.text, e.Text())
448 }
449 }
450 }
451
452 type lowercaseCharsetReader struct {
453 r io.Reader
454 }
455
456 func (c *lowercaseCharsetReader) Read(p []byte) (n int, err error) {
457 n, err = c.r.Read(p)
458 if err != nil {
459 return n, err
460 }
461 for i := 0; i < n; i++ {
462 if p[i] >= 'A' && p[i] <= 'Z' {
463 p[i] = p[i] - 'A' + 'a'
464 }
465 }
466 return n, nil
467 }
468
469 func TestDocumentReadPermissive(t *testing.T) {
470 s := "<select disabled></select>"
471
472 doc := NewDocument()
473 err := doc.ReadFromString(s)
474 if err == nil {
475 t.Fatal("etree: incorrect ReadFromString result")
476 }
477
478 doc.ReadSettings.Permissive = true
479 err = doc.ReadFromString(s)
480 if err != nil {
481 t.Fatal("etree: incorrect ReadFromString result")
482 }
483 }
484
485 func TestEmbeddedComment(t *testing.T) {
486 s := `<a>123<!-- test -->456</a>`
487
488 doc := NewDocument()
489 err := doc.ReadFromString(s)
490 if err != nil {
491 t.Fatal("etree: incorrect ReadFromString result")
492 }
493
494 a := doc.SelectElement("a")
495 checkStrEq(t, a.Text(), "123456")
496 }
497
498 func TestDocumentReadHTMLEntities(t *testing.T) {
499 s := `<store>
500 <book lang="en">
501 <title>&rarr;&nbsp;Great Expectations</title>
502 <author>Charles Dickens</author>
503 </book>
504 </store>`
505
506 doc := NewDocument()
507 err := doc.ReadFromString(s)
508 if err == nil {
509 t.Fatal("etree: incorrect ReadFromString result")
510 }
511
512 doc.ReadSettings.Entity = xml.HTMLEntity
513 err = doc.ReadFromString(s)
514 if err != nil {
515 t.Fatal("etree: incorrect ReadFromString result")
516 }
517 }
518
519 func TestDocumentReadHTMLAutoClose(t *testing.T) {
520 cases := []struct {
521 name string
522 input string
523 want string
524 }{
525 {"empty", ``, ``},
526 {"oneSelfClosing", `<br>`, `<br/>`},
527 {"twoSelfClosingAndText", `<br>some text<br>`, `<br/>some text<br/>`},
528 {
529 name: "largerExample",
530 input: `<img src="cover.jpg">
531 <hr>
532 Author: Charles Dickens<br>
533 Book: Great Expectations<br>`,
534 want: `<img src="cover.jpg"/>
535 <hr/>
536 Author: Charles Dickens<br/>
537 Book: Great Expectations<br/>`},
538 }
539
540 for _, c := range cases {
541 t.Run(c.name, func(t *testing.T) {
542 doc := NewDocument()
543 doc.ReadSettings.Permissive = true
544 doc.ReadSettings.AutoClose = xml.HTMLAutoClose
545 err := doc.ReadFromString(c.input)
546 if err != nil {
547 t.Fatal("etree: ReadFromString() error = ", err)
548 }
549 s, err := doc.WriteToString()
550 if err != nil {
551 t.Fatal("etree: WriteToString() error = ", err)
552 }
553 checkStrEq(t, s, c.want)
554 })
555 }
556 }
557
558 func TestEscapeCodes(t *testing.T) {
559 cases := []struct {
560 input string
561 normal string
562 attrCanonical string
563 textCanonical string
564 }{
565 {
566 "&<>'\"\t\n\r",
567 "<e a=\"&amp;&lt;&gt;&apos;&quot;\t\n\r\">&amp;&lt;&gt;&apos;&quot;\t\n\r</e>",
568 "<e a=\"&amp;&lt;>'&quot;&#x9;&#xA;&#xD;\">&amp;&lt;&gt;&apos;&quot;\t\n\r</e>",
569 "<e a=\"&amp;&lt;&gt;&apos;&quot;\t\n\r\">&amp;&lt;&gt;'\"\t\n&#xD;</e>",
570 },
571 {
572 "\x00\x1f\x08\x09\x0a\x0d",
573 "<e a=\"���\t\n\r\">���\t\n\r</e>",
574 "<e a=\"���&#x9;&#xA;&#xD;\">���\t\n\r</e>",
575 "<e a=\"���\t\n\r\">���\t\n&#xD;</e>",
576 },
577 }
578 for _, c := range cases {
579 doc := NewDocument()
580
581 e := doc.CreateElement("e")
582 e.SetText(c.input)
583 e.CreateAttr("a", c.input)
584
585 doc.WriteSettings.CanonicalText = false
586 doc.WriteSettings.CanonicalAttrVal = false
587 s, err := doc.WriteToString()
588 if err != nil {
589 t.Error("etree: Escape test produced inocrrect result.")
590 }
591 checkStrEq(t, s, c.normal)
592
593 doc.WriteSettings.CanonicalText = false
594 doc.WriteSettings.CanonicalAttrVal = true
595 s, err = doc.WriteToString()
596 if err != nil {
597 t.Error("etree: Escape test produced inocrrect result.")
598 }
599 checkStrEq(t, s, c.attrCanonical)
600
601 doc.WriteSettings.CanonicalText = true
602 doc.WriteSettings.CanonicalAttrVal = false
603 s, err = doc.WriteToString()
604 if err != nil {
605 t.Error("etree: Escape test produced inocrrect result.")
606 }
607 checkStrEq(t, s, c.textCanonical)
608 }
609 }
610
611 func TestSanitizeCData(t *testing.T) {
612 cases := []struct {
613 data string
614 expected string
615 }{
616 {"", "<t><![CDATA[]]></t>"},
617 {"text", "<t><![CDATA[text]]></t>"},
618 {"a<b&c>d", "<t><![CDATA[a<b&c>d]]></t>"},
619 {"]]>", "<t><![CDATA[]]]]><![CDATA[>]]></t>"},
620 {"a]]>b", "<t><![CDATA[a]]]]><![CDATA[>b]]></t>"},
621 {"a]]>b]]>c", "<t><![CDATA[a]]]]><![CDATA[>b]]]]><![CDATA[>c]]></t>"},
622 {"]]]>", "<t><![CDATA[]]]]]><![CDATA[>]]></t>"},
623 {"]]></t><injected/><t>", "<t><![CDATA[]]]]><![CDATA[></t><injected/><t>]]></t>"},
624 }
625 for _, c := range cases {
626 doc := NewDocument()
627 e := doc.CreateElement("t")
628 e.CreateCData(c.data)
629
630 s, err := doc.WriteToString()
631 if err != nil {
632 t.Fatal("etree: failed to serialize document")
633 }
634 checkStrEq(t, s, c.expected)
635 checkTokenIsolation(t, s)
636
637 doc2 := newDocumentFromString2(t, s, ReadSettings{PreserveCData: true})
638 checkStrEq(t, doc2.Root().Text(), c.data)
639 }
640 }
641
642 func TestSanitizeComment(t *testing.T) {
643 cases := []struct {
644 data string
645 expected string
646 }{
647 {"", "<t><!----></t>"},
648 {" comment ", "<t><!-- comment --></t>"},
649 {"-", "<t><!--- --></t>"},
650 {"--", "<t><!--- - --></t>"},
651 {"---", "<t><!--- - - --></t>"},
652 {"a--b", "<t><!--a- -b--></t>"},
653 {"a-b-c", "<t><!--a-b-c--></t>"},
654 {"-->", "<t><!--- ->--></t>"},
655 {"--></t><injected/><t><!--", "<t><!--- -></t><injected/><t><!- - --></t>"},
656 }
657 for _, c := range cases {
658 doc := NewDocument()
659 e := doc.CreateElement("t")
660 e.CreateComment(c.data)
661
662 s, err := doc.WriteToString()
663 if err != nil {
664 t.Fatal("etree: failed to serialize document")
665 }
666 checkStrEq(t, s, c.expected)
667 checkTokenIsolation(t, s)
668 }
669 }
670
671 func TestSanitizeDirective(t *testing.T) {
672 cases := []struct {
673 data string
674 expected string
675 }{
676 {"DOCTYPE root SYSTEM \"root.dtd\"", "<t><!DOCTYPE root SYSTEM \"root.dtd\"></t>"},
677 {"DOCTYPE root [<!ELEMENT root (#PCDATA)>]", "<t><!DOCTYPE root [<!ELEMENT root (#PCDATA)>]></t>"},
678 {"DOCTYPE root [<!ENTITY e \"a>b\">]", "<t><!DOCTYPE root [<!ENTITY e \"a>b\">]></t>"},
679 {"DOCTYPE root [<!-- a > b -->]", "<t><!DOCTYPE root [<!-- a > b -->]></t>"},
680
681 // Unbalanced contents are character-escaped.
682 {"DOCTYPE root><injected/", "<t><!DOCTYPE root&gt;&lt;injected/></t>"},
683 {"DOCTYPE root \"unterminated", "<t><!DOCTYPE root &quot;unterminated></t>"},
684 {"DOCTYPE root [<!ENTITY e \"a\"", "<t><!DOCTYPE root [&lt;!ENTITY e &quot;a&quot;></t>"},
685 {"DOCTYPE root <!-- unterminated", "<t><!DOCTYPE root &lt;!-- unterminated></t>"},
686
687 // The decoder consumes a directive's first character literally, so
688 // contents whose balance depends on that character are escaped.
689 {"\"><injected/>\"", "<t><!&quot;&gt;&lt;injected/&gt;&quot;></t>"},
690 {"<!-- --><injected/><!--", "<t><!&lt;!-- --&gt;&lt;injected/&gt;&lt;!--></t>"},
691
692 // Contents that are empty or that begin with '-' or '[' are preceded
693 // by a space so the directive isn't decoded as a directive, comment
694 // or CDATA section.
695 {"", "<t><! ></t>"},
696 {"-- comment --", "<t><! -- comment --></t>"},
697 {"--> <injected/> <!--", "<t><! --&gt; &lt;injected/&gt; &lt;!--></t>"},
698 {"[CDATA[]]> <injected/>", "<t><! [CDATA[]]&gt; &lt;injected/&gt;></t>"},
699 }
700 for _, c := range cases {
701 doc := NewDocument()
702 e := doc.CreateElement("t")
703 e.CreateDirective(c.data)
704
705 s, err := doc.WriteToString()
706 if err != nil {
707 t.Fatal("etree: failed to serialize document")
708 }
709 checkStrEq(t, s, c.expected)
710 checkTokenIsolation(t, s)
711 }
712 }
713
714 func TestSanitizeProcInst(t *testing.T) {
715 cases := []struct {
716 target string
717 inst string
718 expected string
719 }{
720 {"xml", `version="1.0" encoding="UTF-8"`, `<t><?xml version="1.0" encoding="UTF-8"?></t>`},
721 {"target", "", "<t><?target?></t>"},
722 {"target", "a?>b", "<t><?target a? >b?></t>"},
723 {"target", "?>", "<t><?target ? >?></t>"},
724 {"target", "a??>b", "<t><?target a?? >b?></t>"},
725 {"target", "?></t><injected/><t><?target", "<t><?target ? ></t><injected/><t><?target?></t>"},
726 {"target?>", "inst", "<t><?target? > inst?></t>"},
727 }
728 for _, c := range cases {
729 doc := NewDocument()
730 e := doc.CreateElement("t")
731 e.CreateProcInst(c.target, c.inst)
732
733 s, err := doc.WriteToString()
734 if err != nil {
735 t.Fatal("etree: failed to serialize document")
736 }
737 checkStrEq(t, s, c.expected)
738 checkTokenIsolation(t, s)
739 }
740 }
741
742 func TestFuzzInjection(t *testing.T) {
743 fragments := []string{
744 "<",
745 ">",
746 "-",
747 "--",
748 "-->",
749 "<!--",
750 "]]>",
751 "[CDATA[",
752 "?>",
753 "<?",
754 "!",
755 "\"",
756 "'",
757 "[",
758 "]",
759 "<injected/>",
760 "</t>",
761 "a",
762 " ",
763 "\t",
764 "DOCTYPE",
765 "&",
766 }
767
768 rng := rand.New(rand.NewSource(1))
769 randData := func() string {
770 var sb strings.Builder
771 for i := rng.Intn(15) + 1; i >= 0; i-- {
772 fragment := fragments[rng.Intn(len(fragments))]
773 sb.WriteString(fragment)
774 }
775 return sb.String()
776 }
777
778 for i := range 100000 {
779 data := randData()
780 doc := NewDocument()
781 e := doc.CreateElement("t")
782
783 var kind string
784 switch i % 4 {
785 case 0:
786 e.CreateCData(data)
787 kind = "cdata"
788 case 1:
789 e.CreateComment(data)
790 kind = "comment"
791 case 2:
792 e.CreateDirective(data)
793 kind = "directive"
794 case 3:
795 e.CreateProcInst("t"+data, randData())
796 kind = "procinst"
797 }
798
799 s, err := doc.WriteToString()
800 if err != nil {
801 t.Fatalf("%s write err: %v", kind, err)
802 }
803
804 doc2 := NewDocument()
805 doc2.ReadSettings.PreserveCData = true
806
807 if err := doc2.ReadFromString(s); err != nil {
808 t.Fatalf("%s: data %q produced unparseable xml %q: %v", kind, data, s, err)
809 }
810
811 if len(doc2.Child) != 1 || doc2.Root() == nil || doc2.Root().Tag != "t" {
812 t.Fatalf("%s: data %q escaped the root: %q", kind, data, s)
813 }
814
815 if n := len(doc2.Root().ChildElements()); n != 0 {
816 t.Fatalf("%s: data %q injected %d element(s): %q", kind, data, n, s)
817 }
818
819 if kind == "cdata" && doc2.Root().Text() != data {
820 t.Fatalf("cdata: data %q did not round trip: %q", data, doc2.Root().Text())
821 }
822 }
823 }
824
825 // checkTokenIsolation re-reads the XML string 's', which is expected to
826 // contain a lone root element 't' holding a single token. It confirms that
827 // the token's data remained trapped within the token instead of injecting new
828 // XML into the document.
829 func checkTokenIsolation(t *testing.T, s string) {
830 t.Helper()
831
832 doc := newDocumentFromString2(t, s, ReadSettings{PreserveCData: true})
833 if len(doc.Child) != 1 {
834 t.Errorf("etree: token data escaped its document: %s\n", s)
835 return
836 }
837
838 root := doc.Root()
839 if root == nil || root.Tag != "t" {
840 t.Errorf("etree: token data replaced the root element: %s\n", s)
841 return
842 }
843 if len(root.ChildElements()) != 0 {
844 t.Errorf("etree: token data injected an element: %s\n", s)
845 }
846 }
847
848 func TestCanonical(t *testing.T) {
849 BOM := "\xef\xbb\xbf"
850
851 doc := NewDocument()
852 doc.WriteSettings.CanonicalEndTags = true
853 doc.WriteSettings.CanonicalText = true
854 doc.WriteSettings.CanonicalAttrVal = true
855 doc.CreateCharData(BOM)
856 doc.CreateProcInst("xml-stylesheet", `type="text/xsl" href="style.xsl"`)
857
858 people := doc.CreateElement("People")
859 people.CreateComment("These are all known people")
860
861 jon := people.CreateElement("Person")
862 jon.CreateAttr("name", "Jon O'Reilly")
863 jon.SetText("\r<'\">&\u0004\u0005\u001f�")
864
865 sally := people.CreateElement("Person")
866 sally.CreateAttr("name", "Sally")
867 sally.CreateAttr("escape", "\r\n\t<'\">&")
868
869 doc.Indent(2)
870 s, err := doc.WriteToString()
871 if err != nil {
872 t.Error("etree: WriteSettings WriteTo produced incorrect result.")
873 }
874
875 expected := BOM + `<?xml-stylesheet type="text/xsl" href="style.xsl"?>
876 <People>
877 <!--These are all known people-->
878 <Person name="Jon O'Reilly">&#xD;&lt;'"&gt;&amp;����</Person>
879 <Person name="Sally" escape="&#xD;&#xA;&#x9;&lt;'&quot;>&amp;"></Person>
880 </People>
881 `
882 checkStrEq(t, s, expected)
883 }
884
885 func TestCopy(t *testing.T) {
886 s := `<store>
887 <book lang="en">
888 <title>Great Expectations</title>
889 <author>Charles Dickens</author>
890 </book>
891 </store>`
892
893 doc := newDocumentFromString(t, s)
894
895 s1, err := doc.WriteToString()
896 if err != nil {
897 t.Error("etree: incorrect WriteToString result")
898 }
899
900 doc2 := doc.Copy()
901 checkIndexes(t, &doc2.Element)
902 s2, err := doc2.WriteToString()
903 if err != nil {
904 t.Error("etree: incorrect Copy result")
905 }
906
907 if s1 != s2 {
908 t.Error("etree: mismatched Copy result")
909 t.Error("wanted:\n" + s1)
910 t.Error("got:\n" + s2)
911 }
912
913 e1 := doc.FindElement("./store/book/title")
914 e2 := doc2.FindElement("./store/book/title")
915 if e1 == nil || e2 == nil || e1.parent == nil || e1 == e2 {
916 t.Error("etree: incorrect FindElement result")
917 }
918
919 e1.parent.RemoveChildAt(e1.Index())
920 s1, _ = doc.WriteToString()
921 s2, _ = doc2.WriteToString()
922 if s1 == s2 {
923 t.Error("etree: incorrect result after RemoveElement")
924 }
925 }
926
927 func TestGetPath(t *testing.T) {
928 s := `<a>
929 <b1>
930 <c1>
931 <d1/>
932 <d1a/>
933 </c1>
934 </b1>
935 <b2>
936 <c2>
937 <d2/>
938 </c2>
939 </b2>
940 </a>`
941
942 doc := newDocumentFromString(t, s)
943
944 cases := []struct {
945 from string
946 to string
947 relpath string
948 topath string
949 }{
950 {"a", ".", "..", "/"},
951 {".", "a", "./a", "/a"},
952 {"a/b1/c1/d1", ".", "../../../..", "/"},
953 {".", "a/b1/c1/d1", "./a/b1/c1/d1", "/a/b1/c1/d1"},
954 {"a", "a", ".", "/a"},
955 {"a/b1", "a/b1/c1", "./c1", "/a/b1/c1"},
956 {"a/b1/c1", "a/b1", "..", "/a/b1"},
957 {"a/b1/c1", "a/b1/c1", ".", "/a/b1/c1"},
958 {"a", "a/b1", "./b1", "/a/b1"},
959 {"a/b1", "a", "..", "/a"},
960 {"a", "a/b1/c1", "./b1/c1", "/a/b1/c1"},
961 {"a/b1/c1", "a", "../..", "/a"},
962 {"a/b1/c1/d1", "a", "../../..", "/a"},
963 {"a", "a/b1/c1/d1", "./b1/c1/d1", "/a/b1/c1/d1"},
964 {"a/b1", "a/b2", "../b2", "/a/b2"},
965 {"a/b2", "a/b1", "../b1", "/a/b1"},
966 {"a/b1/c1/d1", "a/b2/c2/d2", "../../../b2/c2/d2", "/a/b2/c2/d2"},
967 {"a/b2/c2/d2", "a/b1/c1/d1", "../../../b1/c1/d1", "/a/b1/c1/d1"},
968 {"a/b1/c1/d1", "a/b1/c1/d1a", "../d1a", "/a/b1/c1/d1a"},
969 }
970
971 for _, c := range cases {
972 fe := doc.FindElement(c.from)
973 te := doc.FindElement(c.to)
974
975 rp := te.GetRelativePath(fe)
976 if rp != c.relpath {
977 t.Errorf("GetRelativePath from '%s' to '%s'. Expected '%s', got '%s'.\n", c.from, c.to, c.relpath, rp)
978 }
979
980 p := te.GetPath()
981 if p != c.topath {
982 t.Errorf("GetPath for '%s'. Expected '%s', got '%s'.\n", c.to, c.topath, p)
983 }
984 }
985 }
986
987 func TestInsertChild(t *testing.T) {
988 s := `<book lang="en">
989 <t:title>Great Expectations</t:title>
990 <author>Charles Dickens</author>
991 </book>
992 `
993
994 doc := newDocumentFromString(t, s)
995
996 year := NewElement("year")
997 year.SetText("1861")
998
999 book := doc.FindElement("//book")
1000 book.InsertChildAt(book.SelectElement("t:title").Index(), year)
1001
1002 expected1 := `<book lang="en">
1003 <year>1861</year>
1004 <t:title>Great Expectations</t:title>
1005 <author>Charles Dickens</author>
1006 </book>
1007 `
1008 doc.Indent(2)
1009 s1, _ := doc.WriteToString()
1010 checkStrEq(t, s1, expected1)
1011
1012 book.RemoveChildAt(year.Index())
1013 book.InsertChildAt(book.SelectElement("author").Index(), year)
1014
1015 expected2 := `<book lang="en">
1016 <t:title>Great Expectations</t:title>
1017 <year>1861</year>
1018 <author>Charles Dickens</author>
1019 </book>
1020 `
1021 doc.Indent(2)
1022 s2, _ := doc.WriteToString()
1023 checkStrEq(t, s2, expected2)
1024
1025 book.RemoveChildAt(year.Index())
1026 book.InsertChildAt(len(book.Child), year)
1027
1028 expected3 := `<book lang="en">
1029 <t:title>Great Expectations</t:title>
1030 <author>Charles Dickens</author>
1031 <year>1861</year>
1032 </book>
1033 `
1034 doc.Indent(2)
1035 s3, _ := doc.WriteToString()
1036 checkStrEq(t, s3, expected3)
1037
1038 book.RemoveChildAt(year.Index())
1039 book.InsertChildAt(999, year)
1040
1041 expected4 := `<book lang="en">
1042 <t:title>Great Expectations</t:title>
1043 <author>Charles Dickens</author>
1044 <year>1861</year>
1045 </book>
1046 `
1047 doc.Indent(2)
1048 s4, _ := doc.WriteToString()
1049 checkStrEq(t, s4, expected4)
1050
1051 year = doc.FindElement("//book/year")
1052 book.InsertChildAt(0, year)
1053
1054 expected5 := `<book lang="en">
1055 <year>1861</year>
1056 <t:title>Great Expectations</t:title>
1057 <author>Charles Dickens</author>
1058 </book>
1059 `
1060
1061 doc.Indent(2)
1062 s5, _ := doc.WriteToString()
1063 checkStrEq(t, s5, expected5)
1064
1065 author := doc.FindElement("//book/author")
1066 year = doc.FindElement("//book/year")
1067 book.InsertChildAt(author.Index(), year)
1068
1069 expected6 := `<book lang="en">
1070 <t:title>Great Expectations</t:title>
1071 <year>1861</year>
1072 <author>Charles Dickens</author>
1073 </book>
1074 `
1075 doc.Indent(2)
1076 s6, _ := doc.WriteToString()
1077 checkStrEq(t, s6, expected6)
1078 }
1079
1080 func TestCdata(t *testing.T) {
1081 var tests = []struct {
1082 in, out string
1083 }{
1084 {`<tag>1234567</tag>`, "1234567"},
1085 {`<tag><![CDATA[1234567]]></tag>`, "1234567"},
1086 {`<tag>1<![CDATA[2]]>3<![CDATA[4]]>5<![CDATA[6]]>7</tag>`, "1234567"},
1087 {`<tag>1<![CDATA[2]]>3<inner>4</inner>5<![CDATA[6]]>7</tag>`, "123"},
1088 {`<tag>1<inner>4</inner>5<![CDATA[6]]>7</tag>`, "1"},
1089 {`<tag><![CDATA[1]]><inner>4</inner>5<![CDATA[6]]>7</tag>`, "1"},
1090 }
1091
1092 for _, test := range tests {
1093 doc := NewDocument()
1094 err := doc.ReadFromString(test.in)
1095 if err != nil {
1096 t.Fatal("etree ReadFromString: " + err.Error())
1097 }
1098
1099 tag := doc.FindElement("tag")
1100 if tag.Text() != test.out {
1101 t.Fatalf("etree invalid cdata. Expected: %v. Got: %v\n", test.out, tag.Text())
1102 }
1103 }
1104 }
1105
1106 func TestAddChild(t *testing.T) {
1107 s := `<book lang="en">
1108 <t:title>Great Expectations</t:title>
1109 <author>Charles Dickens</author>
1110 </book>
1111 `
1112 doc1 := newDocumentFromString(t, s)
1113
1114 doc2 := NewDocument()
1115 root := doc2.CreateElement("root")
1116
1117 for _, e := range doc1.FindElements("//book/*") {
1118 root.AddChild(e)
1119 }
1120
1121 expected1 := `<book lang="en"/>
1122 `
1123 doc1.Indent(2)
1124 s1, _ := doc1.WriteToString()
1125 checkStrEq(t, s1, expected1)
1126
1127 expected2 := `<root>
1128 <t:title>Great Expectations</t:title>
1129 <author>Charles Dickens</author>
1130 </root>
1131 `
1132 doc2.Indent(2)
1133 s2, _ := doc2.WriteToString()
1134 checkStrEq(t, s2, expected2)
1135 }
1136
1137 func TestSetRoot(t *testing.T) {
1138 s := `<?test a="wow"?>
1139 <book>
1140 <title>Great Expectations</title>
1141 <author>Charles Dickens</author>
1142 </book>
1143 `
1144 doc := newDocumentFromString(t, s)
1145
1146 origroot := doc.Root()
1147 if origroot.Parent() != &doc.Element {
1148 t.Error("Root incorrect")
1149 }
1150
1151 newroot := NewElement("root")
1152 doc.SetRoot(newroot)
1153
1154 if doc.Root() != newroot {
1155 t.Error("doc.Root() != newroot")
1156 }
1157 if origroot.Parent() != nil {
1158 t.Error("origroot.Parent() != nil")
1159 }
1160
1161 expected1 := `<?test a="wow"?>
1162 <root/>
1163 `
1164 doc.Indent(2)
1165 s1, _ := doc.WriteToString()
1166 checkStrEq(t, s1, expected1)
1167
1168 doc.SetRoot(origroot)
1169 doc.Indent(2)
1170 expected2 := s
1171 s2, _ := doc.WriteToString()
1172 checkStrEq(t, s2, expected2)
1173
1174 doc2 := NewDocument()
1175 doc2.CreateProcInst("test", `a="wow"`)
1176 doc2.SetRoot(NewElement("root"))
1177 doc2.Indent(2)
1178 expected3 := expected1
1179 s3, _ := doc2.WriteToString()
1180 checkStrEq(t, s3, expected3)
1181
1182 doc2.SetRoot(doc.Root())
1183 doc2.Indent(2)
1184 expected4 := s
1185 s4, _ := doc2.WriteToString()
1186 checkStrEq(t, s4, expected4)
1187
1188 expected5 := `<?test a="wow"?>
1189 `
1190 doc.Indent(2)
1191 s5, _ := doc.WriteToString()
1192 checkStrEq(t, s5, expected5)
1193 }
1194
1195 func TestSortAttrs(t *testing.T) {
1196 s := `<el foo='5' Foo='2' aaa='4' สวัสดี='7' AAA='1' a01='3' z='6' a:ZZZ='9' a:AAA='8'/>`
1197 doc := newDocumentFromString(t, s)
1198 doc.Root().SortAttrs()
1199 doc.Indent(2)
1200 out, _ := doc.WriteToString()
1201 checkStrEq(t, out, `<el AAA="1" Foo="2" a01="3" aaa="4" foo="5" z="6" สวัสดี="7" a:AAA="8" a:ZZZ="9"/>`+"\n")
1202 }
1203
1204 func TestCharsetReaderDefaultSetting(t *testing.T) {
1205 // Test encodings where the default pass-through charset conversion
1206 // should work for common single-byte character encodings.
1207 cases := []string{
1208 `<?xml version="1.0"?><foo></foo>`,
1209 `<?xml version="1.0" encoding="ISO-8859-1"?><foo></foo>`,
1210 `<?xml version="1.0" encoding="Windows-1252"?><foo></foo>`,
1211 `<?xml version="1.0" encoding="UTF-8"?><foo></foo>`,
1212 `<?xml version="1.0" encoding="US-ASCII"?><foo></foo>`,
1213 }
1214
1215 for _, c := range cases {
1216 doc := NewDocument()
1217 if err := doc.ReadFromBytes([]byte(c)); err != nil {
1218 t.Error(err)
1219 }
1220 }
1221 }
1222
1223 func TestCharData(t *testing.T) {
1224 doc := NewDocument()
1225 root := doc.CreateElement("root")
1226 root.CreateCharData("This ")
1227 root.CreateCData("is ")
1228 e1 := NewText("a ")
1229 e2 := NewCData("text ")
1230 root.AddChild(e1)
1231 root.AddChild(e2)
1232 root.CreateCharData("Element!!")
1233
1234 s, err := doc.WriteToString()
1235 if err != nil {
1236 t.Error("etree: failed to serialize document")
1237 }
1238
1239 checkStrEq(t, s, `<root>This <![CDATA[is ]]>a <![CDATA[text ]]>Element!!</root>`)
1240
1241 // Check we can parse the output
1242 err = doc.ReadFromString(s)
1243 if err != nil {
1244 t.Fatal("etree: incorrect ReadFromString result")
1245 }
1246 if doc.Root().Text() != "This is a text Element!!" {
1247 t.Error("etree: invalid text")
1248 }
1249 }
1250
1251 func TestIndentSimple(t *testing.T) {
1252 doc := NewDocument()
1253 root := doc.CreateElement("root")
1254 ch1 := root.CreateElement("child1")
1255 ch1.CreateElement("child2")
1256
1257 // First test Unindent.
1258 doc.Unindent()
1259 s, err := doc.WriteToString()
1260 if err != nil {
1261 t.Error("etree: failed to serialize document")
1262 }
1263 expected := "<root><child1><child2/></child1></root>"
1264 checkStrEq(t, s, expected)
1265
1266 // Now test Indent with NoIndent (which should produce the same result
1267 // as Unindent).
1268 doc.Indent(NoIndent)
1269 s, err = doc.WriteToString()
1270 if err != nil {
1271 t.Error("etree: failed to serialize document")
1272 }
1273 checkStrEq(t, s, expected)
1274
1275 // Run all indent test cases.
1276 tests := []struct {
1277 useTabs, useCRLF bool
1278 ws, nl string
1279 }{
1280 {false, false, " ", "\n"},
1281 {false, true, " ", "\r\n"},
1282 {true, false, "\t", "\n"},
1283 {true, true, "\t", "\r\n"},
1284 }
1285
1286 for _, test := range tests {
1287 doc.WriteSettings.UseCRLF = test.useCRLF
1288 if test.useTabs {
1289 doc.IndentTabs()
1290 s, err := doc.WriteToString()
1291 if err != nil {
1292 t.Error("etree: failed to serialize document")
1293 }
1294 tab := test.ws
1295 expected := "<root>" + test.nl + tab + "<child1>" + test.nl +
1296 tab + tab + "<child2/>" + test.nl + tab +
1297 "</child1>" + test.nl + "</root>" + test.nl
1298 checkStrEq(t, s, expected)
1299 } else {
1300 for i := 0; i < 256; i++ {
1301 doc.Indent(i)
1302 s, err := doc.WriteToString()
1303 if err != nil {
1304 t.Error("etree: failed to serialize document")
1305 }
1306 tab := strings.Repeat(test.ws, i)
1307 expected := "<root>" + test.nl + tab + "<child1>" + test.nl +
1308 tab + tab + "<child2/>" + test.nl + tab +
1309 "</child1>" + test.nl + "</root>" + test.nl
1310 checkStrEq(t, s, expected)
1311 }
1312 }
1313 }
1314 }
1315
1316 func TestIndentWithDefaultSettings(t *testing.T) {
1317 input := `<root>
1318 <child1>
1319 <child2> </child2>
1320 </child1>
1321 </root>`
1322
1323 doc := NewDocument()
1324 err := doc.ReadFromString(input)
1325 if err != nil {
1326 t.Error("etree: failed to read string")
1327 }
1328
1329 settings := NewIndentSettings()
1330 doc.IndentWithSettings(settings)
1331 s, err := doc.WriteToString()
1332 if err != nil {
1333 t.Error("etree: failed to serialize document")
1334 }
1335 expected := "<root>\n <child1>\n <child2/>\n </child1>\n</root>\n"
1336 checkStrEq(t, s, expected)
1337 }
1338
1339 func TestIndentWithSettings(t *testing.T) {
1340 doc := NewDocument()
1341 root := doc.CreateElement("root")
1342 ch1 := root.CreateElement("child1")
1343 ch1.CreateElement("child2")
1344
1345 // First test with NoIndent.
1346 settings := NewIndentSettings()
1347 settings.UseCRLF = false
1348 settings.UseTabs = false
1349 settings.Spaces = NoIndent
1350 doc.IndentWithSettings(settings)
1351 s, err := doc.WriteToString()
1352 if err != nil {
1353 t.Error("etree: failed to serialize document")
1354 }
1355 expected := "<root><child1><child2/></child1></root>"
1356 checkStrEq(t, s, expected)
1357
1358 // Run all indent test cases.
1359 tests := []struct {
1360 useTabs, useCRLF bool
1361 ws, nl string
1362 }{
1363 {false, false, " ", "\n"},
1364 {false, true, " ", "\r\n"},
1365 {true, false, "\t", "\n"},
1366 {true, true, "\t", "\r\n"},
1367 }
1368
1369 for _, test := range tests {
1370 if test.useTabs {
1371 settings := NewIndentSettings()
1372 settings.UseTabs = true
1373 settings.UseCRLF = test.useCRLF
1374 doc.IndentWithSettings(settings)
1375 s, err := doc.WriteToString()
1376 if err != nil {
1377 t.Error("etree: failed to serialize document")
1378 }
1379 tab := test.ws
1380 expected := "<root>" + test.nl + tab + "<child1>" + test.nl +
1381 tab + tab + "<child2/>" + test.nl + tab +
1382 "</child1>" + test.nl + "</root>" + test.nl
1383 checkStrEq(t, s, expected)
1384 } else {
1385 for i := 0; i < 256; i++ {
1386 settings := NewIndentSettings()
1387 settings.Spaces = i
1388 settings.UseTabs = false
1389 settings.UseCRLF = test.useCRLF
1390 doc.IndentWithSettings(settings)
1391 s, err := doc.WriteToString()
1392 if err != nil {
1393 t.Error("etree: failed to serialize document")
1394 }
1395 tab := strings.Repeat(test.ws, i)
1396 expected := "<root>" + test.nl + tab + "<child1>" + test.nl +
1397 tab + tab + "<child2/>" + test.nl + tab +
1398 "</child1>" + test.nl + "</root>" + test.nl
1399 checkStrEq(t, s, expected)
1400 }
1401 }
1402 }
1403 }
1404
1405 func TestIndentPreserveWhitespace(t *testing.T) {
1406 tests := []struct {
1407 input string
1408 expected string
1409 }{
1410 {"<test></test>", "<test/>"},
1411 {"<test> </test>", "<test> </test>"},
1412 {"<test>\t</test>", "<test>\t</test>"},
1413 {"<test>\t\n \t</test>", "<test>\t\n \t</test>"},
1414 {"<test><![CDATA[ ]]></test>", "<test> </test>"},
1415 {"<test> <![CDATA[ ]]> </test>", "<test/>"},
1416 {"<outer> <inner> </inner> </outer>", "<outer>\n <inner> </inner>\n</outer>"},
1417 }
1418
1419 for _, test := range tests {
1420 doc := NewDocument()
1421 err := doc.ReadFromString(test.input)
1422 if err != nil {
1423 t.Error("etree: failed to read string")
1424 }
1425
1426 s := NewIndentSettings()
1427 s.Spaces = 2
1428 s.PreserveLeafWhitespace = true
1429 s.SuppressTrailingWhitespace = true
1430 doc.IndentWithSettings(s)
1431
1432 output, err := doc.WriteToString()
1433 if err != nil {
1434 t.Error("etree: failed to read string")
1435 }
1436 checkStrEq(t, output, test.expected)
1437 }
1438 }
1439
1440 func TestPreserveCData(t *testing.T) {
1441 tests := []struct {
1442 input string
1443 expectedWithPreserve string
1444 expectedWithoutPreserve string
1445 }{
1446 {
1447 "<test><![CDATA[x]]></test>",
1448 "<test><![CDATA[x]]></test>",
1449 "<test>x</test>",
1450 },
1451 {
1452 "<tag><![CDATA[x <b>foo</b>]]></tag>",
1453 "<tag><![CDATA[x <b>foo</b>]]></tag>",
1454 "<tag>x &lt;b&gt;foo&lt;/b&gt;</tag>",
1455 },
1456 {
1457 "<name><![CDATA[My]]> <b>name</b> <![CDATA[is]]></name>",
1458 "<name><![CDATA[My]]> <b>name</b> <![CDATA[is]]></name>",
1459 "<name>My <b>name</b> is</name>",
1460 },
1461 }
1462
1463 for _, test := range tests {
1464 doc := newDocumentFromString2(t, test.input, ReadSettings{PreserveCData: true})
1465 output, _ := doc.WriteToString()
1466 checkStrEq(t, output, test.expectedWithPreserve)
1467 }
1468
1469 for _, test := range tests {
1470 doc := newDocumentFromString2(t, test.input, ReadSettings{PreserveCData: false})
1471 output, _ := doc.WriteToString()
1472 checkStrEq(t, output, test.expectedWithoutPreserve)
1473 }
1474 }
1475
1476 func TestTokenIndexing(t *testing.T) {
1477 s := `<?xml version="1.0" encoding="UTF-8"?>
1478 <?xml-stylesheet type="text/xsl" href="style.xsl"?>
1479 <store xmlns:t="urn:books-com:titles">
1480 <!Directive>
1481 <!--This is a comment-->
1482 <book lang="en">
1483 <t:title>Great Expectations</t:title>
1484 <author>Charles Dickens</author>
1485 <review/>
1486 </book>
1487 </store>`
1488
1489 doc := newDocumentFromString(t, s)
1490 review := doc.FindElement("/store/book/review")
1491 review.SetText("Excellent")
1492
1493 checkIndexes(t, &doc.Element)
1494
1495 doc.Indent(4)
1496 checkIndexes(t, &doc.Element)
1497
1498 doc.Indent(NoIndent)
1499 checkIndexes(t, &doc.Element)
1500
1501 e := NewElement("foo")
1502 store := doc.SelectElement("store")
1503 store.InsertChildAt(0, e)
1504 checkIndexes(t, &doc.Element)
1505
1506 store.RemoveChildAt(0)
1507 checkIndexes(t, &doc.Element)
1508 }
1509
1510 func TestSetText(t *testing.T) {
1511 doc := NewDocument()
1512 root := doc.CreateElement("root")
1513
1514 checkDocEq(t, doc, `<root/>`)
1515 checkStrEq(t, root.Text(), "")
1516 checkIntEq(t, len(root.Child), 0)
1517
1518 root.SetText("foo")
1519 checkDocEq(t, doc, `<root>foo</root>`)
1520 checkStrEq(t, root.Text(), "foo")
1521 checkIntEq(t, len(root.Child), 1)
1522
1523 root.SetText("bar")
1524 checkDocEq(t, doc, `<root>bar</root>`)
1525 checkStrEq(t, root.Text(), "bar")
1526 checkIntEq(t, len(root.Child), 1)
1527
1528 root.CreateCData("cdata")
1529 checkDocEq(t, doc, `<root>bar<![CDATA[cdata]]></root>`)
1530 checkStrEq(t, root.Text(), "barcdata")
1531 checkIntEq(t, len(root.Child), 2)
1532
1533 root.SetText("qux")
1534 checkDocEq(t, doc, `<root>qux</root>`)
1535 checkStrEq(t, root.Text(), "qux")
1536 checkIntEq(t, len(root.Child), 1)
1537
1538 root.CreateCData("cdata")
1539 checkDocEq(t, doc, `<root>qux<![CDATA[cdata]]></root>`)
1540 checkStrEq(t, root.Text(), "quxcdata")
1541 checkIntEq(t, len(root.Child), 2)
1542
1543 root.SetCData("baz")
1544 checkDocEq(t, doc, `<root><![CDATA[baz]]></root>`)
1545 checkStrEq(t, root.Text(), "baz")
1546 checkIntEq(t, len(root.Child), 1)
1547
1548 root.CreateText("corge")
1549 root.CreateCData("grault")
1550 root.CreateText("waldo")
1551 root.CreateCData("fred")
1552 root.CreateElement("child")
1553 checkDocEq(t, doc, `<root><![CDATA[baz]]>corge<![CDATA[grault]]>waldo<![CDATA[fred]]><child/></root>`)
1554 checkStrEq(t, root.Text(), "bazcorgegraultwaldofred")
1555 checkIntEq(t, len(root.Child), 6)
1556
1557 root.SetText("plugh")
1558 checkDocEq(t, doc, `<root>plugh<child/></root>`)
1559 checkStrEq(t, root.Text(), "plugh")
1560 checkIntEq(t, len(root.Child), 2)
1561
1562 root.SetText("")
1563 checkDocEq(t, doc, `<root><child/></root>`)
1564 checkStrEq(t, root.Text(), "")
1565 checkIntEq(t, len(root.Child), 1)
1566
1567 root.SetText("")
1568 checkDocEq(t, doc, `<root><child/></root>`)
1569 checkStrEq(t, root.Text(), "")
1570 checkIntEq(t, len(root.Child), 1)
1571
1572 root.RemoveChildAt(0)
1573 root.CreateText("corge")
1574 root.CreateCData("grault")
1575 root.CreateText("waldo")
1576 root.CreateCData("fred")
1577 root.CreateElement("child")
1578 checkDocEq(t, doc, `<root>corge<![CDATA[grault]]>waldo<![CDATA[fred]]><child/></root>`)
1579 checkStrEq(t, root.Text(), "corgegraultwaldofred")
1580 checkIntEq(t, len(root.Child), 5)
1581
1582 root.SetText("")
1583 checkDocEq(t, doc, `<root><child/></root>`)
1584 checkStrEq(t, root.Text(), "")
1585 checkIntEq(t, len(root.Child), 1)
1586 }
1587
1588 func TestSetTail(t *testing.T) {
1589 doc := NewDocument()
1590 root := doc.CreateElement("root")
1591 child := root.CreateElement("child")
1592 root.CreateText("\n\t")
1593 child.SetText("foo")
1594 checkDocEq(t, doc, "<root><child>foo</child>\n\t</root>")
1595 checkStrEq(t, child.Tail(), "\n\t")
1596 checkIntEq(t, len(root.Child), 2)
1597 checkIntEq(t, len(child.Child), 1)
1598
1599 root.CreateCData(" ")
1600 checkDocEq(t, doc, "<root><child>foo</child>\n\t<![CDATA[ ]]></root>")
1601 checkStrEq(t, child.Tail(), "\n\t ")
1602 checkIntEq(t, len(root.Child), 3)
1603 checkIntEq(t, len(child.Child), 1)
1604
1605 child.SetTail("")
1606 checkDocEq(t, doc, "<root><child>foo</child></root>")
1607 checkStrEq(t, child.Tail(), "")
1608 checkIntEq(t, len(root.Child), 1)
1609 checkIntEq(t, len(child.Child), 1)
1610
1611 child.SetTail("\t\t\t")
1612 checkDocEq(t, doc, "<root><child>foo</child>\t\t\t</root>")
1613 checkStrEq(t, child.Tail(), "\t\t\t")
1614 checkIntEq(t, len(root.Child), 2)
1615 checkIntEq(t, len(child.Child), 1)
1616
1617 child.SetTail("\t\n\n\t")
1618 checkDocEq(t, doc, "<root><child>foo</child>\t\n\n\t</root>")
1619 checkStrEq(t, child.Tail(), "\t\n\n\t")
1620 checkIntEq(t, len(root.Child), 2)
1621 checkIntEq(t, len(child.Child), 1)
1622
1623 child.SetTail("")
1624 checkDocEq(t, doc, "<root><child>foo</child></root>")
1625 checkStrEq(t, child.Tail(), "")
1626 checkIntEq(t, len(root.Child), 1)
1627 checkIntEq(t, len(child.Child), 1)
1628 }
1629
1630 func TestAttrParent(t *testing.T) {
1631 doc := NewDocument()
1632 root := doc.CreateElement("root")
1633 attr1 := root.CreateAttr("bar", "1")
1634 attr2 := root.CreateAttr("qux", "2")
1635
1636 checkIntEq(t, len(root.Attr), 2)
1637 checkElementEq(t, attr1.Element(), root)
1638 checkElementEq(t, attr2.Element(), root)
1639
1640 attr1 = root.RemoveAttr("bar")
1641 attr2 = root.RemoveAttr("qux")
1642 checkElementEq(t, attr1.Element(), nil)
1643 checkElementEq(t, attr2.Element(), nil)
1644
1645 s := `<root a="1" b="2" c="3" d="4"/>`
1646 err := doc.ReadFromString(s)
1647 if err != nil {
1648 t.Error("etree: failed to parse document")
1649 }
1650
1651 root = doc.SelectElement("root")
1652 for i := range root.Attr {
1653 checkElementEq(t, root.Attr[i].Element(), root)
1654 }
1655 }
1656
1657 func TestDefaultNamespaceURI(t *testing.T) {
1658 s := `
1659 <root xmlns="https://root.example.com" xmlns:attrib="https://attrib.example.com" attrib:a="foo" b="bar">
1660 <child1 xmlns="https://child.example.com" attrib:a="foo">
1661 <grandchild1 xmlns="https://grandchild.example.com" a="foo">
1662 </grandchild1>
1663 <grandchild2 a="foo">
1664 <greatgrandchild1 attrib:a="foo"/>
1665 </grandchild2>
1666 </child1>
1667 <child2 a="foo"/>
1668 </root>`
1669
1670 doc := newDocumentFromString(t, s)
1671 root := doc.SelectElement("root")
1672 child1 := root.SelectElement("child1")
1673 child2 := root.SelectElement("child2")
1674 grandchild1 := child1.SelectElement("grandchild1")
1675 grandchild2 := child1.SelectElement("grandchild2")
1676 greatgrandchild1 := grandchild2.SelectElement("greatgrandchild1")
1677
1678 checkStrEq(t, doc.NamespaceURI(), "")
1679 checkStrEq(t, root.NamespaceURI(), "https://root.example.com")
1680 checkStrEq(t, child1.NamespaceURI(), "https://child.example.com")
1681 checkStrEq(t, child2.NamespaceURI(), "https://root.example.com")
1682 checkStrEq(t, grandchild1.NamespaceURI(), "https://grandchild.example.com")
1683 checkStrEq(t, grandchild2.NamespaceURI(), "https://child.example.com")
1684 checkStrEq(t, greatgrandchild1.NamespaceURI(), "https://child.example.com")
1685
1686 checkStrEq(t, root.Attr[0].NamespaceURI(), "")
1687 checkStrEq(t, root.Attr[1].NamespaceURI(), "")
1688 checkStrEq(t, root.Attr[2].NamespaceURI(), "https://attrib.example.com")
1689 checkStrEq(t, root.Attr[3].NamespaceURI(), "")
1690 checkStrEq(t, child1.Attr[0].NamespaceURI(), "")
1691 checkStrEq(t, child1.Attr[1].NamespaceURI(), "https://attrib.example.com")
1692 checkStrEq(t, child2.Attr[0].NamespaceURI(), "")
1693 checkStrEq(t, grandchild1.Attr[0].NamespaceURI(), "")
1694 checkStrEq(t, grandchild1.Attr[1].NamespaceURI(), "")
1695 checkStrEq(t, grandchild2.Attr[0].NamespaceURI(), "")
1696 checkStrEq(t, greatgrandchild1.Attr[0].NamespaceURI(), "https://attrib.example.com")
1697
1698 f := doc.FindElements("//*[namespace-uri()='https://root.example.com']")
1699 if len(f) != 2 || f[0] != root || f[1] != child2 {
1700 t.Error("etree: failed namespace-uri test")
1701 }
1702
1703 f = doc.FindElements("//*[namespace-uri()='https://child.example.com']")
1704 if len(f) != 3 || f[0] != child1 || f[1] != grandchild2 || f[2] != greatgrandchild1 {
1705 t.Error("etree: failed namespace-uri test")
1706 }
1707
1708 f = doc.FindElements("//*[namespace-uri()='https://grandchild.example.com']")
1709 if len(f) != 1 || f[0] != grandchild1 {
1710 t.Error("etree: failed namespace-uri test")
1711 }
1712
1713 f = doc.FindElements("//*[namespace-uri()='']")
1714 if len(f) != 0 {
1715 t.Error("etree: failed namespace-uri test")
1716 }
1717
1718 f = doc.FindElements("//*[namespace-uri()='foo']")
1719 if len(f) != 0 {
1720 t.Error("etree: failed namespace-uri test")
1721 }
1722 }
1723
1724 func TestLocalNamespaceURI(t *testing.T) {
1725 s := `
1726 <a:root xmlns:a="https://root.example.com">
1727 <b:child1 xmlns:b="https://child.example.com">
1728 <c:grandchild1 xmlns:c="https://grandchild.example.com"/>
1729 <b:grandchild2>
1730 <a:greatgrandchild1/>
1731 </b:grandchild2>
1732 <a:grandchild3/>
1733 <grandchild4/>
1734 </b:child1>
1735 <a:child2>
1736 </a:child2>
1737 <child3>
1738 </child3>
1739 </a:root>`
1740
1741 doc := newDocumentFromString(t, s)
1742 root := doc.SelectElement("root")
1743 child1 := root.SelectElement("child1")
1744 child2 := root.SelectElement("child2")
1745 child3 := root.SelectElement("child3")
1746 grandchild1 := child1.SelectElement("grandchild1")
1747 grandchild2 := child1.SelectElement("grandchild2")
1748 grandchild3 := child1.SelectElement("grandchild3")
1749 grandchild4 := child1.SelectElement("grandchild4")
1750 greatgrandchild1 := grandchild2.SelectElement("greatgrandchild1")
1751
1752 checkStrEq(t, doc.NamespaceURI(), "")
1753 checkStrEq(t, root.NamespaceURI(), "https://root.example.com")
1754 checkStrEq(t, child1.NamespaceURI(), "https://child.example.com")
1755 checkStrEq(t, child2.NamespaceURI(), "https://root.example.com")
1756 checkStrEq(t, child3.NamespaceURI(), "")
1757 checkStrEq(t, grandchild1.NamespaceURI(), "https://grandchild.example.com")
1758 checkStrEq(t, grandchild2.NamespaceURI(), "https://child.example.com")
1759 checkStrEq(t, grandchild3.NamespaceURI(), "https://root.example.com")
1760 checkStrEq(t, grandchild4.NamespaceURI(), "")
1761 checkStrEq(t, greatgrandchild1.NamespaceURI(), "https://root.example.com")
1762
1763 f := doc.FindElements("//*[namespace-uri()='https://root.example.com']")
1764 if len(f) != 4 || f[0] != root || f[1] != child2 || f[2] != grandchild3 || f[3] != greatgrandchild1 {
1765 t.Error("etree: failed namespace-uri test")
1766 }
1767
1768 f = doc.FindElements("//*[namespace-uri()='https://child.example.com']")
1769 if len(f) != 2 || f[0] != child1 || f[1] != grandchild2 {
1770 t.Error("etree: failed namespace-uri test")
1771 }
1772
1773 f = doc.FindElements("//*[namespace-uri()='https://grandchild.example.com']")
1774 if len(f) != 1 || f[0] != grandchild1 {
1775 t.Error("etree: failed namespace-uri test")
1776 }
1777
1778 f = doc.FindElements("//*[namespace-uri()='']")
1779 if len(f) != 2 || f[0] != child3 || f[1] != grandchild4 {
1780 t.Error("etree: failed namespace-uri test")
1781 }
1782
1783 f = doc.FindElements("//*[namespace-uri()='foo']")
1784 if len(f) != 0 {
1785 t.Error("etree: failed namespace-uri test")
1786 }
1787 }
1788
1789 func TestWhitespace(t *testing.T) {
1790 s := "<root>\n\t<child>\n\t\t<grandchild> x</grandchild>\n </child>\n</root>"
1791
1792 doc := newDocumentFromString(t, s)
1793 root := doc.Root()
1794 checkIntEq(t, len(root.Child), 3)
1795
1796 cd := root.Child[0].(*CharData)
1797 checkBoolEq(t, cd.IsWhitespace(), true)
1798 checkStrBinaryEq(t, cd.Data, "\n\t")
1799
1800 cd = root.Child[2].(*CharData)
1801 checkBoolEq(t, cd.IsWhitespace(), true)
1802 checkStrBinaryEq(t, cd.Data, "\n")
1803
1804 child := root.SelectElement("child")
1805 checkIntEq(t, len(child.Child), 3)
1806
1807 cd = child.Child[0].(*CharData)
1808 checkBoolEq(t, cd.IsWhitespace(), true)
1809 checkStrBinaryEq(t, cd.Data, "\n\t\t")
1810
1811 cd = child.Child[2].(*CharData)
1812 checkBoolEq(t, cd.IsWhitespace(), true)
1813 checkStrBinaryEq(t, cd.Data, "\n ")
1814
1815 grandchild := child.SelectElement("grandchild")
1816 checkIntEq(t, len(grandchild.Child), 1)
1817
1818 cd = grandchild.Child[0].(*CharData)
1819 checkBoolEq(t, cd.IsWhitespace(), false)
1820
1821 cd.SetData(" ")
1822 checkBoolEq(t, cd.IsWhitespace(), true)
1823
1824 cd.SetData(" x")
1825 checkBoolEq(t, cd.IsWhitespace(), false)
1826
1827 cd.SetData("\t\n\r ")
1828 checkBoolEq(t, cd.IsWhitespace(), true)
1829
1830 cd.SetData("\uFFFD")
1831 checkBoolEq(t, cd.IsWhitespace(), false)
1832
1833 cd.SetData("")
1834 checkBoolEq(t, cd.IsWhitespace(), true)
1835 }
1836
1837 func TestTokenWriteTo(t *testing.T) {
1838 s := `<store>
1839 <!-- comment -->
1840 <book>
1841 <title>Great Expectations</title>
1842 </book>
1843 </store>`
1844 doc := newDocumentFromString(t, s)
1845
1846 writeSettings := WriteSettings{}
1847 indentSettings := IndentSettings{UseTabs: true}
1848
1849 tests := []struct {
1850 path string
1851 expected string
1852 }{
1853 {"//store", "<store>\n\t<!-- comment -->\n\t<book>\n\t\t<title>Great Expectations</title>\n\t</book>\n</store>"},
1854 {"//store/book", "<book>\n\t<title>Great Expectations</title>\n</book>"},
1855 {"//store/book/title", "<title>Great Expectations</title>"},
1856 }
1857 for _, test := range tests {
1858 var buffer bytes.Buffer
1859
1860 c := doc.FindElement(test.path)
1861 c.IndentWithSettings(&indentSettings)
1862 c.WriteTo(&buffer, &writeSettings)
1863 checkStrEq(t, buffer.String(), test.expected)
1864 }
1865 }
1866
1867 func TestReindexChildren(t *testing.T) {
1868 s := `<root>
1869 <child1/>
1870 <child2/>
1871 <child3/>
1872 <child4/>
1873 <child5/>
1874 </root>`
1875 doc := newDocumentFromString(t, s)
1876 doc.Unindent()
1877
1878 root := doc.Root()
1879 if root == nil || root.Tag != "root" || len(root.Child) != 5 {
1880 t.Error("etree: expected root element not found")
1881 }
1882
1883 for i := 0; i < len(root.Child); i++ {
1884 if root.Child[i].Index() != i {
1885 t.Error("etree: incorrect child index found in root element child")
1886 }
1887 }
1888
1889 rand.Shuffle(len(root.Child), func(i, j int) {
1890 root.Child[i], root.Child[j] = root.Child[j], root.Child[i]
1891 })
1892
1893 root.ReindexChildren()
1894
1895 for i := 0; i < len(root.Child); i++ {
1896 if root.Child[i].Index() != i {
1897 t.Error("etree: incorrect child index found in root element child")
1898 }
1899 }
1900 }
1901
1902 func TestPreserveDuplicateAttrs(t *testing.T) {
1903 s := `<element x="value1" y="value2" x="value3" x="value4" y="value5"/>`
1904
1905 checkAttrCount := func(e *Element, n int) {
1906 if len(e.Attr) != n {
1907 t.Errorf("etree: expected %d attributes, got %d", n, len(e.Attr))
1908 }
1909 }
1910 checkAttr := func(e *Element, i int, key, value string) {
1911 if i >= len(e.Attr) {
1912 t.Errorf("etree: attr[%d] out of bounds", i)
1913 return
1914 }
1915 if e.Attr[i].Key != key {
1916 t.Errorf("etree: attr[%d] expected key %s, got %s", i, key, e.Attr[i].Key)
1917 }
1918 if e.Attr[i].Value != value {
1919 t.Errorf("etree: attr[%d] expected value %s, got %s", i, value, e.Attr[i].Value)
1920 }
1921 }
1922
1923 t.Run("enabled", func(t *testing.T) {
1924 doc := newDocumentFromString2(t, s, ReadSettings{PreserveDuplicateAttrs: true})
1925 e := doc.FindElement("element")
1926 checkAttrCount(e, 5)
1927 checkAttr(e, 0, "x", "value1")
1928 checkAttr(e, 1, "y", "value2")
1929 checkAttr(e, 2, "x", "value3")
1930 checkAttr(e, 3, "x", "value4")
1931 checkAttr(e, 4, "y", "value5")
1932 })
1933
1934 t.Run("disabled", func(t *testing.T) {
1935 doc := newDocumentFromString2(t, s, ReadSettings{})
1936 e := doc.FindElement("element")
1937 checkAttrCount(e, 2)
1938 checkAttr(e, 0, "x", "value4")
1939 checkAttr(e, 1, "y", "value5")
1940 })
1941 }
1942
1943 func TestNotNil(t *testing.T) {
1944 s := `<enabled>true</enabled>`
1945
1946 doc := newDocumentFromString(t, s)
1947 doc.SelectElement("enabled").NotNil().SetText("false")
1948 doc.SelectElement("visible").NotNil().SetText("true")
1949
1950 want := `<enabled>false</enabled>`
1951 got, err := doc.WriteToString()
1952 if err != nil {
1953 t.Fatal("etree: failed to write document to string")
1954 }
1955 if got != want {
1956 t.Error("etree: unexpected NotNil result")
1957 t.Error("wanted:\n" + want)
1958 t.Error("got:\n" + got)
1959 }
1960 }
1961
1962 func TestValidateInput(t *testing.T) {
1963 tests := []struct {
1964 s string
1965 err string
1966 }{
1967 {`<root>x</root>`, ""},
1968 {`<root/>`, ""},
1969 {`<root>x`, `XML syntax error on line 1: unexpected EOF`},
1970 {`</root><root>`, `XML syntax error on line 1: unexpected end element </root>`},
1971 {`<>`, `XML syntax error on line 1: expected element name after <`},
1972 {`<root>x</root>trailing`, "etree: invalid XML format"},
1973 {`<root>x</root><`, "etree: invalid XML format"},
1974 {`<root><child>x</child></root1>`, `XML syntax error on line 1: element <root> closed by </root1>`},
1975 }
1976
1977 type readFunc func(doc *Document, s string) error
1978 runTests := func(t *testing.T, read readFunc) {
1979 for i, test := range tests {
1980 doc := NewDocument()
1981 doc.ReadSettings.ValidateInput = true
1982 err := read(doc, test.s)
1983 if err == nil {
1984 if test.err != "" {
1985 t.Errorf("etree: test #%d:\nExpected error:\n %s\nReceived error:\n nil", i, test.err)
1986 }
1987 root := doc.Root()
1988 if root == nil || root.Tag != "root" {
1989 t.Errorf("etree: test #%d: failed to read document after input validation", i)
1990 }
1991 } else {
1992 te := err.Error()
1993 if te != test.err {
1994 t.Errorf("etree: test #%d:\nExpected error;\n %s\nReceived error:\n %s", i, test.err, te)
1995 }
1996 }
1997 }
1998 }
1999
2000 readFromString := func(doc *Document, s string) error {
2001 return doc.ReadFromString(s)
2002 }
2003 t.Run("ReadFromString", func(t *testing.T) { runTests(t, readFromString) })
2004
2005 readFromBytes := func(doc *Document, s string) error {
2006 return doc.ReadFromBytes([]byte(s))
2007 }
2008 t.Run("ReadFromBytes", func(t *testing.T) { runTests(t, readFromBytes) })
2009
2010 readFromFile := func(doc *Document, s string) error {
2011 pathtmp := path.Join(t.TempDir(), "etree-test")
2012 err := os.WriteFile(pathtmp, []byte(s), fs.ModePerm)
2013 if err != nil {
2014 return errors.New("unable to write tmp file for input validation")
2015 }
2016 return doc.ReadFromFile(pathtmp)
2017 }
2018 t.Run("ReadFromFile", func(t *testing.T) { runTests(t, readFromFile) })
2019 }
2020
2021 func TestSiblingElement(t *testing.T) {
2022 doc := newDocumentFromString(t, `<root><a/><b> <b1/> </b> <!--test--> <c/></root>`)
2023
2024 root := doc.SelectElement("root")
2025 a := root.SelectElement("a")
2026 b := root.SelectElement("b")
2027 c := root.SelectElement("c")
2028 b1 := b.SelectElement("b1")
2029
2030 tests := []struct {
2031 e *Element
2032 next *Element
2033 prev *Element
2034 }{
2035 {root, nil, nil},
2036 {a, b, nil},
2037 {b, c, a},
2038 {c, nil, b},
2039 {b1, nil, nil},
2040 }
2041
2042 toString := func(e *Element) string {
2043 if e == nil {
2044 return "nil"
2045 }
2046 return e.Tag
2047 }
2048
2049 for i, test := range tests {
2050 next := test.e.NextSibling()
2051 if next != test.next {
2052 t.Errorf("etree: test #%d unexpected NextSibling result.\n Expected: %s\n Received: %s\n",
2053 i, toString(next), toString(test.next))
2054 }
2055
2056 prev := test.e.PrevSibling()
2057 if prev != test.prev {
2058 t.Errorf("etree: test #%d unexpected PrevSibling result.\n Expected: %s\n Received: %s\n",
2059 i, toString(prev), toString(test.prev))
2060 }
2061 }
2062 }
2063
2064 func TestContinuations(t *testing.T) {
2065 doc := NewDocument()
2066 root := doc.CreateChild("root", func(e *Element) {
2067 e.CreateChild("child1", func(e *Element) {
2068 e.CreateComment("Grandchildren of child #1")
2069 e.CreateChild("grandchild1", func(e *Element) {
2070 e.CreateAttr("attr1", "1")
2071 e.CreateAttr("attr2", "2")
2072 })
2073 e.CreateChild("grandchild2", func(e *Element) {
2074 e.CreateAttr("attr1", "3")
2075 e.CreateAttr("attr2", "4")
2076 })
2077 })
2078 e.CreateChild("child2", func(e *Element) {
2079 e.CreateComment("Grandchildren of child #2")
2080 e.CreateChild("grandchild1", func(e *Element) {
2081 e.CreateAttr("attr1", "5")
2082 e.CreateAttr("attr2", "6")
2083 })
2084 e.CreateChild("grandchild2", func(e *Element) {
2085 e.CreateAttr("attr1", "7")
2086 e.CreateAttr("attr2", "8")
2087 })
2088 })
2089 })
2090 checkStrEq(t, root.Tag, "root")
2091
2092 // Serialize the document to a string
2093 doc.IndentTabs()
2094 s, err := doc.WriteToString()
2095 if err != nil {
2096 t.Error("etree: failed to serialize document")
2097 }
2098
2099 // Make sure the serialized XML matches expectation.
2100 expected := `<root>
2101 <child1>
2102 <!--Grandchildren of child #1-->
2103 <grandchild1 attr1="1" attr2="2"/>
2104 <grandchild2 attr1="3" attr2="4"/>
2105 </child1>
2106 <child2>
2107 <!--Grandchildren of child #2-->
2108 <grandchild1 attr1="5" attr2="6"/>
2109 <grandchild2 attr1="7" attr2="8"/>
2110 </child2>
2111 </root>
2112 `
2113
2114 checkStrEq(t, s, expected)
2115 }
2116
2117 func TestMaxDepth(t *testing.T) {
2118 tests := []struct {
2119 maxDepth int
2120 depth int
2121 err error
2122 }{
2123 {0, defaultMaxDepth, nil},
2124 {0, defaultMaxDepth + 1, ErrMaxDepth},
2125 {-1, defaultMaxDepth, nil},
2126 {-1, defaultMaxDepth + 1, ErrMaxDepth},
2127 {1, 1, nil},
2128 {1, 2, ErrMaxDepth},
2129 {5, 4, nil},
2130 {5, 5, nil},
2131 {5, 6, ErrMaxDepth},
2132 }
2133
2134 for _, test := range tests {
2135 for _, validate := range []bool{false, true} {
2136 s := nestedXML(test.depth)
2137 settings := ReadSettings{MaxDepth: test.maxDepth, ValidateInput: validate}
2138
2139 doc := NewDocument()
2140 doc.ReadSettings = settings
2141 err := doc.ReadFromString(s)
2142 if !errors.Is(err, test.err) {
2143 t.Errorf("etree: ReadFromString(MaxDepth=%d, depth=%d, ValidateInput=%v) returned error %v, expected %v",
2144 test.maxDepth, test.depth, validate, err, test.err)
2145 }
2146
2147 doc = NewDocument()
2148 doc.ReadSettings = settings
2149 err = doc.ReadFromBytes([]byte(s))
2150 if !errors.Is(err, test.err) {
2151 t.Errorf("etree: ReadFromBytes(MaxDepth=%d, depth=%d, ValidateInput=%v) returned error %v, expected %v",
2152 test.maxDepth, test.depth, validate, err, test.err)
2153 }
2154
2155 doc = NewDocument()
2156 doc.ReadSettings = settings
2157 _, err = doc.ReadFrom(strings.NewReader(s))
2158 if !errors.Is(err, test.err) {
2159 t.Errorf("etree: ReadFrom(MaxDepth=%d, depth=%d, ValidateInput=%v) returned error %v, expected %v",
2160 test.maxDepth, test.depth, validate, err, test.err)
2161 }
2162 }
2163 }
2164 }
2165
2166 func nestedXML(depth int) string {
2167 var sb strings.Builder
2168 for i := 0; i < depth; i++ {
2169 sb.WriteString("<a>")
2170 }
2171 for i := 0; i < depth; i++ {
2172 sb.WriteString("</a>")
2173 }
2174 return sb.String()
2175 }