Debian Codegraph @

tests/test_regexopt.py

raw
1 """
2 Tests for pygments.regexopt
3 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
5 :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
6 :license: BSD, see LICENSE for details.
7 """
8
9 import re
10 import random
11 from itertools import combinations_with_replacement
12
13 from pygments.regexopt import regex_opt
14
15 ALPHABET = ['a', 'b', 'c', 'd', 'e']
16
17 N_TRIES = 15
18
19
20 def generate_keywordlist(length):
21 return [''.join(p) for p in
22 combinations_with_replacement(ALPHABET, length)]
23
24
25 def test_randomly():
26 # generate a list of all possible keywords of a certain length using
27 # a restricted alphabet, then choose some to match and make sure only
28 # those do
29 for n in range(3, N_TRIES):
30 kwlist = generate_keywordlist(n)
31 to_match = random.sample(kwlist,
32 random.randint(1, len(kwlist) - 1))
33 no_match = set(kwlist) - set(to_match)
34 rex = re.compile(regex_opt(to_match))
35 assert rex.groups == 1
36 for w in to_match:
37 assert rex.match(w)
38 for w in no_match:
39 assert not rex.match(w)
40
41
42 def test_prefix():
43 opt = regex_opt(('a', 'b'), prefix=r':{1,2}')
44 print(opt)
45 rex = re.compile(opt)
46 assert not rex.match('a')
47 assert rex.match('::a')
48 assert not rex.match(':::') # fullmatch
49
50
51 def test_suffix():
52 opt = regex_opt(('a', 'b'), suffix=r':{1,2}')
53 print(opt)
54 rex = re.compile(opt)
55 assert not rex.match('a')
56 assert rex.match('a::')
57 assert not rex.match(':::') # fullmatch
58
59
60 def test_suffix_opt():
61 # test that detected suffixes remain sorted.
62 opt = regex_opt(('afoo', 'abfoo'))
63 print(opt)
64 rex = re.compile(opt)
65 m = rex.match('abfoo')
66 assert m.end() == 5
67
68
69 def test_different_length_grouping():
70 opt = regex_opt(('a', 'xyz'))
71 print(opt)
72 rex = re.compile(opt)
73 assert rex.match('a')
74 assert rex.match('xyz')
75 assert not rex.match('b')
76 assert rex.groups == 1
77
78
79 def test_same_length_grouping():
80 opt = regex_opt(('a', 'b'))
81 print(opt)
82 rex = re.compile(opt)
83 assert rex.match('a')
84 assert rex.match('b')
85 assert not rex.match('x')
86
87 assert rex.groups == 1
88 groups = rex.match('a').groups()
89 assert groups == ('a',)
90
91
92 def test_same_length_suffix_grouping():
93 opt = regex_opt(('a', 'b'), suffix='(m)')
94 print(opt)
95 rex = re.compile(opt)
96 assert rex.match('am')
97 assert rex.match('bm')
98 assert not rex.match('xm')
99 assert not rex.match('ax')
100 assert rex.groups == 2
101 groups = rex.match('am').groups()
102 assert groups == ('a', 'm')