Repository navigation
Expand file tree
/
Copy pathxpath_function_test.go
More file actions
690 lines (638 loc) · 33.7 KB
/
Copy pathxpath_function_test.go
File metadata and controls
690 lines (638 loc) · 33.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
package xpath
import (
"math"
"strings"
"testing"
)
// Some test examples from http://zvon.org/comp/r/ref-XPath_2.html
func Test_func_boolean(t *testing.T) {
test_xpath_eval(t, empty_example, `true()`, true)
test_xpath_eval(t, empty_example, `false()`, false)
test_xpath_eval(t, empty_example, `boolean(0)`, false)
test_xpath_eval(t, empty_example, `boolean(null)`, false)
test_xpath_eval(t, empty_example, `boolean(1)`, true)
test_xpath_eval(t, empty_example, `boolean(2)`, true)
test_xpath_eval(t, empty_example, `boolean(true)`, false)
test_xpath_eval(t, empty_example, `boolean(1 > 2)`, false)
test_xpath_eval(t, empty_example, `boolean('hello')`, true)
test_xpath_eval(t, empty_example, `boolean('')`, false)
test_xpath_eval(t, empty_example, `boolean(//non-existent-node)`, false)
test_xpath_eval(t, book_example, `boolean(//*[@lang])`, true)
test_xpath_eval(t, book_example, `boolean(//*[@x])`, false)
test_xpath_eval(t, empty_example, `'14' > 0`, true)
test_xpath_eval(t, empty_example, `'abc' = 1`, false) // NaN
test_xpath_eval(t, empty_example, `'2' < '10'`, true)
}
func Test_func_name(t *testing.T) {
test_xpath_eval(t, html_example, `name(//html/@lang)`, "lang")
test_xpath_eval(t, html_example, `name(html/head/title)`, "title")
test_xpath_eval(t, mybook_example, `name(//mybook:book)`, "mybook:book")
test_xpath_eval(t, empty_example, `name(//non-existent-node)`, "")
test_xpath_count(t, html_example, `//*[name() = "li"]`, 3)
test_xpath_elements(t, mybook_example, `//*[name() = 'mybook:book']`, 3, 9)
// text and comment nodes have no name (REC 4.1)
test_xpath_eval(t, html_example, `name(//title/text())`, "")
test_xpath_count(t, html_example, `//title/node()[name() = ""]`, 1)
doc := createNode("", RootNode)
doc.createChildNode("a comment", CommentNode)
test_xpath_eval(t, doc, `name(//comment())`, "")
}
func Test_func_not(t *testing.T) {
test_xpath_eval(t, empty_example, `not(true())`, false)
test_xpath_eval(t, empty_example, `not(false())`, true)
test_xpath_eval(t, empty_example, `not(1 = 2)`, true)
test_xpath_eval(t, empty_example, `not(1 = 1)`, false)
test_xpath_eval(t, empty_example, `not(//non-existent-node)`, true)
test_xpath_eval(t, html_example, `not(//title)`, false)
test_xpath_eval(t, empty_example, `not(0)`, true)
test_xpath_eval(t, empty_example, `not(1)`, false)
test_xpath_eval(t, empty_example, `not('')`, true)
test_xpath_eval(t, empty_example, `not('a')`, false)
test_xpath_eval(t, book_example, `not(count(//book))`, false)
test_xpath_eval(t, book_example, `not(string(//book/@missing))`, true)
test_xpath_elements(t, employee_example, `//employee[not(@id = "1")]`, 8, 13)
test_xpath_elements(t, book_example, `//book[not(year = 2005)]`, 15, 25)
test_xpath_count(t, book_example, `//book[not(title)]`, 0)
}
func Test_func_ceiling_floor(t *testing.T) {
test_xpath_eval(t, empty_example, "ceiling(5.2)", float64(6))
test_xpath_eval(t, empty_example, "floor(5.2)", float64(5))
}
func Test_func_concat(t *testing.T) {
test_xpath_eval(t, empty_example, `concat("1", "2", "3")`, "123")
//test_xpath_eval(t, empty_example, `concat("Ciao!", ())`, "Ciao!")
test_xpath_eval(t, book_example, `concat(//book[1]/title, ", ", //book[1]/year)`, "Everyday Italian, 2005")
result := concatFunc(testQuery("a"), testQuery("b"))(nil, nil).(string)
assertEqual(t, result, "ab")
// concat converts each argument with string() (REC 4.2); number and boolean
// arguments must be stringified, not silently dropped.
test_xpath_eval(t, empty_example, `concat("id-", 5, "-x")`, "id-5-x")
test_xpath_eval(t, empty_example, `concat(1, 2, 3)`, "123")
test_xpath_eval(t, empty_example, `concat("n=", 1 div 4)`, "n=0.25")
test_xpath_eval(t, empty_example, `concat("a", true(), "b")`, "atrueb")
test_xpath_eval(t, empty_example, `concat("a", 1 div 0, "z")`, "aInfinityz")
}
func Test_func_contains(t *testing.T) {
test_xpath_eval(t, empty_example, `contains(//missing, "")`, true)
test_xpath_eval(t, empty_example, `contains("tattoo", "t")`, true)
test_xpath_eval(t, empty_example, `contains("tattoo", "T")`, false)
test_xpath_eval(t, empty_example, `contains("tattoo", "ttt")`, false)
//test_xpath_eval(t, empty_example, `contains("", ())`, true)
test_xpath_elements(t, book_example, `//book[contains(title, "Potter")]`, 9)
test_xpath_elements(t, book_example, `//book[contains(year, "2005")]`, 3, 9)
// both arguments are converted as if by string() (REC 4.2)
test_xpath_eval(t, empty_example, `contains(0, 0)`, true)
test_xpath_eval(t, empty_example, `contains(12345, 34)`, true)
test_xpath_eval(t, empty_example, `contains("a1b", 1)`, true)
test_xpath_eval(t, empty_example, `contains(true(), "ru")`, true)
test_xpath_eval(t, empty_example, `contains("is false", false())`, true)
test_xpath_eval(t, empty_example, `contains(1 div 0, "fin")`, true)
test_xpath_eval(t, empty_example, `contains("tattoo", //missing)`, true)
test_xpath_elements(t, book_example, `//book[contains(year, 5)]`, 3, 9)
test_xpath_elements(t, book_example, `//book[contains(year, //book[3]/year)]`, 15, 25)
}
func Test_func_count(t *testing.T) {
test_xpath_eval(t, book_example, `count(//book)`, float64(4))
test_xpath_eval(t, book_example, `count(//book[3]/author)`, float64(5))
}
func Test_func_ends_with(t *testing.T) {
test_xpath_eval(t, empty_example, `ends-with("tattoo", "tattoo")`, true)
test_xpath_eval(t, empty_example, `ends-with("tattoo", "atto")`, false)
test_xpath_elements(t, book_example, `//book[ends-with(@category,'ing')]`, 3)
test_xpath_elements(t, book_example, `//book[ends-with(./price,'.99')]`, 9, 15)
assertPanic(t, func() { selectNode(html_example, `//*[ends-with(0, 0)]`) }) // arg must be start with string
assertPanic(t, func() { selectNode(html_example, `//*[ends-with(name(), 0)]`) })
}
func Test_func_last(t *testing.T) {
test_xpath_elements(t, book_example, `//bookstore[last()]`, 2)
test_xpath_elements(t, book_example, `//bookstore/book[last()]`, 25)
test_xpath_elements(t, book_example, `(//bookstore/book)[last()]`, 25)
//https: //github.com/antchfx/xpath/issues/76
test_xpath_elements(t, book_example, `(//bookstore/book[year = 2005])[last()]`, 9)
test_xpath_elements(t, book_example, `//bookstore/book[year = 2005][last()]`, 9)
test_xpath_elements(t, html_example, `//ul/li[last()]`, 15)
test_xpath_elements(t, html_example, `(//ul/li)[last()]`, 15)
}
func Test_func_local_name(t *testing.T) {
test_xpath_eval(t, book_example, `local-name(bookstore)`, "bookstore")
test_xpath_eval(t, mybook_example, `local-name(//mybook:book)`, "book")
test_xpath_eval(t, empty_example, `local-name(//non-existent-node)`, "")
test_xpath_elements(t, book_example, `//*[local-name() = 'title']`, 4, 10, 16, 26)
// text and comment nodes have no name (REC 4.1)
test_xpath_eval(t, html_example, `local-name(//title/text())`, "")
test_xpath_count(t, html_example, `//title/node()[local-name() = ""]`, 1)
doc := createNode("", RootNode)
doc.createChildNode("a comment", CommentNode)
test_xpath_eval(t, doc, `local-name(//comment())`, "")
}
func Test_func_starts_with(t *testing.T) {
test_xpath_eval(t, empty_example, `starts-with("missing", "x")`, false)
test_xpath_eval(t, employee_example, `starts-with("tattoo", "tat")`, true)
test_xpath_eval(t, employee_example, `starts-with("tattoo", "att")`, false)
test_xpath_elements(t, book_example, `//book[starts-with(title,'Everyday')]`, 3)
// both arguments are converted as if by string() (REC 4.2)
test_xpath_eval(t, empty_example, `starts-with(0, 0)`, true)
test_xpath_eval(t, empty_example, `starts-with(12345, 12)`, true)
test_xpath_eval(t, empty_example, `starts-with(-1.5, "-1.")`, true)
test_xpath_eval(t, empty_example, `starts-with(true(), "t")`, true)
test_xpath_eval(t, empty_example, `starts-with("tattoo", //missing)`, true)
test_xpath_elements(t, book_example, `//book[starts-with(price, 3)]`, 3, 25)
test_xpath_elements(t, book_example, `//book[starts-with(year, //book[1]/year)]`, 3, 9)
test_xpath_count(t, html_example, `//*[starts-with(name(), 0)]`, 0)
}
func Test_func_string(t *testing.T) {
test_xpath_eval(t, empty_example, `string(1.23)`, "1.23")
test_xpath_eval(t, empty_example, `string(3)`, "3")
test_xpath_eval(t, book_example, `string(//book/@category)`, "cooking")
test_xpath_eval(t, empty_example, `string(true())`, "true")
test_xpath_eval(t, empty_example, `string(false())`, "false")
test_xpath_eval(t, empty_example, `string(//non-existent-node)`, "")
test_xpath_eval(t, employee_example, `string(//employee[1]/name)`, "Opal Kole")
// number->string per XPath 1.0 REC 4.2: decimal form, never an exponent.
test_xpath_eval(t, empty_example, `string(1000000)`, "1000000")
test_xpath_eval(t, empty_example, `string(1234567)`, "1234567")
test_xpath_eval(t, empty_example, `string(123456789)`, "123456789")
test_xpath_eval(t, empty_example, `string(0.00001)`, "0.00001")
test_xpath_eval(t, empty_example, `string(10000000000)`, "10000000000")
test_xpath_eval(t, empty_example, `string(100000000000000000000)`, "100000000000000000000")
// infinity, NaN and negative zero.
test_xpath_eval(t, empty_example, `string(1 div 0)`, "Infinity")
test_xpath_eval(t, empty_example, `string(-1 div 0)`, "-Infinity")
test_xpath_eval(t, empty_example, `string(0 div 0)`, "NaN")
test_xpath_eval(t, empty_example, `string(-0)`, "0")
test_xpath_eval(t, empty_example, `string(0 div -1)`, "0")
// unchanged finite cases (regression guard).
test_xpath_eval(t, empty_example, `string(0.5)`, "0.5")
test_xpath_eval(t, empty_example, `string(-3)`, "-3")
test_xpath_eval(t, empty_example, `string(0.25)`, "0.25")
}
func Test_func_string_empty(t *testing.T) {
// https://github.com/antchfx/xpath/issues/113
// Create the equivalent of <div>hi</div> using TNode
doc := createNode("", RootNode)
div := doc.createChildNode("div", ElementNode)
div.lines = 1 // Assign a line number for the test helper
div.createChildNode("hi", TextNode)
// Use the existing test helper to evaluate the XPath
// The expression selects the div if its string value ("hi") is true in a boolean context.
test_xpath_values(t, doc, `//div[string()]`, "hi")
}
func Test_func_string_join(t *testing.T) {
//(t, empty_example, `string-join(('Now', 'is', 'the', 'time', '...'), '')`, "Now is the time ...")
test_xpath_eval(t, empty_example, `string-join("some text", ";")`, "some text")
test_xpath_eval(t, book_example, `string-join(//book/@category, ";")`, "cooking;children;web;web")
}
func Test_func_string_length(t *testing.T) {
test_xpath_eval(t, empty_example, `string-length("Harp not on that string, madam; that is past.")`, float64(45))
test_xpath_eval(t, empty_example, `string-length(normalize-space(' abc '))`, float64(3))
test_xpath_eval(t, html_example, `string-length(//title/text())`, float64(len("My page")))
test_xpath_eval(t, html_example, `string-length(//html/@lang)`, float64(len("en")))
test_xpath_count(t, employee_example, `//employee[string-length(@id) > 0]`, 3) // = //employee[@id]
// characters, not bytes (REC 4.2)
test_xpath_eval(t, empty_example, `string-length("héllo")`, float64(5))
test_xpath_eval(t, empty_example, `string-length("日本語")`, float64(3))
test_xpath_eval(t, empty_example, `string-length(12345)`, float64(5))
test_xpath_eval(t, empty_example, `string-length(true())`, float64(4))
// no argument means the context node
n := selectNode(employee_example, `//employee[@id="1"]/name`)
test_xpath_eval(t, n, `string-length()`, float64(len("Opal Kole")))
test_xpath_elements(t, book_example, `//book/title[string-length() = 16]`, 4)
}
func Test_func_substring(t *testing.T) {
test_xpath_eval(t, empty_example, `substring("motor car", 6)`, " car")
test_xpath_eval(t, empty_example, `substring("metadata", 4, 3)`, "ada")
test_xpath_eval(t, empty_example, `substring("12345", 1.5, 2.6)`, "234")
// round(-0.5) is 0, so the window is the first two characters.
test_xpath_eval(t, empty_example, `substring("12345", -0.5, 3)`, "12")
test_xpath_eval(t, empty_example, `substring("12345", 0, 1)`, "")
test_xpath_eval(t, empty_example, `substring("12345", 0, 2)`, "1")
test_xpath_eval(t, empty_example, `substring("12345", 0, 3)`, "12")
test_xpath_eval(t, empty_example, `substring(12345, 2, 3)`, "234")
test_xpath_eval(t, empty_example, `substring(1 div 0, 1, 3)`, "Inf")
test_xpath_eval(t, empty_example, `substring("12345", 0, 5)`, "1234")
test_xpath_eval(t, empty_example, `substring("12345", -1, 4)`, "12")
test_xpath_eval(t, empty_example, `substring("12345", -2, 5)`, "12")
test_xpath_eval(t, empty_example, `substring("12345", -2, 2)`, "")
test_xpath_eval(t, empty_example, `substring("12345", -1)`, "12345")
test_xpath_eval(t, empty_example, `substring("12345", 0)`, "12345")
test_xpath_eval(t, empty_example, `substring("12345", 1, 5)`, "12345")
test_xpath_eval(t, empty_example, `substring("12345", 1, 6)`, "12345")
test_xpath_eval(t, empty_example, `substring("12345", 3, 5)`, "345")
test_xpath_eval(t, empty_example, `substring("12345", 2, 10)`, "2345")
test_xpath_eval(t, empty_example, `substring("12345", 5, 10)`, "5")
test_xpath_eval(t, empty_example, `substring("motor car", 6, 20)`, " car")
// positions count characters, not bytes
test_xpath_eval(t, empty_example, `substring("héllo", 1, 3)`, "hél")
test_xpath_eval(t, empty_example, `substring("日本語abc", 2, 2)`, "本語")
test_xpath_eval(t, empty_example, `substring("héllo", 2)`, "éllo")
test_xpath_eval(t, empty_example, `substring("héllo", 1, string-length("héllo"))`, "héllo")
test_xpath_eval(t, empty_example, `substring("12345", -3, 6)`, "12")
test_xpath_eval(t, empty_example, `substring("12345", -1, 7)`, "12345")
test_xpath_eval(t, empty_example, `substring("12345", 1, number("abc"))`, "")
test_xpath_eval(t, empty_example, `substring("12345", number("abc"), 3)`, "")
test_xpath_eval(t, empty_example, `substring("12345", 1, 0)`, "")
test_xpath_eval(t, empty_example, `substring("12345", 6)`, "")
test_xpath_eval(t, empty_example, `substring("12345", 6, 2)`, "")
test_xpath_eval(t, empty_example, `substring(//non-existent-node, 1)`, "")
test_xpath_eval(t, html_example, `substring(//title/child::node(), 1)`, "My page")
// start and length are converted as if by number()
test_xpath_eval(t, empty_example, `substring("12345", "2", "3")`, "234")
test_xpath_eval(t, empty_example, `substring("12345", " 2.5 ")`, "345")
test_xpath_eval(t, empty_example, `substring("12345", true(), true())`, "1")
test_xpath_eval(t, empty_example, `substring("12345", "abc")`, "")
test_xpath_eval(t, empty_example, `substring("12345", //non-existent-node)`, "")
test_xpath_eval(t, empty_example, `substring("12345", 1, //non-existent-node)`, "")
test_xpath_eval(t, html_example, `substring("12345", string-length(//title), 2)`, "")
test_xpath_eval(t, html_example, `substring("My page", count(//title), //title/child::node())`, "")
}
func Test_func_substring_non_finite_start(t *testing.T) {
tests := []struct {
expr string
want string
}{
{`substring("12345", number("abc"))`, ""},
{`substring("12345", 0 div 0)`, ""},
{`substring("", number("abc"))`, ""},
{`substring("héllo", number(""))`, ""},
{`substring(//title, number(//missing))`, ""},
{`substring("12345", number("abc"), 3)`, ""},
{`substring("12345", 1 div 0)`, ""},
{`substring("12345", -1 div 0)`, "12345"},
{`substring("12345", -1 div 0, 1 div 0)`, ""},
}
for _, tt := range tests {
t.Run(tt.expr, func(t *testing.T) {
defer func() {
if err := recover(); err != nil {
t.Fatalf("unexpected panic: %v", err)
}
}()
test_xpath_eval(t, html_example, tt.expr, tt.want)
})
}
}
func Test_func_substring_after(t *testing.T) {
test_xpath_eval(t, empty_example, `substring-after("tattoo", "tat")`, "too")
test_xpath_eval(t, empty_example, `substring-after("tattoo", "tattoo")`, "")
test_xpath_eval(t, empty_example, `substring-after("tattoo", "no-match")`, "")
test_xpath_eval(t, empty_example, `substring-after(//non-existent-node, "tat")`, "")
test_xpath_eval(t, empty_example, `substring-after("tattoo", //non-existent-node)`, "tattoo")
test_xpath_eval(t, empty_example, `substring-after("tattoo", "")`, "tattoo")
test_xpath_eval(t, empty_example, `substring-after("", "")`, "")
test_xpath_eval(t, empty_example, `substring-after("", "tat")`, "")
test_xpath_eval(t, empty_example, `substring-after(12345, 3)`, "45")
test_xpath_eval(t, empty_example, `substring-after("a1b", 1)`, "b")
test_xpath_eval(t, empty_example, `substring-after(1 div 0, "fin")`, "ity")
}
func Test_func_substring_before(t *testing.T) {
test_xpath_eval(t, empty_example, `substring-before("tattoo", "attoo")`, "t")
test_xpath_eval(t, empty_example, `substring-before("tattoo", "tatto")`, "")
test_xpath_eval(t, empty_example, `substring-before("tattoo", "no-match")`, "")
test_xpath_eval(t, empty_example, `substring-before(//non-existent-node, "tat")`, "")
test_xpath_eval(t, empty_example, `substring-before("tattoo", //non-existent-node)`, "")
test_xpath_eval(t, empty_example, `substring-before("tattoo", "")`, "")
test_xpath_eval(t, empty_example, `substring-before("", "tat")`, "")
test_xpath_eval(t, empty_example, `substring-before(12345, 3)`, "12")
test_xpath_eval(t, empty_example, `substring-before(true(), "u")`, "tr")
}
func Test_func_sum_node_conversion(t *testing.T) {
for _, tt := range []struct {
name string
values []string
want string
}{
{"empty set", nil, "0"},
{"numbers", []string{"2", "3"}, "5"},
{"whitespace", []string{" \t2\r\n", "3"}, "5"},
{"invalid first", []string{"invalid", "3"}, "NaN"},
{"invalid last", []string{"2", "invalid"}, "NaN"},
{"empty node", []string{"2", ""}, "NaN"},
} {
t.Run(tt.name, func(t *testing.T) {
root := createNode("", RootNode)
for _, value := range tt.values {
node := root.createChildNode("price", ElementNode)
node.createChildNode(value, TextNode)
}
test_xpath_eval(t, root, `string(sum(/price))`, tt.want)
})
}
}
func Test_func_sum(t *testing.T) {
test_xpath_eval(t, empty_example, `sum(1 + 2)`, float64(3))
test_xpath_eval(t, empty_example, `sum(1.1 + 2)`, float64(3.1))
test_xpath_eval(t, book_example, `sum(//book/price)`, float64(149.93))
test_xpath_elements(t, book_example, `//book[sum(./price) > 40]`, 15)
assertPanic(t, func() { selectNode(html_example, `//title[sum('Hello') = 0]`) })
}
func Test_func_translate(t *testing.T) {
test_xpath_eval(t, empty_example, `translate("bar","abc","ABC")`, "BAr")
test_xpath_eval(t, empty_example, `translate("--aaa--","abc-","ABC")`, "AAA")
test_xpath_eval(t, empty_example, `translate("abcdabc", "abc", "AB")`, "ABdAB")
test_xpath_eval(t, empty_example, `translate('The quick brown fox', 'brown', 'red')`, "The quick red fdx")
// src and dst pair by character position
test_xpath_eval(t, empty_example, `translate("abc", "ab", "áé")`, "áéc")
test_xpath_eval(t, empty_example, `translate("日本語", "日語", "ab")`, "a本b")
}
func Test_func_translate_const(t *testing.T) {
doc := createNode("", RootNode)
root := doc.createChildNode("root", ElementNode)
red := root.createChildNode("item", ElementNode)
red.addAttribute("style", "color:RED")
blue := root.createChildNode("item", ElementNode)
blue.addAttribute("style", "color:blue")
bg := root.createChildNode("item", ElementNode)
bg.addAttribute("style", "BACKGROUND-COLOR:#FF0000")
const upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
const lower = "abcdefghijklmnopqrstuvwxyz"
nodes := selectNodes(doc, `//item[translate(@style, "`+upper+`", "`+lower+`") = "color:red"]`)
assertEqual(t, 1, len(nodes))
// "background-color" contains "color", so all three match.
nodes = selectNodes(doc, `//item[contains(translate(@style, "`+upper+`", "`+lower+`"), "color")]`)
assertEqual(t, 3, len(nodes))
// Deletion: dst shorter than src removes unmatched chars. "color:RED"→"color"; "color:blue"→"colorblue".
nodes = selectNodes(doc, `//item[translate(@style, "`+upper+`:", "") = "color"]`)
assertEqual(t, 1, len(nodes))
uni := createNode("", RootNode)
uroot := uni.createChildNode("root", ElementNode)
ja := uroot.createChildNode("item", ElementNode)
ja.addAttribute("lang", "日本語")
nodes = selectNodes(uni, `//item[translate(@lang, "日語", "ab") = "a本b"]`)
assertEqual(t, 1, len(nodes))
// Empty src is a no-op. "BACKGROUND-COLOR" has uppercase COLOR, so only 2 items contain "color".
nodes = selectNodes(doc, `//item[contains(translate(@style, "", ""), "color")]`)
assertEqual(t, 2, len(nodes))
}
func Test_func_matches(t *testing.T) {
test_xpath_eval(t, empty_example, `matches("abracadabra", "bra")`, true)
test_xpath_eval(t, empty_example, `matches(123, "^123$")`, true)
test_xpath_eval(t, empty_example, `matches("abracadabra", "(?i)^A.*A$")`, true)
test_xpath_eval(t, empty_example, `matches("abracadabra", "^a.*a$")`, true)
test_xpath_eval(t, empty_example, `matches("abracadabra", "^bra")`, false)
assertPanic(t, func() { selectNode(html_example, `//*[matches()]`) }) // arg len check failure
assertPanic(t, func() { selectNode(html_example, "//*[matches(substring(), 0)]") }) // first arg processing failure
assertPanic(t, func() { selectNode(html_example, "//*[matches(@href, substring())]") }) // second arg processing failure
assertPanic(t, func() { selectNode(html_example, "//*[matches(@href, 0)]") }) // second arg not string
assertPanic(t, func() { selectNode(html_example, "//*[matches(@href, '[invalid')]") }) // second arg invalid regexp
// testing unexpected the regular expression.
_, err := Compile(`//*[matches(., '^[\u0621-\u064AA-Za-z\-]+')]`)
assertErr(t, err)
_, err = Compile(`//*[matches(., '//*[matches(., '\w+`)
assertErr(t, err)
}
func Test_func_matches_empty_nodeset(t *testing.T) {
// starts-with, ends-with and contains all answer false here.
test_xpath_eval(t, html_example, `matches(//no-such, 'x')`, false)
test_xpath_eval(t, html_example, `not(matches(//no-such, 'x'))`, true)
test_xpath_eval(t, html_example, `not(starts-with(//no-such, 'x'))`, true)
test_xpath_eval(t, html_example, `not(contains(//no-such, 'x'))`, true)
test_xpath_eval(t, html_example, `not(ends-with(//no-such, 'x'))`, true)
// boolean(X) and not(not(X)) have to agree
test_xpath_eval(t, html_example, `boolean(matches(//no-such, 'x'))`, false)
test_xpath_eval(t, html_example, `not(not(matches(//no-such, 'x')))`, false)
// a missing attribute reaches the same branch
test_xpath_eval(t, html_example, `not(matches(//html/@nosuchattr, 'x'))`, true)
test_xpath_eval(t, empty_example, `ends-with("", "")`, true)
}
func Test_func_number(t *testing.T) {
test_xpath_eval(t, empty_example, `number(10)`, float64(10))
test_xpath_eval(t, empty_example, `number(1.11)`, float64(1.11))
test_xpath_eval(t, empty_example, `number("10") > 10`, false)
test_xpath_eval(t, empty_example, `number("10") = 10`, true)
test_xpath_eval(t, empty_example, `number("123") < 1000`, true)
test_xpath_eval(t, empty_example, `number(//non-existent-node) = 0`, false)
assertTrue(t, math.IsNaN(MustCompile(`number(//non-existent-node)`).Evaluate(createNavigator(empty_example)).(float64)))
assertTrue(t, math.IsNaN(MustCompile(`number("123a")`).Evaluate(createNavigator(empty_example)).(float64)))
test_xpath_eval(t, empty_example, `number(" -12.5 ")`, float64(-12.5))
test_xpath_eval(t, empty_example, `number(".5")`, float64(0.5))
test_xpath_eval(t, empty_example, `number("5.")`, float64(5))
test_xpath_eval(t, empty_example, `number("1e3")`, float64(1000))
test_xpath_eval(t, empty_example, `number("1e309")`, math.Inf(1))
test_xpath_eval(t, empty_example, `number("-1e309")`, math.Inf(-1))
test_xpath_eval(t, empty_example, `number("`+strings.Repeat("9", 400)+`")`, math.Inf(1))
// only an optional minus sign followed by a decimal number is a number
for _, s := range []string{"", "-", ".", "+5", "- 5", "Infinity", "-Infinity", "inf", "NaN", "0x10", "0x1p4", "1_000", "1e", "--5", "\u00a05"} {
v := MustCompile(`number('` + s + `')`).Evaluate(createNavigator(empty_example))
if !math.IsNaN(v.(float64)) {
t.Errorf("number('%s') = %v, want NaN", s, v)
}
}
test_xpath_eval(t, empty_example, `"+1" = 1`, false)
test_xpath_eval(t, empty_example, `"Infinity" = 1 div 0`, false)
// no argument means the context node
n := selectNode(book_example, `//book[1]/price`)
test_xpath_eval(t, n, `number()`, float64(30))
test_xpath_count(t, book_example, `//book/price[number() > 35]`, 2)
}
func Test_func_position(t *testing.T) {
test_xpath_elements(t, book_example, `//book[position() = 1]`, 3)
test_xpath_elements(t, book_example, `//book[(position() mod 2) = 0]`, 9, 25)
test_xpath_elements(t, book_example, `//book[position() = last()]`, 25)
test_xpath_elements(t, book_example, `//book/*[position() = 1]`, 4, 10, 16, 26)
// Test Failed
//test_xpath_elements(t, book_example, `(//book/title)[position() = 1]`, 3)
}
func Test_func_replace(t *testing.T) {
test_xpath_eval(t, empty_example, `replace("abc", "b", "$0x")`, "abxc")
test_xpath_eval(t, empty_example, `replace("abc", "b", "$0_suffix")`, "ab_suffixc")
test_xpath_eval(t, empty_example, `replace("abcd", "(bc)", "$0x/$1y")`, "abcx/bcyd")
test_xpath_eval(t, empty_example, `replace('aa-bb-cc','bb','ee')`, "aa-ee-cc")
test_xpath_eval(t, empty_example, `replace("abracadabra", "bra", "*")`, "a*cada*")
test_xpath_eval(t, empty_example, `replace("abracadabra", "a", "")`, "brcdbr")
// The below xpath expressions is not supported yet
//
test_xpath_eval(t, empty_example, `replace("abracadabra", "a.*a", "*")`, "*")
test_xpath_eval(t, empty_example, `replace("abracadabra", "a.*?a", "*")`, "*c*bra")
// test_xpath_eval(t, empty_example, `replace("abracadabra", ".*?", "$1")`, "*c*bra") // error, because the pattern matches the zero-length string
test_xpath_eval(t, empty_example, `replace("AAAA", "A+", "b")`, "b")
test_xpath_eval(t, empty_example, `replace("AAAA", "A+?", "b")`, "bbbb")
test_xpath_eval(t, empty_example, `replace("darted", "^(.*?)d(.*)$", "$1c$2")`, "carted")
test_xpath_eval(t, empty_example, `replace("abracadabra", "a(.)", "a$1$1")`, "abbraccaddabbra")
test_xpath_eval(t, empty_example, `replace("abcd", "(ab)|(a)", "[1=$1][2=$2]")`, "[1=ab][2=]cd")
test_xpath_eval(t, empty_example, `replace("1/1/c11/1", "(.*)/[^/]+$", "$1")`, "1/1/c11")
test_xpath_eval(t, empty_example, `replace("A/B/C/D/E/F/G/H/I/J/K/L", "([^/]*)/([^/]*)/([^/]*)/([^/]*)/([^/]*)/([^/]*)/([^/]*)/([^/]*)/([^/]*)/(.*)", "$1-$2-$3-$4-$5-$6-$7-$8-$9-$10")`, "A-B-C-D-E-F-G-H-I-J/K/L")
}
func Test_func_reverse(t *testing.T) {
//test_xpath_eval(t, employee_example, `reverse(("hello"))`, "hello") // Not passed
test_xpath_elements(t, employee_example, `reverse(//employee)`, 13, 8, 3)
test_xpath_elements(t, employee_example, `//employee[reverse(.) = reverse(.)]`, 3, 8, 13)
assertPanic(t, func() { selectNode(html_example, "reverse(concat())") }) // invalid node-sets argument.
assertPanic(t, func() { selectNode(html_example, "reverse()") }) // missing node-sets argument.
}
func Test_func_round(t *testing.T) {
// round() returns a number (float64), consistent with ceiling()/floor().
test_xpath_eval(t, empty_example, `round(2.5)`, float64(3))
test_xpath_eval(t, empty_example, `round(2.4999)`, float64(2))
test_xpath_eval(t, empty_example, `round(0.5)`, float64(1))
test_xpath_eval(t, empty_example, `round(3.5)`, float64(4))
// REC §4.4: halves round toward +Infinity, not away from zero.
test_xpath_eval(t, empty_example, `round(-0.5)`, float64(0))
test_xpath_eval(t, empty_example, `round(-1.5)`, float64(-1))
test_xpath_eval(t, empty_example, `round(-2.5)`, float64(-2))
test_xpath_eval(t, empty_example, `round(-0.6)`, float64(-1))
test_xpath_eval(t, empty_example, `round(-0.4)`, float64(0))
// ±Infinity pass through instead of overflowing an int conversion.
test_xpath_eval(t, empty_example, `round(1 div 0)`, math.Inf(1))
test_xpath_eval(t, empty_example, `round(-1 div 0)`, math.Inf(-1))
assertTrue(t, math.IsNaN(MustCompile(`round(0 div 0)`).Evaluate(createNavigator(empty_example)).(float64)))
// A number result composes in further arithmetic (was NaN when round returned int).
test_xpath_eval(t, empty_example, `round(2.5) + 0.5`, float64(3.5))
}
func Test_func_mod(t *testing.T) {
// REC §3.5: truncating remainder; sign follows the dividend.
test_xpath_eval(t, empty_example, `5 mod 3`, float64(2))
test_xpath_eval(t, empty_example, `5 mod -3`, float64(2))
test_xpath_eval(t, empty_example, `-5 mod 3`, float64(-2))
test_xpath_eval(t, empty_example, `6 mod 3`, float64(0))
// operands keep their fractional part (were truncated to int before).
test_xpath_eval(t, empty_example, `5.5 mod 2`, float64(1.5))
test_xpath_eval(t, empty_example, `7.5 mod 3`, float64(1.5))
// mod by zero is NaN, not a panic.
assertTrue(t, math.IsNaN(MustCompile(`5 mod 0`).Evaluate(createNavigator(empty_example)).(float64)))
}
func Test_func_namespace_uri(t *testing.T) {
test_xpath_eval(t, mybook_example, `namespace-uri(//mybook:book)`, "http://www.contoso.com/books")
test_xpath_eval(t, book_example, `namespace-uri(bookstore)`, "")
test_xpath_eval(t, empty_example, `namespace-uri(//non-existent-node)`, "")
test_xpath_elements(t, mybook_example, `//*[namespace-uri()='http://www.contoso.com/books']`, 3, 9)
}
func Test_func_normalize_space_preserves_non_xml_whitespace(t *testing.T) {
for _, tt := range []struct {
name string
input string
want string
}{
{"empty", "", ""},
{"xml whitespace only", " \t\r\n ", ""},
{"xml whitespace runs", "\t a \r\n b ", "a b"},
{"nonbreaking edges", "\u00a0a\u00a0", "\u00a0a\u00a0"},
{"nonbreaking run", "a\u00a0\u00a0b", "a\u00a0\u00a0b"},
{"em space", "\u2003a\u2003", "\u2003a\u2003"},
{"narrow nonbreaking space", "a\u202fb", "a\u202fb"},
{"mixed whitespace", "\t\u00a0 a\n\u2003\r\n", "\u00a0 a \u2003"},
} {
t.Run(tt.name, func(t *testing.T) {
test_xpath_eval(t, empty_example, `normalize-space("`+tt.input+`")`, tt.want)
})
}
}
func Test_func_normalize_space(t *testing.T) {
const testStr = "\t \rloooooooonnnnnnngggggggg \r \n tes \u00a0 t strin \n\n \r g "
const expectedStr = "loooooooonnnnnnngggggggg tes \u00a0 t strin\u00a0 g"
test_xpath_eval(t, empty_example, `normalize-space("`+testStr+`")`, expectedStr)
test_xpath_eval(t, empty_example, `normalize-space(' abc ')`, "abc")
test_xpath_eval(t, empty_example, `normalize-space(12)`, "12")
test_xpath_eval(t, empty_example, `normalize-space(false())`, "false")
n := selectNode(employee_example, `//employee[@id="1"]/name`)
test_xpath_eval(t, n, `normalize-space()`, "Opal Kole")
test_xpath_eval(t, n, `normalize-space(.)`, "Opal Kole")
test_xpath_eval(t, book_example, `normalize-space(//book/title)`, "Everyday Italian")
test_xpath_eval(t, book_example, `normalize-space(//book[1]/title)`, "Everyday Italian")
}
func Test_func_lower_case(t *testing.T) {
test_xpath_eval(t, empty_example, `lower-case("ABc!D")`, "abc!d")
test_xpath_count(t, employee_example, `//name[@from="ca"]`, 0)
test_xpath_elements(t, employee_example, `//name[lower-case(@from) = "ca"]`, 9)
//test_xpath_eval(t, employee_example, `//employee/name/lower-case(text())`, "opal kole", "max miller", "beccaa moss")
}
func Benchmark_NormalizeSpaceFunc(b *testing.B) {
b.ReportAllocs()
const strForNormalization = "\t \rloooooooonnnnnnngggggggg \r \n tes \u00a0 t strin \n\n \r g "
for i := 0; i < b.N; i++ {
_ = normalizespaceFunc(testQuery(strForNormalization))(nil, nil)
}
}
func Benchmark_ConcatFunc(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_ = concatFunc(testQuery("a"), testQuery("b"))(nil, nil)
}
}
func Benchmark_GetHashCode(b *testing.B) {
// Create a more complex test node that will actually go through the full getHashCode paths
doc := createNavigator(book_example)
doc.MoveToRoot()
doc.MoveToChild() // Move to the first element
doc.MoveToChild() // Deeper
// Find a node with attributes
var node NodeNavigator
for {
if doc.NodeType() == AttributeNode || doc.NodeType() == TextNode || doc.NodeType() == CommentNode {
node = doc.Copy()
break
}
if !doc.MoveToNext() {
if !doc.MoveToChild() {
// If we can't find a suitable node, default to using the first element
doc.MoveToRoot()
doc.MoveToChild()
node = doc.Copy()
break
}
}
}
b.Run("getHashCode", func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
n := node.Copy()
_ = getHashCode(n)
}
})
}
func TestEndsWithNodeSetSuffix(t *testing.T) {
tests := []struct {
expression string
want bool
}{
{`ends-with("Everyday Italian", //book[1]/title)`, true},
{`ends-with("prefix-2005", //book[1]/year)`, true},
{`ends-with("prefix-2004", //book[1]/year)`, false},
{`ends-with(//book[1]/title, //book[1]/title)`, true},
{`ends-with("anything", //missing)`, true},
{`ends-with(//missing, //missing)`, true},
}
for _, tt := range tests {
t.Run(tt.expression, func(t *testing.T) {
defer func() {
if err := recover(); err != nil {
t.Fatalf("evaluation panicked: %v", err)
}
}()
test_xpath_eval(t, book_example, tt.expression, tt.want)
})
}
}
func TestFunctionArity(t *testing.T) {
invalid := []string{
`true(1)`, `false(1)`, `last(1)`, `position(1)`,
`not(true(), false())`, `count(//book, //book)`, `sum(//book, 1)`,
`ceiling(1, 2)`, `floor(1, 2)`, `round(1, 2)`,
`normalize-space(" a ", "b")`, `substring("abc", 1, 1, 1)`,
`starts-with("abc", "a", "ignored")`,
`contains("abc", "b", "ignored")`,
`ends-with("abc", "c", "ignored")`,
`lower-case("ABC", "ignored")`, `reverse(//book, //book)`,
}
for _, expression := range invalid {
t.Run(expression, func(t *testing.T) {
if _, err := Compile(expression); err == nil {
t.Fatalf("Compile(%q) accepted an invalid argument count", expression)
}
})
}
valid := []string{
`true()`, `false()`, `last()`, `position()`, `not(true())`,
`count(//book)`, `sum(//book/price)`, `ceiling(1)`, `floor(1)`, `round(1)`,
`normalize-space()`, `normalize-space(" a ")`,
`substring("abc", 1)`, `substring("abc", 1, 1)`,
`starts-with("abc", "a")`, `contains("abc", "b")`, `ends-with("abc", "c")`,
`lower-case("ABC")`, `reverse(//book)`, `concat("a", "b", "c")`,
}
for _, expression := range valid {
t.Run(expression, func(t *testing.T) {
if _, err := Compile(expression); err != nil {
t.Fatalf("Compile(%q): %v", expression, err)
}
})
}
}