| 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 |
# Since Hypothesis doesn't have a hard dependency on attrs, be careful to only import |
| 12 |
# this file when attrs is in sys.modules. |
| 13 |
|
| 14 |
from collections.abc import Collection, Generator, Iterable, Sequence |
| 15 |
from functools import reduce |
| 16 |
from itertools import chain |
| 17 |
from types import EllipsisType |
| 18 |
from typing import Any, TypeVar |
| 19 |
|
| 20 |
import attr |
| 21 |
|
| 22 |
# attr/validators.pyi does not expose types for these, even though they exist |
| 23 |
# in source. |
| 24 |
from attr.validators import ( # type: ignore |
| 25 |
_AndValidator, |
| 26 |
_InstanceOfValidator, |
| 27 |
_InValidator, |
| 28 |
_OptionalValidator, |
| 29 |
) |
| 30 |
from attrs import Attribute, AttrsInstance, Factory |
| 31 |
|
| 32 |
from hypothesis import strategies as st |
| 33 |
from hypothesis.errors import ResolutionFailed |
| 34 |
from hypothesis.internal.compat import get_type_hints |
| 35 |
from hypothesis.strategies._internal.core import BuildsStrategy |
| 36 |
from hypothesis.strategies._internal.strategies import SearchStrategy |
| 37 |
from hypothesis.strategies._internal.types import is_a_type, type_sorting_key |
| 38 |
from hypothesis.utils.conventions import infer |
| 39 |
|
| 40 |
T = TypeVar("T") |
| 41 |
|
| 42 |
|
| 43 |
def get_attribute_by_alias( |
| 44 |
fields: Iterable[Attribute], |
| 45 |
alias: str, |
| 46 |
*, |
| 47 |
target: type[AttrsInstance] | None = None, |
| 48 |
) -> Attribute: |
| 49 |
""" |
| 50 |
Get an attrs attribute by its alias, rather than its name (compare |
| 51 |
getattr(fields, name)). |
| 52 |
|
| 53 |
``target`` is used only to provide a nicer error message, and can be safely |
| 54 |
omitted. |
| 55 |
""" |
| 56 |
# attrs supports defining an alias for a field, which is the name used when |
| 57 |
# defining __init__. The init args are what we pull from when determining |
| 58 |
# what parameters we need to supply to the class, so it's what we need to |
| 59 |
# match against as well, rather than the class-level attribute name. |
| 60 |
matched_fields = [f for f in fields if f.alias == alias] |
| 61 |
if not matched_fields: |
| 62 |
raise TypeError( |
| 63 |
f"Unexpected keyword argument {alias} for attrs class" |
| 64 |
f"{f' {target}' if target else ''}. Expected one of " |
| 65 |
f"{[f.name for f in fields]}" |
| 66 |
) |
| 67 |
# alias is used as an arg in __init__, so it is guaranteed to be unique, if |
| 68 |
# it exists. |
| 69 |
assert len(matched_fields) == 1 |
| 70 |
return matched_fields[0] |
| 71 |
|
| 72 |
|
| 73 |
def from_attrs( |
| 74 |
target: type[AttrsInstance], |
| 75 |
args: tuple[SearchStrategy[Any], ...], |
| 76 |
kwargs: dict[str, SearchStrategy[Any] | EllipsisType], |
| 77 |
to_infer: Iterable[str], |
| 78 |
) -> SearchStrategy: |
| 79 |
"""An internal version of builds(), specialised for Attrs classes.""" |
| 80 |
attributes: tuple[Attribute, ...] = attr.fields(target) |
| 81 |
kwargs = {k: v for k, v in kwargs.items() if v is not infer} |
| 82 |
for name in to_infer: |
| 83 |
attrib = get_attribute_by_alias(attributes, name, target=target) |
| 84 |
kwargs[name] = from_attrs_attribute(attrib, target) |
| 85 |
# We might make this strategy more efficient if we added a layer here that |
| 86 |
# retries drawing if validation fails, for improved composition. |
| 87 |
# The treatment of timezones in datetimes() provides a precedent. |
| 88 |
return BuildsStrategy(target, args, kwargs) |
| 89 |
|
| 90 |
|
| 91 |
def from_attrs_attribute( |
| 92 |
attrib: Attribute, target: type[AttrsInstance] |
| 93 |
) -> SearchStrategy: |
| 94 |
"""Infer a strategy from the metadata on an attr.Attribute object.""" |
| 95 |
# Try inferring from the default argument. Note that this will only help if |
| 96 |
# the user passed `...` to builds() for this attribute, but in that case |
| 97 |
# we use it as the minimal example. |
| 98 |
default: SearchStrategy = st.nothing() |
| 99 |
# attr/__init__.pyi uses overloads to declare Factory as a function, not a |
| 100 |
# class. This is a fib - at runtime and always, it is a class. |
| 101 |
if isinstance(attrib.default, Factory): # type: ignore |
| 102 |
assert attrib.default is not None |
| 103 |
if not attrib.default.takes_self: |
| 104 |
default = st.builds(attrib.default.factory) |
| 105 |
elif attrib.default is not attr.NOTHING: |
| 106 |
default = st.just(attrib.default) |
| 107 |
|
| 108 |
# Try inferring None, exact values, or type from attrs provided validators. |
| 109 |
|
| 110 |
# updated to none() on seeing an OptionalValidator |
| 111 |
null: SearchStrategy = st.nothing() |
| 112 |
# list of in_ validator collections to sample from |
| 113 |
in_collections = [] |
| 114 |
# type constraints to pass to types_to_strategy() |
| 115 |
validator_types = set() |
| 116 |
if attrib.validator is not None: |
| 117 |
validator = attrib.validator |
| 118 |
if isinstance(validator, _OptionalValidator): |
| 119 |
null = st.none() |
| 120 |
validator = validator.validator |
| 121 |
if isinstance(validator, _AndValidator): |
| 122 |
vs = validator._validators |
| 123 |
else: |
| 124 |
vs = [validator] |
| 125 |
for v in vs: |
| 126 |
if isinstance(v, _InValidator): |
| 127 |
if isinstance(v.options, str): |
| 128 |
in_collections.append(list(all_substrings(v.options))) |
| 129 |
else: |
| 130 |
in_collections.append(v.options) |
| 131 |
elif isinstance(v, _InstanceOfValidator): |
| 132 |
validator_types.add(v.type) |
| 133 |
|
| 134 |
# This is the important line. We compose the final strategy from various |
| 135 |
# parts. The default value, if any, is the minimal shrink, followed by |
| 136 |
# None (again, if allowed). We then prefer to sample from values passed |
| 137 |
# to an in_ validator if available, but infer from a type otherwise. |
| 138 |
# Pick one because (sampled_from((1, 2)) | from_type(int)) would usually |
| 139 |
# fail validation by generating e.g. zero! |
| 140 |
if in_collections: |
| 141 |
sample = st.sampled_from(list(ordered_intersection(in_collections))) |
| 142 |
strat = default | null | sample |
| 143 |
else: |
| 144 |
strat = default | null | types_to_strategy(attrib, validator_types) |
| 145 |
|
| 146 |
# Better to give a meaningful error here than an opaque "could not draw" |
| 147 |
# when we try to get a value but have lost track of where this was created. |
| 148 |
if strat.is_empty: |
| 149 |
raise ResolutionFailed( |
| 150 |
"Cannot infer a strategy from the default, validator, type, or " |
| 151 |
f"converter for attribute={attrib!r} of class={target!r}" |
| 152 |
) |
| 153 |
return strat |
| 154 |
|
| 155 |
|
| 156 |
def types_to_strategy(attrib: Attribute, types: Collection[Any]) -> SearchStrategy: |
| 157 |
"""Find all the type metadata for this attribute, reconcile it, and infer a |
| 158 |
strategy from the mess.""" |
| 159 |
# If we know types from the validator(s), that's sufficient. |
| 160 |
if len(types) == 1: |
| 161 |
(typ,) = types |
| 162 |
if isinstance(typ, tuple): |
| 163 |
return st.one_of(*map(st.from_type, typ)) |
| 164 |
return st.from_type(typ) |
| 165 |
elif types: |
| 166 |
# We have a list of tuples of types, and want to find a type |
| 167 |
# (or tuple of types) that is a subclass of all of them. |
| 168 |
type_tuples = [k if isinstance(k, tuple) else (k,) for k in types] |
| 169 |
# Flatten the list, filter types that would fail validation, and |
| 170 |
# sort so that ordering is stable between runs and shrinks well. |
| 171 |
allowed = [ |
| 172 |
t |
| 173 |
for t in set(sum(type_tuples, ())) |
| 174 |
if all(issubclass(t, tup) for tup in type_tuples) |
| 175 |
] |
| 176 |
allowed.sort(key=type_sorting_key) |
| 177 |
return st.one_of([st.from_type(t) for t in allowed]) |
| 178 |
|
| 179 |
# Otherwise, try the `type` attribute as a fallback, and finally try |
| 180 |
# the type hints on a converter (desperate!) before giving up. |
| 181 |
if is_a_type(getattr(attrib, "type", None)): |
| 182 |
assert attrib.type is not None |
| 183 |
# The convoluted test is because variable annotations may be stored |
| 184 |
# in string form; attrs doesn't evaluate them and we don't handle them. |
| 185 |
# See PEP 526, PEP 563, and Hypothesis issue #1004 for details. |
| 186 |
return st.from_type(attrib.type) |
| 187 |
|
| 188 |
converter = getattr(attrib, "converter", None) |
| 189 |
if isinstance(converter, type): |
| 190 |
return st.from_type(converter) |
| 191 |
elif callable(converter): |
| 192 |
hints = get_type_hints(converter) |
| 193 |
if "return" in hints: |
| 194 |
return st.from_type(hints["return"]) |
| 195 |
|
| 196 |
return st.nothing() |
| 197 |
|
| 198 |
|
| 199 |
def ordered_intersection(in_: Sequence[Iterable[T]]) -> Generator[T, None, None]: |
| 200 |
"""Set union of n sequences, ordered for reproducibility across runs.""" |
| 201 |
intersection = reduce(set.intersection, in_, set(in_[0])) |
| 202 |
for x in chain.from_iterable(in_): |
| 203 |
if x in intersection: |
| 204 |
yield x |
| 205 |
intersection.remove(x) |
| 206 |
|
| 207 |
|
| 208 |
def all_substrings(s: str) -> Generator[str, None, None]: |
| 209 |
"""Generate all substrings of `s`, in order of length then occurrence. |
| 210 |
Includes the empty string (first), and any duplicates that are present. |
| 211 |
|
| 212 |
>>> list(all_substrings('010')) |
| 213 |
['', '0', '1', '0', '01', '10', '010'] |
| 214 |
""" |
| 215 |
yield s[:0] |
| 216 |
for n, _ in enumerate(s): |
| 217 |
for i in range(len(s) - n): |
| 218 |
yield s[i : i + n + 1] |