1
+ import re
2
+
1
3
from io import StringIO
2
4
from typing import List
3
5
@@ -159,6 +161,7 @@ def test_stylize_negative_index():
159
161
160
162
161
163
def test_highlight_regex ():
164
+ # As a string
162
165
text = Text ("peek-a-boo" )
163
166
164
167
count = text .highlight_regex (r"NEVER_MATCH" , "red" )
@@ -176,6 +179,7 @@ def test_highlight_regex():
176
179
]
177
180
178
181
text = Text ("Ada Lovelace, Alan Turing" )
182
+
179
183
count = text .highlight_regex (
180
184
r"(?P<yellow>[A-Za-z]+)[ ]+(?P<red>[A-Za-z]+)(?P<NEVER_MATCH>NEVER_MATCH)*"
181
185
)
@@ -189,16 +193,51 @@ def test_highlight_regex():
189
193
Span (19 , 25 , "red" ), # Turing
190
194
]
191
195
196
+ # As a regular expression object
197
+ text = Text ("peek-a-boo" )
198
+
199
+ count = text .highlight_regex (re .compile (r"NEVER_MATCH" ), "red" )
200
+ assert count == 0
201
+ assert len (text ._spans ) == 0
202
+
203
+ # text: peek-a-boo
204
+ # indx: 0123456789
205
+ count = text .highlight_regex (re .compile (r"[a|e|o]+" ), "red" )
206
+ assert count == 3
207
+ assert sorted (text ._spans ) == [
208
+ Span (1 , 3 , "red" ),
209
+ Span (5 , 6 , "red" ),
210
+ Span (8 , 10 , "red" ),
211
+ ]
212
+
213
+ text = Text ("Ada Lovelace, Alan Turing" )
214
+
215
+ count = text .highlight_regex (
216
+ re .compile (r"(?P<yellow>[A-Za-z]+)[ ]+(?P<red>[A-Za-z]+)(?P<NEVER_MATCH>NEVER_MATCH)*" )
217
+ )
218
+
219
+ # The number of matched name should be 2
220
+ assert count == 2
221
+ assert sorted (text ._spans ) == [
222
+ Span (0 , 3 , "yellow" ), # Ada
223
+ Span (4 , 12 , "red" ), # Lovelace
224
+ Span (14 , 18 , "yellow" ), # Alan
225
+ Span (19 , 25 , "red" ), # Turing
226
+ ]
227
+
228
+
192
229
193
230
def test_highlight_regex_callable ():
194
231
text = Text ("Vulnerability CVE-2018-6543 detected" )
195
232
re_cve = r"CVE-\d{4}-\d+"
233
+ compiled_re_cve = re .compile (r"CVE-\d{4}-\d+" )
196
234
197
235
def get_style (text : str ) -> Style :
198
236
return Style .parse (
199
237
f"bold yellow link https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword={ text } "
200
238
)
201
239
240
+ # string
202
241
count = text .highlight_regex (re_cve , get_style )
203
242
assert count == 1
204
243
assert len (text ._spans ) == 1
@@ -209,6 +248,20 @@ def get_style(text: str) -> Style:
209
248
== "https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword=CVE-2018-6543"
210
249
)
211
250
251
+ # Clear the tracked _spans for the regular expression object's use
252
+ text ._spans .clear ()
253
+
254
+ # regular expression object
255
+ count = text .highlight_regex (compiled_re_cve , get_style )
256
+ assert count == 1
257
+ assert len (text ._spans ) == 1
258
+ assert text ._spans [0 ].start == 14
259
+ assert text ._spans [0 ].end == 27
260
+ assert (
261
+ text ._spans [0 ].style .link
262
+ == "https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword=CVE-2018-6543"
263
+ )
264
+
212
265
213
266
def test_highlight_words ():
214
267
text = Text ("Do NOT! touch anything!" )
0 commit comments