| 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 unittest |
| 12 |
from functools import partial |
| 13 |
from types import EllipsisType |
| 14 |
from typing import Any, TypeVar |
| 15 |
|
| 16 |
from django import forms as df, test as dt |
| 17 |
from django.contrib.staticfiles import testing as dst |
| 18 |
from django.core.exceptions import ValidationError |
| 19 |
from django.db import IntegrityError, models as dm |
| 20 |
|
| 21 |
from hypothesis import reject, strategies as st |
| 22 |
from hypothesis.errors import InvalidArgument |
| 23 |
from hypothesis.extra.django._fields import from_field |
| 24 |
from hypothesis.strategies._internal.utils import defines_strategy |
| 25 |
|
| 26 |
ModelT = TypeVar("ModelT", bound=dm.Model) |
| 27 |
|
| 28 |
|
| 29 |
class HypothesisTestCase: |
| 30 |
def setup_example(self): |
| 31 |
self._pre_setup() |
| 32 |
|
| 33 |
def teardown_example(self, example): |
| 34 |
self._post_teardown() |
| 35 |
|
| 36 |
def __call__(self, result=None): |
| 37 |
testMethod = getattr(self, self._testMethodName) |
| 38 |
if getattr(testMethod, "is_hypothesis_test", False): |
| 39 |
return unittest.TestCase.__call__(self, result) |
| 40 |
else: |
| 41 |
return dt.SimpleTestCase.__call__(self, result) |
| 42 |
|
| 43 |
|
| 44 |
class SimpleTestCase(HypothesisTestCase, dt.SimpleTestCase): |
| 45 |
pass |
| 46 |
|
| 47 |
|
| 48 |
class TestCase(HypothesisTestCase, dt.TestCase): |
| 49 |
pass |
| 50 |
|
| 51 |
|
| 52 |
class TransactionTestCase(HypothesisTestCase, dt.TransactionTestCase): |
| 53 |
pass |
| 54 |
|
| 55 |
|
| 56 |
class LiveServerTestCase(HypothesisTestCase, dt.LiveServerTestCase): |
| 57 |
pass |
| 58 |
|
| 59 |
|
| 60 |
class StaticLiveServerTestCase(HypothesisTestCase, dst.StaticLiveServerTestCase): |
| 61 |
pass |
| 62 |
|
| 63 |
|
| 64 |
@defines_strategy() |
| 65 |
def from_model( |
| 66 |
model: type[ModelT], /, **field_strategies: st.SearchStrategy | EllipsisType |
| 67 |
) -> st.SearchStrategy[ModelT]: |
| 68 |
"""Return a strategy for examples of ``model``. |
| 69 |
|
| 70 |
.. warning:: |
| 71 |
Hypothesis creates saved models. This will run inside your testing |
| 72 |
transaction when using the test runner, but if you use the dev console |
| 73 |
this will leave debris in your database. |
| 74 |
|
| 75 |
``model`` must be an subclass of :class:`~django:django.db.models.Model`. |
| 76 |
Strategies for fields may be passed as keyword arguments, for example |
| 77 |
``is_staff=st.just(False)``. In order to support models with fields named |
| 78 |
"model", this is a positional-only parameter. |
| 79 |
|
| 80 |
Hypothesis can often infer a strategy based the field type and validators, |
| 81 |
and will attempt to do so for any required fields. No strategy will be |
| 82 |
inferred for an :class:`~django:django.db.models.AutoField`, nullable field, |
| 83 |
foreign key, or field for which a keyword |
| 84 |
argument is passed to ``from_model()``. For example, |
| 85 |
a Shop type with a foreign key to Company could be generated with:: |
| 86 |
|
| 87 |
shop_strategy = from_model(Shop, company=from_model(Company)) |
| 88 |
|
| 89 |
Like for :func:`~hypothesis.strategies.builds`, you can pass |
| 90 |
``...`` (:obj:`python:Ellipsis`) as a keyword argument to infer a strategy for |
| 91 |
a field which has a default value instead of using the default. |
| 92 |
""" |
| 93 |
if not issubclass(model, dm.Model): |
| 94 |
raise InvalidArgument(f"{model=} must be a subtype of Model") |
| 95 |
|
| 96 |
fields_by_name = {f.name: f for f in model._meta.concrete_fields} |
| 97 |
for name, value in sorted(field_strategies.items()): |
| 98 |
if value is ...: |
| 99 |
field_strategies[name] = from_field(fields_by_name[name]) |
| 100 |
for name, field in sorted(fields_by_name.items()): |
| 101 |
if ( |
| 102 |
name not in field_strategies |
| 103 |
and not field.auto_created |
| 104 |
and not isinstance(field, dm.AutoField) |
| 105 |
and not isinstance(field, getattr(dm, "GeneratedField", ())) |
| 106 |
and field.default is dm.fields.NOT_PROVIDED |
| 107 |
): |
| 108 |
field_strategies[name] = from_field(field) |
| 109 |
|
| 110 |
for field in field_strategies: |
| 111 |
if model._meta.get_field(field).primary_key: |
| 112 |
# The primary key is generated as part of the strategy. We |
| 113 |
# want to find any existing row with this primary key and |
| 114 |
# overwrite its contents. |
| 115 |
kwargs = {field: field_strategies.pop(field)} |
| 116 |
kwargs["defaults"] = st.fixed_dictionaries(field_strategies) # type: ignore |
| 117 |
return _models_impl(st.builds(model.objects.update_or_create, **kwargs)) |
| 118 |
|
| 119 |
# The primary key is not generated as part of the strategy, so we |
| 120 |
# just match against any row that has the same value for all |
| 121 |
# fields. |
| 122 |
return _models_impl(st.builds(model.objects.get_or_create, **field_strategies)) |
| 123 |
|
| 124 |
|
| 125 |
@st.composite |
| 126 |
def _models_impl(draw, strat): |
| 127 |
"""Handle the nasty part of drawing a value for models()""" |
| 128 |
try: |
| 129 |
return draw(strat)[0] |
| 130 |
except IntegrityError: |
| 131 |
reject() |
| 132 |
|
| 133 |
|
| 134 |
@defines_strategy() |
| 135 |
def from_form( |
| 136 |
form: type[df.Form], |
| 137 |
form_kwargs: dict | None = None, |
| 138 |
**field_strategies: st.SearchStrategy | EllipsisType, |
| 139 |
) -> st.SearchStrategy[df.Form]: |
| 140 |
"""Return a strategy for examples of ``form``. |
| 141 |
|
| 142 |
``form`` must be an subclass of :class:`~django:django.forms.Form`. |
| 143 |
Strategies for fields may be passed as keyword arguments, for example |
| 144 |
``is_staff=st.just(False)``. |
| 145 |
|
| 146 |
Hypothesis can often infer a strategy based the field type and validators, |
| 147 |
and will attempt to do so for any required fields. No strategy will be |
| 148 |
inferred for a disabled field or field for which a keyword argument |
| 149 |
is passed to ``from_form()``. |
| 150 |
|
| 151 |
This function uses the fields of an unbound ``form`` instance to determine |
| 152 |
field strategies, any keyword arguments needed to instantiate the unbound |
| 153 |
``form`` instance can be passed into ``from_form()`` as a dict with the |
| 154 |
keyword ``form_kwargs``. E.g.:: |
| 155 |
|
| 156 |
shop_strategy = from_form(Shop, form_kwargs={"company_id": 5}) |
| 157 |
|
| 158 |
Like for :func:`~hypothesis.strategies.builds`, you can pass |
| 159 |
``...`` (:obj:`python:Ellipsis`) as a keyword argument to infer a strategy for |
| 160 |
a field which has a default value instead of using the default. |
| 161 |
""" |
| 162 |
# currently unsupported: |
| 163 |
# ComboField |
| 164 |
# FilePathField |
| 165 |
# ImageField |
| 166 |
form_kwargs = form_kwargs or {} |
| 167 |
if not issubclass(form, df.BaseForm): |
| 168 |
raise InvalidArgument(f"{form=} must be a subtype of Form") |
| 169 |
|
| 170 |
# Forms are a little bit different from models. Model classes have |
| 171 |
# all their fields defined, whereas forms may have different fields |
| 172 |
# per-instance. So, we ought to instantiate the form and get the |
| 173 |
# fields from the instance, thus we need to accept the kwargs for |
| 174 |
# instantiation as well as the explicitly defined strategies |
| 175 |
|
| 176 |
unbound_form = form(**form_kwargs) |
| 177 |
fields_by_name = {} |
| 178 |
for name, field in unbound_form.fields.items(): |
| 179 |
if isinstance(field, df.MultiValueField): |
| 180 |
# PS: So this is a little strange, but MultiValueFields must |
| 181 |
# have their form data encoded in a particular way for the |
| 182 |
# values to actually be picked up by the widget instances' |
| 183 |
# ``value_from_datadict``. |
| 184 |
# E.g. if a MultiValueField named 'mv_field' has 3 |
| 185 |
# sub-fields then the ``value_from_datadict`` will look for |
| 186 |
# 'mv_field_0', 'mv_field_1', and 'mv_field_2'. Here I'm |
| 187 |
# decomposing the individual sub-fields into the names that |
| 188 |
# the form validation process expects |
| 189 |
for i, _field in enumerate(field.fields): |
| 190 |
fields_by_name[f"{name}_{i}"] = _field |
| 191 |
else: |
| 192 |
fields_by_name[name] = field |
| 193 |
|
| 194 |
for name, value in sorted(field_strategies.items()): |
| 195 |
if value is ...: |
| 196 |
field_strategies[name] = from_field(fields_by_name[name]) |
| 197 |
|
| 198 |
for name, field in sorted(fields_by_name.items()): |
| 199 |
if name not in field_strategies and not field.disabled: |
| 200 |
field_strategies[name] = from_field(field) |
| 201 |
|
| 202 |
# files are handled a bit specially in forms. A Form accepts two arguments: |
| 203 |
# `data` and `files`. The former is for normal fields, and the latter is for |
| 204 |
# file fields. |
| 205 |
# see https://docs.djangoproject.com/en/5.1/ref/forms/api/#binding-uploaded-files. |
| 206 |
data_strategies: dict[str, Any] = {} |
| 207 |
file_strategies: dict[str, Any] = {} |
| 208 |
for name, field in field_strategies.items(): |
| 209 |
form_field = fields_by_name[name] |
| 210 |
dictionary = ( |
| 211 |
file_strategies if isinstance(form_field, df.FileField) else data_strategies |
| 212 |
) |
| 213 |
dictionary[name] = field |
| 214 |
|
| 215 |
return _forms_impl( |
| 216 |
st.builds( |
| 217 |
partial(form, **form_kwargs), # type: ignore |
| 218 |
data=st.fixed_dictionaries(data_strategies), |
| 219 |
files=st.fixed_dictionaries(file_strategies), |
| 220 |
) |
| 221 |
) |
| 222 |
|
| 223 |
|
| 224 |
@st.composite |
| 225 |
def _forms_impl(draw, strat): |
| 226 |
"""Handle the nasty part of drawing a value for from_form()""" |
| 227 |
try: |
| 228 |
return draw(strat) |
| 229 |
except ValidationError: |
| 230 |
reject() |