1
+ import re
1
2
from io import StringIO
2
3
from typing import List
3
4
@@ -159,6 +160,7 @@ def test_stylize_negative_index():
159
160
160
161
161
162
def test_highlight_regex ():
163
+ # As a string
162
164
text = Text ("peek-a-boo" )
163
165
164
166
count = text .highlight_regex (r"NEVER_MATCH" , "red" )
@@ -176,6 +178,7 @@ def test_highlight_regex():
176
178
]
177
179
178
180
text = Text ("Ada Lovelace, Alan Turing" )
181
+
179
182
count = text .highlight_regex (
180
183
r"(?P<yellow>[A-Za-z]+)[ ]+(?P<red>[A-Za-z]+)(?P<NEVER_MATCH>NEVER_MATCH)*"
181
184
)
@@ -189,16 +192,52 @@ def test_highlight_regex():
189
192
Span (19 , 25 , "red" ), # Turing
190
193
]
191
194
195
+ # As a regular expression object
196
+ text = Text ("peek-a-boo" )
197
+
198
+ count = text .highlight_regex (re .compile (r"NEVER_MATCH" ), "red" )
199
+ assert count == 0
200
+ assert len (text ._spans ) == 0
201
+
202
+ # text: peek-a-boo
203
+ # indx: 0123456789
204
+ count = text .highlight_regex (re .compile (r"[a|e|o]+" ), "red" )
205
+ assert count == 3
206
+ assert sorted (text ._spans ) == [
207
+ Span (1 , 3 , "red" ),
208
+ Span (5 , 6 , "red" ),
209
+ Span (8 , 10 , "red" ),
210
+ ]
211
+
212
+ text = Text ("Ada Lovelace, Alan Turing" )
213
+
214
+ count = text .highlight_regex (
215
+ re .compile (
216
+ r"(?P<yellow>[A-Za-z]+)[ ]+(?P<red>[A-Za-z]+)(?P<NEVER_MATCH>NEVER_MATCH)*"
217
+ )
218
+ )
219
+
220
+ # The number of matched name should be 2
221
+ assert count == 2
222
+ assert sorted (text ._spans ) == [
223
+ Span (0 , 3 , "yellow" ), # Ada
224
+ Span (4 , 12 , "red" ), # Lovelace
225
+ Span (14 , 18 , "yellow" ), # Alan
226
+ Span (19 , 25 , "red" ), # Turing
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