| 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 |
""" |
| 12 |
Writing tests with Hypothesis frees you from the tedium of deciding on and |
| 13 |
writing out specific inputs to test. Now, the ``hypothesis.extra.ghostwriter`` |
| 14 |
module can write your test functions for you too! |
| 15 |
|
| 16 |
The idea is to provide **an easy way to start** property-based testing, |
| 17 |
**and a seamless transition** to more complex test code - because ghostwritten |
| 18 |
tests are source code that you could have written for yourself. |
| 19 |
|
| 20 |
So just pick a function you'd like tested, and feed it to one of the functions |
| 21 |
below. They follow imports, use but do not require type annotations, and |
| 22 |
generally do their best to write you a useful test. You can also use |
| 23 |
:ref:`our command-line interface <hypothesis-cli>`:: |
| 24 |
|
| 25 |
$ hypothesis write --help |
| 26 |
Usage: hypothesis write [OPTIONS] FUNC... |
| 27 |
|
| 28 |
`hypothesis write` writes property-based tests for you! |
| 29 |
|
| 30 |
Type annotations are helpful but not required for our advanced |
| 31 |
introspection and templating logic. Try running the examples below to see |
| 32 |
how it works: |
| 33 |
|
| 34 |
hypothesis write gzip |
| 35 |
hypothesis write numpy.matmul |
| 36 |
hypothesis write pandas.from_dummies |
| 37 |
hypothesis write re.compile --except re.error |
| 38 |
hypothesis write --equivalent ast.literal_eval eval |
| 39 |
hypothesis write --roundtrip json.dumps json.loads |
| 40 |
hypothesis write --style=unittest --idempotent sorted |
| 41 |
hypothesis write --binary-op operator.add |
| 42 |
|
| 43 |
Options: |
| 44 |
--roundtrip start by testing write/read or encode/decode! |
| 45 |
--equivalent very useful when optimising or refactoring code |
| 46 |
--errors-equivalent --equivalent, but also allows consistent errors |
| 47 |
--idempotent check that f(x) == f(f(x)) |
| 48 |
--binary-op associativity, commutativity, identity element |
| 49 |
--style [pytest|unittest] pytest-style function, or unittest-style method? |
| 50 |
-e, --except OBJ_NAME dotted name of exception(s) to ignore |
| 51 |
--annotate / --no-annotate force ghostwritten tests to be type-annotated |
| 52 |
(or not). By default, match the code to test. |
| 53 |
-h, --help Show this message and exit. |
| 54 |
|
| 55 |
.. tip:: |
| 56 |
|
| 57 |
Using a light theme? Hypothesis respects `NO_COLOR <https://no-color.org/>`__ |
| 58 |
and ``DJANGO_COLORS=light``. |
| 59 |
|
| 60 |
.. note:: |
| 61 |
|
| 62 |
The ghostwriter requires :pypi:`black`, but the generated code only |
| 63 |
requires Hypothesis itself. |
| 64 |
|
| 65 |
.. note:: |
| 66 |
|
| 67 |
Legal questions? While the ghostwriter fragments and logic is under the |
| 68 |
MPL-2.0 license like the rest of Hypothesis, the *output* from the ghostwriter |
| 69 |
is made available under the `Creative Commons Zero (CC0) |
| 70 |
<https://creativecommons.org/public-domain/cc0/>`__ |
| 71 |
public domain dedication, so you can use it without any restrictions. |
| 72 |
""" |
| 73 |
|
| 74 |
import ast |
| 75 |
import builtins |
| 76 |
import contextlib |
| 77 |
import enum |
| 78 |
import inspect |
| 79 |
import os |
| 80 |
import re |
| 81 |
import sys |
| 82 |
import types |
| 83 |
import warnings |
| 84 |
from collections import OrderedDict, defaultdict |
| 85 |
from collections.abc import Callable, Iterable, Mapping |
| 86 |
from itertools import permutations, zip_longest |
| 87 |
from keyword import iskeyword as _iskeyword |
| 88 |
from string import ascii_lowercase |
| 89 |
from textwrap import dedent, indent |
| 90 |
from types import EllipsisType |
| 91 |
from typing import ( |
| 92 |
Any, |
| 93 |
ForwardRef, |
| 94 |
NamedTuple, |
| 95 |
TypeVar, |
| 96 |
get_args, |
| 97 |
get_origin, |
| 98 |
) |
| 99 |
|
| 100 |
import black |
| 101 |
|
| 102 |
from hypothesis import Verbosity, find, settings, strategies as st |
| 103 |
from hypothesis.errors import InvalidArgument, SmallSearchSpaceWarning |
| 104 |
from hypothesis.internal.compat import get_type_hints |
| 105 |
from hypothesis.internal.reflection import get_signature, is_mock |
| 106 |
from hypothesis.internal.validation import check_type |
| 107 |
from hypothesis.provisional import domains |
| 108 |
from hypothesis.strategies._internal.collections import ListStrategy |
| 109 |
from hypothesis.strategies._internal.core import BuildsStrategy |
| 110 |
from hypothesis.strategies._internal.deferred import DeferredStrategy |
| 111 |
from hypothesis.strategies._internal.flatmapped import FlatMapStrategy |
| 112 |
from hypothesis.strategies._internal.lazy import LazyStrategy, unwrap_strategies |
| 113 |
from hypothesis.strategies._internal.strategies import ( |
| 114 |
FilteredStrategy, |
| 115 |
MappedStrategy, |
| 116 |
OneOfStrategy, |
| 117 |
SampledFromStrategy, |
| 118 |
) |
| 119 |
from hypothesis.strategies._internal.types import _global_type_lookup, is_generic_type |
| 120 |
|
| 121 |
IMPORT_SECTION = """ |
| 122 |
# This test code was written by the `hypothesis.extra.ghostwriter` module |
| 123 |
# and is provided under the Creative Commons Zero public domain dedication. |
| 124 |
|
| 125 |
{imports} |
| 126 |
""" |
| 127 |
|
| 128 |
TEMPLATE = """ |
| 129 |
@given({given_args}) |
| 130 |
def test_{test_kind}_{func_name}({arg_names}){return_annotation}: |
| 131 |
{test_body} |
| 132 |
""" |
| 133 |
|
| 134 |
SUPPRESS_BLOCK = """ |
| 135 |
try: |
| 136 |
{test_body} |
| 137 |
except {exceptions}: |
| 138 |
reject() |
| 139 |
""".strip() |
| 140 |
|
| 141 |
Except = type[Exception] | tuple[type[Exception], ...] |
| 142 |
ImportSet = set[str | tuple[str, str]] |
| 143 |
_quietly_settings = settings( |
| 144 |
database=None, |
| 145 |
deadline=None, |
| 146 |
derandomize=True, |
| 147 |
verbosity=Verbosity.quiet, |
| 148 |
) |
| 149 |
|
| 150 |
|
| 151 |
def _dedupe_exceptions(exc: tuple[type[Exception], ...]) -> tuple[type[Exception], ...]: |
| 152 |
# This is reminiscent of de-duplication logic I wrote for flake8-bugbear, |
| 153 |
# but with access to the actual objects we can just check for subclasses. |
| 154 |
# This lets us print e.g. `Exception` instead of `(Exception, OSError)`. |
| 155 |
uniques = list(exc) |
| 156 |
for a, b in permutations(exc, 2): |
| 157 |
if a in uniques and issubclass(a, b): |
| 158 |
uniques.remove(a) |
| 159 |
return tuple(sorted(uniques, key=lambda e: e.__name__)) |
| 160 |
|
| 161 |
|
| 162 |
def _check_except(except_: Except) -> tuple[type[Exception], ...]: |
| 163 |
if isinstance(except_, tuple): |
| 164 |
for i, e in enumerate(except_): |
| 165 |
if not isinstance(e, type) or not issubclass(e, Exception): |
| 166 |
raise InvalidArgument( |
| 167 |
f"Expected an Exception but got except_[{i}]={e!r}" |
| 168 |
f" (type={_get_qualname(type(e))})" |
| 169 |
) |
| 170 |
return except_ |
| 171 |
if not isinstance(except_, type) or not issubclass(except_, Exception): |
| 172 |
raise InvalidArgument( |
| 173 |
"Expected an Exception or tuple of exceptions, but got except_=" |
| 174 |
f"{except_!r} (type={_get_qualname(type(except_))})" |
| 175 |
) |
| 176 |
return (except_,) |
| 177 |
|
| 178 |
|
| 179 |
def _exception_string(except_: tuple[type[Exception], ...]) -> tuple[ImportSet, str]: |
| 180 |
if not except_: |
| 181 |
return set(), "" |
| 182 |
exceptions = [] |
| 183 |
imports: ImportSet = set() |
| 184 |
for ex in _dedupe_exceptions(except_): |
| 185 |
if ex.__qualname__ in dir(builtins): |
| 186 |
exceptions.append(ex.__qualname__) |
| 187 |
else: |
| 188 |
imports.add(ex.__module__) |
| 189 |
exceptions.append(_get_qualname(ex, include_module=True)) |
| 190 |
return imports, ( |
| 191 |
"(" + ", ".join(exceptions) + ")" if len(exceptions) > 1 else exceptions[0] |
| 192 |
) |
| 193 |
|
| 194 |
|
| 195 |
def _check_style(style: str) -> None: |
| 196 |
if style not in ("pytest", "unittest"): |
| 197 |
raise InvalidArgument(f"Valid styles are 'pytest' or 'unittest', got {style!r}") |
| 198 |
|
| 199 |
|
| 200 |
def _exceptions_from_docstring(doc: str) -> tuple[type[Exception], ...]: |
| 201 |
"""Return a tuple of exceptions that the docstring says may be raised. |
| 202 |
|
| 203 |
Note that we ignore non-builtin exception types for simplicity, as this is |
| 204 |
used directly in _write_call() and passing import sets around would be really |
| 205 |
really annoying. |
| 206 |
""" |
| 207 |
# TODO: it would be great to handle Google- and Numpy-style docstrings |
| 208 |
# (e.g. by using the Napoleon Sphinx extension) |
| 209 |
assert isinstance(doc, str), doc |
| 210 |
raises = [] |
| 211 |
for excname in re.compile(r"\:raises\s+(\w+)\:", re.MULTILINE).findall(doc): |
| 212 |
exc_type = getattr(builtins, excname, None) |
| 213 |
if isinstance(exc_type, type) and issubclass(exc_type, Exception): |
| 214 |
raises.append(exc_type) |
| 215 |
return tuple(_dedupe_exceptions(tuple(raises))) |
| 216 |
|
| 217 |
|
| 218 |
def _type_from_doc_fragment(token: str) -> type | None: |
| 219 |
# Special cases for "integer" and for numpy array-like and dtype |
| 220 |
if token == "integer": |
| 221 |
return int |
| 222 |
if "numpy" in sys.modules: |
| 223 |
if re.fullmatch(r"[Aa]rray[-_ ]?like", token): |
| 224 |
return sys.modules["numpy"].ndarray |
| 225 |
elif token == "dtype": |
| 226 |
return sys.modules["numpy"].dtype |
| 227 |
# Natural-language syntax, e.g. "sequence of integers" |
| 228 |
coll_match = re.fullmatch(r"(\w+) of (\w+)", token) |
| 229 |
if coll_match is not None: |
| 230 |
coll_token, elem_token = coll_match.groups() |
| 231 |
elems = _type_from_doc_fragment(elem_token) |
| 232 |
if elems is None and elem_token.endswith("s"): |
| 233 |
elems = _type_from_doc_fragment(elem_token[:-1]) |
| 234 |
if elems is not None and coll_token in ("list", "sequence", "collection"): |
| 235 |
return list[elems] # type: ignore |
| 236 |
# This might be e.g. "array-like of float"; arrays is better than nothing |
| 237 |
# even if we can't conveniently pass a generic type around. |
| 238 |
return _type_from_doc_fragment(coll_token) |
| 239 |
# Check either builtins, or the module for a dotted name |
| 240 |
if "." not in token: |
| 241 |
return getattr(builtins, token, None) |
| 242 |
mod, name = token.rsplit(".", maxsplit=1) |
| 243 |
return getattr(sys.modules.get(mod, None), name, None) |
| 244 |
|
| 245 |
|
| 246 |
def _strip_typevars(type_): |
| 247 |
with contextlib.suppress(Exception): |
| 248 |
if {type(a) for a in get_args(type_)} == {TypeVar}: |
| 249 |
return get_origin(type_) |
| 250 |
return type_ |
| 251 |
|
| 252 |
|
| 253 |
def _strategy_for(param: inspect.Parameter, docstring: str) -> st.SearchStrategy: |
| 254 |
# Example types in docstrings: |
| 255 |
# - `:type a: sequence of integers` |
| 256 |
# - `b (list, tuple, or None): ...` |
| 257 |
# - `c : {"foo", "bar", or None}` |
| 258 |
for pattern in ( |
| 259 |
rf"^\s*\:type\s+{param.name}\:\s+(.+)", # RST-style |
| 260 |
rf"^\s*{param.name} \((.+)\):", # Google-style |
| 261 |
rf"^\s*{param.name} \: (.+)", # Numpy-style |
| 262 |
): |
| 263 |
match = re.search(pattern, docstring, flags=re.MULTILINE) |
| 264 |
if match is None: |
| 265 |
continue |
| 266 |
doc_type = match.group(1) |
| 267 |
doc_type = doc_type.removesuffix(", optional").strip("}{") |
| 268 |
elements = [] |
| 269 |
types = [] |
| 270 |
for token in re.split(r",? +or +| *, *", doc_type): |
| 271 |
for prefix in ("default ", "python "): |
| 272 |
# e.g. `str or None, default "auto"` or `python int or numpy.int64` |
| 273 |
token = token.removeprefix(prefix) |
| 274 |
if not token: |
| 275 |
continue |
| 276 |
try: |
| 277 |
# Elements of `{"inner", "outer"}` etc. |
| 278 |
elements.append(ast.literal_eval(token)) |
| 279 |
continue |
| 280 |
except (ValueError, SyntaxError): |
| 281 |
t = _type_from_doc_fragment(token) |
| 282 |
if isinstance(t, type) or is_generic_type(t): |
| 283 |
assert t is not None |
| 284 |
types.append(_strip_typevars(t)) |
| 285 |
if ( |
| 286 |
param.default is not inspect.Parameter.empty |
| 287 |
and param.default not in elements |
| 288 |
and not isinstance( |
| 289 |
param.default, tuple(t for t in types if isinstance(t, type)) |
| 290 |
) |
| 291 |
): |
| 292 |
with contextlib.suppress(SyntaxError): |
| 293 |
compile(repr(st.just(param.default)), "<string>", "eval") |
| 294 |
elements.insert(0, param.default) |
| 295 |
if elements or types: |
| 296 |
return (st.sampled_from(elements) if elements else st.nothing()) | ( |
| 297 |
st.one_of(*map(st.from_type, types)) if types else st.nothing() |
| 298 |
) |
| 299 |
|
| 300 |
# If our default value is an Enum or a boolean, we assume that any value |
| 301 |
# of that type is acceptable. Otherwise, we only generate the default. |
| 302 |
if isinstance(param.default, bool): |
| 303 |
return st.booleans() |
| 304 |
if isinstance(param.default, enum.Enum): |
| 305 |
return st.sampled_from(type(param.default)) |
| 306 |
if param.default is not inspect.Parameter.empty: |
| 307 |
# Using `st.from_type(type(param.default))` would introduce spurious |
| 308 |
# failures in cases like the `flags` argument to regex functions. |
| 309 |
# Better in to keep it simple, and let the user elaborate if desired. |
| 310 |
return st.just(param.default) |
| 311 |
return _guess_strategy_by_argname(name=param.name.lower()) |
| 312 |
|
| 313 |
|
| 314 |
# fmt: off |
| 315 |
BOOL_NAMES = ( |
| 316 |
"keepdims", "verbose", "debug", "force", "train", "training", "trainable", "bias", |
| 317 |
"shuffle", "show", "load", "pretrained", "save", "overwrite", "normalize", |
| 318 |
"reverse", "success", "enabled", "strict", "copy", "quiet", "required", "inplace", |
| 319 |
"recursive", "enable", "active", "create", "validate", "refresh", "use_bias", |
| 320 |
) |
| 321 |
POSITIVE_INTEGER_NAMES = ( |
| 322 |
"width", "size", "length", "limit", "idx", "stride", "epoch", "epochs", "depth", |
| 323 |
"pid", "steps", "iteration", "iterations", "vocab_size", "ttl", "count", |
| 324 |
) |
| 325 |
FLOAT_NAMES = ( |
| 326 |
"real", "imag", "alpha", "theta", "beta", "sigma", "gamma", "angle", "reward", |
| 327 |
"tau", "temperature", |
| 328 |
) |
| 329 |
STRING_NAMES = ( |
| 330 |
"text", "txt", "password", "label", "prefix", "suffix", "desc", "description", |
| 331 |
"str", "pattern", "subject", "reason", "comment", "prompt", "sentence", "sep", |
| 332 |
) |
| 333 |
# fmt: on |
| 334 |
|
| 335 |
|
| 336 |
def _guess_strategy_by_argname(name: str) -> st.SearchStrategy: |
| 337 |
""" |
| 338 |
If all else fails, we try guessing a strategy based on common argument names. |
| 339 |
|
| 340 |
We wouldn't do this in builds() where strict correctness is required, but for |
| 341 |
the ghostwriter we accept "good guesses" since the user would otherwise have |
| 342 |
to change the strategy anyway - from `nothing()` - if we refused to guess. |
| 343 |
|
| 344 |
A "good guess" is _usually correct_, and _a reasonable mistake_ if not. |
| 345 |
The logic below is therefore based on a manual reading of the builtins and |
| 346 |
some standard-library docs, plus the analysis of about three hundred million |
| 347 |
arguments in https://github.com/HypothesisWorks/hypothesis/issues/3311 |
| 348 |
""" |
| 349 |
# Special-cased names |
| 350 |
if name in ("function", "func", "f"): |
| 351 |
return st.functions() |
| 352 |
if name in ("pred", "predicate"): |
| 353 |
return st.functions(returns=st.booleans(), pure=True) |
| 354 |
if name in ("iterable",): |
| 355 |
return st.iterables(st.integers()) | st.iterables(st.text()) |
| 356 |
if name in ("list", "lst", "ls"): |
| 357 |
return st.lists(st.nothing()) |
| 358 |
if name in ("object",): |
| 359 |
return st.builds(object) |
| 360 |
if "uuid" in name: |
| 361 |
return st.uuids().map(str) |
| 362 |
|
| 363 |
# Names which imply the value is a boolean |
| 364 |
if name.startswith("is_") or name in BOOL_NAMES: |
| 365 |
return st.booleans() |
| 366 |
|
| 367 |
# Names which imply that the value is a number, perhaps in a particular range |
| 368 |
if name in ("amount", "threshold", "number", "num"): |
| 369 |
return st.integers() | st.floats() |
| 370 |
|
| 371 |
if name in ("port",): |
| 372 |
return st.integers(0, 2**16 - 1) |
| 373 |
if ( |
| 374 |
name.endswith("_size") |
| 375 |
or (name.endswith("size") and "_" not in name) |
| 376 |
or re.fullmatch(r"n(um)?_[a-z_]*s", name) |
| 377 |
or name in POSITIVE_INTEGER_NAMES |
| 378 |
): |
| 379 |
return st.integers(min_value=0) |
| 380 |
if name in ("offset", "seed", "dim", "total", "priority"): |
| 381 |
return st.integers() |
| 382 |
|
| 383 |
if name in ("learning_rate", "dropout", "dropout_rate", "epsilon", "eps", "prob"): |
| 384 |
return st.floats(0, 1) |
| 385 |
if name in ("lat", "latitude"): |
| 386 |
return st.floats(-90, 90) |
| 387 |
if name in ("lon", "longitude"): |
| 388 |
return st.floats(-180, 180) |
| 389 |
if name in ("radius", "tol", "tolerance", "rate"): |
| 390 |
return st.floats(min_value=0) |
| 391 |
if name in FLOAT_NAMES: |
| 392 |
return st.floats() |
| 393 |
|
| 394 |
# Names which imply that the value is a string |
| 395 |
if name in ("host", "hostname"): |
| 396 |
return domains() |
| 397 |
if name in ("email",): |
| 398 |
return st.emails() |
| 399 |
if name in ("word", "slug", "api_key"): |
| 400 |
return st.from_regex(r"\w+", fullmatch=True) |
| 401 |
if name in ("char", "character"): |
| 402 |
return st.characters() |
| 403 |
|
| 404 |
if ( |
| 405 |
"file" in name |
| 406 |
or "path" in name |
| 407 |
or name.endswith("_dir") |
| 408 |
or name in ("fname", "dir", "dirname", "directory", "folder") |
| 409 |
): |
| 410 |
# Common names for filesystem paths: these are usually strings, but we |
| 411 |
# don't want to make strings more convenient than pathlib.Path. |
| 412 |
return st.nothing() |
| 413 |
|
| 414 |
if ( |
| 415 |
name.endswith(("_name", "label")) |
| 416 |
or (name.endswith("name") and "_" not in name) |
| 417 |
or ("string" in name and "as" not in name) |
| 418 |
or name in STRING_NAMES |
| 419 |
): |
| 420 |
return st.text() |
| 421 |
|
| 422 |
# Last clever idea: maybe we're looking a plural, and know the singular: |
| 423 |
if re.fullmatch(r"\w*[^s]s", name): |
| 424 |
elems = _guess_strategy_by_argname(name[:-1]) |
| 425 |
if not elems.is_empty: |
| 426 |
return st.lists(elems) |
| 427 |
|
| 428 |
# And if all that failed, we'll return nothing() - the user will have to |
| 429 |
# fill this in by hand, and we'll leave a comment to that effect later. |
| 430 |
return st.nothing() |
| 431 |
|
| 432 |
|
| 433 |
def _get_params_builtin_fn(func: Callable) -> list[inspect.Parameter]: |
| 434 |
if ( |
| 435 |
isinstance(func, (types.BuiltinFunctionType, types.BuiltinMethodType)) |
| 436 |
and hasattr(func, "__doc__") |
| 437 |
and isinstance(func.__doc__, str) |
| 438 |
): |
| 439 |
# inspect.signature doesn't work on all builtin functions or methods. |
| 440 |
# In such cases, we can try to reconstruct simple signatures from the docstring. |
| 441 |
match = re.match(rf"^{func.__name__}\((.+?)\)", func.__doc__) |
| 442 |
if match is None: |
| 443 |
return [] |
| 444 |
args = match.group(1).replace("[", "").replace("]", "") |
| 445 |
params = [] |
| 446 |
# Even if the signature doesn't contain a /, we assume that arguments |
| 447 |
# are positional-only until shown otherwise - the / is often omitted. |
| 448 |
kind: inspect._ParameterKind = inspect.Parameter.POSITIONAL_ONLY |
| 449 |
for arg in args.split(", "): |
| 450 |
arg, *_ = arg.partition("=") |
| 451 |
arg = arg.strip() |
| 452 |
if arg == "/": |
| 453 |
kind = inspect.Parameter.POSITIONAL_OR_KEYWORD |
| 454 |
continue |
| 455 |
if arg.startswith("*") or arg == "...": |
| 456 |
kind = inspect.Parameter.KEYWORD_ONLY |
| 457 |
continue # we omit *varargs, if there are any |
| 458 |
if _iskeyword(arg.lstrip("*")) or not arg.lstrip("*").isidentifier(): |
| 459 |
break # skip all subsequent params if this name is invalid |
| 460 |
params.append(inspect.Parameter(name=arg, kind=kind)) |
| 461 |
return params |
| 462 |
return [] |
| 463 |
|
| 464 |
|
| 465 |
def _get_params_ufunc(func: Callable) -> list[inspect.Parameter]: |
| 466 |
if _is_probably_ufunc(func): |
| 467 |
# `inspect.signature` results vary for ufunc objects, but we can work out |
| 468 |
# what the required parameters would look like if it was reliable. |
| 469 |
# Note that we use args named a, b, c... to match the `operator` module, |
| 470 |
# rather than x1, x2, x3... like the Numpy docs. Because they're pos-only |
| 471 |
# this doesn't make a runtime difference, and it's much nicer for use-cases |
| 472 |
# like `equivalent(numpy.add, operator.add)`. |
| 473 |
return [ |
| 474 |
inspect.Parameter(name=name, kind=inspect.Parameter.POSITIONAL_ONLY) |
| 475 |
for name in ascii_lowercase[: func.nin] # type: ignore |
| 476 |
] |
| 477 |
return [] |
| 478 |
|
| 479 |
|
| 480 |
def _get_params(func: Callable) -> dict[str, inspect.Parameter]: |
| 481 |
"""Get non-vararg parameters of `func` as an ordered dict.""" |
| 482 |
try: |
| 483 |
params = list(get_signature(func).parameters.values()) |
| 484 |
except Exception: |
| 485 |
if params := _get_params_ufunc(func): |
| 486 |
pass |
| 487 |
elif params := _get_params_builtin_fn(func): |
| 488 |
pass |
| 489 |
else: |
| 490 |
# If we haven't managed to recover a signature through the tricks above, |
| 491 |
# we're out of ideas and should just re-raise the exception. |
| 492 |
raise |
| 493 |
else: |
| 494 |
P = inspect.Parameter |
| 495 |
placeholder = [("args", P.VAR_POSITIONAL), ("kwargs", P.VAR_KEYWORD)] |
| 496 |
if ufunc_params := _get_params_ufunc(func): |
| 497 |
# If func is a ufunc, prefer _get_params_ufunc over get_signature, |
| 498 |
# as the latter includes keyword arguments we aren't well-equipped |
| 499 |
# to ghostwrite. |
| 500 |
params = ufunc_params |
| 501 |
elif [(p.name, p.kind) for p in params] == placeholder: |
| 502 |
# If the params we got look like an uninformative placeholder, try fallbacks. |
| 503 |
params = _get_params_builtin_fn(func) or params |
| 504 |
return _params_to_dict(params) |
| 505 |
|
| 506 |
|
| 507 |
def _params_to_dict( |
| 508 |
params: Iterable[inspect.Parameter], |
| 509 |
) -> dict[str, inspect.Parameter]: |
| 510 |
var_param_kinds = (inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD) |
| 511 |
return OrderedDict((p.name, p) for p in params if p.kind not in var_param_kinds) |
| 512 |
|
| 513 |
|
| 514 |
@contextlib.contextmanager |
| 515 |
def _with_any_registered(): |
| 516 |
# If the user has registered their own strategy for Any, leave it alone |
| 517 |
if Any in _global_type_lookup: |
| 518 |
yield |
| 519 |
# We usually want to force from_type(Any) to raise an error because we don't |
| 520 |
# have enough information to accurately resolve user intent, but in this case |
| 521 |
# we can treat it as a synonym for object - this is probably wrong, but you'll |
| 522 |
# get at least _some_ output to edit later. We then reset everything in order |
| 523 |
# to avoid polluting the resolution logic in case you run tests later. |
| 524 |
else: |
| 525 |
try: |
| 526 |
_global_type_lookup[Any] = st.builds(object) |
| 527 |
yield |
| 528 |
finally: |
| 529 |
del _global_type_lookup[Any] |
| 530 |
st.from_type.__clear_cache() |
| 531 |
|
| 532 |
|
| 533 |
def _get_strategies( |
| 534 |
*funcs: Callable, pass_result_to_next_func: bool = False |
| 535 |
) -> dict[str, st.SearchStrategy]: |
| 536 |
"""Return a dict of strategies for the union of arguments to `funcs`. |
| 537 |
|
| 538 |
If `pass_result_to_next_func` is True, assume that the result of each function |
| 539 |
is passed to the next, and therefore skip the first argument of all but the |
| 540 |
first function. |
| 541 |
|
| 542 |
This dict is used to construct our call to the `@given(...)` decorator. |
| 543 |
""" |
| 544 |
assert funcs, "Must pass at least one function" |
| 545 |
given_strategies: dict[str, st.SearchStrategy] = {} |
| 546 |
for i, f in enumerate(funcs): |
| 547 |
params = _get_params(f) |
| 548 |
if pass_result_to_next_func and i >= 1: |
| 549 |
del params[next(iter(params))] |
| 550 |
hints = get_type_hints(f) |
| 551 |
docstring = getattr(f, "__doc__", None) or "" |
| 552 |
builder_args = { |
| 553 |
k: ... if k in hints else _strategy_for(v, docstring) |
| 554 |
for k, v in params.items() |
| 555 |
} |
| 556 |
with _with_any_registered(): |
| 557 |
strat = st.builds(f, **builder_args).wrapped_strategy # type: ignore |
| 558 |
|
| 559 |
if strat.args: |
| 560 |
raise NotImplementedError("Expected to pass everything as kwargs") |
| 561 |
|
| 562 |
for k, v in strat.kwargs.items(): |
| 563 |
if _valid_syntax_repr(v)[1] == "nothing()" and k in hints: |
| 564 |
# e.g. from_type(Hashable) is OK but the unwrapped repr is not |
| 565 |
v = LazyStrategy(st.from_type, (hints[k],), {}) |
| 566 |
if k in given_strategies: |
| 567 |
given_strategies[k] |= v |
| 568 |
else: |
| 569 |
given_strategies[k] = v |
| 570 |
|
| 571 |
# If there is only one function, we pass arguments to @given in the order of |
| 572 |
# that function's signature. Otherwise, we use alphabetical order. |
| 573 |
if len(funcs) == 1: |
| 574 |
return {name: given_strategies[name] for name in _get_params(f)} |
| 575 |
return dict(sorted(given_strategies.items())) |
| 576 |
|
| 577 |
|
| 578 |
def _assert_eq(style: str, a: str, b: str) -> str: |
| 579 |
if style == "unittest": |
| 580 |
return f"self.assertEqual({a}, {b})" |
| 581 |
assert style == "pytest" |
| 582 |
if a.isidentifier() and b.isidentifier(): |
| 583 |
return f"assert {a} == {b}, ({a}, {b})" |
| 584 |
return f"assert {a} == {b}" |
| 585 |
|
| 586 |
|
| 587 |
def _imports_for_object(obj): |
| 588 |
"""Return the imports for `obj`, which may be empty for e.g. lambdas""" |
| 589 |
if type(obj) is getattr(types, "UnionType", object()): |
| 590 |
return {mod for mod, _ in set().union(*map(_imports_for_object, obj.__args__))} |
| 591 |
if isinstance(obj, (re.Pattern, re.Match)): |
| 592 |
return {"re"} |
| 593 |
if isinstance(obj, st.SearchStrategy): |
| 594 |
return _imports_for_strategy(obj) |
| 595 |
if isinstance(obj, getattr(sys.modules.get("numpy"), "dtype", ())): |
| 596 |
return {("numpy", "dtype")} |
| 597 |
try: |
| 598 |
if is_generic_type(obj): |
| 599 |
if isinstance(obj, TypeVar): |
| 600 |
return {(obj.__module__, obj.__name__)} |
| 601 |
with contextlib.suppress(Exception): |
| 602 |
return set().union(*map(_imports_for_object, obj.__args__)) |
| 603 |
if (not callable(obj)) or obj.__name__ == "<lambda>": |
| 604 |
return set() |
| 605 |
name = _get_qualname(obj).split(".")[0] |
| 606 |
return {(_get_module(obj), name)} |
| 607 |
except Exception: |
| 608 |
return set() |
| 609 |
|
| 610 |
|
| 611 |
def _imports_for_strategy(strategy): |
| 612 |
# If we have a lazy from_type strategy, because unwrapping it gives us an |
| 613 |
# error or invalid syntax, import that type and we're done. |
| 614 |
if isinstance(strategy, LazyStrategy): |
| 615 |
imports = { |
| 616 |
imp |
| 617 |
for arg in set(strategy._LazyStrategy__args) |
| 618 |
| set(strategy._LazyStrategy__kwargs.values()) |
| 619 |
for imp in _imports_for_object(_strip_typevars(arg)) |
| 620 |
} |
| 621 |
if re.match(r"from_(type|regex)\(", repr(strategy)): |
| 622 |
return imports |
| 623 |
elif _get_module(strategy.function).startswith("hypothesis.extra."): |
| 624 |
module = _get_module(strategy.function).replace("._array_helpers", ".numpy") |
| 625 |
return {(module, strategy.function.__name__)} | imports |
| 626 |
|
| 627 |
imports = set() |
| 628 |
with warnings.catch_warnings(): |
| 629 |
warnings.simplefilter("ignore", SmallSearchSpaceWarning) |
| 630 |
strategy = unwrap_strategies(strategy) |
| 631 |
|
| 632 |
# Get imports for s.map(f), s.filter(f), s.flatmap(f), including both s and f |
| 633 |
if isinstance(strategy, MappedStrategy): |
| 634 |
imports |= _imports_for_strategy(strategy.mapped_strategy) |
| 635 |
imports |= _imports_for_object(strategy.pack) |
| 636 |
if isinstance(strategy, FilteredStrategy): |
| 637 |
imports |= _imports_for_strategy(strategy.filtered_strategy) |
| 638 |
for f in strategy.flat_conditions: |
| 639 |
imports |= _imports_for_object(f) |
| 640 |
if isinstance(strategy, FlatMapStrategy): |
| 641 |
imports |= _imports_for_strategy(strategy.base) |
| 642 |
imports |= _imports_for_object(strategy.expand) |
| 643 |
|
| 644 |
# recurse through one_of to handle e.g. from_type(Optional[Foo]) |
| 645 |
if isinstance(strategy, OneOfStrategy): |
| 646 |
for s in strategy.element_strategies: |
| 647 |
imports |= _imports_for_strategy(s) |
| 648 |
|
| 649 |
# get imports for the target of builds(), and recurse into the argument strategies |
| 650 |
if isinstance(strategy, BuildsStrategy): |
| 651 |
imports |= _imports_for_object(strategy.target) |
| 652 |
for s in strategy.args: |
| 653 |
imports |= _imports_for_strategy(s) |
| 654 |
for s in strategy.kwargs.values(): |
| 655 |
imports |= _imports_for_strategy(s) |
| 656 |
|
| 657 |
if isinstance(strategy, SampledFromStrategy): |
| 658 |
for obj in strategy.elements: |
| 659 |
imports |= _imports_for_object(obj) |
| 660 |
|
| 661 |
if isinstance(strategy, ListStrategy): |
| 662 |
imports |= _imports_for_strategy(strategy.element_strategy) |
| 663 |
|
| 664 |
return imports |
| 665 |
|
| 666 |
|
| 667 |
def _valid_syntax_repr(strategy): |
| 668 |
# For binary_op, we pass a variable name - so pass it right back again. |
| 669 |
if isinstance(strategy, str): |
| 670 |
return set(), strategy |
| 671 |
# Flatten and de-duplicate any one_of strategies, whether that's from resolving |
| 672 |
# a Union type or combining inputs to multiple functions. |
| 673 |
try: |
| 674 |
if isinstance(strategy, DeferredStrategy): |
| 675 |
strategy = strategy.wrapped_strategy |
| 676 |
if isinstance(strategy, OneOfStrategy): |
| 677 |
seen = set() |
| 678 |
elems = [] |
| 679 |
with warnings.catch_warnings(): |
| 680 |
warnings.simplefilter("ignore", SmallSearchSpaceWarning) |
| 681 |
strategy.element_strategies # might warn on first access |
| 682 |
for s in strategy.element_strategies: |
| 683 |
if isinstance(s, SampledFromStrategy) and s.elements == (os.environ,): |
| 684 |
continue |
| 685 |
if repr(s) not in seen: |
| 686 |
elems.append(s) |
| 687 |
seen.add(repr(s)) |
| 688 |
strategy = st.one_of(elems or st.nothing()) |
| 689 |
# hardcode some special cases for nicer reprs |
| 690 |
if strategy == st.text().wrapped_strategy: |
| 691 |
return set(), "text()" |
| 692 |
if strategy == st.from_type(type): |
| 693 |
return set(), "from_type(type)" |
| 694 |
# Remove any typevars; we don't exploit them so they're just clutter here |
| 695 |
if ( |
| 696 |
isinstance(strategy, LazyStrategy) |
| 697 |
and strategy.function.__name__ == st.from_type.__name__ |
| 698 |
and strategy._LazyStrategy__representation is None |
| 699 |
): |
| 700 |
strategy._LazyStrategy__args = tuple( |
| 701 |
_strip_typevars(a) for a in strategy._LazyStrategy__args |
| 702 |
) |
| 703 |
# Return a syntactically-valid strategy repr, including fixing some |
| 704 |
# strategy reprs and replacing invalid syntax reprs with `"nothing()"`. |
| 705 |
# String-replace to hide the special case in from_type() for Decimal('snan') |
| 706 |
r = ( |
| 707 |
repr(strategy) |
| 708 |
.replace(".filter(_can_hash)", "") |
| 709 |
.replace("hypothesis.strategies.", "") |
| 710 |
) |
| 711 |
# Replace <unknown> with ... in confusing lambdas |
| 712 |
r = re.sub(r"(lambda.*?: )(<unknown>)([,)])", r"\1...\3", r) |
| 713 |
compile(r, "<string>", "eval") |
| 714 |
# Finally, try to work out the imports we need for builds(), .map(), |
| 715 |
# .filter(), and .flatmap() to work without NameError |
| 716 |
imports = {i for i in _imports_for_strategy(strategy) if i[1] in r} |
| 717 |
return imports, r |
| 718 |
except (SyntaxError, RecursionError, InvalidArgument): |
| 719 |
return set(), "nothing()" |
| 720 |
|
| 721 |
|
| 722 |
# When we ghostwrite for a module, we want to treat that as the __module__ for |
| 723 |
# each function, rather than whichever internal file it was actually defined in. |
| 724 |
KNOWN_FUNCTION_LOCATIONS: dict[object, str] = {} |
| 725 |
|
| 726 |
|
| 727 |
def _get_module_helper(obj): |
| 728 |
# Get the __module__ attribute of the object, and return the first ancestor module |
| 729 |
# which contains the object; falling back to the literal __module__ if none do. |
| 730 |
# The goal is to show location from which obj should usually be accessed, rather |
| 731 |
# than what we assume is an internal submodule which defined it. |
| 732 |
module_name = obj.__module__ |
| 733 |
|
| 734 |
# if "collections.abc" is used don't use the deprecated aliases in "collections" |
| 735 |
if module_name == "collections.abc": |
| 736 |
return module_name |
| 737 |
|
| 738 |
dots = [i for i, c in enumerate(module_name) if c == "."] + [None] |
| 739 |
for idx in dots: |
| 740 |
for candidate in (module_name[:idx].lstrip("_"), module_name[:idx]): |
| 741 |
if getattr(sys.modules.get(candidate), obj.__name__, None) is obj: |
| 742 |
KNOWN_FUNCTION_LOCATIONS[obj] = candidate |
| 743 |
return candidate |
| 744 |
return module_name |
| 745 |
|
| 746 |
|
| 747 |
def _get_module(obj): |
| 748 |
if obj in KNOWN_FUNCTION_LOCATIONS: |
| 749 |
return KNOWN_FUNCTION_LOCATIONS[obj] |
| 750 |
try: |
| 751 |
return _get_module_helper(obj) |
| 752 |
except AttributeError: |
| 753 |
if not _is_probably_ufunc(obj): |
| 754 |
raise |
| 755 |
for module_name in sorted(sys.modules, key=lambda n: tuple(n.split("."))): |
| 756 |
if obj is getattr(sys.modules[module_name], obj.__name__, None): |
| 757 |
KNOWN_FUNCTION_LOCATIONS[obj] = module_name |
| 758 |
return module_name |
| 759 |
raise RuntimeError(f"Could not find module for ufunc {obj.__name__} ({obj!r}") |
| 760 |
|
| 761 |
|
| 762 |
def _get_qualname(obj: Any, *, include_module: bool = False) -> str: |
| 763 |
# Replacing angle-brackets for objects defined in `.<locals>.` |
| 764 |
qname = getattr(obj, "__qualname__", obj.__name__) |
| 765 |
qname = qname.replace("<", "_").replace(">", "_").replace(" ", "") |
| 766 |
if include_module: |
| 767 |
return _get_module(obj) + "." + qname |
| 768 |
return qname |
| 769 |
|
| 770 |
|
| 771 |
def _write_call( |
| 772 |
func: Callable, *pass_variables: str, except_: Except = Exception, assign: str = "" |
| 773 |
) -> str: |
| 774 |
"""Write a call to `func` with explicit and implicit arguments. |
| 775 |
|
| 776 |
>>> _write_call(sorted, "my_seq", "func") |
| 777 |
"builtins.sorted(my_seq, key=func, reverse=reverse)" |
| 778 |
|
| 779 |
>>> write_call(f, assign="var1") |
| 780 |
"var1 = f()" |
| 781 |
|
| 782 |
The fancy part is that we'll check the docstring for any known exceptions |
| 783 |
which `func` might raise, and catch-and-reject on them... *unless* they're |
| 784 |
subtypes of `except_`, which will be handled in an outer try-except block. |
| 785 |
""" |
| 786 |
args = ", ".join( |
| 787 |
( |
| 788 |
(v or p.name) |
| 789 |
if p.kind is inspect.Parameter.POSITIONAL_ONLY |
| 790 |
else f"{p.name}={v or p.name}" |
| 791 |
) |
| 792 |
for v, p in zip_longest(pass_variables, _get_params(func).values()) |
| 793 |
) |
| 794 |
call = f"{_get_qualname(func, include_module=True)}({args})" |
| 795 |
if assign: |
| 796 |
call = f"{assign} = {call}" |
| 797 |
raises = _exceptions_from_docstring(getattr(func, "__doc__", "") or "") |
| 798 |
exnames = [ex.__name__ for ex in raises if not issubclass(ex, except_)] |
| 799 |
if not exnames: |
| 800 |
return call |
| 801 |
return SUPPRESS_BLOCK.format( |
| 802 |
test_body=indent(call, prefix=" "), |
| 803 |
exceptions="(" + ", ".join(exnames) + ")" if len(exnames) > 1 else exnames[0], |
| 804 |
) |
| 805 |
|
| 806 |
|
| 807 |
def _st_strategy_names(s: str) -> str: |
| 808 |
"""Replace strategy name() with st.name(). |
| 809 |
|
| 810 |
Uses a tricky re.sub() to avoid problems with frozensets() matching |
| 811 |
sets() too. |
| 812 |
""" |
| 813 |
names = "|".join(sorted(st.__all__, key=len, reverse=True)) |
| 814 |
return re.sub(pattern=rf"\b(?:{names})\b[^= ]", repl=r"st.\g<0>", string=s) |
| 815 |
|
| 816 |
|
| 817 |
def _make_test_body( |
| 818 |
*funcs: Callable, |
| 819 |
ghost: str, |
| 820 |
test_body: str, |
| 821 |
except_: tuple[type[Exception], ...], |
| 822 |
assertions: str = "", |
| 823 |
style: str, |
| 824 |
given_strategies: Mapping[str, str | st.SearchStrategy] | None = None, |
| 825 |
imports: ImportSet | None = None, |
| 826 |
annotate: bool, |
| 827 |
) -> tuple[ImportSet, str]: |
| 828 |
# A set of modules to import - we might add to this later. The import code |
| 829 |
# is written later, so we can have one import section for multiple magic() |
| 830 |
# test functions. |
| 831 |
imports = (imports or set()) | {_get_module(f) for f in funcs} |
| 832 |
|
| 833 |
# Get strategies for all the arguments to each function we're testing. |
| 834 |
with _with_any_registered(): |
| 835 |
given_strategies = given_strategies or _get_strategies( |
| 836 |
*funcs, pass_result_to_next_func=ghost in ("idempotent", "roundtrip") |
| 837 |
) |
| 838 |
reprs = [((k, *_valid_syntax_repr(v))) for k, v in given_strategies.items()] |
| 839 |
imports = imports.union(*(imp for _, imp, _ in reprs)) |
| 840 |
given_args = ", ".join(f"{k}={v}" for k, _, v in reprs) |
| 841 |
given_args = _st_strategy_names(given_args) |
| 842 |
|
| 843 |
if except_: |
| 844 |
# Convert to strings, either builtin names or qualified names. |
| 845 |
imp, exc_string = _exception_string(except_) |
| 846 |
imports.update(imp) |
| 847 |
# And finally indent the existing test body into a try-except block |
| 848 |
# which catches these exceptions and calls `hypothesis.reject()`. |
| 849 |
test_body = SUPPRESS_BLOCK.format( |
| 850 |
test_body=indent(test_body, prefix=" "), |
| 851 |
exceptions=exc_string, |
| 852 |
) |
| 853 |
|
| 854 |
if assertions: |
| 855 |
test_body = f"{test_body}\n{assertions}" |
| 856 |
|
| 857 |
# Indent our test code to form the body of a function or method. |
| 858 |
argnames = ["self"] if style == "unittest" else [] |
| 859 |
if annotate: |
| 860 |
argnames.extend(_annotate_args(given_strategies, funcs, imports)) |
| 861 |
else: |
| 862 |
argnames.extend(given_strategies) |
| 863 |
|
| 864 |
body = TEMPLATE.format( |
| 865 |
given_args=given_args, |
| 866 |
test_kind=ghost, |
| 867 |
func_name="_".join(_get_qualname(f).replace(".", "_") for f in funcs), |
| 868 |
arg_names=", ".join(argnames), |
| 869 |
return_annotation=" -> None" if annotate else "", |
| 870 |
test_body=indent(test_body, prefix=" "), |
| 871 |
) |
| 872 |
|
| 873 |
# For unittest-style, indent method further into a class body |
| 874 |
if style == "unittest": |
| 875 |
imports.add("unittest") |
| 876 |
body = "class Test{}{}(unittest.TestCase):\n{}".format( |
| 877 |
ghost.title(), |
| 878 |
"".join(_get_qualname(f).replace(".", "").title() for f in funcs), |
| 879 |
indent(body, " "), |
| 880 |
) |
| 881 |
|
| 882 |
return imports, body |
| 883 |
|
| 884 |
|
| 885 |
def _annotate_args( |
| 886 |
argnames: Iterable[str], funcs: Iterable[Callable], imports: ImportSet |
| 887 |
) -> Iterable[str]: |
| 888 |
arg_parameters: defaultdict[str, set[Any]] = defaultdict(set) |
| 889 |
for func in funcs: |
| 890 |
try: |
| 891 |
params = tuple(get_signature(func, eval_str=True).parameters.values()) |
| 892 |
except Exception: |
| 893 |
# don't add parameters if the annotations could not be evaluated |
| 894 |
pass |
| 895 |
else: |
| 896 |
for key, param in _params_to_dict(params).items(): |
| 897 |
if param.annotation != inspect.Parameter.empty: |
| 898 |
arg_parameters[key].add(param.annotation) |
| 899 |
|
| 900 |
for argname in argnames: |
| 901 |
parameters = arg_parameters.get(argname) |
| 902 |
annotation = _parameters_to_annotation_name(parameters, imports) |
| 903 |
if annotation is None: |
| 904 |
yield argname |
| 905 |
else: |
| 906 |
yield f"{argname}: {annotation}" |
| 907 |
|
| 908 |
|
| 909 |
class _AnnotationData(NamedTuple): |
| 910 |
type_name: str |
| 911 |
imports: set[str] |
| 912 |
|
| 913 |
|
| 914 |
def _parameters_to_annotation_name( |
| 915 |
parameters: Iterable[Any] | None, imports: ImportSet |
| 916 |
) -> str | None: |
| 917 |
if parameters is None: |
| 918 |
return None |
| 919 |
annotations = tuple( |
| 920 |
annotation |
| 921 |
for annotation in map(_parameter_to_annotation, parameters) |
| 922 |
if annotation is not None |
| 923 |
) |
| 924 |
if not annotations: |
| 925 |
return None |
| 926 |
if len(annotations) == 1: |
| 927 |
type_name, new_imports = annotations[0] |
| 928 |
imports.update(new_imports) |
| 929 |
return type_name |
| 930 |
joined = _join_generics(("typing.Union", {"typing"}), annotations) |
| 931 |
if joined is None: |
| 932 |
return None |
| 933 |
imports.update(joined.imports) |
| 934 |
return joined.type_name |
| 935 |
|
| 936 |
|
| 937 |
def _join_generics( |
| 938 |
origin_type_data: tuple[str, set[str]] | None, |
| 939 |
annotations: Iterable[_AnnotationData | None], |
| 940 |
) -> _AnnotationData | None: |
| 941 |
if origin_type_data is None: |
| 942 |
return None |
| 943 |
|
| 944 |
# because typing.Optional is converted to a Union, it also contains None |
| 945 |
# since typing.Optional only accepts one type variable, we need to remove it |
| 946 |
if origin_type_data is not None and origin_type_data[0] == "typing.Optional": |
| 947 |
annotations = ( |
| 948 |
annotation |
| 949 |
for annotation in annotations |
| 950 |
if annotation is None or annotation.type_name != "None" |
| 951 |
) |
| 952 |
|
| 953 |
origin_type, imports = origin_type_data |
| 954 |
joined = _join_argument_annotations(annotations) |
| 955 |
if joined is None or not joined[0]: |
| 956 |
return None |
| 957 |
|
| 958 |
arg_types, new_imports = joined |
| 959 |
imports.update(new_imports) |
| 960 |
return _AnnotationData("{}[{}]".format(origin_type, ", ".join(arg_types)), imports) |
| 961 |
|
| 962 |
|
| 963 |
def _join_argument_annotations( |
| 964 |
annotations: Iterable[_AnnotationData | None], |
| 965 |
) -> tuple[list[str], set[str]] | None: |
| 966 |
imports: set[str] = set() |
| 967 |
arg_types: list[str] = [] |
| 968 |
|
| 969 |
for annotation in annotations: |
| 970 |
if annotation is None: |
| 971 |
return None |
| 972 |
arg_types.append(annotation.type_name) |
| 973 |
imports.update(annotation.imports) |
| 974 |
|
| 975 |
return arg_types, imports |
| 976 |
|
| 977 |
|
| 978 |
def _parameter_to_annotation(parameter: Any) -> _AnnotationData | None: |
| 979 |
# if a ForwardRef could not be resolved |
| 980 |
if isinstance(parameter, str): |
| 981 |
return None |
| 982 |
|
| 983 |
if isinstance(parameter, ForwardRef): |
| 984 |
if sys.version_info[:2] < (3, 14): |
| 985 |
forwarded_value = parameter.__forward_value__ |
| 986 |
if forwarded_value is None: |
| 987 |
return None |
| 988 |
else: |
| 989 |
# ForwardRef.__forward_value__ was removed in 3.14 in favor of |
| 990 |
# ForwardRef.evaluate(). See also PEP 649, PEP 749, and |
| 991 |
# typing.evaluate_forward_ref. |
| 992 |
# |
| 993 |
# .evaluate() with Format.VALUE (the default) throws if the name |
| 994 |
# could not be resolved. |
| 995 |
# https://docs.python.org/3.14/library/annotationlib.html#annotationlib.ForwardRef.evaluate |
| 996 |
try: |
| 997 |
forwarded_value = parameter.evaluate() |
| 998 |
except Exception: |
| 999 |
return None |
| 1000 |
return _parameter_to_annotation(forwarded_value) |
| 1001 |
|
| 1002 |
# the arguments of Callable are in a list |
| 1003 |
if isinstance(parameter, list): |
| 1004 |
joined = _join_argument_annotations( |
| 1005 |
_parameter_to_annotation(param) for param in parameter |
| 1006 |
) |
| 1007 |
if joined is None: |
| 1008 |
return None |
| 1009 |
arg_type_names, new_imports = joined |
| 1010 |
return _AnnotationData("[{}]".format(", ".join(arg_type_names)), new_imports) |
| 1011 |
|
| 1012 |
if isinstance(parameter, type): |
| 1013 |
if parameter.__module__ == "builtins": |
| 1014 |
return _AnnotationData( |
| 1015 |
"None" if parameter.__name__ == "NoneType" else parameter.__name__, |
| 1016 |
set(), |
| 1017 |
) |
| 1018 |
|
| 1019 |
type_name = _get_qualname(parameter, include_module=True) |
| 1020 |
|
| 1021 |
# the types.UnionType does not support type arguments and needs to be translated |
| 1022 |
if type_name == "types.UnionType": |
| 1023 |
return _AnnotationData("typing.Union", {"typing"}) |
| 1024 |
else: |
| 1025 |
if hasattr(parameter, "__module__") and hasattr(parameter, "__name__"): |
| 1026 |
type_name = _get_qualname(parameter, include_module=True) |
| 1027 |
else: |
| 1028 |
type_name = str(parameter) |
| 1029 |
|
| 1030 |
if type_name.startswith("hypothesis.strategies."): |
| 1031 |
return _AnnotationData(type_name.replace("hypothesis.strategies", "st"), set()) |
| 1032 |
|
| 1033 |
origin_type = get_origin(parameter) |
| 1034 |
|
| 1035 |
# if not generic or no generic arguments |
| 1036 |
if origin_type is None or origin_type == parameter: |
| 1037 |
return _AnnotationData(type_name, set(type_name.rsplit(".", maxsplit=1)[:-1])) |
| 1038 |
|
| 1039 |
arg_types = get_args(parameter) |
| 1040 |
if {type(a) for a in arg_types} == {TypeVar}: |
| 1041 |
arg_types = () |
| 1042 |
|
| 1043 |
# typing types get translated to classes that don't support generics |
| 1044 |
origin_annotation: _AnnotationData | None |
| 1045 |
if type_name.startswith("typing."): |
| 1046 |
try: |
| 1047 |
new_type_name = type_name[: type_name.index("[")] |
| 1048 |
except ValueError: |
| 1049 |
new_type_name = type_name |
| 1050 |
origin_annotation = _AnnotationData(new_type_name, {"typing"}) |
| 1051 |
else: |
| 1052 |
origin_annotation = _parameter_to_annotation(origin_type) |
| 1053 |
|
| 1054 |
if arg_types: |
| 1055 |
return _join_generics( |
| 1056 |
origin_annotation, |
| 1057 |
(_parameter_to_annotation(arg_type) for arg_type in arg_types), |
| 1058 |
) |
| 1059 |
return origin_annotation |
| 1060 |
|
| 1061 |
|
| 1062 |
def _are_annotations_used(*functions: Callable) -> bool: |
| 1063 |
for function in functions: |
| 1064 |
try: |
| 1065 |
params = get_signature(function).parameters.values() |
| 1066 |
except Exception: |
| 1067 |
pass |
| 1068 |
else: |
| 1069 |
if any(param.annotation != inspect.Parameter.empty for param in params): |
| 1070 |
return True |
| 1071 |
return False |
| 1072 |
|
| 1073 |
|
| 1074 |
def _make_test(imports: ImportSet, body: str) -> str: |
| 1075 |
# Discarding "builtins." and "__main__" probably isn't particularly useful |
| 1076 |
# for user code, but important for making a good impression in demos. |
| 1077 |
body = body.replace("builtins.", "").replace("__main__.", "") |
| 1078 |
imports |= {("hypothesis", "given"), ("hypothesis", "strategies as st")} |
| 1079 |
if " reject()\n" in body: |
| 1080 |
imports.add(("hypothesis", "reject")) |
| 1081 |
|
| 1082 |
do_not_import = {"builtins", "__main__", "hypothesis.strategies"} |
| 1083 |
direct = {f"import {i}" for i in imports - do_not_import if isinstance(i, str)} |
| 1084 |
from_imports = defaultdict(set) |
| 1085 |
for module, name in {i for i in imports if isinstance(i, tuple)}: |
| 1086 |
if not (module.startswith("hypothesis.strategies") and name in st.__all__): |
| 1087 |
from_imports[module].add(name) |
| 1088 |
from_ = { |
| 1089 |
"from {} import {}".format(module, ", ".join(sorted(names))) |
| 1090 |
for module, names in from_imports.items() |
| 1091 |
if isinstance(module, str) and module not in do_not_import |
| 1092 |
} |
| 1093 |
header = IMPORT_SECTION.format(imports="\n".join(sorted(direct) + sorted(from_))) |
| 1094 |
nothings = body.count("st.nothing()") |
| 1095 |
if nothings == 1: |
| 1096 |
header += "# TODO: replace st.nothing() with an appropriate strategy\n\n" |
| 1097 |
elif nothings >= 1: |
| 1098 |
header += "# TODO: replace st.nothing() with appropriate strategies\n\n" |
| 1099 |
return black.format_str(header + body, mode=black.Mode()) |
| 1100 |
|
| 1101 |
|
| 1102 |
def _is_probably_ufunc(obj): |
| 1103 |
# See https://numpy.org/doc/stable/reference/ufuncs.html - there doesn't seem |
| 1104 |
# to be an upstream function to detect this, so we just guess. |
| 1105 |
has_attributes = [ |
| 1106 |
"nin", |
| 1107 |
"nout", |
| 1108 |
"nargs", |
| 1109 |
"ntypes", |
| 1110 |
"types", |
| 1111 |
"identity", |
| 1112 |
"signature", |
| 1113 |
] |
| 1114 |
return callable(obj) and all(hasattr(obj, name) for name in has_attributes) |
| 1115 |
|
| 1116 |
|
| 1117 |
# If we have a pair of functions where one name matches the regex and the second |
| 1118 |
# is the result of formatting the template with matched groups, our magic() |
| 1119 |
# ghostwriter will write a roundtrip test for them. Additional patterns welcome. |
| 1120 |
ROUNDTRIP_PAIRS = ( |
| 1121 |
# Defined prefix, shared postfix. The easy cases. |
| 1122 |
(r"write(.+)", "read{}"), |
| 1123 |
(r"save(.+)", "load{}"), |
| 1124 |
(r"dump(.+)", "load{}"), |
| 1125 |
(r"to(.+)", "from{}"), |
| 1126 |
# Known stem, maybe matching prefixes, maybe matching postfixes. |
| 1127 |
(r"(.*)en(.+)", "{}de{}"), |
| 1128 |
# Shared postfix, prefix only on "inverse" function |
| 1129 |
(r"(.+)", "de{}"), |
| 1130 |
(r"(?!safe)(.+)", "un{}"), # safe_load / unsafe_load isn't a roundtrip |
| 1131 |
# a2b_postfix and b2a_postfix. Not a fan of this pattern, but it's pretty |
| 1132 |
# common in code imitating an C API - see e.g. the stdlib binascii module. |
| 1133 |
(r"(.+)2(.+?)(_.+)?", "{1}2{0}{2}"), |
| 1134 |
# Common in e.g. the colorsys module |
| 1135 |
(r"(.+)_to_(.+)", "{1}_to_{0}"), |
| 1136 |
# Sockets patterns |
| 1137 |
(r"(inet|if)_(.+)to(.+)", "{0}_{2}to{1}"), |
| 1138 |
(r"(\w)to(\w)(.+)", "{1}to{0}{2}"), |
| 1139 |
(r"send(.+)", "recv{}"), |
| 1140 |
(r"send(.+)", "receive{}"), |
| 1141 |
) |
| 1142 |
|
| 1143 |
|
| 1144 |
def _get_testable_functions(thing: object) -> dict[str, Callable]: |
| 1145 |
by_name = {} |
| 1146 |
if callable(thing): |
| 1147 |
funcs: list[Any | None] = [thing] |
| 1148 |
elif isinstance(thing, types.ModuleType): |
| 1149 |
if hasattr(thing, "__all__"): |
| 1150 |
funcs = [getattr(thing, name, None) for name in thing.__all__] |
| 1151 |
elif hasattr(thing, "__package__"): |
| 1152 |
pkg = thing.__package__ |
| 1153 |
funcs = [ |
| 1154 |
v |
| 1155 |
for k, v in vars(thing).items() |
| 1156 |
if callable(v) |
| 1157 |
and not is_mock(v) |
| 1158 |
and ((not pkg) or getattr(v, "__module__", pkg).startswith(pkg)) |
| 1159 |
and not k.startswith("_") |
| 1160 |
] |
| 1161 |
if pkg and any(getattr(f, "__module__", pkg) == pkg for f in funcs): |
| 1162 |
funcs = [f for f in funcs if getattr(f, "__module__", pkg) == pkg] |
| 1163 |
else: |
| 1164 |
raise InvalidArgument(f"Can't test non-module non-callable {thing!r}") |
| 1165 |
|
| 1166 |
for f in list(funcs): |
| 1167 |
if inspect.isclass(f): |
| 1168 |
funcs += [ |
| 1169 |
v.__get__(f) |
| 1170 |
for k, v in vars(f).items() |
| 1171 |
if hasattr(v, "__func__") and not is_mock(v) and not k.startswith("_") |
| 1172 |
] |
| 1173 |
for f in funcs: |
| 1174 |
try: |
| 1175 |
if ( |
| 1176 |
(not is_mock(f)) |
| 1177 |
and callable(f) |
| 1178 |
and _get_params(f) |
| 1179 |
and not isinstance(f, enum.EnumMeta) |
| 1180 |
): |
| 1181 |
if getattr(thing, "__name__", None): |
| 1182 |
if inspect.isclass(thing): |
| 1183 |
KNOWN_FUNCTION_LOCATIONS[f] = _get_module_helper(thing) |
| 1184 |
elif isinstance(thing, types.ModuleType): |
| 1185 |
KNOWN_FUNCTION_LOCATIONS[f] = thing.__name__ |
| 1186 |
try: |
| 1187 |
_get_params(f) |
| 1188 |
by_name[_get_qualname(f, include_module=True)] = f |
| 1189 |
except Exception: |
| 1190 |
# usually inspect.signature on C code such as socket.inet_aton, |
| 1191 |
# or Pandas 'CallableDynamicDoc' object has no attr. '__name__' |
| 1192 |
pass |
| 1193 |
except (TypeError, ValueError): |
| 1194 |
pass |
| 1195 |
return by_name |
| 1196 |
|
| 1197 |
|
| 1198 |
def magic( |
| 1199 |
*modules_or_functions: Callable | types.ModuleType, |
| 1200 |
except_: Except = (), |
| 1201 |
style: str = "pytest", |
| 1202 |
annotate: bool | None = None, |
| 1203 |
) -> str: |
| 1204 |
"""Guess which ghostwriters to use, for a module or collection of functions. |
| 1205 |
|
| 1206 |
As for all ghostwriters, the ``except_`` argument should be an |
| 1207 |
:class:`python:Exception` or tuple of exceptions, and ``style`` may be either |
| 1208 |
``"pytest"`` to write test functions or ``"unittest"`` to write test methods |
| 1209 |
and :class:`~python:unittest.TestCase`. |
| 1210 |
|
| 1211 |
After finding the public functions attached to any modules, the ``magic`` |
| 1212 |
ghostwriter looks for pairs of functions to pass to :func:`~roundtrip`, |
| 1213 |
then checks for :func:`~binary_operation` and :func:`~ufunc` functions, |
| 1214 |
and any others are passed to :func:`~fuzz`. |
| 1215 |
|
| 1216 |
For example, try :command:`hypothesis write gzip` on the command line! |
| 1217 |
""" |
| 1218 |
except_ = _check_except(except_) |
| 1219 |
_check_style(style) |
| 1220 |
if not modules_or_functions: |
| 1221 |
raise InvalidArgument("Must pass at least one function or module to test.") |
| 1222 |
|
| 1223 |
parts = [] |
| 1224 |
by_name = {} |
| 1225 |
imports = set() |
| 1226 |
|
| 1227 |
for thing in modules_or_functions: |
| 1228 |
by_name.update(found := _get_testable_functions(thing)) |
| 1229 |
if (not found) and isinstance(thing, types.ModuleType): |
| 1230 |
msg = f"# Found no testable functions in {thing.__name__} (from {thing.__file__!r})" |
| 1231 |
mods: list = [] |
| 1232 |
for k in sorted(sys.modules, key=len): |
| 1233 |
if ( |
| 1234 |
k.startswith(f"{thing.__name__}.") |
| 1235 |
and "._" not in k.removeprefix(thing.__name__) |
| 1236 |
and not k.startswith(tuple(f"{m}." for m in mods)) |
| 1237 |
and _get_testable_functions(sys.modules[k]) |
| 1238 |
): |
| 1239 |
mods.append(k) |
| 1240 |
if mods: |
| 1241 |
msg += ( |
| 1242 |
f"\n# Try writing tests for submodules, e.g. by using:\n" |
| 1243 |
f"# hypothesis write {' '.join(sorted(mods))}" |
| 1244 |
) |
| 1245 |
parts.append(msg) |
| 1246 |
|
| 1247 |
if not by_name: |
| 1248 |
return "\n\n".join(parts) |
| 1249 |
|
| 1250 |
if annotate is None: |
| 1251 |
annotate = _are_annotations_used(*by_name.values()) |
| 1252 |
|
| 1253 |
def make_(how, *args, **kwargs): |
| 1254 |
imp, body = how(*args, **kwargs, except_=except_, style=style) |
| 1255 |
imports.update(imp) |
| 1256 |
parts.append(body) |
| 1257 |
|
| 1258 |
# Look for pairs of functions that roundtrip, based on known naming patterns. |
| 1259 |
for writename, readname in ROUNDTRIP_PAIRS: |
| 1260 |
for name in sorted(by_name): |
| 1261 |
match = re.fullmatch(writename, name.split(".")[-1]) |
| 1262 |
if match: |
| 1263 |
inverse_name = readname.format(*match.groups()) |
| 1264 |
for other in sorted( |
| 1265 |
n for n in by_name if n.split(".")[-1] == inverse_name |
| 1266 |
): |
| 1267 |
make_( |
| 1268 |
_make_roundtrip_body, |
| 1269 |
(by_name.pop(name), by_name.pop(other)), |
| 1270 |
annotate=annotate, |
| 1271 |
) |
| 1272 |
break |
| 1273 |
else: |
| 1274 |
try: |
| 1275 |
other_func = getattr( |
| 1276 |
sys.modules[_get_module(by_name[name])], |
| 1277 |
inverse_name, |
| 1278 |
) |
| 1279 |
_get_params(other_func) # we want to skip if this fails |
| 1280 |
except Exception: |
| 1281 |
pass |
| 1282 |
else: |
| 1283 |
make_( |
| 1284 |
_make_roundtrip_body, |
| 1285 |
(by_name.pop(name), other_func), |
| 1286 |
annotate=annotate, |
| 1287 |
) |
| 1288 |
|
| 1289 |
# Look for equivalent functions: same name, all required arguments of any can |
| 1290 |
# be found in all signatures, and if all have return-type annotations they match. |
| 1291 |
names = defaultdict(list) |
| 1292 |
for _, f in sorted(by_name.items()): |
| 1293 |
names[_get_qualname(f)].append(f) |
| 1294 |
for group in names.values(): |
| 1295 |
if len(group) >= 2 and len({frozenset(_get_params(f)) for f in group}) == 1: |
| 1296 |
sentinel = object() |
| 1297 |
returns = {get_type_hints(f).get("return", sentinel) for f in group} |
| 1298 |
if len(returns - {sentinel}) <= 1: |
| 1299 |
make_(_make_equiv_body, group, annotate=annotate) |
| 1300 |
for f in group: |
| 1301 |
by_name.pop(_get_qualname(f, include_module=True)) |
| 1302 |
|
| 1303 |
# Look for binary operators - functions with two identically-typed arguments, |
| 1304 |
# and the same return type. The latter restriction might be lifted later. |
| 1305 |
for name, func in sorted(by_name.items()): |
| 1306 |
hints = get_type_hints(func) |
| 1307 |
hints.pop("return", None) |
| 1308 |
params = _get_params(func) |
| 1309 |
if (len(hints) == len(params) == 2) or ( |
| 1310 |
_get_module(func) == "operator" |
| 1311 |
and "item" not in func.__name__ |
| 1312 |
and tuple(params) in [("a", "b"), ("x", "y")] |
| 1313 |
): |
| 1314 |
a, b = hints.values() or [Any, Any] |
| 1315 |
arg1, arg2 = params |
| 1316 |
if a == b and len(arg1) == len(arg2) <= 3: |
| 1317 |
# https://en.wikipedia.org/wiki/Distributive_property#Other_examples |
| 1318 |
known = { |
| 1319 |
"mul": "add", |
| 1320 |
"matmul": "add", |
| 1321 |
"or_": "and_", |
| 1322 |
"and_": "or_", |
| 1323 |
}.get(func.__name__, "") |
| 1324 |
distributes_over = getattr(sys.modules[_get_module(func)], known, None) |
| 1325 |
make_( |
| 1326 |
_make_binop_body, |
| 1327 |
func, |
| 1328 |
commutative=func.__name__ != "matmul", |
| 1329 |
distributes_over=distributes_over, |
| 1330 |
annotate=annotate, |
| 1331 |
) |
| 1332 |
del by_name[name] |
| 1333 |
|
| 1334 |
# Look for Numpy ufuncs or gufuncs, and write array-oriented tests for them. |
| 1335 |
if "numpy" in sys.modules: |
| 1336 |
for name, func in sorted(by_name.items()): |
| 1337 |
if _is_probably_ufunc(func): |
| 1338 |
make_(_make_ufunc_body, func, annotate=annotate) |
| 1339 |
del by_name[name] |
| 1340 |
|
| 1341 |
# For all remaining callables, just write a fuzz-test. In principle we could |
| 1342 |
# guess at equivalence or idempotence; but it doesn't seem accurate enough to |
| 1343 |
# be worth the trouble when it's so easy for the user to specify themselves. |
| 1344 |
for _, f in sorted(by_name.items()): |
| 1345 |
make_( |
| 1346 |
_make_test_body, |
| 1347 |
f, |
| 1348 |
test_body=_write_call(f, except_=except_), |
| 1349 |
ghost="fuzz", |
| 1350 |
annotate=annotate, |
| 1351 |
) |
| 1352 |
return _make_test(imports, "\n".join(parts)) |
| 1353 |
|
| 1354 |
|
| 1355 |
def fuzz( |
| 1356 |
func: Callable, |
| 1357 |
*, |
| 1358 |
except_: Except = (), |
| 1359 |
style: str = "pytest", |
| 1360 |
annotate: bool | None = None, |
| 1361 |
) -> str: |
| 1362 |
"""Write source code for a property-based test of ``func``. |
| 1363 |
|
| 1364 |
The resulting test checks that valid input only leads to expected exceptions. |
| 1365 |
For example: |
| 1366 |
|
| 1367 |
.. code-block:: python |
| 1368 |
|
| 1369 |
from re import compile, error |
| 1370 |
|
| 1371 |
from hypothesis.extra import ghostwriter |
| 1372 |
|
| 1373 |
ghostwriter.fuzz(compile, except_=error) |
| 1374 |
|
| 1375 |
Gives: |
| 1376 |
|
| 1377 |
.. code-block:: python |
| 1378 |
|
| 1379 |
# This test code was written by the `hypothesis.extra.ghostwriter` module |
| 1380 |
# and is provided under the Creative Commons Zero public domain dedication. |
| 1381 |
import re |
| 1382 |
|
| 1383 |
from hypothesis import given, reject, strategies as st |
| 1384 |
|
| 1385 |
# TODO: replace st.nothing() with an appropriate strategy |
| 1386 |
|
| 1387 |
|
| 1388 |
@given(pattern=st.nothing(), flags=st.just(0)) |
| 1389 |
def test_fuzz_compile(pattern, flags): |
| 1390 |
try: |
| 1391 |
re.compile(pattern=pattern, flags=flags) |
| 1392 |
except re.error: |
| 1393 |
reject() |
| 1394 |
|
| 1395 |
Note that it includes all the required imports. |
| 1396 |
Because the ``pattern`` parameter doesn't have annotations or a default argument, |
| 1397 |
you'll need to specify a strategy - for example :func:`~hypothesis.strategies.text` |
| 1398 |
or :func:`~hypothesis.strategies.binary`. After that, you have a test! |
| 1399 |
""" |
| 1400 |
if not callable(func): |
| 1401 |
raise InvalidArgument(f"Got non-callable {func=}") |
| 1402 |
except_ = _check_except(except_) |
| 1403 |
_check_style(style) |
| 1404 |
|
| 1405 |
if annotate is None: |
| 1406 |
annotate = _are_annotations_used(func) |
| 1407 |
|
| 1408 |
imports, body = _make_test_body( |
| 1409 |
func, |
| 1410 |
test_body=_write_call(func, except_=except_), |
| 1411 |
except_=except_, |
| 1412 |
ghost="fuzz", |
| 1413 |
style=style, |
| 1414 |
annotate=annotate, |
| 1415 |
) |
| 1416 |
return _make_test(imports, body) |
| 1417 |
|
| 1418 |
|
| 1419 |
def idempotent( |
| 1420 |
func: Callable, |
| 1421 |
*, |
| 1422 |
except_: Except = (), |
| 1423 |
style: str = "pytest", |
| 1424 |
annotate: bool | None = None, |
| 1425 |
) -> str: |
| 1426 |
"""Write source code for a property-based test of ``func``. |
| 1427 |
|
| 1428 |
The resulting test checks that if you call ``func`` on it's own output, |
| 1429 |
the result does not change. For example: |
| 1430 |
|
| 1431 |
.. code-block:: python |
| 1432 |
|
| 1433 |
from typing import Sequence |
| 1434 |
|
| 1435 |
from hypothesis.extra import ghostwriter |
| 1436 |
|
| 1437 |
|
| 1438 |
def timsort(seq: Sequence[int]) -> Sequence[int]: |
| 1439 |
return sorted(seq) |
| 1440 |
|
| 1441 |
|
| 1442 |
ghostwriter.idempotent(timsort) |
| 1443 |
|
| 1444 |
Gives: |
| 1445 |
|
| 1446 |
.. code-block:: python |
| 1447 |
|
| 1448 |
# This test code was written by the `hypothesis.extra.ghostwriter` module |
| 1449 |
# and is provided under the Creative Commons Zero public domain dedication. |
| 1450 |
|
| 1451 |
from hypothesis import given, strategies as st |
| 1452 |
|
| 1453 |
|
| 1454 |
@given(seq=st.one_of(st.binary(), st.binary().map(bytearray), st.lists(st.integers()))) |
| 1455 |
def test_idempotent_timsort(seq): |
| 1456 |
result = timsort(seq=seq) |
| 1457 |
repeat = timsort(seq=result) |
| 1458 |
assert result == repeat, (result, repeat) |
| 1459 |
""" |
| 1460 |
if not callable(func): |
| 1461 |
raise InvalidArgument(f"Got non-callable {func=}") |
| 1462 |
except_ = _check_except(except_) |
| 1463 |
_check_style(style) |
| 1464 |
|
| 1465 |
if annotate is None: |
| 1466 |
annotate = _are_annotations_used(func) |
| 1467 |
|
| 1468 |
imports, body = _make_test_body( |
| 1469 |
func, |
| 1470 |
test_body="result = {}\nrepeat = {}".format( |
| 1471 |
_write_call(func, except_=except_), |
| 1472 |
_write_call(func, "result", except_=except_), |
| 1473 |
), |
| 1474 |
except_=except_, |
| 1475 |
assertions=_assert_eq(style, "result", "repeat"), |
| 1476 |
ghost="idempotent", |
| 1477 |
style=style, |
| 1478 |
annotate=annotate, |
| 1479 |
) |
| 1480 |
return _make_test(imports, body) |
| 1481 |
|
| 1482 |
|
| 1483 |
def _make_roundtrip_body(funcs, except_, style, annotate): |
| 1484 |
first_param = next(iter(_get_params(funcs[0]))) |
| 1485 |
test_lines = [ |
| 1486 |
_write_call(funcs[0], assign="value0", except_=except_), |
| 1487 |
*( |
| 1488 |
_write_call(f, f"value{i}", assign=f"value{i + 1}", except_=except_) |
| 1489 |
for i, f in enumerate(funcs[1:]) |
| 1490 |
), |
| 1491 |
] |
| 1492 |
return _make_test_body( |
| 1493 |
*funcs, |
| 1494 |
test_body="\n".join(test_lines), |
| 1495 |
except_=except_, |
| 1496 |
assertions=_assert_eq(style, first_param, f"value{len(funcs) - 1}"), |
| 1497 |
ghost="roundtrip", |
| 1498 |
style=style, |
| 1499 |
annotate=annotate, |
| 1500 |
) |
| 1501 |
|
| 1502 |
|
| 1503 |
def roundtrip( |
| 1504 |
*funcs: Callable, |
| 1505 |
except_: Except = (), |
| 1506 |
style: str = "pytest", |
| 1507 |
annotate: bool | None = None, |
| 1508 |
) -> str: |
| 1509 |
"""Write source code for a property-based test of ``funcs``. |
| 1510 |
|
| 1511 |
The resulting test checks that if you call the first function, pass the result |
| 1512 |
to the second (and so on), the final result is equal to the first input argument. |
| 1513 |
|
| 1514 |
This is a *very* powerful property to test, especially when the config options |
| 1515 |
are varied along with the object to round-trip. For example, try ghostwriting |
| 1516 |
a test for :func:`python:json.dumps` - would you have thought of all that? |
| 1517 |
|
| 1518 |
.. code-block:: shell |
| 1519 |
|
| 1520 |
hypothesis write --roundtrip json.dumps json.loads |
| 1521 |
""" |
| 1522 |
if not funcs: |
| 1523 |
raise InvalidArgument("Round-trip of zero functions is meaningless.") |
| 1524 |
for i, f in enumerate(funcs): |
| 1525 |
if not callable(f): |
| 1526 |
raise InvalidArgument(f"Got non-callable funcs[{i}]={f!r}") |
| 1527 |
except_ = _check_except(except_) |
| 1528 |
_check_style(style) |
| 1529 |
|
| 1530 |
if annotate is None: |
| 1531 |
annotate = _are_annotations_used(*funcs) |
| 1532 |
|
| 1533 |
return _make_test(*_make_roundtrip_body(funcs, except_, style, annotate)) |
| 1534 |
|
| 1535 |
|
| 1536 |
def _get_varnames(funcs): |
| 1537 |
var_names = [f"result_{f.__name__}" for f in funcs] |
| 1538 |
if len(set(var_names)) < len(var_names): |
| 1539 |
var_names = [f"result_{f.__name__}_{_get_module(f)}" for f in funcs] |
| 1540 |
if len(set(var_names)) < len(var_names): |
| 1541 |
var_names = [f"result_{i}_{f.__name__}" for i, f in enumerate(funcs)] |
| 1542 |
return var_names |
| 1543 |
|
| 1544 |
|
| 1545 |
def _make_equiv_body(funcs, except_, style, annotate): |
| 1546 |
var_names = _get_varnames(funcs) |
| 1547 |
test_lines = [ |
| 1548 |
_write_call(f, assign=vname, except_=except_) |
| 1549 |
for vname, f in zip(var_names, funcs, strict=True) |
| 1550 |
] |
| 1551 |
assertions = "\n".join( |
| 1552 |
_assert_eq(style, var_names[0], vname) for vname in var_names[1:] |
| 1553 |
) |
| 1554 |
|
| 1555 |
return _make_test_body( |
| 1556 |
*funcs, |
| 1557 |
test_body="\n".join(test_lines), |
| 1558 |
except_=except_, |
| 1559 |
assertions=assertions, |
| 1560 |
ghost="equivalent", |
| 1561 |
style=style, |
| 1562 |
annotate=annotate, |
| 1563 |
) |
| 1564 |
|
| 1565 |
|
| 1566 |
EQUIV_FIRST_BLOCK = """ |
| 1567 |
try: |
| 1568 |
{} |
| 1569 |
exc_type = None |
| 1570 |
target(1, label="input was valid") |
| 1571 |
{}except Exception as exc: |
| 1572 |
exc_type = type(exc) |
| 1573 |
""".strip() |
| 1574 |
|
| 1575 |
EQUIV_CHECK_BLOCK = """ |
| 1576 |
if exc_type: |
| 1577 |
with {ctx}(exc_type): |
| 1578 |
{check_raises} |
| 1579 |
else: |
| 1580 |
{call} |
| 1581 |
{compare} |
| 1582 |
""".rstrip() |
| 1583 |
|
| 1584 |
|
| 1585 |
def _make_equiv_errors_body(funcs, except_, style, annotate): |
| 1586 |
var_names = _get_varnames(funcs) |
| 1587 |
first, *rest = funcs |
| 1588 |
first_call = _write_call(first, assign=var_names[0], except_=except_) |
| 1589 |
extra_imports, suppress = _exception_string(except_) |
| 1590 |
extra_imports.add(("hypothesis", "target")) |
| 1591 |
catch = f"except {suppress}:\n reject()\n" if suppress else "" |
| 1592 |
test_lines = [EQUIV_FIRST_BLOCK.format(indent(first_call, prefix=" "), catch)] |
| 1593 |
|
| 1594 |
for vname, f in zip(var_names[1:], rest, strict=True): |
| 1595 |
if style == "pytest": |
| 1596 |
ctx = "pytest.raises" |
| 1597 |
extra_imports.add("pytest") |
| 1598 |
else: |
| 1599 |
assert style == "unittest" |
| 1600 |
ctx = "self.assertRaises" |
| 1601 |
block = EQUIV_CHECK_BLOCK.format( |
| 1602 |
ctx=ctx, |
| 1603 |
check_raises=indent(_write_call(f, except_=()), " "), |
| 1604 |
call=indent(_write_call(f, assign=vname, except_=()), " "), |
| 1605 |
compare=indent(_assert_eq(style, var_names[0], vname), " "), |
| 1606 |
) |
| 1607 |
test_lines.append(block) |
| 1608 |
|
| 1609 |
imports, source_code = _make_test_body( |
| 1610 |
*funcs, |
| 1611 |
test_body="\n".join(test_lines), |
| 1612 |
except_=(), |
| 1613 |
ghost="equivalent", |
| 1614 |
style=style, |
| 1615 |
annotate=annotate, |
| 1616 |
) |
| 1617 |
return imports | extra_imports, source_code |
| 1618 |
|
| 1619 |
|
| 1620 |
def equivalent( |
| 1621 |
*funcs: Callable, |
| 1622 |
allow_same_errors: bool = False, |
| 1623 |
except_: Except = (), |
| 1624 |
style: str = "pytest", |
| 1625 |
annotate: bool | None = None, |
| 1626 |
) -> str: |
| 1627 |
"""Write source code for a property-based test of ``funcs``. |
| 1628 |
|
| 1629 |
The resulting test checks that calling each of the functions returns |
| 1630 |
an equal value. This can be used as a classic 'oracle', such as testing |
| 1631 |
a fast sorting algorithm against the :func:`python:sorted` builtin, or |
| 1632 |
for differential testing where none of the compared functions are fully |
| 1633 |
trusted but any difference indicates a bug (e.g. running a function on |
| 1634 |
different numbers of threads, or simply multiple times). |
| 1635 |
|
| 1636 |
The functions should have reasonably similar signatures, as only the |
| 1637 |
common parameters will be passed the same arguments - any other parameters |
| 1638 |
will be allowed to vary. |
| 1639 |
|
| 1640 |
If allow_same_errors is True, then the test will pass if calling each of |
| 1641 |
the functions returns an equal value, *or* if the first function raises an |
| 1642 |
exception and each of the others raises an exception of the same type. |
| 1643 |
This relaxed mode can be useful for code synthesis projects. |
| 1644 |
""" |
| 1645 |
if len(funcs) < 2: |
| 1646 |
raise InvalidArgument("Need at least two functions to compare.") |
| 1647 |
for i, f in enumerate(funcs): |
| 1648 |
if not callable(f): |
| 1649 |
raise InvalidArgument(f"Got non-callable funcs[{i}]={f!r}") |
| 1650 |
check_type(bool, allow_same_errors, "allow_same_errors") |
| 1651 |
except_ = _check_except(except_) |
| 1652 |
_check_style(style) |
| 1653 |
|
| 1654 |
if annotate is None: |
| 1655 |
annotate = _are_annotations_used(*funcs) |
| 1656 |
|
| 1657 |
if allow_same_errors and not any(issubclass(Exception, ex) for ex in except_): |
| 1658 |
imports, source_code = _make_equiv_errors_body(funcs, except_, style, annotate) |
| 1659 |
else: |
| 1660 |
imports, source_code = _make_equiv_body(funcs, except_, style, annotate) |
| 1661 |
return _make_test(imports, source_code) |
| 1662 |
|
| 1663 |
|
| 1664 |
X = TypeVar("X") |
| 1665 |
Y = TypeVar("Y") |
| 1666 |
|
| 1667 |
|
| 1668 |
def binary_operation( |
| 1669 |
func: Callable[[X, X], Y], |
| 1670 |
*, |
| 1671 |
associative: bool = True, |
| 1672 |
commutative: bool = True, |
| 1673 |
identity: X | EllipsisType | None = ..., |
| 1674 |
distributes_over: Callable[[X, X], X] | None = None, |
| 1675 |
except_: Except = (), |
| 1676 |
style: str = "pytest", |
| 1677 |
annotate: bool | None = None, |
| 1678 |
) -> str: |
| 1679 |
"""Write property tests for the binary operation ``func``. |
| 1680 |
|
| 1681 |
While :wikipedia:`binary operations <Binary_operation>` are not particularly |
| 1682 |
common, they have such nice properties to test that it seems a shame not to |
| 1683 |
demonstrate them with a ghostwriter. For an operator ``f``, test that: |
| 1684 |
|
| 1685 |
- if :wikipedia:`associative <Associative_property>`, |
| 1686 |
``f(a, f(b, c)) == f(f(a, b), c)`` |
| 1687 |
- if :wikipedia:`commutative <Commutative_property>`, ``f(a, b) == f(b, a)`` |
| 1688 |
- if :wikipedia:`identity <Identity_element>` is not None, ``f(a, identity) == a`` |
| 1689 |
- if :wikipedia:`distributes_over <Distributive_property>` is ``+``, |
| 1690 |
``f(a, b) + f(a, c) == f(a, b+c)`` |
| 1691 |
|
| 1692 |
For example: |
| 1693 |
|
| 1694 |
.. code-block:: python |
| 1695 |
|
| 1696 |
ghostwriter.binary_operation( |
| 1697 |
operator.mul, |
| 1698 |
identity=1, |
| 1699 |
distributes_over=operator.add, |
| 1700 |
style="unittest", |
| 1701 |
) |
| 1702 |
""" |
| 1703 |
if not callable(func): |
| 1704 |
raise InvalidArgument(f"Got non-callable {func=}") |
| 1705 |
except_ = _check_except(except_) |
| 1706 |
_check_style(style) |
| 1707 |
check_type(bool, associative, "associative") |
| 1708 |
check_type(bool, commutative, "commutative") |
| 1709 |
if distributes_over is not None and not callable(distributes_over): |
| 1710 |
raise InvalidArgument( |
| 1711 |
f"{distributes_over=} must be an operation which " |
| 1712 |
f"distributes over {func.__name__}" |
| 1713 |
) |
| 1714 |
if not any([associative, commutative, identity, distributes_over]): |
| 1715 |
raise InvalidArgument( |
| 1716 |
"You must select at least one property of the binary operation to test." |
| 1717 |
) |
| 1718 |
|
| 1719 |
if annotate is None: |
| 1720 |
annotate = _are_annotations_used(func) |
| 1721 |
|
| 1722 |
imports, body = _make_binop_body( |
| 1723 |
func, |
| 1724 |
associative=associative, |
| 1725 |
commutative=commutative, |
| 1726 |
identity=identity, |
| 1727 |
distributes_over=distributes_over, |
| 1728 |
except_=except_, |
| 1729 |
style=style, |
| 1730 |
annotate=annotate, |
| 1731 |
) |
| 1732 |
return _make_test(imports, body) |
| 1733 |
|
| 1734 |
|
| 1735 |
def _make_binop_body( |
| 1736 |
func: Callable[[X, X], Y], |
| 1737 |
*, |
| 1738 |
associative: bool = True, |
| 1739 |
commutative: bool = True, |
| 1740 |
identity: X | EllipsisType | None = ..., |
| 1741 |
distributes_over: Callable[[X, X], X] | None = None, |
| 1742 |
except_: tuple[type[Exception], ...], |
| 1743 |
style: str, |
| 1744 |
annotate: bool, |
| 1745 |
) -> tuple[ImportSet, str]: |
| 1746 |
strategies = _get_strategies(func) |
| 1747 |
operands, b = (strategies.pop(p) for p in list(_get_params(func))[:2]) |
| 1748 |
if repr(operands) != repr(b): |
| 1749 |
operands |= b |
| 1750 |
operands_name = func.__name__ + "_operands" |
| 1751 |
|
| 1752 |
all_imports = set() |
| 1753 |
parts = [] |
| 1754 |
|
| 1755 |
def maker( |
| 1756 |
sub_property: str, |
| 1757 |
args: str, |
| 1758 |
body: str, |
| 1759 |
right: str | None = None, |
| 1760 |
) -> None: |
| 1761 |
if right is None: |
| 1762 |
assertions = "" |
| 1763 |
else: |
| 1764 |
body = f"{body}\n{right}" |
| 1765 |
assertions = _assert_eq(style, "left", "right") |
| 1766 |
imports, body = _make_test_body( |
| 1767 |
func, |
| 1768 |
test_body=body, |
| 1769 |
ghost=sub_property + "_binary_operation", |
| 1770 |
except_=except_, |
| 1771 |
assertions=assertions, |
| 1772 |
style=style, |
| 1773 |
given_strategies={**strategies, **{n: operands_name for n in args}}, |
| 1774 |
annotate=annotate, |
| 1775 |
) |
| 1776 |
all_imports.update(imports) |
| 1777 |
if style == "unittest": |
| 1778 |
endline = "(unittest.TestCase):\n" |
| 1779 |
body = body[body.index(endline) + len(endline) + 1 :] |
| 1780 |
parts.append(body) |
| 1781 |
|
| 1782 |
if associative: |
| 1783 |
maker( |
| 1784 |
"associative", |
| 1785 |
"abc", |
| 1786 |
_write_call(func, "a", _write_call(func, "b", "c"), assign="left"), |
| 1787 |
_write_call( |
| 1788 |
func, |
| 1789 |
_write_call(func, "a", "b"), |
| 1790 |
"c", |
| 1791 |
assign="right", |
| 1792 |
), |
| 1793 |
) |
| 1794 |
if commutative: |
| 1795 |
maker( |
| 1796 |
"commutative", |
| 1797 |
"ab", |
| 1798 |
_write_call(func, "a", "b", assign="left"), |
| 1799 |
_write_call(func, "b", "a", assign="right"), |
| 1800 |
) |
| 1801 |
if identity is not None: |
| 1802 |
# Guess that the identity element is the minimal example from our operands |
| 1803 |
# strategy. This is correct often enough to be worthwhile, and close enough |
| 1804 |
# that it's a good starting point to edit much of the rest. |
| 1805 |
if identity is ...: |
| 1806 |
try: |
| 1807 |
identity = find(operands, lambda x: True, settings=_quietly_settings) |
| 1808 |
except Exception: |
| 1809 |
identity = "identity element here" # type: ignore |
| 1810 |
# If the repr of this element is invalid Python, stringify it - this |
| 1811 |
# can't be executed as-is, but at least makes it clear what should |
| 1812 |
# happen. E.g. type(None) -> <class 'NoneType'> -> quoted. |
| 1813 |
try: |
| 1814 |
# We don't actually execute this code object; we're just compiling |
| 1815 |
# to check that the repr is syntactically valid. HOWEVER, we're |
| 1816 |
# going to output that code string into test code which will be |
| 1817 |
# executed; so you still shouldn't ghostwrite for hostile code. |
| 1818 |
compile(repr(identity), "<string>", "exec") |
| 1819 |
except SyntaxError: |
| 1820 |
identity = repr(identity) # type: ignore |
| 1821 |
identity_parts = [ |
| 1822 |
f"{identity = }", |
| 1823 |
_assert_eq( |
| 1824 |
style, |
| 1825 |
"a", |
| 1826 |
_write_call(func, "a", "identity"), |
| 1827 |
), |
| 1828 |
_assert_eq( |
| 1829 |
style, |
| 1830 |
"a", |
| 1831 |
_write_call(func, "identity", "a"), |
| 1832 |
), |
| 1833 |
] |
| 1834 |
maker("identity", "a", "\n".join(identity_parts)) |
| 1835 |
if distributes_over: |
| 1836 |
do = distributes_over |
| 1837 |
dist_parts = [ |
| 1838 |
_write_call(func, "a", _write_call(do, "b", "c"), assign="left"), |
| 1839 |
_write_call( |
| 1840 |
do, |
| 1841 |
_write_call(func, "a", "b"), |
| 1842 |
_write_call(func, "a", "c"), |
| 1843 |
assign="ldist", |
| 1844 |
), |
| 1845 |
_assert_eq(style, "ldist", "left"), |
| 1846 |
"\n", |
| 1847 |
_write_call(func, _write_call(do, "a", "b"), "c", assign="right"), |
| 1848 |
_write_call( |
| 1849 |
do, |
| 1850 |
_write_call(func, "a", "c"), |
| 1851 |
_write_call(func, "b", "c"), |
| 1852 |
assign="rdist", |
| 1853 |
), |
| 1854 |
_assert_eq(style, "rdist", "right"), |
| 1855 |
] |
| 1856 |
maker(do.__name__ + "_distributes_over", "abc", "\n".join(dist_parts)) |
| 1857 |
|
| 1858 |
operands_imports, operands_repr = _valid_syntax_repr(operands) |
| 1859 |
all_imports.update(operands_imports) |
| 1860 |
operands_repr = _st_strategy_names(operands_repr) |
| 1861 |
classdef = "" |
| 1862 |
if style == "unittest": |
| 1863 |
classdef = f"class TestBinaryOperation{func.__name__}(unittest.TestCase):\n " |
| 1864 |
return ( |
| 1865 |
all_imports, |
| 1866 |
classdef + f"{operands_name} = {operands_repr}\n" + "\n".join(parts), |
| 1867 |
) |
| 1868 |
|
| 1869 |
|
| 1870 |
def ufunc( |
| 1871 |
func: Callable, |
| 1872 |
*, |
| 1873 |
except_: Except = (), |
| 1874 |
style: str = "pytest", |
| 1875 |
annotate: bool | None = None, |
| 1876 |
) -> str: |
| 1877 |
"""Write a property-based test for the :doc:`array ufunc <numpy:reference/ufuncs>` ``func``. |
| 1878 |
|
| 1879 |
The resulting test checks that your ufunc or :doc:`gufunc |
| 1880 |
<numpy:reference/c-api/generalized-ufuncs>` has the expected broadcasting and dtype casting |
| 1881 |
behaviour. You will probably want to add extra assertions, but as with the other |
| 1882 |
ghostwriters this gives you a great place to start. |
| 1883 |
|
| 1884 |
.. code-block:: shell |
| 1885 |
|
| 1886 |
hypothesis write numpy.matmul |
| 1887 |
""" |
| 1888 |
if not _is_probably_ufunc(func): |
| 1889 |
raise InvalidArgument(f"{func=} does not seem to be a ufunc") |
| 1890 |
except_ = _check_except(except_) |
| 1891 |
_check_style(style) |
| 1892 |
|
| 1893 |
if annotate is None: |
| 1894 |
annotate = _are_annotations_used(func) |
| 1895 |
|
| 1896 |
return _make_test( |
| 1897 |
*_make_ufunc_body(func, except_=except_, style=style, annotate=annotate) |
| 1898 |
) |
| 1899 |
|
| 1900 |
|
| 1901 |
def _make_ufunc_body(func, *, except_, style, annotate): |
| 1902 |
import hypothesis.extra.numpy as npst |
| 1903 |
|
| 1904 |
if func.signature is None: |
| 1905 |
shapes = npst.mutually_broadcastable_shapes(num_shapes=func.nin) |
| 1906 |
else: |
| 1907 |
shapes = npst.mutually_broadcastable_shapes(signature=func.signature) |
| 1908 |
shapes.function.__module__ = npst.__name__ |
| 1909 |
|
| 1910 |
body = """ |
| 1911 |
input_shapes, expected_shape = shapes |
| 1912 |
input_dtypes, expected_dtype = types.split("->") |
| 1913 |
array_strats = [ |
| 1914 |
arrays(dtype=dtp, shape=shp, elements={{"allow_nan": True}}) |
| 1915 |
for dtp, shp in zip(input_dtypes, input_shapes) |
| 1916 |
] |
| 1917 |
|
| 1918 |
{array_names} = data.draw(st.tuples(*array_strats)) |
| 1919 |
result = {call} |
| 1920 |
""".format( |
| 1921 |
array_names=", ".join(ascii_lowercase[: func.nin]), |
| 1922 |
call=_write_call(func, *ascii_lowercase[: func.nin], except_=except_), |
| 1923 |
) |
| 1924 |
assertions = "\n{shape_assert}\n{type_assert}".format( |
| 1925 |
shape_assert=_assert_eq(style, "result.shape", "expected_shape"), |
| 1926 |
type_assert=_assert_eq(style, "result.dtype.char", "expected_dtype"), |
| 1927 |
) |
| 1928 |
|
| 1929 |
qname = _get_qualname(func, include_module=True) |
| 1930 |
obj_sigs = ["O" in sig for sig in func.types] |
| 1931 |
if all(obj_sigs) or not any(obj_sigs): |
| 1932 |
types = f"sampled_from({qname}.types)" |
| 1933 |
else: |
| 1934 |
types = f"sampled_from([sig for sig in {qname}.types if 'O' not in sig])" |
| 1935 |
|
| 1936 |
return _make_test_body( |
| 1937 |
func, |
| 1938 |
test_body=dedent(body).strip(), |
| 1939 |
except_=except_, |
| 1940 |
assertions=assertions, |
| 1941 |
ghost="ufunc" if func.signature is None else "gufunc", |
| 1942 |
style=style, |
| 1943 |
given_strategies={"data": st.data(), "shapes": shapes, "types": types}, |
| 1944 |
imports={("hypothesis.extra.numpy", "arrays")}, |
| 1945 |
annotate=annotate, |
| 1946 |
) |