codecraftai-testbase 1.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ccai/factories/py.typed +0 -0
- ccai/factories/testbasedefaulttypefactory.py +25 -0
- ccai/testbase/__init__.py +63 -0
- ccai/testbase/breakpoints.py +110 -0
- ccai/testbase/cli/__init__.py +13 -0
- ccai/testbase/cli/cmdtree/agents/__init__.py +28 -0
- ccai/testbase/cli/cmdtree/agents/config/__init__.py +24 -0
- ccai/testbase/cli/cmdtree/agents/config/extract.py +94 -0
- ccai/testbase/cli/cmdtree/agents/formatting.py +71 -0
- ccai/testbase/cli/cmdtree/agents/jsosparser.py +119 -0
- ccai/testbase/cli/cmdtree/agents/pathresolver.py +34 -0
- ccai/testbase/cli/cmdtree/agents/summary/__init__.py +26 -0
- ccai/testbase/cli/cmdtree/agents/summary/compare.py +128 -0
- ccai/testbase/cli/cmdtree/agents/summary/extract.py +91 -0
- ccai/testbase/cli/cmdtree/agents/testresult/__init__.py +28 -0
- ccai/testbase/cli/cmdtree/agents/testresult/extract.py +77 -0
- ccai/testbase/cli/cmdtree/agents/testresult/failures.py +73 -0
- ccai/testbase/cli/cmdtree/agents/testresult/list.py +63 -0
- ccai/testbase/cli/cmdtree/services/__init__.py +27 -0
- ccai/testbase/cli/cmdtree/services/results.py +66 -0
- ccai/testbase/cli/cmdtree/testing/__init__.py +30 -0
- ccai/testbase/cli/cmdtree/testing/jobs.py +175 -0
- ccai/testbase/cli/cmdtree/testing/query.py +131 -0
- ccai/testbase/cli/cmdtree/testing/run.py +263 -0
- ccai/testbase/cli/cmdtree/utilities/__init__.py +28 -0
- ccai/testbase/cli/cmdtree/utilities/timestamp.py +33 -0
- ccai/testbase/cli/options.py +370 -0
- ccai/testbase/cli/testbase_command.py +64 -0
- ccai/testbase/cli/utilities.py +31 -0
- ccai/testbase/configuration.py +324 -0
- ccai/testbase/constraints.py +998 -0
- ccai/testbase/coupling/__init__.py +569 -0
- ccai/testbase/coupling/basecoupling.py +69 -0
- ccai/testbase/coupling/configurationcoupling.py +138 -0
- ccai/testbase/coupling/integrationcoupling.py +842 -0
- ccai/testbase/coupling/validatorcoupling.py +127 -0
- ccai/testbase/debuggingext.py +281 -0
- ccai/testbase/debuglogging.py +407 -0
- ccai/testbase/debugports.py +469 -0
- ccai/testbase/declaration/__init__.py +13 -0
- ccai/testbase/declaration/attachments.py +222 -0
- ccai/testbase/declaration/originations.py +217 -0
- ccai/testbase/declaration/parameterization.py +160 -0
- ccai/testbase/declaration/registrations.py +476 -0
- ccai/testbase/diagnostic_level.py +197 -0
- ccai/testbase/diagnostic_streaming.py +1534 -0
- ccai/testbase/diagnostics.py +1685 -0
- ccai/testbase/entrypoints.py +485 -0
- ccai/testbase/environment.py +162 -0
- ccai/testbase/errors/testruntimeouterror.py +50 -0
- ccai/testbase/expressions.py +355 -0
- ccai/testbase/factories.py +277 -0
- ccai/testbase/factoryprotocols.py +35 -0
- ccai/testbase/features.py +913 -0
- ccai/testbase/initialize.py +210 -0
- ccai/testbase/injection/__init__.py +25 -0
- ccai/testbase/injection/injectiongroup.py +493 -0
- ccai/testbase/injection/injectionmoment.py +155 -0
- ccai/testbase/injection/injectionregistry.py +823 -0
- ccai/testbase/injection/injectionscope.py +2589 -0
- ccai/testbase/injection/introspection.py +514 -0
- ccai/testbase/markers.py +665 -0
- ccai/testbase/mocking.py +4856 -0
- ccai/testbase/origins/__init__.py +13 -0
- ccai/testbase/origins/resourceorigin.py +110 -0
- ccai/testbase/origins/validatororigin.py +111 -0
- ccai/testbase/output/__init__.py +17 -0
- ccai/testbase/output/outputcontext.py +201 -0
- ccai/testbase/output/runmetadata.py +184 -0
- ccai/testbase/properties/__init__.py +40 -0
- ccai/testbase/properties/assumptions.py +56 -0
- ccai/testbase/properties/decorators.py +173 -0
- ccai/testbase/properties/propertyrunner.py +449 -0
- ccai/testbase/properties/strategies.py +1592 -0
- ccai/testbase/properties/unittestsupport.py +87 -0
- ccai/testbase/py.typed +0 -0
- ccai/testbase/queries.py +95 -0
- ccai/testbase/resourcelifespan.py +24 -0
- ccai/testbase/results/__init__.py +35 -0
- ccai/testbase/results/exceptions.py +60 -0
- ccai/testbase/results/filtering/__init__.py +26 -0
- ccai/testbase/results/filtering/resultfilter.py +570 -0
- ccai/testbase/results/model/__init__.py +32 -0
- ccai/testbase/results/model/buildinfo.py +54 -0
- ccai/testbase/results/model/checkresult.py +183 -0
- ccai/testbase/results/model/forwardinginfo.py +30 -0
- ccai/testbase/results/model/jobcontainer.py +32 -0
- ccai/testbase/results/model/jobinfo.py +91 -0
- ccai/testbase/results/model/nestedprogressinfo.py +211 -0
- ccai/testbase/results/model/pipelineinfo.py +51 -0
- ccai/testbase/results/model/progressaggregator.py +551 -0
- ccai/testbase/results/model/progresscode.py +29 -0
- ccai/testbase/results/model/progressdelivery.py +51 -0
- ccai/testbase/results/model/progressinfo.py +84 -0
- ccai/testbase/results/model/progresstype.py +24 -0
- ccai/testbase/results/model/renderinfo.py +30 -0
- ccai/testbase/results/model/resultcode.py +28 -0
- ccai/testbase/results/model/resultcontainer.py +95 -0
- ccai/testbase/results/model/resultnode.py +258 -0
- ccai/testbase/results/model/resulttype.py +34 -0
- ccai/testbase/results/model/streaminginfo.py +111 -0
- ccai/testbase/results/model/taskinggroup.py +85 -0
- ccai/testbase/results/model/taskingresult.py +297 -0
- ccai/testbase/results/model/testcontainer.py +35 -0
- ccai/testbase/results/model/testresult.py +170 -0
- ccai/testbase/results/recorders/__init__.py +31 -0
- ccai/testbase/results/recorders/csvresultrecorder.py +414 -0
- ccai/testbase/results/recorders/jsonresultrecorder.py +467 -0
- ccai/testbase/results/recorders/resultrecorder.py +1472 -0
- ccai/testbase/results/recorders/stdoutresultrecorder.py +70 -0
- ccai/testbase/results/recorders/xmlresultrecorder.py +305 -0
- ccai/testbase/results/utilities.py +141 -0
- ccai/testbase/sequencing/__init__.py +13 -0
- ccai/testbase/sequencing/sequencermodulescope.py +96 -0
- ccai/testbase/sequencing/sequencerscopebase.py +91 -0
- ccai/testbase/sequencing/sequencersessionscope.py +84 -0
- ccai/testbase/sequencing/sequencertestscope.py +249 -0
- ccai/testbase/sequencing/sequencertestsetupscope.py +86 -0
- ccai/testbase/sequencing/testactivity.py +111 -0
- ccai/testbase/sequencing/testsequencer.py +3072 -0
- ccai/testbase/server/__init__.py +13 -0
- ccai/testbase/server/resultserver.py +599 -0
- ccai/testbase/sources/__init__.py +13 -0
- ccai/testbase/sources/configurationsource.py +32 -0
- ccai/testbase/sources/integrationsource.py +29 -0
- ccai/testbase/sources/resourcesource.py +27 -0
- ccai/testbase/sources/sourcebase.py +71 -0
- ccai/testbase/sources/unknownsource.py +30 -0
- ccai/testbase/sources/validatorsource.py +28 -0
- ccai/testbase/tandem/__init__.py +13 -0
- ccai/testbase/tandem/validators.py +286 -0
- ccai/testbase/testcollector.py +230 -0
- ccai/testbase/testgroup.py +54 -0
- ccai/testbase/testjob.py +600 -0
- ccai/testbase/testref.py +64 -0
- ccai/testbase/utilities.py +472 -0
- ccai/testbase/verification.py +768 -0
- codecraftai_testbase-1.3.0.dist-info/METADATA +99 -0
- codecraftai_testbase-1.3.0.dist-info/RECORD +142 -0
- codecraftai_testbase-1.3.0.dist-info/WHEEL +4 -0
- codecraftai_testbase-1.3.0.dist-info/entry_points.txt +3 -0
- codecraftai_testbase-1.3.0.dist-info/licenses/LICENSE.md +204 -0
|
@@ -0,0 +1,1592 @@
|
|
|
1
|
+
"""
|
|
2
|
+
.. module:: ccai.testbase.properties.strategies
|
|
3
|
+
:platform: Darwin, Linux, Unix, Windows
|
|
4
|
+
:synopsis: Module for property testing strategies — composable random value generators.
|
|
5
|
+
|
|
6
|
+
This module provides the ``Strategy`` base class and a comprehensive set of
|
|
7
|
+
built-in strategy implementations for generating random test inputs. All
|
|
8
|
+
strategies support deterministic generation via ``random.Random`` instances,
|
|
9
|
+
value shrinking for counterexample minimization, and human-readable
|
|
10
|
+
descriptions for query mode output.
|
|
11
|
+
|
|
12
|
+
.. moduleauthor:: Myron Walker <myron.walker@gmail.com>
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
__author__ = "Myron Walker"
|
|
18
|
+
__copyright__ = "Copyright 2025, Code Craft AI LLC"
|
|
19
|
+
__credits__ = []
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
from typing import Any, Callable, Dict, Iterator, Optional, Sequence, Tuple, Union
|
|
23
|
+
|
|
24
|
+
import functools
|
|
25
|
+
import random
|
|
26
|
+
import re
|
|
27
|
+
import re._parser as _regex_parser
|
|
28
|
+
import string
|
|
29
|
+
import unicodedata
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class Strategy:
|
|
33
|
+
"""
|
|
34
|
+
Abstract base class for all property testing strategies.
|
|
35
|
+
|
|
36
|
+
A strategy is a composable generator that produces random values of
|
|
37
|
+
a specific type. Strategies support three operations:
|
|
38
|
+
|
|
39
|
+
- **generate(rng)**: Produce a random value using the given RNG
|
|
40
|
+
- **shrink(value)**: Yield progressively simpler versions of a value
|
|
41
|
+
- **describe()**: Return a human-readable description of this strategy
|
|
42
|
+
|
|
43
|
+
All built-in strategies use only the ``random`` and ``string`` modules
|
|
44
|
+
from the Python standard library.
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
def generate(self, rng: random.Random) -> Any:
|
|
48
|
+
"""
|
|
49
|
+
Generate a random value using the provided random number generator.
|
|
50
|
+
|
|
51
|
+
:param rng: A ``random.Random`` instance for deterministic generation.
|
|
52
|
+
:returns: A randomly generated value of the appropriate type.
|
|
53
|
+
:raises NotImplementedError: If the subclass does not implement this method.
|
|
54
|
+
"""
|
|
55
|
+
raise NotImplementedError("Subclasses must implement generate()")
|
|
56
|
+
|
|
57
|
+
def shrink(self, value: Any) -> Iterator[Any]:
|
|
58
|
+
"""
|
|
59
|
+
Yield progressively simpler versions of the given value.
|
|
60
|
+
|
|
61
|
+
The shrinking process attempts to reduce a failing input to
|
|
62
|
+
a minimal counterexample. Yielded values should be "simpler"
|
|
63
|
+
than the input (e.g., closer to zero for integers, shorter
|
|
64
|
+
for strings).
|
|
65
|
+
|
|
66
|
+
The default implementation yields nothing (no shrinking).
|
|
67
|
+
|
|
68
|
+
:param value: The value to shrink.
|
|
69
|
+
:returns: An iterator of simpler values.
|
|
70
|
+
"""
|
|
71
|
+
return iter([])
|
|
72
|
+
|
|
73
|
+
def describe(self) -> str:
|
|
74
|
+
"""
|
|
75
|
+
Return a human-readable description of this strategy.
|
|
76
|
+
|
|
77
|
+
Used in query mode output and error messages to describe
|
|
78
|
+
what kind of values this strategy generates.
|
|
79
|
+
|
|
80
|
+
:returns: A string description of the strategy configuration.
|
|
81
|
+
"""
|
|
82
|
+
return self.__class__.__name__
|
|
83
|
+
|
|
84
|
+
def map(self, fn: Callable) -> 'MappedStrategy':
|
|
85
|
+
"""
|
|
86
|
+
Returns a new strategy that applies ``fn`` to each generated value.
|
|
87
|
+
|
|
88
|
+
Example::
|
|
89
|
+
|
|
90
|
+
st.integers(0, 100).map(lambda x: x * 2)
|
|
91
|
+
|
|
92
|
+
:param fn: A callable to transform generated values.
|
|
93
|
+
:returns: A ``MappedStrategy`` wrapping this strategy.
|
|
94
|
+
"""
|
|
95
|
+
return MappedStrategy(self, fn)
|
|
96
|
+
|
|
97
|
+
def filter(self, predicate: Callable, max_tries: int = 100) -> 'FilteredStrategy':
|
|
98
|
+
"""
|
|
99
|
+
Returns a new strategy that only yields values satisfying
|
|
100
|
+
the given predicate.
|
|
101
|
+
|
|
102
|
+
If the predicate is not satisfied after ``max_tries`` attempts,
|
|
103
|
+
an ``UnsatisfiedAssumption`` exception is raised.
|
|
104
|
+
|
|
105
|
+
Example::
|
|
106
|
+
|
|
107
|
+
st.integers(-100, 100).filter(lambda x: x != 0)
|
|
108
|
+
|
|
109
|
+
:param predicate: A callable returning truthy for acceptable values.
|
|
110
|
+
:param max_tries: Maximum generation attempts before giving up.
|
|
111
|
+
:returns: A ``FilteredStrategy`` wrapping this strategy.
|
|
112
|
+
"""
|
|
113
|
+
return FilteredStrategy(self, predicate, max_tries)
|
|
114
|
+
|
|
115
|
+
def flatmap(self, fn: Callable) -> 'FlatMappedStrategy':
|
|
116
|
+
"""
|
|
117
|
+
Returns a new strategy that generates a value from this strategy,
|
|
118
|
+
passes it to ``fn`` to obtain a second strategy, and then generates
|
|
119
|
+
from that second strategy.
|
|
120
|
+
|
|
121
|
+
Example::
|
|
122
|
+
|
|
123
|
+
st.integers(1, 5).flatmap(lambda n: st.text(min_size=n, max_size=n))
|
|
124
|
+
|
|
125
|
+
:param fn: A callable that accepts a generated value and returns
|
|
126
|
+
a ``Strategy`` instance.
|
|
127
|
+
:returns: A ``FlatMappedStrategy`` wrapping this strategy.
|
|
128
|
+
"""
|
|
129
|
+
return FlatMappedStrategy(self, fn)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
class IntegerStrategy(Strategy):
|
|
133
|
+
"""
|
|
134
|
+
Strategy that generates random integers within an inclusive range.
|
|
135
|
+
|
|
136
|
+
Shrinking moves values toward zero: first yields 0 (if in range),
|
|
137
|
+
then yields the value halved repeatedly.
|
|
138
|
+
|
|
139
|
+
:param min_value: The minimum integer value (inclusive). Default is -1000000.
|
|
140
|
+
:param max_value: The maximum integer value (inclusive). Default is 1000000.
|
|
141
|
+
"""
|
|
142
|
+
|
|
143
|
+
def __init__(self, min_value: int = -1000000, max_value: int = 1000000):
|
|
144
|
+
self._min_value = min_value
|
|
145
|
+
self._max_value = max_value
|
|
146
|
+
|
|
147
|
+
def generate(self, rng: random.Random) -> int:
|
|
148
|
+
return rng.randint(self._min_value, self._max_value)
|
|
149
|
+
|
|
150
|
+
def shrink(self, value: int) -> Iterator[int]:
|
|
151
|
+
if value == 0:
|
|
152
|
+
return
|
|
153
|
+
|
|
154
|
+
# Try zero first
|
|
155
|
+
if self._min_value <= 0 <= self._max_value:
|
|
156
|
+
yield 0
|
|
157
|
+
|
|
158
|
+
# Then halve toward zero
|
|
159
|
+
current = value
|
|
160
|
+
while abs(current) > 1:
|
|
161
|
+
current = current // 2
|
|
162
|
+
if self._min_value <= current <= self._max_value and current != 0:
|
|
163
|
+
yield current
|
|
164
|
+
|
|
165
|
+
def describe(self) -> str:
|
|
166
|
+
parts = []
|
|
167
|
+
if self._min_value != -1000000:
|
|
168
|
+
parts.append(f"min_value={self._min_value}")
|
|
169
|
+
if self._max_value != 1000000:
|
|
170
|
+
parts.append(f"max_value={self._max_value}")
|
|
171
|
+
args = ", ".join(parts)
|
|
172
|
+
return f"integers({args})"
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
class FloatStrategy(Strategy):
|
|
176
|
+
"""
|
|
177
|
+
Strategy that generates random floating-point numbers within a range.
|
|
178
|
+
|
|
179
|
+
Shrinking moves values toward 0.0, halving repeatedly.
|
|
180
|
+
|
|
181
|
+
:param min_value: The minimum float value. Default is -1e6.
|
|
182
|
+
:param max_value: The maximum float value. Default is 1e6.
|
|
183
|
+
"""
|
|
184
|
+
|
|
185
|
+
def __init__(self, min_value: float = -1e6, max_value: float = 1e6):
|
|
186
|
+
self._min_value = min_value
|
|
187
|
+
self._max_value = max_value
|
|
188
|
+
|
|
189
|
+
def generate(self, rng: random.Random) -> float:
|
|
190
|
+
return rng.uniform(self._min_value, self._max_value)
|
|
191
|
+
|
|
192
|
+
def shrink(self, value: float) -> Iterator[float]:
|
|
193
|
+
if value == 0.0:
|
|
194
|
+
return
|
|
195
|
+
|
|
196
|
+
# Try zero first
|
|
197
|
+
if self._min_value <= 0.0 <= self._max_value:
|
|
198
|
+
yield 0.0
|
|
199
|
+
|
|
200
|
+
# Then halve toward zero
|
|
201
|
+
current = value
|
|
202
|
+
while abs(current) > 1e-10:
|
|
203
|
+
current = current / 2.0
|
|
204
|
+
if self._min_value <= current <= self._max_value and current != 0.0:
|
|
205
|
+
yield current
|
|
206
|
+
|
|
207
|
+
def describe(self) -> str:
|
|
208
|
+
parts = []
|
|
209
|
+
if self._min_value != -1e6:
|
|
210
|
+
parts.append(f"min_value={self._min_value}")
|
|
211
|
+
if self._max_value != 1e6:
|
|
212
|
+
parts.append(f"max_value={self._max_value}")
|
|
213
|
+
args = ", ".join(parts)
|
|
214
|
+
return f"floats({args})"
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
class BooleanStrategy(Strategy):
|
|
218
|
+
"""
|
|
219
|
+
Strategy that generates random boolean values.
|
|
220
|
+
|
|
221
|
+
Shrinking yields ``False`` when given ``True``.
|
|
222
|
+
"""
|
|
223
|
+
|
|
224
|
+
def generate(self, rng: random.Random) -> bool:
|
|
225
|
+
return rng.choice([True, False])
|
|
226
|
+
|
|
227
|
+
def shrink(self, value: bool) -> Iterator[bool]:
|
|
228
|
+
if value:
|
|
229
|
+
yield False
|
|
230
|
+
|
|
231
|
+
def describe(self) -> str:
|
|
232
|
+
return "booleans()"
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
class TextStrategy(Strategy):
|
|
236
|
+
"""
|
|
237
|
+
Strategy that generates random strings from a given alphabet.
|
|
238
|
+
|
|
239
|
+
Shrinking first yields the empty string, then the first half,
|
|
240
|
+
then removes single characters one at a time.
|
|
241
|
+
|
|
242
|
+
:param alphabet: The characters to draw from. Can be a string or a
|
|
243
|
+
``Strategy`` that generates individual characters. Default is
|
|
244
|
+
ASCII letters and digits.
|
|
245
|
+
:param min_size: Minimum string length. Default is 0.
|
|
246
|
+
:param max_size: Maximum string length. Default is 100.
|
|
247
|
+
"""
|
|
248
|
+
|
|
249
|
+
def __init__(self, alphabet: Union[str, 'Strategy', None] = None,
|
|
250
|
+
min_size: int = 0, max_size: int = 100):
|
|
251
|
+
if alphabet is None:
|
|
252
|
+
self._alphabet = string.ascii_letters + string.digits
|
|
253
|
+
else:
|
|
254
|
+
self._alphabet = alphabet
|
|
255
|
+
self._min_size = min_size
|
|
256
|
+
self._max_size = max_size
|
|
257
|
+
|
|
258
|
+
def generate(self, rng: random.Random) -> str:
|
|
259
|
+
length = rng.randint(self._min_size, self._max_size)
|
|
260
|
+
if isinstance(self._alphabet, Strategy):
|
|
261
|
+
return "".join(self._alphabet.generate(rng) for _ in range(length))
|
|
262
|
+
return "".join(rng.choice(self._alphabet) for _ in range(length))
|
|
263
|
+
|
|
264
|
+
def shrink(self, value: str) -> Iterator[str]:
|
|
265
|
+
if len(value) <= self._min_size:
|
|
266
|
+
return
|
|
267
|
+
|
|
268
|
+
# Try empty string
|
|
269
|
+
if self._min_size == 0:
|
|
270
|
+
yield ""
|
|
271
|
+
|
|
272
|
+
# Try first half
|
|
273
|
+
half = len(value) // 2
|
|
274
|
+
if half >= self._min_size and half > 0:
|
|
275
|
+
yield value[:half]
|
|
276
|
+
|
|
277
|
+
# Try removing single characters
|
|
278
|
+
for i in range(len(value)):
|
|
279
|
+
shrunk = value[:i] + value[i + 1:]
|
|
280
|
+
if len(shrunk) >= self._min_size:
|
|
281
|
+
yield shrunk
|
|
282
|
+
|
|
283
|
+
def describe(self) -> str:
|
|
284
|
+
parts = []
|
|
285
|
+
if isinstance(self._alphabet, Strategy):
|
|
286
|
+
parts.append(f"alphabet={self._alphabet.describe()}")
|
|
287
|
+
elif self._alphabet != string.ascii_letters + string.digits:
|
|
288
|
+
parts.append(f"alphabet='{self._alphabet}'")
|
|
289
|
+
if self._min_size != 0:
|
|
290
|
+
parts.append(f"min_size={self._min_size}")
|
|
291
|
+
if self._max_size != 100:
|
|
292
|
+
parts.append(f"max_size={self._max_size}")
|
|
293
|
+
args = ", ".join(parts)
|
|
294
|
+
return f"text({args})"
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
class CharacterStrategy(Strategy):
|
|
298
|
+
"""
|
|
299
|
+
Strategy that generates single characters.
|
|
300
|
+
|
|
301
|
+
Can generate from a codepoint range, unicode categories, or an
|
|
302
|
+
explicit character set.
|
|
303
|
+
|
|
304
|
+
Precedence is: ``characters``, then a codepoint range, then
|
|
305
|
+
``categories``, then all printable characters.
|
|
306
|
+
|
|
307
|
+
:param categories: Tuple of unicode category identifiers to generate from.
|
|
308
|
+
Currently maps to predefined character sets for simplicity.
|
|
309
|
+
:param characters: An explicit string of characters to choose from.
|
|
310
|
+
If provided, takes precedence over everything else.
|
|
311
|
+
:param min_codepoint: Inclusive lower bound of a codepoint range.
|
|
312
|
+
:param max_codepoint: Inclusive upper bound of a codepoint range.
|
|
313
|
+
Either bound may be given alone; the other defaults to 0 or to
|
|
314
|
+
0x10FFFF respectively.
|
|
315
|
+
"""
|
|
316
|
+
|
|
317
|
+
_CATEGORY_MAP = {
|
|
318
|
+
"L": string.ascii_letters,
|
|
319
|
+
"Lu": string.ascii_uppercase,
|
|
320
|
+
"Ll": string.ascii_lowercase,
|
|
321
|
+
"N": string.digits,
|
|
322
|
+
"Nd": string.digits,
|
|
323
|
+
"P": string.punctuation,
|
|
324
|
+
"S": "!@#$%^&*",
|
|
325
|
+
"Z": " \t\n",
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
# Codepoints that cannot stand alone in a str: the surrogate range is not
|
|
329
|
+
# encodable, so including it would make generated text unserialisable.
|
|
330
|
+
_SURROGATE_FIRST = 0xD800
|
|
331
|
+
_SURROGATE_LAST = 0xDFFF
|
|
332
|
+
|
|
333
|
+
_MAX_CODEPOINT = 0x10FFFF
|
|
334
|
+
|
|
335
|
+
def __init__(self, categories: Optional[Tuple[str, ...]] = None,
|
|
336
|
+
characters: Optional[str] = None,
|
|
337
|
+
min_codepoint: Optional[int] = None,
|
|
338
|
+
max_codepoint: Optional[int] = None,
|
|
339
|
+
whitelist_categories: Optional[Tuple[str, ...]] = None,
|
|
340
|
+
blacklist_categories: Optional[Tuple[str, ...]] = None,
|
|
341
|
+
whitelist_characters: Optional[str] = None,
|
|
342
|
+
blacklist_characters: Optional[str] = None):
|
|
343
|
+
# whitelist_categories is the same request as categories, under the
|
|
344
|
+
# name callers coming from other property libraries already use.
|
|
345
|
+
allowed = categories
|
|
346
|
+
if allowed is None:
|
|
347
|
+
allowed = whitelist_categories
|
|
348
|
+
|
|
349
|
+
if characters is not None:
|
|
350
|
+
selected = characters
|
|
351
|
+
elif min_codepoint is not None or max_codepoint is not None:
|
|
352
|
+
selected = self._from_codepoints(
|
|
353
|
+
min_codepoint=min_codepoint, max_codepoint=max_codepoint)
|
|
354
|
+
elif allowed is not None:
|
|
355
|
+
chars = ""
|
|
356
|
+
for cat in allowed:
|
|
357
|
+
chars += self._CATEGORY_MAP.get(cat, "")
|
|
358
|
+
selected = chars if chars else string.printable
|
|
359
|
+
else:
|
|
360
|
+
selected = string.printable
|
|
361
|
+
|
|
362
|
+
if blacklist_categories is not None:
|
|
363
|
+
selected = self._without_categories(
|
|
364
|
+
selected, excluded=blacklist_categories)
|
|
365
|
+
|
|
366
|
+
# Character-level allow/deny, applied last so they can rescue or
|
|
367
|
+
# remove individual characters the category filters got wrong. These
|
|
368
|
+
# are distinct from the *_categories arguments: those name unicode
|
|
369
|
+
# classes, these name literal characters.
|
|
370
|
+
if whitelist_characters is not None:
|
|
371
|
+
for character in whitelist_characters:
|
|
372
|
+
if character not in selected:
|
|
373
|
+
selected = selected + character
|
|
374
|
+
|
|
375
|
+
if blacklist_characters is not None:
|
|
376
|
+
denied = set(blacklist_characters)
|
|
377
|
+
kept = "".join(c for c in selected if c not in denied)
|
|
378
|
+
if len(kept) == 0:
|
|
379
|
+
errmsg = (
|
|
380
|
+
"characters() blacklist_characters={!r} removes every "
|
|
381
|
+
"candidate character.".format(blacklist_characters)
|
|
382
|
+
)
|
|
383
|
+
raise ValueError(errmsg)
|
|
384
|
+
selected = kept
|
|
385
|
+
|
|
386
|
+
self._characters = selected
|
|
387
|
+
|
|
388
|
+
@classmethod
|
|
389
|
+
def _without_categories(cls, selected: str, *,
|
|
390
|
+
excluded: Tuple[str, ...]) -> str:
|
|
391
|
+
"""
|
|
392
|
+
Drop characters belonging to any excluded unicode category.
|
|
393
|
+
|
|
394
|
+
Matching uses each character's REAL unicode category rather than
|
|
395
|
+
the approximate ``_CATEGORY_MAP``, because that map only covers a
|
|
396
|
+
handful of ASCII sets and the categories callers exclude — ``Cs``
|
|
397
|
+
for surrogates, ``Cc`` for control characters — are not in it. A
|
|
398
|
+
one-letter code matches the whole major class, so ``C`` excludes
|
|
399
|
+
``Cc``, ``Cf`` and ``Cs`` alike.
|
|
400
|
+
|
|
401
|
+
:param selected: The character set to filter.
|
|
402
|
+
:param excluded: The unicode categories to remove.
|
|
403
|
+
|
|
404
|
+
:returns: The filtered character set.
|
|
405
|
+
|
|
406
|
+
:raises ValueError: When the exclusion removes everything, which
|
|
407
|
+
means the request cannot be satisfied and would otherwise fail
|
|
408
|
+
later inside ``generate``.
|
|
409
|
+
"""
|
|
410
|
+
wanted = set(excluded)
|
|
411
|
+
majors = {code for code in wanted if len(code) == 1}
|
|
412
|
+
|
|
413
|
+
kept = []
|
|
414
|
+
for character in selected:
|
|
415
|
+
category = unicodedata.category(character)
|
|
416
|
+
if category in wanted:
|
|
417
|
+
continue
|
|
418
|
+
if category[:1] in majors:
|
|
419
|
+
continue
|
|
420
|
+
kept.append(character)
|
|
421
|
+
|
|
422
|
+
if len(kept) == 0:
|
|
423
|
+
errmsg = (
|
|
424
|
+
"characters() blacklist_categories={} removes every "
|
|
425
|
+
"candidate character.".format(tuple(excluded))
|
|
426
|
+
)
|
|
427
|
+
raise ValueError(errmsg)
|
|
428
|
+
|
|
429
|
+
rtnval = "".join(kept)
|
|
430
|
+
return rtnval
|
|
431
|
+
|
|
432
|
+
@classmethod
|
|
433
|
+
def _from_codepoints(cls, *, min_codepoint: Optional[int],
|
|
434
|
+
max_codepoint: Optional[int]) -> str:
|
|
435
|
+
"""
|
|
436
|
+
Build the character set spanning a codepoint range.
|
|
437
|
+
|
|
438
|
+
Surrogates are excluded: they are not independently encodable, so
|
|
439
|
+
a generated string containing one cannot be written out, and the
|
|
440
|
+
failure would surface far from here.
|
|
441
|
+
|
|
442
|
+
:param min_codepoint: Inclusive lower bound, or None for 0.
|
|
443
|
+
:param max_codepoint: Inclusive upper bound, or None for the
|
|
444
|
+
maximum codepoint.
|
|
445
|
+
|
|
446
|
+
:returns: The character set.
|
|
447
|
+
|
|
448
|
+
:raises ValueError: When the range is inverted or empty, which is
|
|
449
|
+
always a mistake at the call site rather than something to
|
|
450
|
+
silently widen.
|
|
451
|
+
"""
|
|
452
|
+
low = min_codepoint if min_codepoint is not None else 0
|
|
453
|
+
high = max_codepoint if max_codepoint is not None else \
|
|
454
|
+
cls._MAX_CODEPOINT
|
|
455
|
+
|
|
456
|
+
if low > high:
|
|
457
|
+
errmsg = (
|
|
458
|
+
"characters() received an inverted codepoint range: "
|
|
459
|
+
"min_codepoint={} is above max_codepoint={}.".format(low, high)
|
|
460
|
+
)
|
|
461
|
+
raise ValueError(errmsg)
|
|
462
|
+
|
|
463
|
+
selected = [
|
|
464
|
+
chr(point) for point in range(low, high + 1)
|
|
465
|
+
if not (cls._SURROGATE_FIRST <= point <= cls._SURROGATE_LAST)
|
|
466
|
+
]
|
|
467
|
+
|
|
468
|
+
if len(selected) == 0:
|
|
469
|
+
errmsg = (
|
|
470
|
+
"characters() codepoint range {}..{} selects no usable "
|
|
471
|
+
"characters.".format(low, high)
|
|
472
|
+
)
|
|
473
|
+
raise ValueError(errmsg)
|
|
474
|
+
|
|
475
|
+
rtnval = "".join(selected)
|
|
476
|
+
return rtnval
|
|
477
|
+
|
|
478
|
+
def generate(self, rng: random.Random) -> str:
|
|
479
|
+
return rng.choice(self._characters)
|
|
480
|
+
|
|
481
|
+
def describe(self) -> str:
|
|
482
|
+
if self._characters == string.printable:
|
|
483
|
+
return "characters()"
|
|
484
|
+
return f"characters(characters='{self._characters[:20]}...')" if len(self._characters) > 20 \
|
|
485
|
+
else f"characters(characters='{self._characters}')"
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
class ListStrategy(Strategy):
|
|
489
|
+
"""
|
|
490
|
+
Strategy that generates random lists of elements.
|
|
491
|
+
|
|
492
|
+
Each element is generated using the provided element strategy.
|
|
493
|
+
Shrinking first yields the empty list, then the first half,
|
|
494
|
+
then tries removing single elements.
|
|
495
|
+
|
|
496
|
+
:param element: A ``Strategy`` for generating individual list elements.
|
|
497
|
+
:param min_size: Minimum list length. Default is 0.
|
|
498
|
+
:param max_size: Maximum list length. Default is 50.
|
|
499
|
+
:param unique: When True, no two elements compare equal.
|
|
500
|
+
:param unique_by: A callable returning the value to compare for
|
|
501
|
+
uniqueness, e.g. ``unique_by=lambda entry: entry["name"]``.
|
|
502
|
+
Uniqueness is best-effort: a strategy whose value space is smaller
|
|
503
|
+
than ``max_size`` yields a shorter list rather than looping.
|
|
504
|
+
"""
|
|
505
|
+
|
|
506
|
+
def __init__(self, element: Strategy, min_size: int = 0,
|
|
507
|
+
max_size: int = 50, unique: bool = False,
|
|
508
|
+
unique_by=None):
|
|
509
|
+
self._element = element
|
|
510
|
+
self._min_size = min_size
|
|
511
|
+
self._max_size = max_size
|
|
512
|
+
self._unique = unique
|
|
513
|
+
self._unique_by = unique_by
|
|
514
|
+
|
|
515
|
+
# Uniqueness is best-effort: a strategy with a small value space cannot
|
|
516
|
+
# always yield max_size distinct values, so generation stops early rather
|
|
517
|
+
# than looping forever. min_size is still honoured where the space allows.
|
|
518
|
+
_UNIQUE_ATTEMPT_FACTOR = 10
|
|
519
|
+
|
|
520
|
+
def generate(self, rng: random.Random) -> list:
|
|
521
|
+
length = rng.randint(self._min_size, self._max_size)
|
|
522
|
+
|
|
523
|
+
if self._unique is False and self._unique_by is None:
|
|
524
|
+
return [self._element.generate(rng) for _ in range(length)]
|
|
525
|
+
|
|
526
|
+
key = self._unique_by
|
|
527
|
+
if key is None:
|
|
528
|
+
def key(value):
|
|
529
|
+
return value
|
|
530
|
+
|
|
531
|
+
collected = []
|
|
532
|
+
seen = set()
|
|
533
|
+
attempts = 0
|
|
534
|
+
budget = max(length * self._UNIQUE_ATTEMPT_FACTOR, length + 10)
|
|
535
|
+
|
|
536
|
+
while len(collected) < length and attempts < budget:
|
|
537
|
+
attempts += 1
|
|
538
|
+
candidate = self._element.generate(rng)
|
|
539
|
+
marker = key(candidate)
|
|
540
|
+
try:
|
|
541
|
+
if marker in seen:
|
|
542
|
+
continue
|
|
543
|
+
seen.add(marker)
|
|
544
|
+
except TypeError:
|
|
545
|
+
# An unhashable key still gets uniqueness, just linearly.
|
|
546
|
+
if marker in [key(v) for v in collected]:
|
|
547
|
+
continue
|
|
548
|
+
collected.append(candidate)
|
|
549
|
+
|
|
550
|
+
return collected
|
|
551
|
+
|
|
552
|
+
def shrink(self, value: list) -> Iterator[list]:
|
|
553
|
+
if len(value) <= self._min_size:
|
|
554
|
+
return
|
|
555
|
+
|
|
556
|
+
# Try empty list
|
|
557
|
+
if self._min_size == 0:
|
|
558
|
+
yield []
|
|
559
|
+
|
|
560
|
+
# Try first half
|
|
561
|
+
half = len(value) // 2
|
|
562
|
+
if half >= self._min_size and half > 0:
|
|
563
|
+
yield value[:half]
|
|
564
|
+
|
|
565
|
+
# Try removing single elements
|
|
566
|
+
for i in range(len(value)):
|
|
567
|
+
shrunk = value[:i] + value[i + 1:]
|
|
568
|
+
if len(shrunk) >= self._min_size:
|
|
569
|
+
yield shrunk
|
|
570
|
+
|
|
571
|
+
def describe(self) -> str:
|
|
572
|
+
parts = [self._element.describe()]
|
|
573
|
+
if self._min_size != 0:
|
|
574
|
+
parts.append(f"min_size={self._min_size}")
|
|
575
|
+
if self._max_size != 50:
|
|
576
|
+
parts.append(f"max_size={self._max_size}")
|
|
577
|
+
return f"lists({', '.join(parts)})"
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
class TupleStrategy(Strategy):
|
|
581
|
+
"""
|
|
582
|
+
Strategy that generates random tuples with elements from
|
|
583
|
+
the given strategies.
|
|
584
|
+
|
|
585
|
+
Each position in the tuple is generated by its corresponding strategy.
|
|
586
|
+
Shrinking attempts to shrink individual elements in order.
|
|
587
|
+
|
|
588
|
+
:param strategies: One ``Strategy`` per tuple position.
|
|
589
|
+
"""
|
|
590
|
+
|
|
591
|
+
def __init__(self, *strategies: Strategy):
|
|
592
|
+
self._strategies = strategies
|
|
593
|
+
|
|
594
|
+
def generate(self, rng: random.Random) -> tuple:
|
|
595
|
+
return tuple(s.generate(rng) for s in self._strategies)
|
|
596
|
+
|
|
597
|
+
def shrink(self, value: tuple) -> Iterator[tuple]:
|
|
598
|
+
# Try shrinking each element individually
|
|
599
|
+
for i, strategy in enumerate(self._strategies):
|
|
600
|
+
for shrunk_elem in strategy.shrink(value[i]):
|
|
601
|
+
result = list(value)
|
|
602
|
+
result[i] = shrunk_elem
|
|
603
|
+
yield tuple(result)
|
|
604
|
+
|
|
605
|
+
def describe(self) -> str:
|
|
606
|
+
inner = ", ".join(s.describe() for s in self._strategies)
|
|
607
|
+
return f"tuples({inner})"
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
class DictionaryStrategy(Strategy):
|
|
611
|
+
"""
|
|
612
|
+
Strategy that generates random dictionaries.
|
|
613
|
+
|
|
614
|
+
Keys and values are generated using separate strategies.
|
|
615
|
+
Shrinking first yields the empty dict, then the first half of keys,
|
|
616
|
+
then removes single keys.
|
|
617
|
+
|
|
618
|
+
:param keys: A ``Strategy`` for generating dictionary keys.
|
|
619
|
+
:param values: A ``Strategy`` for generating dictionary values.
|
|
620
|
+
:param min_size: Minimum number of entries. Default is 0.
|
|
621
|
+
:param max_size: Maximum number of entries. Default is 20.
|
|
622
|
+
"""
|
|
623
|
+
|
|
624
|
+
def __init__(self, keys: Strategy, values: Strategy,
|
|
625
|
+
min_size: int = 0, max_size: int = 20):
|
|
626
|
+
self._keys = keys
|
|
627
|
+
self._values = values
|
|
628
|
+
self._min_size = min_size
|
|
629
|
+
self._max_size = max_size
|
|
630
|
+
|
|
631
|
+
def generate(self, rng: random.Random) -> dict:
|
|
632
|
+
length = rng.randint(self._min_size, self._max_size)
|
|
633
|
+
result = {}
|
|
634
|
+
for _ in range(length):
|
|
635
|
+
k = self._keys.generate(rng)
|
|
636
|
+
v = self._values.generate(rng)
|
|
637
|
+
result[k] = v
|
|
638
|
+
return result
|
|
639
|
+
|
|
640
|
+
def shrink(self, value: dict) -> Iterator[dict]:
|
|
641
|
+
if len(value) <= self._min_size:
|
|
642
|
+
return
|
|
643
|
+
|
|
644
|
+
# Try empty dict
|
|
645
|
+
if self._min_size == 0:
|
|
646
|
+
yield {}
|
|
647
|
+
|
|
648
|
+
# Try first half of keys
|
|
649
|
+
keys = list(value.keys())
|
|
650
|
+
half = len(keys) // 2
|
|
651
|
+
if half >= self._min_size and half > 0:
|
|
652
|
+
yield {k: value[k] for k in keys[:half]}
|
|
653
|
+
|
|
654
|
+
# Try removing single keys
|
|
655
|
+
for key in keys:
|
|
656
|
+
shrunk = {k: v for k, v in value.items() if k != key}
|
|
657
|
+
if len(shrunk) >= self._min_size:
|
|
658
|
+
yield shrunk
|
|
659
|
+
|
|
660
|
+
def describe(self) -> str:
|
|
661
|
+
parts = [self._keys.describe(), self._values.describe()]
|
|
662
|
+
if self._min_size != 0:
|
|
663
|
+
parts.append(f"min_size={self._min_size}")
|
|
664
|
+
if self._max_size != 20:
|
|
665
|
+
parts.append(f"max_size={self._max_size}")
|
|
666
|
+
return f"dictionaries({', '.join(parts)})"
|
|
667
|
+
|
|
668
|
+
|
|
669
|
+
class SampledFromStrategy(Strategy):
|
|
670
|
+
"""
|
|
671
|
+
Strategy that randomly selects a value from a fixed sequence.
|
|
672
|
+
|
|
673
|
+
No shrinking is performed since the elements are pre-defined.
|
|
674
|
+
|
|
675
|
+
:param elements: A sequence of values to sample from.
|
|
676
|
+
"""
|
|
677
|
+
|
|
678
|
+
def __init__(self, elements: Sequence):
|
|
679
|
+
if len(elements) == 0:
|
|
680
|
+
raise ValueError("sampled_from requires a non-empty sequence")
|
|
681
|
+
self._elements = elements
|
|
682
|
+
|
|
683
|
+
def generate(self, rng: random.Random) -> Any:
|
|
684
|
+
return rng.choice(self._elements)
|
|
685
|
+
|
|
686
|
+
def describe(self) -> str:
|
|
687
|
+
if len(self._elements) <= 5:
|
|
688
|
+
return f"sampled_from({list(self._elements)})"
|
|
689
|
+
return f"sampled_from([{self._elements[0]}, ... ({len(self._elements)} elements)])"
|
|
690
|
+
|
|
691
|
+
|
|
692
|
+
class OneOfStrategy(Strategy):
|
|
693
|
+
"""
|
|
694
|
+
Strategy that randomly selects one sub-strategy and then generates
|
|
695
|
+
a value from it.
|
|
696
|
+
|
|
697
|
+
:param strategies: Two or more strategies to choose from.
|
|
698
|
+
"""
|
|
699
|
+
|
|
700
|
+
def __init__(self, *strategies: Strategy):
|
|
701
|
+
if len(strategies) < 2:
|
|
702
|
+
raise ValueError("one_of requires at least two strategies")
|
|
703
|
+
self._strategies = strategies
|
|
704
|
+
|
|
705
|
+
def generate(self, rng: random.Random) -> Any:
|
|
706
|
+
chosen = rng.choice(self._strategies)
|
|
707
|
+
return chosen.generate(rng)
|
|
708
|
+
|
|
709
|
+
def shrink(self, value: Any) -> Iterator[Any]:
|
|
710
|
+
# Attempt to shrink using each sub-strategy
|
|
711
|
+
for strategy in self._strategies:
|
|
712
|
+
try:
|
|
713
|
+
for shrunk in strategy.shrink(value):
|
|
714
|
+
yield shrunk
|
|
715
|
+
except (TypeError, ValueError, AttributeError):
|
|
716
|
+
continue
|
|
717
|
+
|
|
718
|
+
def describe(self) -> str:
|
|
719
|
+
inner = ", ".join(s.describe() for s in self._strategies)
|
|
720
|
+
return f"one_of({inner})"
|
|
721
|
+
|
|
722
|
+
|
|
723
|
+
class JustStrategy(Strategy):
|
|
724
|
+
"""
|
|
725
|
+
Strategy that always returns the same fixed value.
|
|
726
|
+
|
|
727
|
+
No shrinking is performed since the value is constant.
|
|
728
|
+
|
|
729
|
+
:param value: The fixed value to always return.
|
|
730
|
+
"""
|
|
731
|
+
|
|
732
|
+
def __init__(self, value: Any):
|
|
733
|
+
self._value = value
|
|
734
|
+
|
|
735
|
+
def generate(self, rng: random.Random) -> Any:
|
|
736
|
+
return self._value
|
|
737
|
+
|
|
738
|
+
def describe(self) -> str:
|
|
739
|
+
return f"just({self._value!r})"
|
|
740
|
+
|
|
741
|
+
|
|
742
|
+
class CompositeStrategy(Strategy):
|
|
743
|
+
"""
|
|
744
|
+
Strategy defined by a user function that uses a ``draw`` callable
|
|
745
|
+
to pull values from other strategies.
|
|
746
|
+
|
|
747
|
+
Created by the ``@composite`` decorator.
|
|
748
|
+
|
|
749
|
+
:param fn: The composite strategy function.
|
|
750
|
+
:param args: Positional arguments (beyond the first ``draw`` param).
|
|
751
|
+
:param kwargs: Keyword arguments to pass to the function.
|
|
752
|
+
"""
|
|
753
|
+
|
|
754
|
+
def __init__(self, fn: Callable, args: tuple = (), kwargs: Optional[dict] = None):
|
|
755
|
+
self._fn = fn
|
|
756
|
+
self._args = args
|
|
757
|
+
self._kwargs = kwargs or {}
|
|
758
|
+
|
|
759
|
+
def generate(self, rng: random.Random) -> Any:
|
|
760
|
+
def draw(strategy: Strategy) -> Any:
|
|
761
|
+
return strategy.generate(rng)
|
|
762
|
+
return self._fn(draw, *self._args, **self._kwargs)
|
|
763
|
+
|
|
764
|
+
def describe(self) -> str:
|
|
765
|
+
return f"composite({self._fn.__name__})"
|
|
766
|
+
|
|
767
|
+
|
|
768
|
+
class ExplicitStrategy(Strategy):
|
|
769
|
+
"""
|
|
770
|
+
Strategy that yields values from a predetermined sequence.
|
|
771
|
+
|
|
772
|
+
Values are cycled in order, wrapping around when the sequence
|
|
773
|
+
is exhausted. The random number generator is ignored — this
|
|
774
|
+
strategy always produces the same deterministic sequence.
|
|
775
|
+
|
|
776
|
+
No shrinking is performed since the values are user-specified.
|
|
777
|
+
|
|
778
|
+
:param values: A non-empty sequence of values to yield.
|
|
779
|
+
"""
|
|
780
|
+
|
|
781
|
+
def __init__(self, values: Sequence):
|
|
782
|
+
if len(values) == 0:
|
|
783
|
+
raise ValueError("explicit requires a non-empty sequence of values")
|
|
784
|
+
self._values = list(values)
|
|
785
|
+
self._index = 0
|
|
786
|
+
|
|
787
|
+
def generate(self, rng: random.Random) -> Any:
|
|
788
|
+
value = self._values[self._index % len(self._values)]
|
|
789
|
+
self._index += 1
|
|
790
|
+
return value
|
|
791
|
+
|
|
792
|
+
def describe(self) -> str:
|
|
793
|
+
if len(self._values) <= 3:
|
|
794
|
+
return f"explicit({self._values!r})"
|
|
795
|
+
return f"explicit([{self._values[0]!r}, ... ({len(self._values)} values)])"
|
|
796
|
+
|
|
797
|
+
|
|
798
|
+
# =============================================================================
|
|
799
|
+
# Strategy Combinators
|
|
800
|
+
# =============================================================================
|
|
801
|
+
|
|
802
|
+
|
|
803
|
+
class MappedStrategy(Strategy):
|
|
804
|
+
"""
|
|
805
|
+
Strategy that applies a transformation function to values generated
|
|
806
|
+
by a source strategy.
|
|
807
|
+
|
|
808
|
+
Created by :meth:`Strategy.map`.
|
|
809
|
+
|
|
810
|
+
:param source: The underlying strategy to generate values from.
|
|
811
|
+
:param fn: A callable applied to each generated value.
|
|
812
|
+
"""
|
|
813
|
+
|
|
814
|
+
def __init__(self, source: Strategy, fn: Callable):
|
|
815
|
+
self._source = source
|
|
816
|
+
self._fn = fn
|
|
817
|
+
|
|
818
|
+
def generate(self, rng: random.Random) -> Any:
|
|
819
|
+
return self._fn(self._source.generate(rng))
|
|
820
|
+
|
|
821
|
+
def shrink(self, value: Any) -> Iterator[Any]:
|
|
822
|
+
# We cannot invert the map, so we try shrinking the source
|
|
823
|
+
# and re-mapping. This requires knowing the original pre-map
|
|
824
|
+
# value, which we don't have — so no shrinking for mapped.
|
|
825
|
+
return iter([])
|
|
826
|
+
|
|
827
|
+
def describe(self) -> str:
|
|
828
|
+
return f"{self._source.describe()}.map(...)"
|
|
829
|
+
|
|
830
|
+
|
|
831
|
+
class FilteredStrategy(Strategy):
|
|
832
|
+
"""
|
|
833
|
+
Strategy that only yields values from a source strategy that
|
|
834
|
+
satisfy a given predicate.
|
|
835
|
+
|
|
836
|
+
Created by :meth:`Strategy.filter`.
|
|
837
|
+
|
|
838
|
+
:param source: The underlying strategy to generate values from.
|
|
839
|
+
:param predicate: A callable that returns truthy for acceptable values.
|
|
840
|
+
:param max_tries: Maximum generation attempts before raising.
|
|
841
|
+
"""
|
|
842
|
+
|
|
843
|
+
def __init__(self, source: Strategy, predicate: Callable,
|
|
844
|
+
max_tries: int = 100):
|
|
845
|
+
self._source = source
|
|
846
|
+
self._predicate = predicate
|
|
847
|
+
self._max_tries = max_tries
|
|
848
|
+
|
|
849
|
+
def generate(self, rng: random.Random) -> Any:
|
|
850
|
+
from ccai.testbase.properties.assumptions import UnsatisfiedAssumption
|
|
851
|
+
|
|
852
|
+
for _ in range(self._max_tries):
|
|
853
|
+
value = self._source.generate(rng)
|
|
854
|
+
if self._predicate(value):
|
|
855
|
+
return value
|
|
856
|
+
|
|
857
|
+
raise UnsatisfiedAssumption(
|
|
858
|
+
f"Could not satisfy filter after {self._max_tries} attempts "
|
|
859
|
+
f"on strategy {self._source.describe()}"
|
|
860
|
+
)
|
|
861
|
+
|
|
862
|
+
def shrink(self, value: Any) -> Iterator[Any]:
|
|
863
|
+
for shrunk in self._source.shrink(value):
|
|
864
|
+
if self._predicate(shrunk):
|
|
865
|
+
yield shrunk
|
|
866
|
+
|
|
867
|
+
def describe(self) -> str:
|
|
868
|
+
return f"{self._source.describe()}.filter(...)"
|
|
869
|
+
|
|
870
|
+
|
|
871
|
+
class FlatMappedStrategy(Strategy):
|
|
872
|
+
"""
|
|
873
|
+
Strategy that generates a value from a source strategy, passes it
|
|
874
|
+
to a function to obtain a second strategy, and generates from that.
|
|
875
|
+
|
|
876
|
+
Created by :meth:`Strategy.flatmap`.
|
|
877
|
+
|
|
878
|
+
:param source: The underlying strategy to generate the initial value.
|
|
879
|
+
:param fn: A callable that accepts the generated value and returns
|
|
880
|
+
a ``Strategy`` instance.
|
|
881
|
+
"""
|
|
882
|
+
|
|
883
|
+
def __init__(self, source: Strategy, fn: Callable):
|
|
884
|
+
self._source = source
|
|
885
|
+
self._fn = fn
|
|
886
|
+
|
|
887
|
+
def generate(self, rng: random.Random) -> Any:
|
|
888
|
+
first = self._source.generate(rng)
|
|
889
|
+
second_strategy = self._fn(first)
|
|
890
|
+
return second_strategy.generate(rng)
|
|
891
|
+
|
|
892
|
+
def describe(self) -> str:
|
|
893
|
+
return f"{self._source.describe()}.flatmap(...)"
|
|
894
|
+
|
|
895
|
+
|
|
896
|
+
# =============================================================================
|
|
897
|
+
# Additional Built-in Strategies
|
|
898
|
+
# =============================================================================
|
|
899
|
+
|
|
900
|
+
|
|
901
|
+
class NoneStrategy(Strategy):
|
|
902
|
+
"""
|
|
903
|
+
Strategy that always generates ``None``.
|
|
904
|
+
|
|
905
|
+
No shrinking is performed since the value is constant.
|
|
906
|
+
"""
|
|
907
|
+
|
|
908
|
+
def generate(self, rng: random.Random) -> None:
|
|
909
|
+
return None
|
|
910
|
+
|
|
911
|
+
def describe(self) -> str:
|
|
912
|
+
return "none()"
|
|
913
|
+
|
|
914
|
+
|
|
915
|
+
class BinaryStrategy(Strategy):
|
|
916
|
+
"""
|
|
917
|
+
Strategy that generates random ``bytes`` objects.
|
|
918
|
+
|
|
919
|
+
Shrinking first yields empty bytes, then the first half,
|
|
920
|
+
then removes single bytes.
|
|
921
|
+
|
|
922
|
+
:param min_size: Minimum byte sequence length. Default is 0.
|
|
923
|
+
:param max_size: Maximum byte sequence length. Default is 100.
|
|
924
|
+
"""
|
|
925
|
+
|
|
926
|
+
def __init__(self, min_size: int = 0, max_size: int = 100):
|
|
927
|
+
self._min_size = min_size
|
|
928
|
+
self._max_size = max_size
|
|
929
|
+
|
|
930
|
+
def generate(self, rng: random.Random) -> bytes:
|
|
931
|
+
length = rng.randint(self._min_size, self._max_size)
|
|
932
|
+
return bytes(rng.randint(0, 255) for _ in range(length))
|
|
933
|
+
|
|
934
|
+
def shrink(self, value: bytes) -> Iterator[bytes]:
|
|
935
|
+
if len(value) <= self._min_size:
|
|
936
|
+
return
|
|
937
|
+
|
|
938
|
+
# Try empty bytes
|
|
939
|
+
if self._min_size == 0:
|
|
940
|
+
yield b""
|
|
941
|
+
|
|
942
|
+
# Try first half
|
|
943
|
+
half = len(value) // 2
|
|
944
|
+
if half >= self._min_size and half > 0:
|
|
945
|
+
yield value[:half]
|
|
946
|
+
|
|
947
|
+
# Try removing single bytes
|
|
948
|
+
for i in range(len(value)):
|
|
949
|
+
shrunk = value[:i] + value[i + 1:]
|
|
950
|
+
if len(shrunk) >= self._min_size:
|
|
951
|
+
yield shrunk
|
|
952
|
+
|
|
953
|
+
def describe(self) -> str:
|
|
954
|
+
parts = []
|
|
955
|
+
if self._min_size != 0:
|
|
956
|
+
parts.append(f"min_size={self._min_size}")
|
|
957
|
+
if self._max_size != 100:
|
|
958
|
+
parts.append(f"max_size={self._max_size}")
|
|
959
|
+
args = ", ".join(parts)
|
|
960
|
+
return f"binary({args})"
|
|
961
|
+
|
|
962
|
+
|
|
963
|
+
class SetStrategy(Strategy):
|
|
964
|
+
"""
|
|
965
|
+
Strategy that generates random ``set`` objects.
|
|
966
|
+
|
|
967
|
+
Each element is generated using the provided element strategy.
|
|
968
|
+
Due to set uniqueness constraints, the actual size may be smaller
|
|
969
|
+
than requested if the element strategy produces duplicates.
|
|
970
|
+
|
|
971
|
+
Shrinking first yields the empty set, then the first half,
|
|
972
|
+
then tries removing single elements.
|
|
973
|
+
|
|
974
|
+
:param element: A ``Strategy`` for generating individual set elements.
|
|
975
|
+
:param min_size: Minimum set size. Default is 0.
|
|
976
|
+
:param max_size: Maximum set size. Default is 50.
|
|
977
|
+
"""
|
|
978
|
+
|
|
979
|
+
def __init__(self, element: Strategy, min_size: int = 0, max_size: int = 50):
|
|
980
|
+
self._element = element
|
|
981
|
+
self._min_size = min_size
|
|
982
|
+
self._max_size = max_size
|
|
983
|
+
|
|
984
|
+
def generate(self, rng: random.Random) -> set:
|
|
985
|
+
target_length = rng.randint(self._min_size, self._max_size)
|
|
986
|
+
result = set()
|
|
987
|
+
# Allow extra attempts for uniqueness
|
|
988
|
+
for _ in range(target_length * 3):
|
|
989
|
+
if len(result) >= target_length:
|
|
990
|
+
break
|
|
991
|
+
result.add(self._element.generate(rng))
|
|
992
|
+
return result
|
|
993
|
+
|
|
994
|
+
def shrink(self, value: set) -> Iterator[set]:
|
|
995
|
+
if len(value) <= self._min_size:
|
|
996
|
+
return
|
|
997
|
+
|
|
998
|
+
# Try empty set
|
|
999
|
+
if self._min_size == 0:
|
|
1000
|
+
yield set()
|
|
1001
|
+
|
|
1002
|
+
# Try first half
|
|
1003
|
+
items = list(value)
|
|
1004
|
+
half = len(items) // 2
|
|
1005
|
+
if half >= self._min_size and half > 0:
|
|
1006
|
+
yield set(items[:half])
|
|
1007
|
+
|
|
1008
|
+
# Try removing single elements
|
|
1009
|
+
for item in items:
|
|
1010
|
+
shrunk = value - {item}
|
|
1011
|
+
if len(shrunk) >= self._min_size:
|
|
1012
|
+
yield shrunk
|
|
1013
|
+
|
|
1014
|
+
def describe(self) -> str:
|
|
1015
|
+
parts = [self._element.describe()]
|
|
1016
|
+
if self._min_size != 0:
|
|
1017
|
+
parts.append(f"min_size={self._min_size}")
|
|
1018
|
+
if self._max_size != 50:
|
|
1019
|
+
parts.append(f"max_size={self._max_size}")
|
|
1020
|
+
return f"sets({', '.join(parts)})"
|
|
1021
|
+
|
|
1022
|
+
|
|
1023
|
+
class FrozenSetStrategy(Strategy):
|
|
1024
|
+
"""
|
|
1025
|
+
Strategy that generates random ``frozenset`` objects.
|
|
1026
|
+
|
|
1027
|
+
Delegates to :class:`SetStrategy` for generation and converts
|
|
1028
|
+
the result to a frozenset.
|
|
1029
|
+
|
|
1030
|
+
:param element: A ``Strategy`` for generating individual elements.
|
|
1031
|
+
:param min_size: Minimum size. Default is 0.
|
|
1032
|
+
:param max_size: Maximum size. Default is 50.
|
|
1033
|
+
"""
|
|
1034
|
+
|
|
1035
|
+
def __init__(self, element: Strategy, min_size: int = 0, max_size: int = 50):
|
|
1036
|
+
self._inner = SetStrategy(element, min_size, max_size)
|
|
1037
|
+
self._min_size = min_size
|
|
1038
|
+
|
|
1039
|
+
def generate(self, rng: random.Random) -> frozenset:
|
|
1040
|
+
return frozenset(self._inner.generate(rng))
|
|
1041
|
+
|
|
1042
|
+
def shrink(self, value: frozenset) -> Iterator[frozenset]:
|
|
1043
|
+
for shrunk_set in self._inner.shrink(set(value)):
|
|
1044
|
+
yield frozenset(shrunk_set)
|
|
1045
|
+
|
|
1046
|
+
def describe(self) -> str:
|
|
1047
|
+
inner_desc = self._inner.describe()
|
|
1048
|
+
# Replace "sets(" with "frozensets("
|
|
1049
|
+
return "frozen" + inner_desc
|
|
1050
|
+
|
|
1051
|
+
|
|
1052
|
+
class FixedDictionaryStrategy(Strategy):
|
|
1053
|
+
"""
|
|
1054
|
+
Strategy that generates dictionaries with a fixed set of keys,
|
|
1055
|
+
where each key's value is drawn from a corresponding strategy.
|
|
1056
|
+
|
|
1057
|
+
Shrinking attempts to shrink individual values.
|
|
1058
|
+
|
|
1059
|
+
:param mapping: A dictionary mapping keys to ``Strategy`` instances.
|
|
1060
|
+
"""
|
|
1061
|
+
|
|
1062
|
+
def __init__(self, mapping: Dict[str, Strategy]):
|
|
1063
|
+
self._mapping = mapping
|
|
1064
|
+
|
|
1065
|
+
def generate(self, rng: random.Random) -> dict:
|
|
1066
|
+
return {
|
|
1067
|
+
key: strategy.generate(rng)
|
|
1068
|
+
for key, strategy in self._mapping.items()
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
def shrink(self, value: dict) -> Iterator[dict]:
|
|
1072
|
+
# Try shrinking each value individually
|
|
1073
|
+
for key, strategy in self._mapping.items():
|
|
1074
|
+
if key in value:
|
|
1075
|
+
for shrunk_val in strategy.shrink(value[key]):
|
|
1076
|
+
result = dict(value)
|
|
1077
|
+
result[key] = shrunk_val
|
|
1078
|
+
yield result
|
|
1079
|
+
|
|
1080
|
+
def describe(self) -> str:
|
|
1081
|
+
inner = ", ".join(
|
|
1082
|
+
f"{k!r}: {v.describe()}" for k, v in self._mapping.items()
|
|
1083
|
+
)
|
|
1084
|
+
return f"fixed_dictionaries({{{inner}}})"
|
|
1085
|
+
|
|
1086
|
+
|
|
1087
|
+
class BuildsStrategy(Strategy):
|
|
1088
|
+
"""
|
|
1089
|
+
Strategy that constructs instances of a callable (typically a class)
|
|
1090
|
+
by generating values for its arguments from strategies.
|
|
1091
|
+
|
|
1092
|
+
:param target: The callable to invoke with generated arguments.
|
|
1093
|
+
:param arg_strategies: Positional argument strategies.
|
|
1094
|
+
:param kwarg_strategies: Keyword argument strategies.
|
|
1095
|
+
"""
|
|
1096
|
+
|
|
1097
|
+
def __init__(self, target: Callable, arg_strategies: Tuple[Strategy, ...] = (),
|
|
1098
|
+
kwarg_strategies: Optional[Dict[str, Strategy]] = None):
|
|
1099
|
+
self._target = target
|
|
1100
|
+
self._arg_strategies = arg_strategies
|
|
1101
|
+
self._kwarg_strategies = kwarg_strategies or {}
|
|
1102
|
+
|
|
1103
|
+
def generate(self, rng: random.Random) -> Any:
|
|
1104
|
+
args = tuple(s.generate(rng) for s in self._arg_strategies)
|
|
1105
|
+
kwargs = {
|
|
1106
|
+
k: s.generate(rng) for k, s in self._kwarg_strategies.items()
|
|
1107
|
+
}
|
|
1108
|
+
return self._target(*args, **kwargs)
|
|
1109
|
+
|
|
1110
|
+
def describe(self) -> str:
|
|
1111
|
+
parts = []
|
|
1112
|
+
for s in self._arg_strategies:
|
|
1113
|
+
parts.append(s.describe())
|
|
1114
|
+
for k, s in self._kwarg_strategies.items():
|
|
1115
|
+
parts.append(f"{k}={s.describe()}")
|
|
1116
|
+
args = ", ".join(parts)
|
|
1117
|
+
name = getattr(self._target, '__name__', repr(self._target))
|
|
1118
|
+
return f"builds({name}, {args})"
|
|
1119
|
+
|
|
1120
|
+
|
|
1121
|
+
# =============================================================================
|
|
1122
|
+
# Composite Decorator
|
|
1123
|
+
# =============================================================================
|
|
1124
|
+
|
|
1125
|
+
|
|
1126
|
+
def composite(fn: Callable) -> Callable:
|
|
1127
|
+
"""
|
|
1128
|
+
Decorator that converts a function into a strategy factory.
|
|
1129
|
+
|
|
1130
|
+
The decorated function receives a ``draw`` callable as its first
|
|
1131
|
+
argument. Calling ``draw(strategy)`` pulls a random value from the
|
|
1132
|
+
given strategy during generation.
|
|
1133
|
+
|
|
1134
|
+
Example::
|
|
1135
|
+
|
|
1136
|
+
@composite
|
|
1137
|
+
def sorted_lists(draw, min_size=0, max_size=10):
|
|
1138
|
+
xs = draw(lists(integers(), min_size=min_size, max_size=max_size))
|
|
1139
|
+
return sorted(xs)
|
|
1140
|
+
|
|
1141
|
+
# Use as: @given(xs=sorted_lists(min_size=1))
|
|
1142
|
+
|
|
1143
|
+
:param fn: A function that accepts ``draw`` as its first argument
|
|
1144
|
+
and returns a generated value.
|
|
1145
|
+
:returns: A factory function that produces ``CompositeStrategy`` instances.
|
|
1146
|
+
"""
|
|
1147
|
+
@functools.wraps(fn)
|
|
1148
|
+
def wrapper(*args, **kwargs):
|
|
1149
|
+
return CompositeStrategy(fn, args=args, kwargs=kwargs)
|
|
1150
|
+
return wrapper
|
|
1151
|
+
|
|
1152
|
+
|
|
1153
|
+
# =============================================================================
|
|
1154
|
+
# Public Convenience Functions
|
|
1155
|
+
# =============================================================================
|
|
1156
|
+
|
|
1157
|
+
|
|
1158
|
+
def integers(min_value: int = -1000000, max_value: int = 1000000) -> IntegerStrategy:
|
|
1159
|
+
"""
|
|
1160
|
+
Creates a strategy that generates random integers within an inclusive range.
|
|
1161
|
+
|
|
1162
|
+
:param min_value: The minimum integer value (inclusive). Default is -1000000.
|
|
1163
|
+
:param max_value: The maximum integer value (inclusive). Default is 1000000.
|
|
1164
|
+
:returns: An ``IntegerStrategy`` instance.
|
|
1165
|
+
"""
|
|
1166
|
+
return IntegerStrategy(min_value=min_value, max_value=max_value)
|
|
1167
|
+
|
|
1168
|
+
|
|
1169
|
+
def floats(min_value: float = -1e6, max_value: float = 1e6) -> FloatStrategy:
|
|
1170
|
+
"""
|
|
1171
|
+
Creates a strategy that generates random floating-point numbers.
|
|
1172
|
+
|
|
1173
|
+
:param min_value: The minimum float value. Default is -1e6.
|
|
1174
|
+
:param max_value: The maximum float value. Default is 1e6.
|
|
1175
|
+
:returns: A ``FloatStrategy`` instance.
|
|
1176
|
+
"""
|
|
1177
|
+
return FloatStrategy(min_value=min_value, max_value=max_value)
|
|
1178
|
+
|
|
1179
|
+
|
|
1180
|
+
def text(alphabet: Union[str, Strategy, None] = None,
|
|
1181
|
+
min_size: int = 0, max_size: int = 100) -> TextStrategy:
|
|
1182
|
+
"""
|
|
1183
|
+
Creates a strategy that generates random strings.
|
|
1184
|
+
|
|
1185
|
+
:param alphabet: Characters to draw from. Can be a string or a character
|
|
1186
|
+
strategy. Default is ASCII letters and digits.
|
|
1187
|
+
:param min_size: Minimum string length. Default is 0.
|
|
1188
|
+
:param max_size: Maximum string length. Default is 100.
|
|
1189
|
+
:returns: A ``TextStrategy`` instance.
|
|
1190
|
+
"""
|
|
1191
|
+
return TextStrategy(alphabet=alphabet, min_size=min_size, max_size=max_size)
|
|
1192
|
+
|
|
1193
|
+
|
|
1194
|
+
def booleans() -> BooleanStrategy:
|
|
1195
|
+
"""
|
|
1196
|
+
Creates a strategy that generates random boolean values.
|
|
1197
|
+
|
|
1198
|
+
:returns: A ``BooleanStrategy`` instance.
|
|
1199
|
+
"""
|
|
1200
|
+
return BooleanStrategy()
|
|
1201
|
+
|
|
1202
|
+
|
|
1203
|
+
def lists(element: Strategy, min_size: int = 0, max_size: int = 50,
|
|
1204
|
+
unique: bool = False, unique_by=None) -> ListStrategy:
|
|
1205
|
+
"""
|
|
1206
|
+
Creates a strategy that generates random lists.
|
|
1207
|
+
|
|
1208
|
+
:param element: A strategy for generating individual list elements.
|
|
1209
|
+
:param min_size: Minimum list length. Default is 0.
|
|
1210
|
+
:param max_size: Maximum list length. Default is 50.
|
|
1211
|
+
:returns: A ``ListStrategy`` instance.
|
|
1212
|
+
"""
|
|
1213
|
+
return ListStrategy(element=element, min_size=min_size,
|
|
1214
|
+
max_size=max_size, unique=unique,
|
|
1215
|
+
unique_by=unique_by)
|
|
1216
|
+
|
|
1217
|
+
|
|
1218
|
+
def tuples(*strategies: Strategy) -> TupleStrategy:
|
|
1219
|
+
"""
|
|
1220
|
+
Creates a strategy that generates random tuples.
|
|
1221
|
+
|
|
1222
|
+
Each position in the tuple is generated by its corresponding strategy.
|
|
1223
|
+
|
|
1224
|
+
:param strategies: One strategy per tuple position.
|
|
1225
|
+
:returns: A ``TupleStrategy`` instance.
|
|
1226
|
+
"""
|
|
1227
|
+
return TupleStrategy(*strategies)
|
|
1228
|
+
|
|
1229
|
+
|
|
1230
|
+
def dictionaries(keys: Strategy, values: Strategy,
|
|
1231
|
+
min_size: int = 0, max_size: int = 20) -> DictionaryStrategy:
|
|
1232
|
+
"""
|
|
1233
|
+
Creates a strategy that generates random dictionaries.
|
|
1234
|
+
|
|
1235
|
+
:param keys: A strategy for generating dictionary keys.
|
|
1236
|
+
:param values: A strategy for generating dictionary values.
|
|
1237
|
+
:param min_size: Minimum number of entries. Default is 0.
|
|
1238
|
+
:param max_size: Maximum number of entries. Default is 20.
|
|
1239
|
+
:returns: A ``DictionaryStrategy`` instance.
|
|
1240
|
+
"""
|
|
1241
|
+
return DictionaryStrategy(keys=keys, values=values, min_size=min_size, max_size=max_size)
|
|
1242
|
+
|
|
1243
|
+
|
|
1244
|
+
def sampled_from(elements: Sequence) -> SampledFromStrategy:
|
|
1245
|
+
"""
|
|
1246
|
+
Creates a strategy that randomly selects from a fixed sequence.
|
|
1247
|
+
|
|
1248
|
+
:param elements: A non-empty sequence of values to sample from.
|
|
1249
|
+
:returns: A ``SampledFromStrategy`` instance.
|
|
1250
|
+
"""
|
|
1251
|
+
return SampledFromStrategy(elements=elements)
|
|
1252
|
+
|
|
1253
|
+
|
|
1254
|
+
def one_of(*strategies: Strategy) -> OneOfStrategy:
|
|
1255
|
+
"""
|
|
1256
|
+
Creates a strategy that randomly picks one sub-strategy and generates
|
|
1257
|
+
a value from it.
|
|
1258
|
+
|
|
1259
|
+
:param strategies: Two or more strategies to choose from.
|
|
1260
|
+
:returns: A ``OneOfStrategy`` instance.
|
|
1261
|
+
"""
|
|
1262
|
+
return OneOfStrategy(*strategies)
|
|
1263
|
+
|
|
1264
|
+
|
|
1265
|
+
def just(value: Any) -> JustStrategy:
|
|
1266
|
+
"""
|
|
1267
|
+
Creates a strategy that always returns the same fixed value.
|
|
1268
|
+
|
|
1269
|
+
:param value: The fixed value to always return.
|
|
1270
|
+
:returns: A ``JustStrategy`` instance.
|
|
1271
|
+
"""
|
|
1272
|
+
return JustStrategy(value=value)
|
|
1273
|
+
|
|
1274
|
+
|
|
1275
|
+
def characters(categories: Optional[Tuple[str, ...]] = None,
|
|
1276
|
+
characters: Optional[str] = None,
|
|
1277
|
+
min_codepoint: Optional[int] = None,
|
|
1278
|
+
max_codepoint: Optional[int] = None,
|
|
1279
|
+
whitelist_categories: Optional[Tuple[str, ...]] = None,
|
|
1280
|
+
blacklist_categories: Optional[Tuple[str, ...]] = None,
|
|
1281
|
+
whitelist_characters: Optional[str] = None,
|
|
1282
|
+
blacklist_characters: Optional[str] = None
|
|
1283
|
+
) -> CharacterStrategy:
|
|
1284
|
+
"""
|
|
1285
|
+
Creates a strategy that generates single characters.
|
|
1286
|
+
|
|
1287
|
+
A codepoint range is the usual way to ask for a band such as
|
|
1288
|
+
printable ASCII::
|
|
1289
|
+
|
|
1290
|
+
st.text(alphabet=st.characters(min_codepoint=33,
|
|
1291
|
+
max_codepoint=126))
|
|
1292
|
+
|
|
1293
|
+
:param categories: Tuple of unicode category identifiers.
|
|
1294
|
+
:param characters: An explicit set of characters to choose from.
|
|
1295
|
+
:param min_codepoint: Inclusive lower bound of a codepoint range.
|
|
1296
|
+
:param max_codepoint: Inclusive upper bound of a codepoint range.
|
|
1297
|
+
:param whitelist_categories: Unicode categories to generate from; the
|
|
1298
|
+
same request as ``categories``, under the name callers coming from
|
|
1299
|
+
other property libraries use.
|
|
1300
|
+
:param blacklist_categories: Unicode categories to exclude, applied
|
|
1301
|
+
after the base set is chosen so it composes with any of the above.
|
|
1302
|
+
:returns: A ``CharacterStrategy`` instance.
|
|
1303
|
+
"""
|
|
1304
|
+
return CharacterStrategy(categories=categories, characters=characters,
|
|
1305
|
+
min_codepoint=min_codepoint,
|
|
1306
|
+
max_codepoint=max_codepoint,
|
|
1307
|
+
whitelist_categories=whitelist_categories,
|
|
1308
|
+
blacklist_categories=blacklist_categories,
|
|
1309
|
+
whitelist_characters=whitelist_characters,
|
|
1310
|
+
blacklist_characters=blacklist_characters)
|
|
1311
|
+
|
|
1312
|
+
|
|
1313
|
+
def explicit(values: Sequence) -> ExplicitStrategy:
|
|
1314
|
+
"""
|
|
1315
|
+
Creates a strategy that yields predetermined values in sequence.
|
|
1316
|
+
|
|
1317
|
+
Values are cycled in order. The RNG is ignored — this strategy
|
|
1318
|
+
always produces the same deterministic output. Useful for
|
|
1319
|
+
reproducing known failures or testing specific edge cases.
|
|
1320
|
+
|
|
1321
|
+
Example::
|
|
1322
|
+
|
|
1323
|
+
@given(params=st.explicit([
|
|
1324
|
+
{'a': '1', 'b': '2'},
|
|
1325
|
+
{'x': 'hello'},
|
|
1326
|
+
]))
|
|
1327
|
+
def test_known_case(params):
|
|
1328
|
+
...
|
|
1329
|
+
|
|
1330
|
+
:param values: A non-empty sequence of values to yield.
|
|
1331
|
+
:returns: An ``ExplicitStrategy`` instance.
|
|
1332
|
+
"""
|
|
1333
|
+
return ExplicitStrategy(values=values)
|
|
1334
|
+
|
|
1335
|
+
|
|
1336
|
+
def none() -> NoneStrategy:
|
|
1337
|
+
"""
|
|
1338
|
+
Creates a strategy that always generates ``None``.
|
|
1339
|
+
|
|
1340
|
+
:returns: A ``NoneStrategy`` instance.
|
|
1341
|
+
"""
|
|
1342
|
+
return NoneStrategy()
|
|
1343
|
+
|
|
1344
|
+
|
|
1345
|
+
def binary(min_size: int = 0, max_size: int = 100) -> BinaryStrategy:
|
|
1346
|
+
"""
|
|
1347
|
+
Creates a strategy that generates random ``bytes`` objects.
|
|
1348
|
+
|
|
1349
|
+
:param min_size: Minimum byte sequence length. Default is 0.
|
|
1350
|
+
:param max_size: Maximum byte sequence length. Default is 100.
|
|
1351
|
+
:returns: A ``BinaryStrategy`` instance.
|
|
1352
|
+
"""
|
|
1353
|
+
return BinaryStrategy(min_size=min_size, max_size=max_size)
|
|
1354
|
+
|
|
1355
|
+
|
|
1356
|
+
def sets(element: Strategy, min_size: int = 0, max_size: int = 50) -> SetStrategy:
|
|
1357
|
+
"""
|
|
1358
|
+
Creates a strategy that generates random ``set`` objects.
|
|
1359
|
+
|
|
1360
|
+
:param element: A strategy for generating individual set elements.
|
|
1361
|
+
:param min_size: Minimum set size. Default is 0.
|
|
1362
|
+
:param max_size: Maximum set size. Default is 50.
|
|
1363
|
+
:returns: A ``SetStrategy`` instance.
|
|
1364
|
+
"""
|
|
1365
|
+
return SetStrategy(element=element, min_size=min_size, max_size=max_size)
|
|
1366
|
+
|
|
1367
|
+
|
|
1368
|
+
def frozensets(element: Strategy, min_size: int = 0, max_size: int = 50) -> FrozenSetStrategy:
|
|
1369
|
+
"""
|
|
1370
|
+
Creates a strategy that generates random ``frozenset`` objects.
|
|
1371
|
+
|
|
1372
|
+
:param element: A strategy for generating individual elements.
|
|
1373
|
+
:param min_size: Minimum size. Default is 0.
|
|
1374
|
+
:param max_size: Maximum size. Default is 50.
|
|
1375
|
+
:returns: A ``FrozenSetStrategy`` instance.
|
|
1376
|
+
"""
|
|
1377
|
+
return FrozenSetStrategy(element=element, min_size=min_size, max_size=max_size)
|
|
1378
|
+
|
|
1379
|
+
|
|
1380
|
+
def fixed_dictionaries(mapping: Dict[str, Strategy]) -> FixedDictionaryStrategy:
|
|
1381
|
+
"""
|
|
1382
|
+
Creates a strategy that generates dictionaries with a fixed set of keys.
|
|
1383
|
+
|
|
1384
|
+
Each key's value is drawn from its corresponding strategy.
|
|
1385
|
+
|
|
1386
|
+
:param mapping: A dictionary mapping keys to ``Strategy`` instances.
|
|
1387
|
+
:returns: A ``FixedDictionaryStrategy`` instance.
|
|
1388
|
+
"""
|
|
1389
|
+
return FixedDictionaryStrategy(mapping=mapping)
|
|
1390
|
+
|
|
1391
|
+
|
|
1392
|
+
def builds(target: Callable, *arg_strategies: Strategy,
|
|
1393
|
+
**kwarg_strategies: Strategy) -> BuildsStrategy:
|
|
1394
|
+
"""
|
|
1395
|
+
Creates a strategy that constructs instances by calling ``target``
|
|
1396
|
+
with values generated from the provided strategies.
|
|
1397
|
+
|
|
1398
|
+
Example::
|
|
1399
|
+
|
|
1400
|
+
@dataclass
|
|
1401
|
+
class Point:
|
|
1402
|
+
x: int
|
|
1403
|
+
y: int
|
|
1404
|
+
|
|
1405
|
+
point_strategy = builds(Point, x=st.integers(), y=st.integers())
|
|
1406
|
+
|
|
1407
|
+
:param target: The callable to invoke with generated values.
|
|
1408
|
+
:param arg_strategies: Strategies for positional arguments.
|
|
1409
|
+
:param kwarg_strategies: Strategies for keyword arguments.
|
|
1410
|
+
:returns: A ``BuildsStrategy`` instance.
|
|
1411
|
+
"""
|
|
1412
|
+
return BuildsStrategy(target=target, arg_strategies=arg_strategies,
|
|
1413
|
+
kwarg_strategies=kwarg_strategies)
|
|
1414
|
+
|
|
1415
|
+
|
|
1416
|
+
class RegexStrategy(Strategy):
|
|
1417
|
+
"""
|
|
1418
|
+
Strategy that generates strings matching a regular expression.
|
|
1419
|
+
|
|
1420
|
+
Generation is REGEX-DIRECTED: the pattern is parsed and the tree walked
|
|
1421
|
+
to construct a matching string. Rejection sampling — generating random
|
|
1422
|
+
text and filtering — was rejected because it effectively never succeeds
|
|
1423
|
+
for anchored patterns like ``^[a-z]([a-z0-9-]{0,12}[a-z0-9])?$``, and
|
|
1424
|
+
would turn a working strategy into a hang.
|
|
1425
|
+
|
|
1426
|
+
Every generated value is verified against the pattern before being
|
|
1427
|
+
returned. If the walk ever produces a non-matching string that is a
|
|
1428
|
+
bug here, and failing loudly is far better than feeding
|
|
1429
|
+
non-conformant data into a test that assumes conformance.
|
|
1430
|
+
|
|
1431
|
+
:param pattern: A pattern string or compiled pattern.
|
|
1432
|
+
:param fullmatch: When True the whole string must match, which is what
|
|
1433
|
+
an anchored pattern means in practice.
|
|
1434
|
+
"""
|
|
1435
|
+
|
|
1436
|
+
# Fallbacks for unbounded repeats and for `.`, which would otherwise have
|
|
1437
|
+
# no upper bound to draw from.
|
|
1438
|
+
_UNBOUNDED_REPEAT_CAP = 8
|
|
1439
|
+
_ANY_CHARACTERS = string.ascii_lowercase + string.digits
|
|
1440
|
+
|
|
1441
|
+
_CATEGORY_CHARACTERS = {
|
|
1442
|
+
"CATEGORY_DIGIT": string.digits,
|
|
1443
|
+
"CATEGORY_NOT_DIGIT": string.ascii_letters,
|
|
1444
|
+
"CATEGORY_SPACE": " \t",
|
|
1445
|
+
"CATEGORY_NOT_SPACE": string.ascii_letters + string.digits,
|
|
1446
|
+
"CATEGORY_WORD": string.ascii_letters + string.digits + "_",
|
|
1447
|
+
"CATEGORY_NOT_WORD": "-.,;:!?",
|
|
1448
|
+
}
|
|
1449
|
+
|
|
1450
|
+
def __init__(self, pattern, fullmatch: bool = False):
|
|
1451
|
+
if hasattr(pattern, "pattern"):
|
|
1452
|
+
self._compiled = pattern
|
|
1453
|
+
else:
|
|
1454
|
+
self._compiled = re.compile(pattern)
|
|
1455
|
+
|
|
1456
|
+
self._fullmatch = fullmatch
|
|
1457
|
+
self._tree = _regex_parser.parse(self._compiled.pattern,
|
|
1458
|
+
self._compiled.flags)
|
|
1459
|
+
return
|
|
1460
|
+
|
|
1461
|
+
def generate(self, rng: random.Random) -> str:
|
|
1462
|
+
produced = self._emit(self._tree, rng)
|
|
1463
|
+
|
|
1464
|
+
check = self._compiled.fullmatch if self._fullmatch \
|
|
1465
|
+
else self._compiled.search
|
|
1466
|
+
if check(produced) is None:
|
|
1467
|
+
errmsg = (
|
|
1468
|
+
"from_regex generated {!r}, which does not match {!r}. "
|
|
1469
|
+
"This is a defect in the pattern walk, not in the "
|
|
1470
|
+
"pattern.".format(produced, self._compiled.pattern)
|
|
1471
|
+
)
|
|
1472
|
+
raise ValueError(errmsg)
|
|
1473
|
+
|
|
1474
|
+
return produced
|
|
1475
|
+
|
|
1476
|
+
def shrink(self, value: str):
|
|
1477
|
+
# Shrinking has to preserve the match, so only prefixes that still
|
|
1478
|
+
# match are offered; anything else would hand the test a value the
|
|
1479
|
+
# strategy could never have produced.
|
|
1480
|
+
check = self._compiled.fullmatch if self._fullmatch \
|
|
1481
|
+
else self._compiled.search
|
|
1482
|
+
for size in range(len(value) - 1, 0, -1):
|
|
1483
|
+
candidate = value[:size]
|
|
1484
|
+
if check(candidate) is not None:
|
|
1485
|
+
yield candidate
|
|
1486
|
+
|
|
1487
|
+
def describe(self) -> str:
|
|
1488
|
+
return "from_regex({!r})".format(self._compiled.pattern)
|
|
1489
|
+
|
|
1490
|
+
def _emit(self, nodes, rng: random.Random) -> str:
|
|
1491
|
+
parts = []
|
|
1492
|
+
for op, arg in nodes:
|
|
1493
|
+
name = str(op)
|
|
1494
|
+
if name == "LITERAL":
|
|
1495
|
+
parts.append(chr(arg))
|
|
1496
|
+
elif name == "NOT_LITERAL":
|
|
1497
|
+
choices = [c for c in self._ANY_CHARACTERS if c != chr(arg)]
|
|
1498
|
+
parts.append(rng.choice(choices))
|
|
1499
|
+
elif name == "IN":
|
|
1500
|
+
parts.append(rng.choice(self._in_characters(arg)))
|
|
1501
|
+
elif name == "ANY":
|
|
1502
|
+
parts.append(rng.choice(self._ANY_CHARACTERS))
|
|
1503
|
+
elif name in ("MAX_REPEAT", "MIN_REPEAT"):
|
|
1504
|
+
low, high, sub = arg
|
|
1505
|
+
if high > self._UNBOUNDED_REPEAT_CAP:
|
|
1506
|
+
high = max(low, self._UNBOUNDED_REPEAT_CAP)
|
|
1507
|
+
count = rng.randint(low, high)
|
|
1508
|
+
for _ in range(count):
|
|
1509
|
+
parts.append(self._emit(sub, rng))
|
|
1510
|
+
elif name == "SUBPATTERN":
|
|
1511
|
+
parts.append(self._emit(arg[3], rng))
|
|
1512
|
+
elif name == "BRANCH":
|
|
1513
|
+
parts.append(self._emit(rng.choice(arg[1]), rng))
|
|
1514
|
+
elif name == "AT":
|
|
1515
|
+
# Anchors match a position, not a character.
|
|
1516
|
+
continue
|
|
1517
|
+
elif name == "ATOMIC_GROUP":
|
|
1518
|
+
parts.append(self._emit(arg, rng))
|
|
1519
|
+
else:
|
|
1520
|
+
errmsg = (
|
|
1521
|
+
"from_regex does not support the {} construct in {!r}. "
|
|
1522
|
+
"Rewrite the pattern or build the strategy "
|
|
1523
|
+
"explicitly.".format(name, self._compiled.pattern)
|
|
1524
|
+
)
|
|
1525
|
+
raise ValueError(errmsg)
|
|
1526
|
+
|
|
1527
|
+
return "".join(parts)
|
|
1528
|
+
|
|
1529
|
+
def _in_characters(self, items) -> str:
|
|
1530
|
+
"""
|
|
1531
|
+
Resolve a character-class node to the characters it admits.
|
|
1532
|
+
|
|
1533
|
+
:param items: The parsed class members.
|
|
1534
|
+
|
|
1535
|
+
:returns: The admissible characters.
|
|
1536
|
+
"""
|
|
1537
|
+
negated = any(str(op) == "NEGATE" for op, _a in items)
|
|
1538
|
+
|
|
1539
|
+
collected = []
|
|
1540
|
+
for op, arg in items:
|
|
1541
|
+
name = str(op)
|
|
1542
|
+
if name == "NEGATE":
|
|
1543
|
+
continue
|
|
1544
|
+
if name == "LITERAL":
|
|
1545
|
+
collected.append(chr(arg))
|
|
1546
|
+
elif name == "RANGE":
|
|
1547
|
+
collected.extend(chr(point)
|
|
1548
|
+
for point in range(arg[0], arg[1] + 1))
|
|
1549
|
+
elif name == "CATEGORY":
|
|
1550
|
+
collected.extend(
|
|
1551
|
+
self._CATEGORY_CHARACTERS.get(str(arg), ""))
|
|
1552
|
+
else:
|
|
1553
|
+
errmsg = (
|
|
1554
|
+
"from_regex does not support {} inside a character class "
|
|
1555
|
+
"in {!r}.".format(name, self._compiled.pattern)
|
|
1556
|
+
)
|
|
1557
|
+
raise ValueError(errmsg)
|
|
1558
|
+
|
|
1559
|
+
if negated is True:
|
|
1560
|
+
denied = set(collected)
|
|
1561
|
+
collected = [c for c in self._ANY_CHARACTERS if c not in denied]
|
|
1562
|
+
|
|
1563
|
+
if len(collected) == 0:
|
|
1564
|
+
errmsg = (
|
|
1565
|
+
"from_regex found an empty character class in {!r}.".format(
|
|
1566
|
+
self._compiled.pattern)
|
|
1567
|
+
)
|
|
1568
|
+
raise ValueError(errmsg)
|
|
1569
|
+
|
|
1570
|
+
return "".join(collected)
|
|
1571
|
+
|
|
1572
|
+
|
|
1573
|
+
def from_regex(pattern, fullmatch: bool = False) -> RegexStrategy:
|
|
1574
|
+
"""
|
|
1575
|
+
Creates a strategy that generates strings matching a regex.
|
|
1576
|
+
|
|
1577
|
+
Example::
|
|
1578
|
+
|
|
1579
|
+
_name = st.from_regex(re.compile(r"^[a-z][a-z0-9-]{0,12}$"),
|
|
1580
|
+
fullmatch=True)
|
|
1581
|
+
|
|
1582
|
+
:param pattern: A pattern string or compiled pattern.
|
|
1583
|
+
:param fullmatch: When True the whole generated string must match.
|
|
1584
|
+
:returns: A ``RegexStrategy`` instance.
|
|
1585
|
+
"""
|
|
1586
|
+
return RegexStrategy(pattern, fullmatch=fullmatch)
|
|
1587
|
+
|
|
1588
|
+
|
|
1589
|
+
# ``SearchStrategy`` is what other property libraries call this base class, and
|
|
1590
|
+
# test suites use it in type annotations. Aliased rather than renamed so
|
|
1591
|
+
# existing references to ``Strategy`` keep working.
|
|
1592
|
+
SearchStrategy = Strategy
|