Debian Codegraph @

hypothesis-python/tests/cover/test_regex.py

raw
1 # This file is part of Hypothesis, which may be found at
2 # https://github.com/HypothesisWorks/hypothesis/
3 #
4 # Copyright the Hypothesis Authors.
5 # Individual contributors are listed in AUTHORS.rst and the git log.
6 #
7 # This Source Code Form is subject to the terms of the Mozilla Public License,
8 # v. 2.0. If a copy of the MPL was not distributed with this file, You can
9 # obtain one at https://mozilla.org/MPL/2.0/.
10
11 import re
12 import sys
13 import unicodedata
14
15 import pytest
16
17 from hypothesis import HealthCheck, Phase, assume, given, settings, strategies as st
18 from hypothesis.errors import InvalidArgument
19 from hypothesis.internal.compat import PYPY
20 from hypothesis.strategies._internal.regex import (
21 SPACE_CHARS,
22 UNICODE_DIGIT_CATEGORIES,
23 UNICODE_SPACE_CATEGORIES,
24 UNICODE_SPACE_CHARS,
25 UNICODE_WORD_CATEGORIES,
26 base_regex_strategy,
27 regex_strategy,
28 )
29
30 from tests.common.debug import (
31 assert_all_examples,
32 assert_no_examples,
33 check_can_generate_examples,
34 find_any,
35 )
36
37
38 def is_ascii(s):
39 return all(ord(c) < 128 for c in s)
40
41
42 def is_digit(s):
43 return all(unicodedata.category(c) in UNICODE_DIGIT_CATEGORIES for c in s)
44
45
46 def is_space(s):
47 return all(c in SPACE_CHARS for c in s)
48
49
50 def is_unicode_space(s):
51 return all(
52 unicodedata.category(c) in UNICODE_SPACE_CATEGORIES or c in UNICODE_SPACE_CHARS
53 for c in s
54 )
55
56
57 def is_word(s):
58 return all(
59 c == "_" or unicodedata.category(c) in UNICODE_WORD_CATEGORIES for c in s
60 )
61
62
63 def ascii_regex(pattern):
64 return re.compile(pattern, re.ASCII)
65
66
67 def unicode_regex(pattern):
68 return re.compile(pattern, re.UNICODE)
69
70
71 def _test_matching_pattern(pattern, *, isvalidchar, is_unicode=False):
72 r = unicode_regex(pattern) if is_unicode else ascii_regex(pattern)
73
74 codepoints = range(sys.maxunicode + 1) if is_unicode else range(1, 128)
75 for c in [chr(x) for x in codepoints]:
76 if isvalidchar(c):
77 msg = "%r supposed to match %r (%r, category %r), but it doesn't"
78 assert r.search(c), msg % (pattern, c, c, unicodedata.category(c))
79 else:
80 assert not r.search(c), (
81 f'"{pattern}" supposed not to match {c!r} (category '
82 f"{unicodedata.category(c)!r}), but it does"
83 )
84
85
86 @pytest.mark.parametrize(
87 "category,predicate", [(r"\w", is_word), (r"\d", is_digit), (r"\s", None)]
88 )
89 @pytest.mark.parametrize("invert", [False, True])
90 @pytest.mark.parametrize("is_unicode", [False, True])
91 def test_matching(category, predicate, invert, is_unicode):
92 if predicate is None:
93 # Special behaviour due to \x1c, INFORMATION SEPARATOR FOUR
94 predicate = is_unicode_space if is_unicode else is_space
95 if invert:
96 category = category.swapcase()
97
98 def pred(s):
99 return not predicate(s)
100
101 else:
102 pred = predicate
103
104 _test_matching_pattern(category, isvalidchar=pred, is_unicode=is_unicode)
105
106
107 @pytest.mark.skipif(
108 settings.get_current_profile_name() == "crosshair",
109 reason="takes ~30s each; CrossHair strings just aren't fast enough",
110 )
111 @pytest.mark.parametrize(
112 "pattern",
113 [
114 ".", # anything
115 "a",
116 "abc",
117 "[a][b][c]",
118 "[^a][^b][^c]", # literals
119 "[a-z0-9_]",
120 "[^a-z0-9_]", # range and negative range
121 "ab?",
122 "ab*",
123 "ab+", # quantifiers
124 "ab{5}",
125 "ab{5,10}",
126 "ab{,10}",
127 "ab{5,}", # repeaters
128 "ab|cd|ef", # branch
129 "(foo)+",
130 "(['\"])[a-z]+\\1",
131 "(?:[a-z])(['\"])[a-z]+\\1",
132 "(?P<foo>['\"])[a-z]+(?P=foo)", # groups
133 "^abc", # beginning
134 "\\d",
135 "[\\d]",
136 "[^\\D]",
137 "\\w",
138 "[\\w]",
139 "[^\\W]",
140 "\\s",
141 "[\\s]",
142 "[^\\S]", # categories
143 ],
144 )
145 @pytest.mark.parametrize("encode", [None, False, True])
146 def test_can_generate(pattern, encode):
147 alphabet = st.characters(max_codepoint=1000) if encode is None else None
148 if encode:
149 pattern = pattern.encode("ascii")
150 assert_all_examples(
151 st.from_regex(pattern, alphabet=alphabet),
152 re.compile(pattern).search,
153 settings=settings(suppress_health_check=[HealthCheck.data_too_large]),
154 )
155
156
157 @pytest.mark.parametrize(
158 "pattern",
159 [
160 re.compile("\\Aa\\Z", re.IGNORECASE),
161 "(?i)\\Aa\\Z",
162 re.compile("\\A[ab]\\Z", re.IGNORECASE),
163 "(?i)\\A[ab]\\Z",
164 ],
165 )
166 def test_literals_with_ignorecase(pattern):
167 strategy = st.from_regex(pattern)
168
169 find_any(strategy, lambda s: s == "a")
170 find_any(strategy, lambda s: s == "A")
171
172
173 @pytest.mark.parametrize(
174 "pattern", [re.compile("\\A[^a][^b]\\Z", re.IGNORECASE), "(?i)\\A[^a][^b]\\Z"]
175 )
176 def test_not_literal_with_ignorecase(pattern):
177 assert_all_examples(
178 st.from_regex(pattern),
179 lambda s: s[0] not in ("a", "A") and s[1] not in ("b", "B"),
180 )
181
182
183 def test_any_doesnt_generate_newline():
184 assert_all_examples(st.from_regex("\\A.\\Z"), lambda s: s != "\n")
185
186
187 @pytest.mark.parametrize("pattern", [re.compile("\\A.\\Z", re.DOTALL), "(?s)\\A.\\Z"])
188 def test_any_with_dotall_generate_newline(pattern):
189 find_any(st.from_regex(pattern), lambda s: s == "\n", settings(max_examples=10**6))
190
191
192 @pytest.mark.parametrize("pattern", [re.compile(b"\\A.\\Z", re.DOTALL), b"(?s)\\A.\\Z"])
193 def test_any_with_dotall_generate_newline_binary(pattern):
194 find_any(st.from_regex(pattern), lambda s: s == b"\n", settings(max_examples=10**6))
195
196
197 @pytest.mark.skipif(
198 settings.get_current_profile_name() == "crosshair",
199 reason="takes ~30s each; CrossHair strings just aren't fast enough",
200 )
201 @pytest.mark.parametrize(
202 "pattern",
203 ["\\d", "[\\d]", "[^\\D]", "\\w", "[\\w]", "[^\\W]", "\\s", "[\\s]", "[^\\S]"],
204 )
205 @pytest.mark.parametrize("is_unicode", [False, True])
206 @pytest.mark.parametrize("invert", [False, True])
207 def test_groups(pattern, is_unicode, invert):
208 if "d" in pattern.lower():
209 group_pred = is_digit
210 elif "w" in pattern.lower():
211 group_pred = is_word
212 else:
213 # Special behaviour due to \x1c, INFORMATION SEPARATOR FOUR
214 group_pred = is_unicode_space if is_unicode else is_space
215
216 if invert:
217 pattern = pattern.swapcase()
218 _p = group_pred
219
220 def group_pred(s):
221 return not _p(s)
222
223 pattern = f"^{pattern}\\Z"
224
225 compiler = unicode_regex if is_unicode else ascii_regex
226 strategy = st.from_regex(compiler(pattern))
227
228 find_any(strategy.filter(group_pred), is_ascii)
229 if is_unicode:
230 find_any(strategy, lambda s: group_pred(s) and not is_ascii(s))
231
232 assert_all_examples(strategy, group_pred)
233
234
235 def test_caret_in_the_middle_does_not_generate_anything():
236 r = re.compile("a^b")
237
238 assert_no_examples(st.from_regex(r))
239
240
241 def test_end_with_terminator_does_not_pad():
242 assert_all_examples(st.from_regex("abc\\Z"), lambda x: x[-3:] == "abc")
243
244
245 def test_end():
246 strategy = st.from_regex("\\Aabc$")
247
248 find_any(strategy, lambda s: s == "abc")
249 find_any(strategy, lambda s: s == "abc\n")
250
251
252 def test_groupref_exists():
253 assert_all_examples(
254 st.from_regex("^(<)?a(?(1)>)$"), lambda s: s in ("a", "a\n", "<a>", "<a>\n")
255 )
256 assert_all_examples(
257 st.from_regex("^(a)?(?(1)b|c)$"), lambda s: s in ("ab", "ab\n", "c", "c\n")
258 )
259
260
261 def test_impossible_negative_lookahead():
262 assert_no_examples(st.from_regex("(?!foo)foo"))
263
264
265 @given(st.from_regex("(\\Afoo\\Z)"))
266 def test_can_handle_boundaries_nested(s):
267 assert s == "foo"
268
269
270 def test_groupref_not_shared_between_regex():
271 # If group references are (incorrectly!) shared between regex, this would
272 # fail as the would only be one reference.
273 check_can_generate_examples(
274 st.tuples(st.from_regex("(a)\\1"), st.from_regex("(b)\\1"))
275 )
276
277
278 @pytest.mark.skipif(
279 PYPY, # Skip for now so we can test the rest
280 reason=r"Triggers bugs in poor handling of unicode in re for these implementations",
281 )
282 @given(st.data())
283 def test_group_ref_is_not_shared_between_identical_regex(data):
284 pattern = re.compile("^(.+)\\1\\Z", re.UNICODE)
285 x = data.draw(base_regex_strategy(pattern, alphabet=st.characters()))
286 y = data.draw(base_regex_strategy(pattern, alphabet=st.characters()))
287 assume(x != y)
288 assert pattern.match(x).end() == len(x)
289 assert pattern.match(y).end() == len(y)
290
291
292 @given(st.data())
293 def test_does_not_leak_groups(data):
294 a = data.draw(base_regex_strategy(re.compile("^(a)\\Z"), alphabet=st.characters()))
295 assert a == "a"
296 b = data.draw(
297 base_regex_strategy(re.compile("^(?(1)a|b)(.)\\Z"), alphabet=st.characters())
298 )
299 assert b[0] == "b"
300
301
302 def test_positive_lookbehind():
303 find_any(st.from_regex(".*(?<=ab)c"), lambda s: s.endswith("abc"))
304
305
306 def test_positive_lookahead():
307 find_any(st.from_regex("a(?=bc).*"), lambda s: s.startswith("abc"))
308
309
310 def test_negative_lookbehind():
311 # no efficient support
312 strategy = st.from_regex("[abc]*(?<!abc)d")
313
314 assert_all_examples(strategy, lambda s: not s.endswith("abcd"))
315 assert_no_examples(strategy, lambda s: s.endswith("abcd"))
316
317
318 def test_negative_lookahead():
319 # no efficient support
320 strategy = st.from_regex("^ab(?!cd)[abcd]*")
321
322 assert_all_examples(strategy, lambda s: not s.startswith("abcd"))
323 assert_no_examples(strategy, lambda s: s.startswith("abcd"))
324
325
326 @given(st.from_regex("^a+\\Z"))
327 def test_generates_only_the_provided_characters_given_boundaries(xs):
328 assert set(xs) == {"a"}
329
330
331 @given(st.from_regex("^(.)?\\1\\Z"))
332 def test_group_backref_may_not_be_present(s):
333 assert len(s) == 2
334 assert s[0] == s[1]
335
336
337 def test_subpattern_flags():
338 strategy = st.from_regex("(?i)\\Aa(?-i:b)\\Z")
339
340 # "a" is case insensitive
341 find_any(strategy, lambda s: s[0] == "a")
342 find_any(strategy, lambda s: s[0] == "A")
343 # "b" is case sensitive
344 find_any(strategy, lambda s: s[1] == "b")
345
346 assert_no_examples(strategy, lambda s: s[1] == "B")
347
348
349 def test_can_handle_binary_regex_which_is_not_ascii():
350 bad = b"\xad"
351 assert_all_examples(st.from_regex(bad), lambda x: bad in x)
352
353
354 @pytest.mark.parametrize("pattern", [b".", "."])
355 def test_regex_have_same_type_as_pattern(pattern):
356 @given(st.from_regex(pattern))
357 def test_result_type(s):
358 assert type(s) == type(pattern)
359
360 test_result_type()
361
362
363 def test_can_pad_strings_arbitrarily():
364 find_any(st.from_regex("a"), lambda x: x[0] != "a")
365 find_any(st.from_regex("a"), lambda x: x[-1] != "a")
366
367
368 def test_can_pad_empty_strings():
369 find_any(st.from_regex(""), bool)
370 find_any(st.from_regex(b""), bool)
371
372
373 def test_can_pad_strings_with_newlines():
374 find_any(st.from_regex("^$"), bool)
375 find_any(st.from_regex(b"^$"), bool)
376
377
378 def test_given_multiline_regex_can_insert_after_dollar():
379 find_any(
380 st.from_regex(re.compile("\\Ahi$", re.MULTILINE)),
381 lambda x: "\n" in x and x.split("\n")[1],
382 )
383
384
385 def test_given_multiline_regex_can_insert_before_caret():
386 find_any(
387 st.from_regex(re.compile("^hi\\Z", re.MULTILINE)),
388 lambda x: "\n" in x and x.split("\n")[0],
389 )
390
391
392 def test_does_not_left_pad_beginning_of_string_marker():
393 assert_all_examples(st.from_regex("\\Afoo"), lambda x: x.startswith("foo"))
394
395
396 def test_bare_caret_can_produce():
397 find_any(st.from_regex("^"), bool)
398
399
400 def test_bare_dollar_can_produce():
401 find_any(st.from_regex("$"), bool)
402
403
404 def test_shared_union():
405 # This gets parsed as [(ANY, None), (BRANCH, (None, [[], []]))], the
406 # interesting feature of which is that it contains empty sub-expressions
407 # in the branch.
408 find_any(st.from_regex(".|."))
409
410
411 @given(st.data())
412 def test_issue_992_regression(data):
413 strat = st.from_regex(
414 re.compile(
415 r"""\d + # the integral part
416 \. # the decimal point
417 \d * # some fractional digits""",
418 re.VERBOSE,
419 )
420 )
421 data.draw(strat)
422
423
424 @pytest.mark.parametrize(
425 "pattern,matching_str",
426 [
427 ("a", "a"),
428 ("[Aa]", "A"),
429 ("[ab]*", "abb"),
430 (b"[Aa]", b"A"),
431 (b"[ab]*", b"abb"),
432 (re.compile("[ab]*", re.IGNORECASE), "aBb"),
433 (re.compile(b"[ab]", re.IGNORECASE), b"A"),
434 ],
435 )
436 def test_fullmatch_generates_example(pattern, matching_str):
437 find_any(
438 st.from_regex(pattern, fullmatch=True),
439 lambda s: s == matching_str,
440 )
441
442
443 @pytest.mark.parametrize(
444 "pattern,eqiv_pattern",
445 [
446 (r"", r"\A\Z"),
447 (b"", rb"\A\Z"),
448 (r"(?#comment)", r"\A\Z"),
449 (rb"(?#comment)", rb"\A\Z"),
450 ("a", "\\Aa\\Z"),
451 ("[Aa]", "\\A[Aa]\\Z"),
452 ("[ab]*", "\\A[ab]*\\Z"),
453 (b"[Aa]", rb"\A[Aa]\Z"),
454 (b"[ab]*", rb"\A[ab]*\Z"),
455 (re.compile("[ab]*", re.IGNORECASE), re.compile("\\A[ab]*\\Z", re.IGNORECASE)),
456 (re.compile(rb"[ab]", re.IGNORECASE), re.compile(rb"\A[ab]\Z", re.IGNORECASE)),
457 ],
458 )
459 def test_fullmatch_matches(pattern, eqiv_pattern):
460 assert_all_examples(
461 st.from_regex(pattern, fullmatch=True), lambda s: re.match(eqiv_pattern, s)
462 )
463
464
465 def test_fullmatch_must_be_bool():
466 with pytest.raises(InvalidArgument):
467 st.from_regex("a", fullmatch=None).validate()
468
469
470 def test_issue_1786_regression():
471 st.from_regex(re.compile("\\\\", flags=re.IGNORECASE)).validate()
472
473
474 def test_sets_allow_multichar_output_in_ignorecase_mode():
475 # CharacterBuilder.strategy includes logic to add multi-character strings
476 # via sampled_from(), if any are whitelisted as matching. See issue #2657.
477 find_any(
478 st.from_regex(re.compile("[\u0130_]", re.IGNORECASE)),
479 lambda s: len(s) > 1,
480 )
481
482
483 def test_internals_can_disable_newline_from_dollar_for_jsonschema():
484 pattern = "^abc$"
485 find_any(st.from_regex(pattern), lambda s: s == "abc\n")
486 assert_all_examples(
487 regex_strategy(
488 pattern,
489 False,
490 alphabet=st.characters(),
491 _temp_jsonschema_hack_no_end_newline=True,
492 ),
493 lambda s: s == "abc",
494 )
495
496
497 @given(st.from_regex(r"[^.].*", alphabet=st.sampled_from("abc") | st.just(".")))
498 def test_can_pass_union_for_alphabet(_):
499 pass
500
501
502 @pytest.mark.parametrize("explain", [False, True])
503 def test_regex_output_should_print_as_string(explain):
504 phases = [Phase.generate, Phase.shrink]
505 if explain:
506 phases.append(Phase.explain)
507
508 @settings(phases=phases)
509 @given(s=st.from_regex(r"..", fullmatch=True))
510 def test(s):
511 raise AssertionError
512
513 with pytest.raises(AssertionError) as err:
514 test()
515
516 explain_line = " # or any other generated value" if explain else ""
517
518 expected = f"""
519 Falsifying example: test(
520 s='00',{explain_line}
521 )
522 """
523
524 assert "\n".join(err.value.__notes__).strip() == expected.strip()