-
-
Notifications
You must be signed in to change notification settings - Fork 255
/
validate_test.go
579 lines (529 loc) · 13.7 KB
/
validate_test.go
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
package agents
import (
"encoding/json"
"fmt"
"net/http"
"reflect"
"regexp/syntax"
"sort"
"strings"
"testing"
)
// TestAnalyzePattern tests analyzePattern function on many cases, including
// edge cases.
func TestAnalyzePattern(t *testing.T) {
cases := []struct {
input string
wantError string
wantPatterns []string
wantRe bool
shouldMatchRe []string
shouldNotMatchRe []string
}{
{
input: "simple phrase",
wantPatterns: []string{"simple phrase"},
},
{
input: "^begin anchor",
wantPatterns: []string{"^begin anchor"},
},
{
input: "end anchor$",
wantPatterns: []string{"end anchor$"},
},
{
input: "^both anchors$",
wantPatterns: []string{"^both anchors$"},
},
{
input: "(alter|nation)",
wantPatterns: []string{"alter", "nation"},
},
{
input: "too many [aA][lL][tT][eE][rR][nN][aA][tT][iI][oO][nN][sS]",
wantPatterns: []string{"too many "},
wantRe: true,
shouldMatchRe: []string{"too many ALTERNATIONs"},
shouldNotMatchRe: []string{"too many combinations "},
},
{
input: "(alter|nation) concatenation (alter|nation)",
wantPatterns: []string{
"alter concatenation alter",
"alter concatenation nation",
"nation concatenation alter",
"nation concatenation nation",
},
},
{
input: "clas[sS] of [c]haract[eiu]rs",
wantPatterns: []string{
"clasS of characters",
"clasS of charactirs",
"clasS of characturs",
"class of characters",
"class of charactirs",
"class of characturs",
},
},
{
input: "ranges [0-3]x[a-c]",
wantPatterns: []string{
"ranges 0xa", "ranges 0xb", "ranges 0xc",
"ranges 1xa", "ranges 1xb", "ranges 1xc",
"ranges 2xa", "ranges 2xb", "ranges 2xc",
"ranges 3xa", "ranges 3xb", "ranges 3xc",
},
},
{
input: "Quest?",
wantPatterns: []string{"Ques", "Quest"},
},
{
input: "Q?ue(st)?",
wantPatterns: []string{"Que", "Quest", "ue", "uest"},
},
{
input: "too many combinations [0-9][a-z]",
wantPatterns: []string{"too many combinations "},
wantRe: true,
shouldMatchRe: []string{"too many combinations 0a"},
shouldNotMatchRe: []string{"too many combinations "},
},
{
input: "negation in char class [^x]",
wantPatterns: []string{"negation in char class "},
wantRe: true,
shouldMatchRe: []string{"negation in char class y"},
shouldNotMatchRe: []string{"negation in char class x"},
},
{
input: "any char .",
wantPatterns: []string{"any char "},
wantRe: true,
shouldMatchRe: []string{"any char x"},
shouldNotMatchRe: []string{"any char_x"},
},
{
input: `word \boundary`,
wantPatterns: []string{"oundary"},
wantRe: true,
shouldMatchRe: []string{"word oundary"},
shouldNotMatchRe: []string{"word boundary"},
},
{
input: "asterisk*",
wantPatterns: []string{"asteris"},
wantRe: true,
shouldMatchRe: []string{"asteris", "asterisk", "asteriskk"},
shouldNotMatchRe: []string{"asterik"},
},
{
input: "plus+",
wantPatterns: []string{"plu"},
wantRe: true,
shouldMatchRe: []string{"plus", "pluss"},
shouldNotMatchRe: []string{"plu"},
},
{
input: "repeat{3,5}$",
wantPatterns: []string{"repeattt$", "repeatttt$", "repeattttt$"},
},
{
input: "repeat{1,120}$",
wantPatterns: []string{"repea"},
wantRe: true,
shouldMatchRe: []string{"repeattt", "repeatttt", "repeattttt"},
shouldNotMatchRe: []string{"repea5"},
},
{
input: "broken re[",
wantError: "does not compile",
},
{
input: "n?o? ?l?o?n?g? ?l?i?t?e?r?a?l?",
wantError: "does not contain sufficiently long literal",
},
}
for _, tc := range cases {
tc := tc
t.Run(tc.input, func(t *testing.T) {
gotPatterns, re, err := analyzePattern(tc.input)
if tc.wantError != "" {
if err == nil {
t.Fatalf("expected to get an error, got success")
}
if !strings.Contains(err.Error(), tc.wantError) {
t.Fatalf("the error returned must contain text %q, got %q", tc.wantError, err.Error())
}
return
}
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
sort.Strings(tc.wantPatterns)
sort.Strings(gotPatterns)
if !reflect.DeepEqual(tc.wantPatterns, gotPatterns) {
t.Fatalf("returned list of patterns (%#v) does not match the expected value (%#v)", gotPatterns, tc.wantPatterns)
}
if !tc.wantRe {
if re != nil {
t.Fatalf("unexpectedly got a re")
}
return
}
if re == nil {
t.Fatalf("expected to get a re, got nil")
}
for _, text := range tc.shouldMatchRe {
if !re.MatchString(text) {
t.Fatalf("test %q must match against the re, but it doesn't", text)
}
}
for _, text := range tc.shouldNotMatchRe {
if re.MatchString(text) {
t.Fatalf("test %q must not match against the re, but it does", text)
}
}
})
}
}
// TestLiteralizeRegexp tests expansion of a regexp to a list of literals.
func TestLiteralizeRegexp(t *testing.T) {
cases := []struct {
input string
maxLiterals int
wantOutput []string
wantOverflow bool
}{
{
input: "simple phrase",
maxLiterals: 100,
wantOutput: []string{"simple phrase"},
},
{
input: "cases [1-2x-z]",
maxLiterals: 100,
wantOutput: []string{"cases 1", "cases 2", "cases x", "cases y", "cases z"},
},
{
input: "[Ii]gnore case",
maxLiterals: 100,
wantOutput: []string{"Ignore case", "ignore case"},
},
{
input: "overflow [1-2x-z]",
maxLiterals: 2,
wantOverflow: true,
},
}
for _, tc := range cases {
tc := tc
t.Run(tc.input, func(t *testing.T) {
re, err := syntax.Parse(tc.input, syntax.Perl)
if err != nil {
t.Fatalf("failed to parse regexp %q: %v", tc.input, err)
}
gotPatterns, ok := literalizeRegexp(re, tc.maxLiterals)
if tc.wantOverflow {
if ok {
t.Fatalf("expected to get an overflow, got success")
}
return
}
if !ok {
t.Fatalf("unexpected overflow")
}
sort.Strings(tc.wantOutput)
sort.Strings(gotPatterns)
if !reflect.DeepEqual(tc.wantOutput, gotPatterns) {
t.Fatalf("returned list of patterns (%#v) does not match the expected value (%#v)", gotPatterns, tc.wantOutput)
}
})
}
}
// TestCombinations tests combinations() function.
func TestCombinations(t *testing.T) {
cases := []struct {
name string
input [][]string
maxLiterals int
wantOutput []string
wantOverflow bool
}{
{
name: "1x1",
input: [][]string{{"A"}, {"B"}},
maxLiterals: 100,
wantOutput: []string{"AB"},
},
{
name: "0x1",
input: [][]string{{}, {"B"}},
maxLiterals: 100,
wantOutput: []string{},
},
{
name: "1x2",
input: [][]string{{"A"}, {"1", "2"}},
maxLiterals: 100,
wantOutput: []string{"A1", "A2"},
},
{
name: "2x2",
input: [][]string{{"A", "B"}, {"1", "2"}},
maxLiterals: 100,
wantOutput: []string{"A1", "A2", "B1", "B2"},
},
{
name: "empty string as an option",
input: [][]string{{"A", ""}, {"1", "2"}},
maxLiterals: 100,
wantOutput: []string{"A1", "A2", "1", "2"},
},
{
name: "overflow",
input: [][]string{{"A", "B"}, {"1", "2"}},
maxLiterals: 3,
wantOverflow: true,
},
}
for _, tc := range cases {
tc := tc
t.Run(tc.name, func(t *testing.T) {
gotPatterns, ok := combinations(tc.input, tc.maxLiterals)
if tc.wantOverflow {
if ok {
t.Fatalf("expected to get an overflow, got success")
}
return
}
if !ok {
t.Fatalf("unexpected overflow")
}
sort.Strings(tc.wantOutput)
sort.Strings(gotPatterns)
if !reflect.DeepEqual(tc.wantOutput, gotPatterns) {
t.Fatalf("returned list of patterns (%#v) does not match the expected value (%#v)", gotPatterns, tc.wantOutput)
}
})
}
}
// TestUnwrapCase tests unwrapping literals of case-insensitive regexps.
func TestUnwrapCase(t *testing.T) {
cases := []struct {
name string
ignoreCase bool
inputPatterns []string
maxLiterals int
wantOutput []string
wantOverflow bool
}{
{
name: "simple phrase",
inputPatterns: []string{"simple phrase"},
maxLiterals: 100,
wantOutput: []string{"simple phrase"},
},
{
name: "ignore case",
ignoreCase: true,
inputPatterns: []string{"i"},
maxLiterals: 100,
wantOutput: []string{"i", "I"},
},
{
name: "ignore case two letters",
ignoreCase: true,
inputPatterns: []string{"ic"},
maxLiterals: 100,
wantOutput: []string{"IC", "Ic", "iC", "ic"},
},
{
name: "ignore case two words",
ignoreCase: true,
inputPatterns: []string{"i", "c"},
maxLiterals: 100,
wantOutput: []string{"C", "I", "c", "i"},
},
{
name: "ignore case overflow",
ignoreCase: true,
inputPatterns: []string{"long text"},
maxLiterals: 100,
wantOverflow: true,
},
}
for _, tc := range cases {
tc := tc
t.Run(tc.name, func(t *testing.T) {
re := &syntax.Regexp{}
if tc.ignoreCase {
re.Flags = syntax.FoldCase
}
gotPatterns, ok := unwrapCase(re, tc.inputPatterns, tc.maxLiterals)
if tc.wantOverflow {
if ok {
t.Fatalf("expected to get an overflow, got success")
}
return
}
if !ok {
t.Fatalf("unexpected overflow")
}
sort.Strings(tc.wantOutput)
sort.Strings(gotPatterns)
if !reflect.DeepEqual(tc.wantOutput, gotPatterns) {
t.Fatalf("returned list of patterns (%#v) does not match the expected value (%#v)", gotPatterns, tc.wantOutput)
}
})
}
}
// TestFindLongestCommonLiteral tests finding longest literal in a regexp.
func TestFindLongestCommonLiteral(t *testing.T) {
cases := []struct {
input string
wantOutput string
}{
{
input: "simple phrase",
wantOutput: "simple phrase",
},
{
input: "simple (phrase)?",
wantOutput: "simple ",
},
{
input: "[iI]",
wantOutput: "",
},
{
input: "[i]b",
wantOutput: "ib",
},
{
input: "simple (phrase)+",
wantOutput: "simple ",
},
{
input: "a*",
wantOutput: "",
},
{
input: "(abc)|(ab)",
wantOutput: "",
},
}
for _, tc := range cases {
tc := tc
t.Run(tc.input, func(t *testing.T) {
re, err := syntax.Parse(tc.input, syntax.Perl)
if err != nil {
t.Fatalf("failed to parse regexp %q: %v", tc.input, err)
}
gotOutput := findLongestCommonLiteral(re)
if gotOutput != tc.wantOutput {
t.Fatalf("returned value (%q) does not match the expected value (%q)", gotOutput, tc.wantOutput)
}
})
}
}
func contains(list []int, value int) bool {
for _, elem := range list {
if elem == value {
return true
}
}
return false
}
func TestPatterns(t *testing.T) {
// Loading all crawlers with go:embed
// some validation happens in UnmarshalJSON.
allCrawlers := Crawlers
// There are at least 10 crawlers.
if len(allCrawlers) < 10 {
t.Errorf("Number of crawlers must be at least 10, got %d.", len(allCrawlers))
}
if IsCrawler(browserUA) {
t.Errorf("Browser UA %q was detected as a crawler.", browserUA)
}
if len(MatchingCrawlers(browserUA)) != 0 {
t.Errorf("MatchingCrawlers found crawlers matching Browser UA %q.", browserUA)
}
for i, crawler := range allCrawlers {
t.Run(crawler.Pattern, func(t *testing.T) {
fmt.Println(crawler.Pattern)
for _, instance := range crawler.Instances {
if !IsCrawler(instance) {
t.Errorf("Instance %q is not detected as a crawler.", instance)
}
hits := MatchingCrawlers(instance)
if !contains(hits, i) {
t.Errorf("Crawler with index %d (pattern %q) is not in the list returned by MatchingCrawlers(%q): %v.", i, crawler.Pattern, instance, hits)
}
}
})
}
}
func TestFalseNegatives(t *testing.T) {
const browsersURL = "https://raw.githubusercontent.com/microlinkhq/top-user-agents/master/src/index.json"
resp, err := http.Get(browsersURL)
if err != nil {
t.Fatalf("Failed to fetch the list of browser User Agents from %s: %v.", browsersURL, err)
}
t.Cleanup(func() {
if err := resp.Body.Close(); err != nil {
t.Fatal(err)
}
})
var browsers []string
if err := json.NewDecoder(resp.Body).Decode(&browsers); err != nil {
t.Fatalf("Failed to parse the list of browser User Agents: %v.", err)
}
for _, userAgent := range browsers {
if IsCrawler(userAgent) {
t.Errorf("Browser User Agent %q is recognized as a crawler.", userAgent)
}
indices := MatchingCrawlers(userAgent)
if len(indices) != 0 {
t.Errorf("Browser User Agent %q matches with crawlers %v.", userAgent, indices)
}
}
}
const (
crawlerUA = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36 Google (+https://developers.google.com/+/web/snippet/"
browserUA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) obsidian/1.5.3 Chrome/114.0.5735.289 Electron/25.8.1 Safari/537.36"
)
func BenchmarkIsCrawlerPositive(b *testing.B) {
b.SetBytes(int64(len(crawlerUA)))
for n := 0; n < b.N; n++ {
if !IsCrawler(crawlerUA) {
b.Fail()
}
}
}
func BenchmarkMatchingCrawlersPositive(b *testing.B) {
b.SetBytes(int64(len(crawlerUA)))
for n := 0; n < b.N; n++ {
if len(MatchingCrawlers(crawlerUA)) == 0 {
b.Fail()
}
}
}
func BenchmarkIsCrawlerNegative(b *testing.B) {
b.SetBytes(int64(len(browserUA)))
for n := 0; n < b.N; n++ {
if IsCrawler(browserUA) {
b.Fail()
}
}
}
func BenchmarkMatchingCrawlersNegative(b *testing.B) {
b.SetBytes(int64(len(browserUA)))
for n := 0; n < b.N; n++ {
if len(MatchingCrawlers(browserUA)) != 0 {
b.Fail()
}
}
}