Debian Codegraph @

hypothesis-python/src/hypothesis/extra/django/_fields.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 from collections.abc import Callable
14 from datetime import datetime, timedelta
15 from decimal import Decimal
16 from functools import lru_cache
17 from typing import Any, TypeAlias, TypeVar, Union
18
19 import django
20 from django import forms as df
21 from django.conf import settings
22 from django.core.files.base import ContentFile
23 from django.core.validators import (
24 validate_ipv4_address,
25 validate_ipv6_address,
26 validate_ipv46_address,
27 )
28 from django.db import models as dm
29
30 from hypothesis import strategies as st
31 from hypothesis.errors import InvalidArgument, ResolutionFailed
32 from hypothesis.internal.validation import check_type
33 from hypothesis.provisional import urls
34 from hypothesis.strategies import emails
35
36 # Use old-style union to avoid hitting
37 # https://github.com/sphinx-doc/sphinx/issues/11211
38 AnyField: TypeAlias = Union[dm.Field, df.Field] # noqa: UP007
39 F = TypeVar("F", bound=AnyField)
40
41
42 def numeric_bounds_from_validators(
43 field, min_value=float("-inf"), max_value=float("inf")
44 ):
45 for v in field.validators:
46 if isinstance(v, django.core.validators.MinValueValidator):
47 min_value = max(min_value, v.limit_value)
48 elif isinstance(v, django.core.validators.MaxValueValidator):
49 max_value = min(max_value, v.limit_value)
50 return min_value, max_value
51
52
53 def integers_for_field(min_value, max_value):
54 def inner(field):
55 return st.integers(*numeric_bounds_from_validators(field, min_value, max_value))
56
57 return inner
58
59
60 @lru_cache
61 def timezones():
62 # From Django 4.0, the default is to use zoneinfo instead of pytz.
63 assert getattr(django.conf.settings, "USE_TZ", False)
64 if django.VERSION < (5, 0, 0) and getattr(
65 django.conf.settings, "USE_DEPRECATED_PYTZ", True
66 ):
67 from hypothesis.extra.pytz import timezones
68 else:
69 from hypothesis.strategies import timezones
70
71 return timezones()
72
73
74 # Mapping of field types, to strategy objects or functions of (type) -> strategy
75 _FieldLookUpType = dict[
76 type[AnyField],
77 st.SearchStrategy | Callable[[Any], st.SearchStrategy],
78 ]
79 _global_field_lookup: _FieldLookUpType = {
80 dm.SmallIntegerField: integers_for_field(-32768, 32767),
81 dm.IntegerField: integers_for_field(-2147483648, 2147483647),
82 dm.BigIntegerField: integers_for_field(-9223372036854775808, 9223372036854775807),
83 dm.PositiveIntegerField: integers_for_field(0, 2147483647),
84 dm.PositiveSmallIntegerField: integers_for_field(0, 32767),
85 dm.BooleanField: st.booleans(),
86 dm.DateField: st.dates(),
87 dm.EmailField: emails(),
88 dm.FloatField: st.floats(),
89 dm.NullBooleanField: st.one_of(st.none(), st.booleans()),
90 dm.URLField: urls(),
91 dm.UUIDField: st.uuids(),
92 df.DateField: st.dates(),
93 df.DurationField: st.timedeltas(),
94 df.EmailField: emails(),
95 df.FloatField: lambda field: st.floats(
96 *numeric_bounds_from_validators(field), allow_nan=False, allow_infinity=False
97 ),
98 df.IntegerField: integers_for_field(-2147483648, 2147483647),
99 df.NullBooleanField: st.one_of(st.none(), st.booleans()),
100 df.URLField: urls(),
101 df.UUIDField: st.uuids(),
102 df.FileField: st.builds(
103 ContentFile, st.binary(min_size=1), name=st.text(min_size=1, max_size=100)
104 ),
105 }
106
107 _ipv6_strings = st.one_of(
108 st.ip_addresses(v=6).map(str),
109 st.ip_addresses(v=6).map(lambda addr: addr.exploded),
110 )
111
112
113 def register_for(field_type):
114 def inner(func):
115 _global_field_lookup[field_type] = func
116 return func
117
118 return inner
119
120
121 @register_for(dm.DateTimeField)
122 @register_for(df.DateTimeField)
123 def _for_datetime(field):
124 if getattr(django.conf.settings, "USE_TZ", False):
125 # avoid https://code.djangoproject.com/ticket/35683
126 return st.datetimes(
127 min_value=datetime.min + timedelta(days=1),
128 max_value=datetime.max - timedelta(days=1),
129 timezones=timezones(),
130 )
131 return st.datetimes()
132
133
134 def using_sqlite():
135 try:
136 return (
137 getattr(django.conf.settings, "DATABASES", {})
138 .get("default", {})
139 .get("ENGINE", "")
140 .endswith(".sqlite3")
141 )
142 except django.core.exceptions.ImproperlyConfigured:
143 return None
144
145
146 @register_for(dm.TimeField)
147 def _for_model_time(field):
148 # SQLITE supports TZ-aware datetimes, but not TZ-aware times.
149 if getattr(django.conf.settings, "USE_TZ", False) and not using_sqlite():
150 return st.times(timezones=timezones())
151 return st.times()
152
153
154 @register_for(df.TimeField)
155 def _for_form_time(field):
156 if getattr(django.conf.settings, "USE_TZ", False):
157 return st.times(timezones=timezones())
158 return st.times()
159
160
161 @register_for(dm.DurationField)
162 def _for_duration(field):
163 # SQLite stores timedeltas as six bytes of microseconds
164 if using_sqlite():
165 delta = timedelta(microseconds=2**47 - 1)
166 return st.timedeltas(-delta, delta)
167 return st.timedeltas()
168
169
170 @register_for(dm.SlugField)
171 @register_for(df.SlugField)
172 def _for_slug(field):
173 min_size = 1
174 if getattr(field, "blank", False) or not getattr(field, "required", True):
175 min_size = 0
176 return st.text(
177 alphabet=string.ascii_letters + string.digits,
178 min_size=min_size,
179 max_size=field.max_length,
180 )
181
182
183 @register_for(dm.GenericIPAddressField)
184 def _for_model_ip(field):
185 return {
186 "ipv4": st.ip_addresses(v=4).map(str),
187 "ipv6": _ipv6_strings,
188 "both": st.ip_addresses(v=4).map(str) | _ipv6_strings,
189 }[field.protocol.lower()]
190
191
192 @register_for(df.GenericIPAddressField)
193 def _for_form_ip(field):
194 # the IP address form fields have no direct indication of which type
195 # of address they want, so direct comparison with the validator
196 # function has to be used instead. Sorry for the potato logic here
197 if validate_ipv46_address in field.default_validators:
198 return st.ip_addresses(v=4).map(str) | _ipv6_strings
199 if validate_ipv4_address in field.default_validators:
200 return st.ip_addresses(v=4).map(str)
201 if validate_ipv6_address in field.default_validators:
202 return _ipv6_strings
203 raise ResolutionFailed(f"No IP version validator on {field=}")
204
205
206 @register_for(dm.DecimalField)
207 @register_for(df.DecimalField)
208 def _for_decimal(field):
209 min_value, max_value = numeric_bounds_from_validators(field)
210 bound = Decimal(10**field.max_digits - 1) / (10**field.decimal_places)
211 return st.decimals(
212 min_value=max(min_value, -bound),
213 max_value=min(max_value, bound),
214 places=field.decimal_places,
215 )
216
217
218 def length_bounds_from_validators(field):
219 min_size = 1
220 max_size = field.max_length
221 for v in field.validators:
222 if isinstance(v, django.core.validators.MinLengthValidator):
223 min_size = max(min_size, v.limit_value)
224 elif isinstance(v, django.core.validators.MaxLengthValidator):
225 max_size = min(max_size or v.limit_value, v.limit_value)
226 return min_size, max_size
227
228
229 @register_for(dm.BinaryField)
230 def _for_binary(field):
231 min_size, max_size = length_bounds_from_validators(field)
232 if getattr(field, "blank", False) or not getattr(field, "required", True):
233 return st.just(b"") | st.binary(min_size=min_size, max_size=max_size)
234 return st.binary(min_size=min_size, max_size=max_size)
235
236
237 @register_for(dm.CharField)
238 @register_for(dm.TextField)
239 @register_for(df.CharField)
240 @register_for(df.RegexField)
241 def _for_text(field):
242 # We can infer a vastly more precise strategy by considering the
243 # validators as well as the field type. This is a minimal proof of
244 # concept, but we intend to leverage the idea much more heavily soon.
245 # See https://github.com/HypothesisWorks/hypothesis-python/issues/1116
246 regexes = [
247 re.compile(v.regex, v.flags) if isinstance(v.regex, str) else v.regex
248 for v in field.validators
249 if isinstance(v, django.core.validators.RegexValidator) and not v.inverse_match
250 ]
251 if regexes:
252 # This strategy generates according to one of the regexes, and
253 # filters using the others. It can therefore learn to generate
254 # from the most restrictive and filter with permissive patterns.
255 # Not maximally efficient, but it makes pathological cases rarer.
256 # If you want a challenge: extend https://qntm.org/greenery to
257 # compute intersections of the full Python regex language.
258 return st.one_of(*(st.from_regex(r) for r in regexes))
259 # If there are no (usable) regexes, we use a standard text strategy.
260 min_size, max_size = length_bounds_from_validators(field)
261 strategy = st.text(
262 alphabet=st.characters(exclude_characters="\x00", exclude_categories=("Cs",)),
263 min_size=min_size,
264 max_size=max_size,
265 ).filter(lambda s: min_size <= len(s.strip()))
266 if getattr(field, "blank", False) or not getattr(field, "required", True):
267 return st.just("") | strategy
268 return strategy
269
270
271 if "django.contrib.auth" in settings.INSTALLED_APPS:
272 from django.contrib.auth.forms import UsernameField
273
274 register_for(UsernameField)(_for_text)
275
276
277 @register_for(df.BooleanField)
278 def _for_form_boolean(field):
279 if field.required:
280 return st.just(True)
281 return st.booleans()
282
283
284 def _model_choice_strategy(field):
285 def _strategy():
286 if field.choices is None:
287 # The field was instantiated with queryset=None, and not
288 # subsequently updated.
289 raise InvalidArgument(
290 "Cannot create strategy for ModelChoicesField with no choices"
291 )
292 elif hasattr(field, "_choices"):
293 # The choices property was set manually.
294 choices = field._choices
295 else:
296 # choices is not None, and was not set manually, so we
297 # must have a QuerySet.
298 choices = field.queryset
299
300 if not choices.ordered:
301 raise InvalidArgument(
302 f"Cannot create strategy for {field.__class__.__name__} with a choices "
303 "attribute derived from a QuerySet without an explicit ordering - this may "
304 "cause Hypothesis to produce unstable results between runs."
305 )
306
307 return st.sampled_from(
308 [
309 (
310 choice.value
311 if isinstance(choice, df.models.ModelChoiceIteratorValue)
312 else choice # Empty value, if included.
313 )
314 for choice, _ in field.choices
315 ]
316 )
317
318 # Accessing field.choices causes database access, so defer the strategy.
319 return st.deferred(_strategy)
320
321
322 @register_for(df.ModelChoiceField)
323 def _for_model_choice(field):
324 return _model_choice_strategy(field)
325
326
327 @register_for(df.ModelMultipleChoiceField)
328 def _for_model_multiple_choice(field):
329 min_size = 1 if field.required else 0
330 return st.lists(_model_choice_strategy(field), min_size=min_size, unique=True)
331
332
333 def register_field_strategy(
334 field_type: type[AnyField], strategy: st.SearchStrategy
335 ) -> None:
336 """Add an entry to the global field-to-strategy lookup used by
337 :func:`~hypothesis.extra.django.from_field`.
338
339 ``field_type`` must be a subtype of :class:`django.db.models.Field` or
340 :class:`django.forms.Field`, which must not already be registered.
341 ``strategy`` must be a :class:`~hypothesis.strategies.SearchStrategy`.
342 """
343 if not issubclass(field_type, (dm.Field, df.Field)):
344 raise InvalidArgument(f"{field_type=} must be a subtype of Field")
345 check_type(st.SearchStrategy, strategy, "strategy")
346 if field_type in _global_field_lookup:
347 raise InvalidArgument(
348 f"{field_type=} already has a registered "
349 f"strategy ({_global_field_lookup[field_type]!r})"
350 )
351 if issubclass(field_type, dm.AutoField):
352 raise InvalidArgument("Cannot register a strategy for an AutoField")
353 _global_field_lookup[field_type] = strategy
354
355
356 def from_field(field: F) -> st.SearchStrategy[F | None]:
357 """Return a strategy for values that fit the given field.
358
359 This function is used by :func:`~hypothesis.extra.django.from_form` and
360 :func:`~hypothesis.extra.django.from_model` for any fields that require
361 a value, or for which you passed ``...`` (:obj:`python:Ellipsis`) to infer
362 a strategy from an annotation.
363
364 It's pretty similar to the core :func:`~hypothesis.strategies.from_type`
365 function, with a subtle but important difference: ``from_field`` takes a
366 Field *instance*, rather than a Field *subtype*, so that it has access to
367 instance attributes such as string length and validators.
368 """
369 check_type((dm.Field, df.Field), field, "field")
370
371 # The following isinstance check must occur *before* the getattr
372 # check. In the case of ModelChoicesField, evaluating
373 # field.choices causes database access, which we want to avoid if
374 # we don't have a connection (the generated strategies for
375 # ModelChoicesField defer evaluation of `choices').
376 if not isinstance(field, df.ModelChoiceField) and getattr(field, "choices", False):
377 choices: list = []
378 for value, name_or_optgroup in field.choices:
379 if isinstance(name_or_optgroup, (list, tuple)):
380 choices.extend(key for key, _ in name_or_optgroup)
381 else:
382 choices.append(value)
383 # form fields automatically include an empty choice, strip it out
384 if "" in choices:
385 choices.remove("")
386 min_size = 1
387 if isinstance(field, (dm.CharField, dm.TextField)) and field.blank:
388 choices.insert(0, "")
389 elif isinstance(field, (df.Field)) and not field.required:
390 choices.insert(0, "")
391 min_size = 0
392 strategy = st.sampled_from(choices)
393 if isinstance(field, (df.MultipleChoiceField, df.TypedMultipleChoiceField)):
394 strategy = st.lists(st.sampled_from(choices), min_size=min_size)
395 else:
396 if type(field) not in _global_field_lookup:
397 if getattr(field, "null", False):
398 return st.none()
399 raise ResolutionFailed(f"Could not infer a strategy for {field!r}")
400 strategy = _global_field_lookup[type(field)] # type: ignore
401 if not isinstance(strategy, st.SearchStrategy):
402 strategy = strategy(field)
403 assert isinstance(strategy, st.SearchStrategy)
404 if field.validators:
405
406 def validate(value):
407 try:
408 field.run_validators(value)
409 return True
410 except django.core.exceptions.ValidationError:
411 return False
412
413 strategy = strategy.filter(validate)
414
415 if getattr(field, "null", False):
416 return st.none() | strategy
417 return strategy