Debian Codegraph @

hypothesis-python/tests/nocover/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 string
13 import sys
14 from functools import reduce
15
16 import pytest
17
18 from hypothesis import assume, given, reject, strategies as st
19 from hypothesis.strategies._internal.regex import (
20 IncompatibleWithAlphabet,
21 base_regex_strategy,
22 )
23
24
25 @st.composite
26 def charset(draw):
27 negated = draw(st.booleans())
28 chars = draw(st.text(string.ascii_letters + string.digits, min_size=1))
29 if negated:
30 return f"[^{chars}]"
31 else:
32 return f"[{chars}]"
33
34
35 COMBINED_MATCHER = re.compile("[?+*]{2}")
36
37
38 @st.composite
39 def conservative_regex(draw):
40 result = draw(
41 st.one_of(
42 st.just("."),
43 st.sampled_from([re.escape(c) for c in string.printable]),
44 charset(),
45 CONSERVATIVE_REGEX.map(lambda s: f"({s})"),
46 CONSERVATIVE_REGEX.map(lambda s: s + "+"),
47 CONSERVATIVE_REGEX.map(lambda s: s + "?"),
48 CONSERVATIVE_REGEX.map(lambda s: s + "*"),
49 st.lists(CONSERVATIVE_REGEX, min_size=1, max_size=3).map("|".join),
50 st.lists(CONSERVATIVE_REGEX, min_size=1, max_size=3).map("".join),
51 )
52 )
53 assume(COMBINED_MATCHER.search(result) is None)
54 control = sum(result.count(c) for c in "?+*")
55 assume(control <= 3)
56 assume(I_WITH_DOT not in result) # known to be weird
57 return result
58
59
60 CONSERVATIVE_REGEX = conservative_regex()
61 FLAGS = st.sets(
62 st.sampled_from([re.ASCII, re.IGNORECASE, re.MULTILINE, re.DOTALL])
63 ).map(lambda flag_set: reduce(int.__or__, flag_set, 0))
64
65
66 @given(st.data())
67 def test_conservative_regex_are_correct_by_construction(data):
68 pattern = re.compile(data.draw(CONSERVATIVE_REGEX), flags=data.draw(FLAGS))
69 result = data.draw(base_regex_strategy(pattern, alphabet=st.characters()))
70 # We'll skip "capital I with dot above" due to awful casefolding behaviour
71 # and "latin small letter dotless i" for the same reason.
72 assume({"ı", "İ"}.isdisjoint(pattern.pattern + result))
73 assert pattern.search(result) is not None
74
75
76 @given(st.data())
77 def test_fuzz_stuff(data):
78 pattern = data.draw(
79 st.text(min_size=1, max_size=5)
80 | st.binary(min_size=1, max_size=5)
81 | CONSERVATIVE_REGEX.filter(bool)
82 )
83 flags = data.draw(FLAGS)
84
85 try:
86 regex = re.compile(pattern, flags=flags)
87 except (re.error, FutureWarning):
88 # Possible nested sets, e.g. "[[", trigger a FutureWarning
89 reject()
90
91 try:
92 ex = data.draw(st.from_regex(regex))
93 except IncompatibleWithAlphabet:
94 if isinstance(pattern, str) and flags & re.ASCII:
95 with pytest.raises(UnicodeEncodeError):
96 pattern.encode("ascii")
97 regex = re.compile(pattern, flags=flags ^ re.ASCII)
98 ex = data.draw(st.from_regex(regex))
99 else:
100 raise
101
102 assert regex.search(ex)
103
104
105 @pytest.mark.skipif(sys.version_info[:2] < (3, 11), reason="new syntax")
106 @given(st.data())
107 def test_regex_atomic_group(data):
108 pattern = "a(?>bc|b)c"
109 ex = data.draw(st.from_regex(pattern))
110 assert re.search(pattern, ex)
111
112
113 @pytest.mark.skipif(sys.version_info[:2] < (3, 11), reason="new syntax")
114 @given(st.data())
115 def test_regex_possessive(data):
116 pattern = '"[^"]*+"'
117 ex = data.draw(st.from_regex(pattern))
118 assert re.search(pattern, ex)
119
120
121 # Some preliminaries, to establish what's happening:
122 I_WITH_DOT = "\u0130"
123 assert I_WITH_DOT.swapcase() == "i\u0307" # note: string of length two!
124 assert re.compile(I_WITH_DOT, flags=re.IGNORECASE).match(I_WITH_DOT.swapcase())
125
126
127 @given(st.data())
128 def test_case_insensitive_not_literal_never_constructs_multichar_match(data):
129 # So our goal is to confirm that we can never accidentally create a non-matching
130 # string by assembling individually allowed characters.
131 pattern = re.compile(f"[^{I_WITH_DOT}]+", flags=re.IGNORECASE)
132 strategy = st.from_regex(pattern, fullmatch=True)
133 for _ in range(5):
134 s = data.draw(strategy)
135 assert pattern.fullmatch(s) is not None
136 # And to be on the safe side, we implement this stronger property:
137 assert set(s).isdisjoint(I_WITH_DOT.swapcase())
138
139
140 @given(st.from_regex(re.compile(f"[^{I_WITH_DOT}_]", re.IGNORECASE), fullmatch=True))
141 def test_no_error_converting_negated_sets_to_strategy(s):
142 # CharactersBuilder no longer triggers an internal error converting sets
143 # or negated sets to a strategy when multi-char strings are whitelisted.
144 pass