Debian Codegraph @

hypothesis-python/src/hypothesis/provisional.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 """This module contains various provisional APIs and strategies.
12
13 It is intended for internal use, to ease code reuse, and is not stable.
14 Point releases may move or break the contents at any time!
15
16 Internet strategies should conform to :rfc:`3986` or the authoritative
17 definitions it links to. If not, report the bug!
18 """
19 # https://tools.ietf.org/html/rfc3696
20
21 import string
22 from functools import lru_cache
23 from importlib import resources
24
25 from hypothesis import strategies as st
26 from hypothesis.errors import InvalidArgument
27 from hypothesis.internal.conjecture import utils as cu
28 from hypothesis.internal.conjecture.data import ConjectureData
29 from hypothesis.strategies import DrawFn
30 from hypothesis.strategies._internal.utils import defines_strategy
31
32 URL_SAFE_CHARACTERS = frozenset(string.ascii_letters + string.digits + "$-_.+!*'(),~")
33 FRAGMENT_SAFE_CHARACTERS = URL_SAFE_CHARACTERS | {"?", "/"}
34
35
36 @lru_cache(maxsize=1)
37 def get_top_level_domains() -> tuple[str, ...]:
38 # This file is sourced from http://data.iana.org/TLD/tlds-alpha-by-domain.txt
39 # The file contains additional information about the date that it was last updated.
40 traversable = resources.files("hypothesis.vendor") / "tlds-alpha-by-domain.txt"
41 _comment, *_tlds = traversable.read_text(encoding="utf-8").splitlines()
42 assert _comment.startswith("#")
43
44 # Remove special-use domain names from the list. For more discussion
45 # see https://github.com/HypothesisWorks/hypothesis/pull/3572
46 return ("COM", *sorted((d for d in _tlds if d != "ARPA"), key=len))
47
48
49 @st.composite
50 def _recase_randomly(draw: DrawFn, tld: str) -> str:
51 tld = list(tld)
52 changes = draw(st.tuples(*(st.booleans() for _ in range(len(tld)))))
53 for i, change_case in enumerate(changes):
54 if change_case:
55 tld[i] = tld[i].lower() if tld[i].isupper() else tld[i].upper()
56 return "".join(tld)
57
58
59 class DomainNameStrategy(st.SearchStrategy[str]):
60 @staticmethod
61 def clean_inputs(
62 minimum: int, maximum: int, value: int | None, variable_name: str
63 ) -> int:
64 if value is None:
65 value = maximum
66 elif not isinstance(value, int):
67 raise InvalidArgument(
68 f"Expected integer but {variable_name} is a {type(value).__name__}"
69 )
70 elif not minimum <= value <= maximum:
71 raise InvalidArgument(
72 f"Invalid value {minimum!r} < {variable_name}={value!r} < {maximum!r}"
73 )
74 return value
75
76 def __init__(
77 self, max_length: int | None = None, max_element_length: int | None = None
78 ) -> None:
79 """
80 A strategy for :rfc:`1035` fully qualified domain names.
81
82 The upper limit for max_length is 255 in accordance with :rfc:`1035#section-2.3.4`
83 The lower limit for max_length is 4, corresponding to a two letter domain
84 with a single letter subdomain.
85 The upper limit for max_element_length is 63 in accordance with :rfc:`1035#section-2.3.4`
86 The lower limit for max_element_length is 1 in accordance with :rfc:`1035#section-2.3.4`
87 """
88 # https://tools.ietf.org/html/rfc1035#section-2.3.4
89
90 max_length = self.clean_inputs(4, 255, max_length, "max_length")
91 max_element_length = self.clean_inputs(
92 1, 63, max_element_length, "max_element_length"
93 )
94
95 super().__init__()
96 self.max_length = max_length
97 self.max_element_length = max_element_length
98
99 # These regular expressions are constructed to match the documented
100 # information in https://tools.ietf.org/html/rfc1035#section-2.3.1
101 # which defines the allowed syntax of a subdomain string.
102 if self.max_element_length == 1:
103 label_regex = r"[a-zA-Z]"
104 elif self.max_element_length == 2:
105 label_regex = r"[a-zA-Z][a-zA-Z0-9]?"
106 else:
107 maximum_center_character_pattern_repetitions = self.max_element_length - 2
108 label_regex = r"[a-zA-Z]([a-zA-Z0-9\-]{0,%d}[a-zA-Z0-9])?" % (
109 maximum_center_character_pattern_repetitions,
110 )
111
112 # Construct reusable strategies here to avoid a performance hit by doing
113 # so repeatedly in do_draw.
114
115 # 1 - Select a valid top-level domain (TLD) name
116 # 2 - Check that the number of characters in our selected TLD won't
117 # prevent us from generating at least a 1 character subdomain.
118 # 3 - Randomize the TLD between upper and lower case characters.
119
120 self.domain_strategy = (
121 st.sampled_from(get_top_level_domains())
122 .filter(lambda tld: len(tld) + 2 <= self.max_length)
123 .flatmap(_recase_randomly)
124 )
125
126 # RFC-5890 s2.3.1 says such labels are reserved, and since we don't
127 # want to bother with xn-- punycode labels we'll exclude them all.
128 self.elem_strategy = st.from_regex(label_regex, fullmatch=True).filter(
129 lambda label: len(label) < 4 or label[2:4] != "--"
130 )
131
132 def do_draw(self, data: ConjectureData) -> str:
133 domain = data.draw(self.domain_strategy)
134 # The maximum possible number of subdomains is 126,
135 # 1 character subdomain + 1 '.' character, * 126 = 252,
136 # with a max of 255, that leaves 3 characters for a TLD.
137 # Allowing any more subdomains would not leave enough
138 # characters for even the shortest possible TLDs.
139 elements = cu.many(data, min_size=1, average_size=3, max_size=126)
140 while elements.more():
141 # Generate a new valid subdomain using the regex strategy.
142 sub_domain = data.draw(self.elem_strategy)
143 if len(domain) + len(sub_domain) >= self.max_length:
144 data.stop_span(discard=True)
145 break
146 domain = sub_domain + "." + domain
147 return domain
148
149
150 @defines_strategy(force_reusable_values=True)
151 def domains(
152 *, max_length: int = 255, max_element_length: int = 63
153 ) -> st.SearchStrategy[str]:
154 """Generate :rfc:`1035` compliant fully qualified domain names."""
155 return DomainNameStrategy(
156 max_length=max_length, max_element_length=max_element_length
157 )
158
159
160 # The `urls()` strategy uses this to generate URL fragments (e.g. "#foo").
161 # It has been extracted to top-level so that we can test it independently
162 # of `urls()`, which helps with getting non-flaky coverage of the lambda.
163 _url_fragments_strategy = (
164 st.lists(
165 st.builds(
166 lambda char, encode: (
167 f"%{ord(char):02X}"
168 if (encode or char not in FRAGMENT_SAFE_CHARACTERS)
169 else char
170 ),
171 st.characters(min_codepoint=0, max_codepoint=255),
172 st.booleans(),
173 ),
174 min_size=1,
175 )
176 .map("".join)
177 .map("#{}".format)
178 )
179
180
181 @defines_strategy(force_reusable_values=True)
182 def urls() -> st.SearchStrategy[str]:
183 """A strategy for :rfc:`3986`, generating http/https URLs.
184
185 The generated URLs could, at least in theory, be passed to an HTTP client
186 and fetched.
187
188 """
189
190 def url_encode(s: str) -> str:
191 return "".join(c if c in URL_SAFE_CHARACTERS else f"%{ord(c):02X}" for c in s)
192
193 schemes = st.sampled_from(["http", "https"])
194 ports = st.integers(min_value=1, max_value=2**16 - 1).map(":{}".format)
195 paths = st.lists(st.text(string.printable).map(url_encode)).map("/".join)
196
197 return st.builds(
198 "{}://{}{}/{}{}".format,
199 schemes,
200 domains(),
201 st.just("") | ports,
202 paths,
203 st.just("") | _url_fragments_strategy,
204 )