Debian Codegraph @

xpath_test.go

raw
1 package xpath
2
3 import (
4 "bytes"
5 "fmt"
6 "math"
7 "reflect"
8 "sort"
9 "strings"
10 "testing"
11 )
12
13 var (
14 employee_example = createEmployeeExample()
15 book_example = createBookExample()
16 html_example = createHtmlExample()
17 empty_example = createNode("", RootNode)
18 mybook_example = createMyBookExample()
19 )
20
21 type testQuery string
22
23 func (t testQuery) Select(_ iterator) NodeNavigator {
24 panic("implement me")
25 }
26
27 func (t testQuery) Clone() query {
28 return t
29 }
30
31 func (t testQuery) Evaluate(_ iterator) interface{} {
32 return string(t)
33 }
34
35 func (t testQuery) ValueType() resultType {
36 return xpathResultType.Any
37 }
38
39 func (t testQuery) Properties() queryProp {
40 return queryProps.None
41 }
42
43 func test_xpath_elements(t *testing.T, root *TNode, expr string, expected ...int) {
44 result := selectNodes(root, expr)
45
46 var gotLines []int
47 for i := 0; i < len(result); i++ {
48 gotLines = append(gotLines, result[i].lines)
49 }
50
51 if !reflect.DeepEqual(gotLines, expected) {
52 t.Fatalf("expected lines %+v, got %+v", expected, gotLines)
53 }
54 }
55
56 func test_xpath_values(t testing.TB, root *TNode, expr string, expected ...string) {
57 result := selectNodes(root, expr)
58 assertEqual(t, len(expected), len(result))
59
60 for i := 0; i < len(expected); i++ {
61 assertEqual(t, expected[i], result[i].Value())
62 }
63 }
64
65 func test_xpath_tags(t *testing.T, root *TNode, expr string, expected ...string) {
66 result := selectNodes(root, expr)
67 assertEqual(t, len(expected), len(result))
68
69 for i := 0; i < len(expected); i++ {
70 assertEqual(t, expected[i], result[i].Data)
71 }
72 }
73
74 func test_xpath_count(t *testing.T, root *TNode, expr string, expected int) {
75 result := selectNodes(root, expr)
76 assertEqual(t, expected, len(result))
77 }
78
79 func test_xpath_eval(t *testing.T, root *TNode, expr string, expected ...interface{}) {
80 e, err := Compile(expr)
81 assertNoErr(t, err)
82
83 v := e.Evaluate(createNavigator(root))
84 // if is a node-set
85 if iter, ok := v.(*NodeIterator); ok {
86 got := iterateNavs(iter)
87 assertEqual(t, len(expected), len(got))
88 for i := 0; i < len(expected); i++ {
89 assertEqual(t, expected[i], got[i])
90 }
91 return
92 }
93 assertEqual(t, expected[0], v)
94 }
95
96 func Test_Predicates_MultiParent(t *testing.T) {
97 // https://github.com/antchfx/xpath/issues/75
98 /*
99 <measCollecFile xmlns="http://www.3gpp.org/ftp/specs/archive/32_series/32.435#measCollec">
100 <measData>
101 <measInfo>
102 <measType p="1">field1</measType>
103 <measType p="2">field2</measType>
104 <measValue>
105 <r p="1">31854</r>
106 <r p="2">159773</r>
107 </measValue>
108 </measInfo>
109 <measInfo measInfoId="metric_name2">
110 <measType p="1">field3</measType>
111 <measType p="2">field4</measType>
112 <measValue>
113 <r p="1">1234</r>
114 <r p="2">567</r>
115 </measValue>
116 </measInfo>
117 </measData>
118 </measCollecFile>
119 */
120 doc := createNode("", RootNode)
121 measCollecFile := doc.createChildNode("measCollecFile", ElementNode)
122 measData := measCollecFile.createChildNode("measData", ElementNode)
123 data := []struct {
124 measType map[string]string
125 measValue map[string]string
126 }{
127 {measType: map[string]string{"1": "field1", "2": "field2"}, measValue: map[string]string{"1": "31854", "2": "159773"}},
128 {measType: map[string]string{"1": "field3", "2": "field4"}, measValue: map[string]string{"1": "1234", "2": "567"}},
129 }
130 for j := 0; j < len(data); j++ {
131 d := data[j]
132 measInfo := measData.createChildNode("measInfo", ElementNode)
133 measType := measInfo.createChildNode("measType", ElementNode)
134
135 var keys []string
136 for k := range d.measType {
137 keys = append(keys, k)
138 }
139 sort.Strings(keys)
140
141 for _, k := range keys {
142 measType.addAttribute("p", k)
143 measType.createChildNode(d.measType[k], TextNode)
144 }
145
146 measValue := measInfo.createChildNode("measValue", ElementNode)
147 keys = make([]string, 0)
148 for k := range d.measValue {
149 keys = append(keys, k)
150 }
151 sort.Strings(keys)
152 for _, k := range keys {
153 r := measValue.createChildNode("r", ElementNode)
154 r.addAttribute("p", k)
155 r.createChildNode(d.measValue[k], TextNode)
156 }
157 }
158 test_xpath_values(t, doc, `//r[@p=../../measType/@p]`, "31854", "159773", "1234", "567")
159
160 }
161
162 func TestCompile(t *testing.T) {
163 var err error
164 _, err = Compile("//a")
165 assertNil(t, err)
166 _, err = Compile("//a[id=']/span")
167 assertErr(t, err)
168 _, err = Compile("//ul/li/@class")
169 assertNil(t, err)
170 _, err = Compile("/a/b/(c, .[not(c)])")
171 assertNil(t, err)
172 _, err = Compile("/pre:foo")
173 assertNil(t, err)
174 }
175
176 func TestInvalidXPath(t *testing.T) {
177 var err error
178 _, err = Compile("()")
179 assertErr(t, err)
180 _, err = Compile("(1,2,3)")
181 assertErr(t, err)
182 }
183
184 // A variable reference nested inside a larger expression used to compile
185 // without error and then panic at select time, because the builder had no
186 // case for variable nodes and left a nil sub-query behind. Compilation should
187 // report it as undeclared, matching the bare "$x" case.
188 func TestCompileUndeclaredVariable(t *testing.T) {
189 for _, expr := range []string{"$x", "$x/@attr", "$var + 1", "//a[$x]"} {
190 if _, err := Compile(expr); err == nil {
191 t.Errorf("Compile(%q) expected an error for the undeclared variable, got nil", expr)
192 }
193 }
194 }
195
196 func TestCompileWithNS(t *testing.T) {
197 _, err := CompileWithNS("/foo", nil)
198 assertNil(t, err)
199 _, err = CompileWithNS("/foo", map[string]string{})
200 assertNil(t, err)
201 _, err = CompileWithNS("/foo", map[string]string{"a": "b"})
202 assertNil(t, err)
203 _, err = CompileWithNS("/a:foo", map[string]string{"a": "b"})
204 assertNil(t, err)
205 _, err = CompileWithNS("/u:foo", map[string]string{"a": "b"})
206 assertErr(t, err)
207 }
208
209 func TestNamespacePrefixQuery(t *testing.T) {
210 /*
211 <?xml version="1.0" encoding="UTF-8"?>
212 <books>
213 <book>book1</book>
214 <b:book xmlns:b="ns">book2</b:book>
215 <c:book xmlns:c="ns">book3</c:book>
216 </books>
217 */
218 doc := createNode("", RootNode)
219 books := doc.createChildNode("books", ElementNode)
220 books.lines = 2
221 book1 := books.createChildNode("book", ElementNode)
222 book1.lines = 3
223 book1.createChildNode("book1", TextNode)
224 book2 := books.createChildNode("b:book", ElementNode)
225 book2.lines = 4
226 book2.addAttribute("xmlns:b", "ns")
227 book2.createChildNode("book2", TextNode)
228 book3 := books.createChildNode("c:book", ElementNode)
229 book3.lines = 5
230 book3.addAttribute("xmlns:c", "ns")
231 book3.createChildNode("book3", TextNode)
232
233 test_xpath_elements(t, doc, `//b:book`, 4) // expected [4 , 5]
234
235 // With namespace bindings:
236 exp, _ := CompileWithNS("//x:book", map[string]string{"x": "ns"})
237 nodes := iterateNodes(exp.Select(createNavigator(doc)))
238 assertEqual(t, 2, len(nodes))
239 assertEqual(t, "book2", nodes[0].Value())
240 assertEqual(t, "book3", nodes[1].Value())
241 }
242
243 func TestMustCompile(t *testing.T) {
244 expr := MustCompile("//")
245 assertTrue(t, expr != nil)
246
247 if wanted := (nopQuery{}); expr.q != wanted {
248 t.Fatalf("wanted nopQuery object but got %s", expr)
249 }
250 iter := expr.Select(createNavigator(html_example))
251 if iter.MoveNext() {
252 t.Fatal("should be an empty node list but got one")
253 }
254 }
255
256 func Test_plusFunc(t *testing.T) {
257 // 1+1
258 assertEqual(t, float64(2), plusFunc(nil, float64(1), float64(1)))
259 // string +
260 assertEqual(t, float64(2), plusFunc(nil, "1", "1"))
261 // invalid string
262 v := plusFunc(nil, "a", 1)
263 assertTrue(t, math.IsNaN(v.(float64)))
264 // Nodeset
265 // TODO
266 }
267
268 func Test_minusFunc(t *testing.T) {
269 // 1 - 1
270 assertEqual(t, float64(0), minusFunc(nil, float64(1), float64(1)))
271 // string
272 assertEqual(t, float64(0), minusFunc(nil, "1", "1"))
273 // invalid string
274 v := minusFunc(nil, "a", 1)
275 assertTrue(t, math.IsNaN(v.(float64)))
276 }
277
278 func TestNodeType(t *testing.T) {
279 tests := []struct {
280 expr string
281 expected NodeType
282 }{
283 {`//employee`, ElementNode},
284 {`//name[text()]`, ElementNode},
285 {`//name/text()`, TextNode},
286 {`//employee/@id`, AttributeNode},
287 }
288 for _, test := range tests {
289 v := selectNode(employee_example, test.expr)
290 assertTrue(t, v != nil)
291 assertEqual(t, test.expected, v.Type)
292 }
293
294 doc := createNode("", RootNode)
295 doc.createChildNode("<!-- This is a comment -->", CommentNode)
296 n := selectNode(doc, "//comment()")
297 assertTrue(t, n != nil)
298 assertEqual(t, CommentNode, n.Type)
299 }
300
301 func iterateNavs(t *NodeIterator) []*TNodeNavigator {
302 var nodes []*TNodeNavigator
303 for t.MoveNext() {
304 node := t.Current().(*TNodeNavigator)
305 nodes = append(nodes, node)
306 }
307 return nodes
308 }
309
310 func iterateNodes(t *NodeIterator) []*TNode {
311 var nodes []*TNode
312 for t.MoveNext() {
313 n := t.Current().(*TNodeNavigator)
314 if n.NodeType() == AttributeNode {
315 childNode := &TNode{
316 Type: TextNode,
317 Data: n.Value(),
318 }
319 nodes = append(nodes, &TNode{
320 Parent: n.curr,
321 Type: AttributeNode,
322 Data: n.LocalName(),
323 FirstChild: childNode,
324 LastChild: childNode,
325 })
326 } else {
327 nodes = append(nodes, n.curr)
328 }
329
330 }
331 return nodes
332 }
333
334 func selectNode(root *TNode, expr string) *TNode {
335 list := selectNodes(root, expr)
336 if len(list) == 0 {
337 return nil
338 }
339 return list[0]
340 }
341
342 func selectNodes(root *TNode, expr string) []*TNode {
343 t := Select(createNavigator(root), expr)
344 c := make(map[uint64]bool)
345 var list []*TNode
346 for _, n := range iterateNodes(t) {
347 m := getHashCode(createNavigator(n))
348 if _, ok := c[m]; ok {
349 continue
350 }
351 c[m] = true
352 list = append(list, n)
353 }
354 return list
355 }
356
357 func joinValues(nodes []*TNode) string {
358 s := make([]string, 0)
359 for _, n := range nodes {
360 s = append(s, n.Value())
361 }
362 return strings.Join(s, ",")
363 }
364
365 func createNavigator(n *TNode) *TNodeNavigator {
366 return &TNodeNavigator{curr: n, root: n, attr: -1}
367 }
368
369 type Attribute struct {
370 Key, Value string
371 }
372
373 type TNode struct {
374 Parent, FirstChild, LastChild, PrevSibling, NextSibling *TNode
375
376 Type NodeType
377 Data string
378 Attr []Attribute
379 NamespaceURL string
380 Prefix string
381 lines int
382 }
383
384 func (n *TNode) Value() string {
385 if n.Type == TextNode {
386 return n.Data
387 }
388
389 var buff bytes.Buffer
390 var output func(*TNode)
391 output = func(node *TNode) {
392 if node.Type == TextNode {
393 buff.WriteString(node.Data)
394 }
395 for child := node.FirstChild; child != nil; child = child.NextSibling {
396 output(child)
397 }
398 }
399 output(n)
400 return buff.String()
401 }
402
403 // TNodeNavigator is for navigating TNode.
404 type TNodeNavigator struct {
405 curr, root *TNode
406 attr int
407 }
408
409 func (n *TNodeNavigator) NodeType() NodeType {
410 switch n.curr.Type {
411 case CommentNode:
412 return CommentNode
413 case TextNode:
414 return TextNode
415 case ElementNode:
416 if n.attr != -1 {
417 return AttributeNode
418 }
419 return ElementNode
420 }
421 return n.curr.Type
422 }
423
424 func (n *TNodeNavigator) LocalName() string {
425 if n.attr != -1 {
426 return n.curr.Attr[n.attr].Key
427 }
428 name := n.curr.Data
429 if strings.Contains(name, ":") {
430 return strings.Split(name, ":")[1]
431 }
432 return name
433 }
434
435 func (n *TNodeNavigator) Prefix() string {
436 if n.attr == -1 && strings.Contains(n.curr.Data, ":") {
437 return strings.Split(n.curr.Data, ":")[0]
438 }
439 return n.curr.Prefix
440 }
441
442 func (n *TNodeNavigator) NamespaceURL() string {
443 if n.Prefix() != "" {
444 for _, a := range n.curr.Attr {
445 if a.Key == "xmlns:"+n.Prefix() {
446 return a.Value
447 }
448 }
449 }
450 return n.curr.NamespaceURL
451 }
452
453 func (n *TNodeNavigator) Value() string {
454 switch n.curr.Type {
455 case CommentNode:
456 return n.curr.Data
457 case ElementNode:
458 if n.attr != -1 {
459 return n.curr.Attr[n.attr].Value
460 }
461 var buf bytes.Buffer
462 node := n.curr.FirstChild
463 for node != nil {
464 if node.Type == TextNode {
465 buf.WriteString(strings.TrimSpace(node.Data))
466 }
467 node = node.NextSibling
468 }
469 return buf.String()
470 case TextNode:
471 return n.curr.Data
472 }
473 return ""
474 }
475
476 func (n *TNodeNavigator) Copy() NodeNavigator {
477 n2 := *n
478 return &n2
479 }
480
481 func (n *TNodeNavigator) MoveToRoot() {
482 n.curr = n.root
483 }
484
485 func (n *TNodeNavigator) MoveToParent() bool {
486 if n.attr != -1 {
487 n.attr = -1
488 return true
489 } else if node := n.curr.Parent; node != nil {
490 n.curr = node
491 return true
492 }
493 return false
494 }
495
496 func (n *TNodeNavigator) MoveToNextAttribute() bool {
497 if n.attr >= len(n.curr.Attr)-1 {
498 return false
499 }
500 n.attr++
501 return true
502 }
503
504 func (n *TNodeNavigator) MoveToChild() bool {
505 if n.attr != -1 {
506 return false
507 }
508 if node := n.curr.FirstChild; node != nil {
509 n.curr = node
510 return true
511 }
512 return false
513 }
514
515 func (n *TNodeNavigator) MoveToFirst() bool {
516 if n.attr != -1 || n.curr.PrevSibling == nil {
517 return false
518 }
519 for {
520 node := n.curr.PrevSibling
521 if node == nil {
522 break
523 }
524 n.curr = node
525 }
526 return true
527 }
528
529 func (n *TNodeNavigator) String() string {
530 return n.Value()
531 }
532
533 func (n *TNodeNavigator) MoveToNext() bool {
534 if n.attr != -1 {
535 return false
536 }
537 if node := n.curr.NextSibling; node != nil {
538 n.curr = node
539 return true
540 }
541 return false
542 }
543
544 func (n *TNodeNavigator) MoveToPrevious() bool {
545 if n.attr != -1 {
546 return false
547 }
548 if node := n.curr.PrevSibling; node != nil {
549 n.curr = node
550 return true
551 }
552 return false
553 }
554
555 func (n *TNodeNavigator) MoveTo(other NodeNavigator) bool {
556 node, ok := other.(*TNodeNavigator)
557 if !ok || node.root != n.root {
558 return false
559 }
560
561 n.curr = node.curr
562 n.attr = node.attr
563 return true
564 }
565
566 func createNode(data string, typ NodeType) *TNode {
567 return &TNode{Data: data, Type: typ, Attr: make([]Attribute, 0)}
568 }
569
570 func (n *TNode) createChildNode(data string, typ NodeType) *TNode {
571 m := createNode(data, typ)
572 m.Parent = n
573 if n.FirstChild == nil {
574 n.FirstChild = m
575 } else {
576 n.LastChild.NextSibling = m
577 m.PrevSibling = n.LastChild
578 }
579 n.LastChild = m
580 return m
581 }
582
583 func (n *TNode) appendNode(data string, typ NodeType) *TNode {
584 m := createNode(data, typ)
585 m.Parent = n.Parent
586 n.NextSibling = m
587 m.PrevSibling = n
588 if n.Parent != nil {
589 n.Parent.LastChild = m
590 }
591 return m
592 }
593
594 func (n *TNode) addAttribute(k, v string) {
595 n.Attr = append(n.Attr, Attribute{k, v})
596 }
597
598 func (n *TNode) getAttribute(key string) string {
599 for i := 0; i < len(n.Attr); i++ {
600 if n.Attr[i].Key == key {
601 return n.Attr[i].Value
602 }
603 }
604 return ""
605 }
606
607 func createElementAttr(line int, name string, attrs map[string]string, children ...*TNode) *TNode {
608 el := createElement(line, name, children...)
609 for k, v := range attrs {
610 el.addAttribute(k, v)
611 }
612 return el
613 }
614
615 func createElement(line int, name string, children ...*TNode) *TNode {
616 nodeType := ElementNode
617 if name == "" {
618 nodeType = RootNode
619 }
620 n := createNode(name, nodeType)
621 n.lines = line
622 for _, c := range children {
623 c.Parent = n
624 c.PrevSibling = n.LastChild
625 if c.PrevSibling == nil {
626 n.FirstChild = c
627 } else {
628 c.PrevSibling.NextSibling = c
629 }
630 n.LastChild = c
631 }
632 return n
633 }
634
635 func createBookExample() *TNode {
636 /*
637 <?xml version="1.0" encoding="UTF-8"?>
638 <bookstore>
639 <book category="cooking">
640 <title lang="en">Everyday Italian</title>
641 <author>Giada De Laurentiis</author>
642 <year>2005</year>
643 <price>30.00</price>
644 </book>
645 <book category="children">
646 <title lang="en">Harry Potter</title>
647 <author>J K. Rowling</author>
648 <year>2005</year>
649 <price>29.99</price>
650 </book>
651 <book category="web">
652 <title lang="en">XQuery Kick Start</title>
653 <author>James McGovern</author>
654 <author>Per Bothner</author>
655 <author>Kurt Cagle</author>
656 <author>James Linn</author>
657 <author>Vaidyanathan Nagarajan</author>
658 <year>2003</year>
659 <price>49.99</price>
660 </book>
661 <book category="web">
662 <title lang="en">Learning XML</title>
663 <author>Erik T. Ray</author>
664 <year>2003</year>
665 <price>39.95</price>
666 </book>
667 </bookstore>
668 */
669 type Element struct {
670 Data string
671 Attributes map[string]string
672 }
673 books := []struct {
674 category string
675 title Element
676 year int
677 price float64
678 authors []string
679 }{
680 {
681 category: "cooking",
682 title: Element{"Everyday Italian", map[string]string{"lang": "en"}},
683 year: 2005,
684 price: 30.00,
685 authors: []string{"Giada De Laurentiis"},
686 },
687 {
688 category: "children",
689 title: Element{"Harry Potter", map[string]string{"lang": "en"}},
690 year: 2005,
691 price: 29.99,
692 authors: []string{"J K. Rowling"},
693 },
694 {
695 category: "web",
696 title: Element{"XQuery Kick Start", map[string]string{"lang": "en"}},
697 year: 2003,
698 price: 49.99,
699 authors: []string{"James McGovern", "Per Bothner", "Kurt Cagle", "James Linn", "Vaidyanathan Nagarajan"},
700 },
701 {
702 category: "web",
703 title: Element{"Learning XML", map[string]string{"lang": "en"}},
704 year: 2003,
705 price: 39.95,
706 authors: []string{"Erik T. Ray"},
707 },
708 }
709
710 var lines = 0
711 doc := createNode("", RootNode)
712 lines++
713 bookstore := doc.createChildNode("bookstore", ElementNode)
714 lines++
715 bookstore.lines = lines
716 for i := 0; i < len(books); i++ {
717 v := books[i]
718 lines++
719
720 book := bookstore.createChildNode("book", ElementNode)
721 book.lines = lines
722 lines++
723 book.addAttribute("category", v.category)
724 // title
725 title := book.createChildNode("title", ElementNode)
726 title.lines = lines
727 lines++
728 for k, v := range v.title.Attributes {
729 title.addAttribute(k, v)
730 }
731 title.createChildNode(v.title.Data, TextNode)
732 // authors
733 for j := 0; j < len(v.authors); j++ {
734 author := book.createChildNode("author", ElementNode)
735 author.lines = lines
736 lines++
737 author.createChildNode(v.authors[j], TextNode)
738 }
739 // year
740 year := book.createChildNode("year", ElementNode)
741 year.lines = lines
742 lines++
743 year.createChildNode(fmt.Sprintf("%d", v.year), TextNode)
744 // price
745 price := book.createChildNode("price", ElementNode)
746 price.lines = lines
747 lines++
748 price.createChildNode(fmt.Sprintf("%.2f", v.price), TextNode)
749 }
750 return doc
751 }
752
753 // The example document from https://way2tutorial.com/xml/xpath-node-test.php
754 func createEmployeeExample() *TNode {
755 /*
756 <?xml version="1.0" standalone="yes"?>
757 <empinfo>
758 <employee id="1">
759 <name>Opal Kole</name>
760 <designation discipline="web" experience="3 year">Senior Engineer</designation>
761 <email>[email protected]</email>
762 </employee>
763 <employee id="2">
764 <name from="CA">Max Miller</name>
765 <designation discipline="DBA" experience="2 year">DBA Engineer</designation>
766 <email>[email protected]</email>
767 </employee>
768 <employee id="3">
769 <name>Beccaa Moss</name>
770 <designation discipline="appdev">Application Developer</designation>
771 <email>[email protected]</email>
772 </employee>
773 </empinfo>
774 */
775
776 type Element struct {
777 Data string
778 Attributes map[string]string
779 }
780 var lines = 0
781 doc := createNode("", RootNode)
782 lines++ // 1
783 empinfo := doc.createChildNode("empinfo", ElementNode)
784 lines++
785 empinfo.lines = lines
786 var employees = []struct {
787 name Element
788 designation Element
789 email Element
790 }{
791 {
792 name: Element{Data: "Opal Kole"},
793 designation: Element{Data: "Senior Engineer", Attributes: map[string]string{
794 "discipline": "web",
795 "experience": "3 year",
796 }},
797 email: Element{Data: "[email protected]"},
798 },
799 {
800 name: Element{Data: "Max Miller", Attributes: map[string]string{"from": "CA"}},
801 designation: Element{Data: "DBA Engineer", Attributes: map[string]string{
802 "discipline": "DBA",
803 "experience": "2 year",
804 }},
805 email: Element{Data: "[email protected]"},
806 },
807 {
808 name: Element{Data: "Beccaa Moss"},
809 designation: Element{Data: "Application Developer", Attributes: map[string]string{
810 "discipline": "appdev",
811 }},
812 email: Element{Data: "[email protected]"},
813 },
814 }
815 for i := 0; i < len(employees); i++ {
816 v := employees[i]
817 lines++
818 // employee
819 employee := empinfo.createChildNode("employee", ElementNode)
820 employee.addAttribute("id", fmt.Sprintf("%d", i+1))
821 employee.lines = lines
822 lines++
823 // name
824 name := employee.createChildNode("name", ElementNode)
825 name.createChildNode(v.name.Data, TextNode)
826 for k, n := range v.name.Attributes {
827 name.addAttribute(k, n)
828 }
829 name.lines = lines
830 lines++
831 // designation
832 designation := employee.createChildNode("designation", ElementNode)
833 designation.createChildNode(v.designation.Data, TextNode)
834 for k, n := range v.designation.Attributes {
835 designation.addAttribute(k, n)
836 }
837 designation.lines = lines
838 lines++
839 // email
840 email := employee.createChildNode("email", ElementNode)
841 email.createChildNode(v.email.Data, TextNode)
842 for k, n := range v.email.Attributes {
843 email.addAttribute(k, n)
844 }
845 email.lines = lines
846 // skiping closed tag
847 lines++
848 }
849 return doc
850 }
851
852 func createHtmlExample() *TNode {
853 /*
854 <html lang="en">
855 <head>
856 <title>My page</title>
857 <meta name="language" content="en" />
858 </head>
859 <body>
860 <h2>Welcome to my page</h2>
861 <ul>
862 <li>
863 <a href="/">Home</a>
864 </li>
865 <li>
866 <a href="/about">About</a>
867 </li>
868 <li>
869 <a href="/account">Login</a>
870 </li>
871 <li></li>
872 </ul>
873 <p>This is the first paragraph.</p>
874 <!-- this is the end -->
875 </body>
876 </html>
877 */
878 lines := 0
879 doc := createNode("", RootNode)
880 lines++
881 xhtml := doc.createChildNode("html", ElementNode)
882 xhtml.lines = lines
883 xhtml.addAttribute("lang", "en")
884 lines++
885 // head container
886 head := xhtml.createChildNode("head", ElementNode)
887 head.lines = lines
888 lines++
889 title := head.createChildNode("title", ElementNode)
890 title.lines = lines
891 title.createChildNode("My page", TextNode)
892 lines++
893 meta := head.createChildNode("meta", ElementNode)
894 meta.lines = lines
895 meta.addAttribute("name", "language")
896 meta.addAttribute("content", "en")
897 // skip the head
898 lines++
899 lines++
900 body := xhtml.createChildNode("body", ElementNode)
901 body.lines = lines
902 lines++
903 h2 := body.createChildNode("h2", ElementNode)
904 h2.lines = lines
905 h2.createChildNode("Welcome to my page", TextNode)
906 lines++
907 links := []struct {
908 text string
909 href string
910 }{
911 {text: "Home", href: "/"},
912 {text: "About", href: "/About"},
913 {text: "Login", href: "/account"},
914 }
915
916 ul := body.createChildNode("ul", ElementNode)
917 ul.lines = lines
918 lines++
919 for i := 0; i < len(links); i++ {
920 link := links[i]
921 li := ul.createChildNode("li", ElementNode)
922 li.lines = lines
923 lines++
924 a := li.createChildNode("a", ElementNode)
925 a.lines = lines
926 a.addAttribute("href", link.href)
927 a.createChildNode(link.text, TextNode)
928 lines++
929 // skip the <li>
930 lines++
931 }
932 // skip the last ul
933 lines++
934 p := body.createChildNode("p", ElementNode)
935 p.lines = lines
936 lines++
937 p.createChildNode("This is the first paragraph.", TextNode)
938 lines++
939 comment := body.createChildNode("<!-- this is the end -->", CommentNode)
940 comment.lines = lines
941 lines++
942 return doc
943 }
944
945 func createMyBookExample() *TNode {
946 /*
947 <?xml version="1.0" encoding="utf-8"?>
948 <books xmlns:mybook="http://www.contoso.com/books">
949 <mybook:book id="bk101">
950 <title>XML Developer's Guide</title>
951 <author>Gambardella, Matthew</author>
952 <price>44.95</price>
953 <publish_date>2000-10-01</publish_date>
954 </mybook:book>
955 <mybook:book id="bk102">
956 <title>Midnight Rain</title>
957 <author>Ralls, Kim</author>
958 <price>5.95</price>
959 <publish_date>2000-12-16</publish_date>
960 </mybook:book>
961 </books>
962 */
963 var (
964 prefix string = "mybook"
965 namespaceURL string = "http://www.contoso.com/books"
966 )
967 lines := 1
968 doc := createNode("", RootNode)
969 doc.lines = lines
970 lines++
971 books := doc.createChildNode("books", ElementNode)
972 books.addAttribute("xmlns:mybook", namespaceURL)
973 books.lines = lines
974 lines++
975 data := []struct {
976 id string
977 title string
978 author string
979 price float64
980 publish string
981 }{
982 {id: "bk101", title: "XML Developer's Guide", author: "Gambardella, Matthew", price: 44.95, publish: "2000-10-01"},
983 {id: "bk102", title: "Midnight Rain", author: "Ralls, Kim", price: 5.95, publish: "2000-12-16"},
984 }
985 for i := 0; i < len(data); i++ {
986 v := data[i]
987 book := books.createChildNode("book", ElementNode)
988 book.addAttribute("id", v.id)
989 book.Prefix = prefix
990 book.NamespaceURL = namespaceURL
991 book.lines = lines
992 lines++
993 title := book.createChildNode("title", ElementNode)
994 title.createChildNode(v.title, TextNode)
995 title.lines = lines
996 lines++
997 author := book.createChildNode("author", ElementNode)
998 author.createChildNode(v.author, TextNode)
999 author.lines = lines
1000 lines++
1001 price := book.createChildNode("price", ElementNode)
1002 price.createChildNode(fmt.Sprintf("%.2f", v.price), TextNode)
1003 price.lines = lines
1004 lines++
1005 publish_date := book.createChildNode("publish_date", ElementNode)
1006 publish_date.createChildNode(v.publish, TextNode)
1007 publish_date.lines = lines
1008 lines++
1009 // skip the last of book element
1010 lines++
1011 }
1012 return doc
1013 }
1014
1015 func TestMergeQueryStaleStateAcrossEvaluations(t *testing.T) {
1016 // A "//name" step compiles to a *mergeQuery; re-evaluating one compiled
1017 // expression against a second document must not reuse the first document's
1018 // node list.
1019 doc := createNode("", RootNode)
1020 foo := doc.createChildNode("foo", ElementNode)
1021 foo.createChildNode("bar", ElementNode)
1022 foo.createChildNode("bar", ElementNode)
1023 empty := createNode("", RootNode)
1024
1025 expr := MustCompile("//bar[true()] and count(//foo)=0")
1026 assertFalse(t, expr.Evaluate(createNavigator(empty)).(bool))
1027 assertFalse(t, expr.Evaluate(createNavigator(doc)).(bool))
1028 assertFalse(t, expr.Evaluate(createNavigator(empty)).(bool))
1029 }
1030
1031 func TestMultiplyOperatorAfterName(t *testing.T) {
1032 // https://github.com/antchfx/xpath/issues/126 — '*' is not a name character (XPath 1.0 §3.7).
1033 // A name immediately followed by '*' with no surrounding spaces (e.g. `price*0.01`) must be
1034 // scanned as name · MultiplyOperator · number. Before the fix it lexed as a single name
1035 // "price*0.01", which selected an empty node-set and evaluated to NaN.
1036 doc := createNode("", RootNode)
1037 price := doc.createChildNode("price", ElementNode)
1038 price.createChildNode("3231000", TextNode)
1039
1040 test_xpath_eval(t, doc, `price*0.01`, float64(32310)) // no spaces — the fix
1041 test_xpath_eval(t, doc, `price * 0.01`, float64(32310)) // with spaces — already worked
1042
1043 // Namespace/axis wildcards must keep compiling ('*' handled outside isName).
1044 for _, expr := range []string{`//*`, `//foo:*`, `child::*`} {
1045 if _, err := Compile(expr); err != nil {
1046 t.Errorf("Compile(%q) failed: %v", expr, err)
1047 }
1048 }
1049 }