| 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 |
Write patches which add @example() decorators for discovered test cases. |
| 13 |
|
| 14 |
Requires `hypothesis[codemods,ghostwriter]` installed, i.e. black and libcst. |
| 15 |
|
| 16 |
This module is used by Hypothesis' builtin pytest plugin for failing examples |
| 17 |
discovered during testing, and by HypoFuzz for _covering_ examples discovered |
| 18 |
during fuzzing. |
| 19 |
""" |
| 20 |
|
| 21 |
import ast |
| 22 |
import difflib |
| 23 |
import hashlib |
| 24 |
import inspect |
| 25 |
import re |
| 26 |
import sys |
| 27 |
import types |
| 28 |
from ast import literal_eval |
| 29 |
from collections.abc import Sequence |
| 30 |
from contextlib import suppress |
| 31 |
from datetime import date, datetime, timedelta, timezone |
| 32 |
from pathlib import Path |
| 33 |
from typing import Any |
| 34 |
|
| 35 |
import libcst as cst |
| 36 |
from libcst import matchers as m |
| 37 |
from libcst.codemod import CodemodContext, VisitorBasedCodemodCommand |
| 38 |
from libcst.metadata import ExpressionContext, ExpressionContextProvider |
| 39 |
|
| 40 |
from hypothesis.configuration import storage_directory |
| 41 |
from hypothesis.version import __version__ |
| 42 |
|
| 43 |
try: |
| 44 |
import black |
| 45 |
except ImportError: |
| 46 |
black = None # type: ignore |
| 47 |
|
| 48 |
HEADER = """\ |
| 49 |
From HEAD Mon Sep 17 00:00:00 2001 |
| 50 |
From: {author} |
| 51 |
Date: {when:%a, %d %b %Y %H:%M:%S} |
| 52 |
Subject: [PATCH] {msg} |
| 53 |
|
| 54 |
--- |
| 55 |
""" |
| 56 |
FAIL_MSG = "discovered failure" |
| 57 |
_space_only_re = re.compile("^ +$", re.MULTILINE) |
| 58 |
_leading_space_re = re.compile("(^[ ]*)(?:[^ \n])", re.MULTILINE) |
| 59 |
|
| 60 |
|
| 61 |
def dedent(text: str) -> tuple[str, str]: |
| 62 |
# Simplified textwrap.dedent, for valid Python source code only |
| 63 |
text = _space_only_re.sub("", text) |
| 64 |
prefix = min(_leading_space_re.findall(text), key=len) |
| 65 |
return re.sub(r"(?m)^" + prefix, "", text), prefix |
| 66 |
|
| 67 |
|
| 68 |
def indent(text: str, prefix: str) -> str: |
| 69 |
return "".join(prefix + line for line in text.splitlines(keepends=True)) |
| 70 |
|
| 71 |
|
| 72 |
class AddExamplesCodemod(VisitorBasedCodemodCommand): |
| 73 |
DESCRIPTION = "Add explicit examples to failing tests." |
| 74 |
|
| 75 |
def __init__( |
| 76 |
self, |
| 77 |
context: CodemodContext, |
| 78 |
fn_examples: dict[str, list[tuple[cst.Call, str]]], |
| 79 |
strip_via: tuple[str, ...] = (), |
| 80 |
decorator: str = "example", |
| 81 |
width: int = 88, |
| 82 |
): |
| 83 |
"""Add @example() decorator(s) for failing test(s). |
| 84 |
|
| 85 |
`code` is the source code of the module where the test functions are defined. |
| 86 |
`fn_examples` is a dict of function name to list-of-failing-examples. |
| 87 |
""" |
| 88 |
assert fn_examples, "This codemod does nothing without fn_examples." |
| 89 |
super().__init__(context) |
| 90 |
|
| 91 |
self.decorator_func = cst.parse_expression(decorator) |
| 92 |
self.line_length = width |
| 93 |
value_in_strip_via: Any = m.MatchIfTrue( |
| 94 |
lambda x: literal_eval(x.value) in strip_via |
| 95 |
) |
| 96 |
self.strip_matching = m.Call( |
| 97 |
m.Attribute(m.Call(), m.Name("via")), |
| 98 |
[m.Arg(m.SimpleString() & value_in_strip_via)], |
| 99 |
) |
| 100 |
|
| 101 |
# Codemod the failing examples to Call nodes usable as decorators |
| 102 |
self.fn_examples = { |
| 103 |
k: tuple( |
| 104 |
d |
| 105 |
for (node, via) in nodes |
| 106 |
if (d := self.__call_node_to_example_dec(node, via)) |
| 107 |
) |
| 108 |
for k, nodes in fn_examples.items() |
| 109 |
} |
| 110 |
|
| 111 |
def __call_node_to_example_dec( |
| 112 |
self, node: cst.Call, via: str |
| 113 |
) -> cst.Decorator | None: |
| 114 |
# If we have black installed, remove trailing comma, _unless_ there's a comment |
| 115 |
node = node.with_changes( |
| 116 |
func=self.decorator_func, |
| 117 |
args=( |
| 118 |
[ |
| 119 |
a.with_changes( |
| 120 |
comma=( |
| 121 |
a.comma |
| 122 |
if m.findall(a.comma, m.Comment()) |
| 123 |
else cst.MaybeSentinel.DEFAULT |
| 124 |
) |
| 125 |
) |
| 126 |
for a in node.args |
| 127 |
] |
| 128 |
if black |
| 129 |
else node.args |
| 130 |
), |
| 131 |
) |
| 132 |
via: cst.BaseExpression = cst.Call( |
| 133 |
func=cst.Attribute(node, cst.Name("via")), |
| 134 |
args=[cst.Arg(cst.SimpleString(repr(via)))], |
| 135 |
) |
| 136 |
if black: # pragma: no branch |
| 137 |
try: |
| 138 |
pretty = black.format_str( |
| 139 |
cst.Module([]).code_for_node(via), |
| 140 |
mode=black.Mode(line_length=self.line_length), |
| 141 |
) |
| 142 |
except (ImportError, AttributeError): # pragma: no cover |
| 143 |
return None # See https://github.com/psf/black/pull/4224 |
| 144 |
via = cst.parse_expression(pretty.strip()) |
| 145 |
return cst.Decorator(via) |
| 146 |
|
| 147 |
def leave_FunctionDef( |
| 148 |
self, _original_node: cst.FunctionDef, updated_node: cst.FunctionDef |
| 149 |
) -> cst.FunctionDef: |
| 150 |
return updated_node.with_changes( |
| 151 |
# TODO: improve logic for where in the list to insert this decorator |
| 152 |
decorators=tuple( |
| 153 |
d |
| 154 |
for d in updated_node.decorators |
| 155 |
# `findall()` to see through the identity function workaround on py38 |
| 156 |
if not m.findall(d, self.strip_matching) |
| 157 |
) |
| 158 |
+ self.fn_examples.get(updated_node.name.value, ()) |
| 159 |
) |
| 160 |
|
| 161 |
|
| 162 |
def get_patch_for( |
| 163 |
func: Any, |
| 164 |
examples: Sequence[tuple[str, str]], |
| 165 |
*, |
| 166 |
strip_via: tuple[str, ...] = (), |
| 167 |
) -> tuple[str, str, str] | None: |
| 168 |
# Skip this if we're unable to find the location of this function. |
| 169 |
try: |
| 170 |
module = sys.modules[func.__module__] |
| 171 |
file_path = Path(module.__file__) # type: ignore |
| 172 |
except Exception: |
| 173 |
return None |
| 174 |
|
| 175 |
fname = ( |
| 176 |
file_path.relative_to(Path.cwd()) |
| 177 |
if file_path.is_relative_to(Path.cwd()) |
| 178 |
else file_path |
| 179 |
) |
| 180 |
patch = _get_patch_for( |
| 181 |
func, examples, strip_via=strip_via, namespace=module.__dict__ |
| 182 |
) |
| 183 |
if patch is None: |
| 184 |
return None |
| 185 |
|
| 186 |
before, after = patch |
| 187 |
return (str(fname), before, after) |
| 188 |
|
| 189 |
|
| 190 |
# split out for easier testing of patches in hypofuzz, where the function to |
| 191 |
# apply the patch to may not be loaded in sys.modules. |
| 192 |
def _get_patch_for( |
| 193 |
func: Any, |
| 194 |
examples: Sequence[tuple[str, str]], |
| 195 |
*, |
| 196 |
strip_via: tuple[str, ...] = (), |
| 197 |
namespace: dict[str, Any], |
| 198 |
) -> tuple[str, str] | None: |
| 199 |
try: |
| 200 |
before = inspect.getsource(func) |
| 201 |
except Exception: # pragma: no cover |
| 202 |
return None |
| 203 |
|
| 204 |
modules_in_test_scope = sorted( |
| 205 |
((k, v) for (k, v) in namespace.items() if isinstance(v, types.ModuleType)), |
| 206 |
key=lambda kv: len(kv[1].__name__), |
| 207 |
) |
| 208 |
|
| 209 |
# The printed examples might include object reprs which are invalid syntax, |
| 210 |
# so we parse here and skip over those. If _none_ are valid, there's no patch. |
| 211 |
call_nodes: list[tuple[cst.Call, str]] = [] |
| 212 |
|
| 213 |
# we want to preserve order, but remove duplicates. |
| 214 |
seen_examples = set() |
| 215 |
for ex, via in examples: |
| 216 |
if (ex, via) in seen_examples: |
| 217 |
continue |
| 218 |
seen_examples.add((ex, via)) |
| 219 |
|
| 220 |
with suppress(Exception): |
| 221 |
node: Any = cst.parse_module(ex) |
| 222 |
the_call = node.body[0].body[0].value |
| 223 |
assert isinstance(the_call, cst.Call), the_call |
| 224 |
# Check for st.data(), which doesn't support explicit examples |
| 225 |
data = m.Arg(m.Call(m.Name("data"), args=[m.Arg(m.Ellipsis())])) |
| 226 |
if m.matches(the_call, m.Call(args=[m.ZeroOrMore(), data, m.ZeroOrMore()])): |
| 227 |
return None |
| 228 |
|
| 229 |
# Many reprs use the unqualified name of the type, e.g. np.array() |
| 230 |
# -> array([...]), so here we find undefined names and look them up |
| 231 |
# on each module which was in the test's global scope. |
| 232 |
names = {} |
| 233 |
for anode in ast.walk(ast.parse(ex, "eval")): |
| 234 |
if ( |
| 235 |
isinstance(anode, ast.Name) |
| 236 |
and isinstance(anode.ctx, ast.Load) |
| 237 |
and anode.id not in names |
| 238 |
and anode.id not in namespace |
| 239 |
): |
| 240 |
for k, v in modules_in_test_scope: |
| 241 |
if anode.id in v.__dict__: |
| 242 |
names[anode.id] = cst.parse_expression(f"{k}.{anode.id}") |
| 243 |
break |
| 244 |
|
| 245 |
# LibCST doesn't track Load()/Store() state of names by default, so we have |
| 246 |
# to do a bit of a dance here, *and* explicitly handle keyword arguments |
| 247 |
# which are treated as Load() context - but even if that's fixed later |
| 248 |
# we'll still want to support older versions. |
| 249 |
with suppress(Exception): |
| 250 |
wrapper = cst.metadata.MetadataWrapper(node) |
| 251 |
kwarg_names = { |
| 252 |
node.keyword # type: ignore |
| 253 |
for node in m.findall(wrapper, m.Arg(keyword=m.Name())) |
| 254 |
} |
| 255 |
node = m.replace( |
| 256 |
wrapper, |
| 257 |
m.Name(value=m.MatchIfTrue(names.__contains__)) |
| 258 |
& m.MatchMetadata(ExpressionContextProvider, ExpressionContext.LOAD) |
| 259 |
& m.MatchIfTrue(lambda n, k=kwarg_names: n not in k), # type: ignore |
| 260 |
replacement=lambda node, _, ns=names: ns[node.value], # type: ignore |
| 261 |
) |
| 262 |
node = node.body[0].body[0].value |
| 263 |
assert isinstance(node, cst.Call), node |
| 264 |
call_nodes.append((node, via)) |
| 265 |
|
| 266 |
if not call_nodes: |
| 267 |
return None |
| 268 |
|
| 269 |
if ( |
| 270 |
namespace.get("hypothesis") is sys.modules["hypothesis"] |
| 271 |
and "given" not in namespace # more reliably present than `example` |
| 272 |
): |
| 273 |
decorator_func = "hypothesis.example" |
| 274 |
else: |
| 275 |
decorator_func = "example" |
| 276 |
|
| 277 |
# Do the codemod and return a triple containing location and replacement info. |
| 278 |
dedented, prefix = dedent(before) |
| 279 |
try: |
| 280 |
node = cst.parse_module(dedented) |
| 281 |
except Exception: # pragma: no cover |
| 282 |
# inspect.getsource() sometimes returns a decorator alone, which is invalid |
| 283 |
return None |
| 284 |
after = AddExamplesCodemod( |
| 285 |
CodemodContext(), |
| 286 |
fn_examples={func.__name__: call_nodes}, |
| 287 |
strip_via=strip_via, |
| 288 |
decorator=decorator_func, |
| 289 |
width=88 - len(prefix), # to match Black's default formatting |
| 290 |
).transform_module(node) |
| 291 |
return (before, indent(after.code, prefix=prefix)) |
| 292 |
|
| 293 |
|
| 294 |
def make_patch( |
| 295 |
triples: Sequence[tuple[str, str, str]], |
| 296 |
*, |
| 297 |
msg: str = "Hypothesis: add explicit examples", |
| 298 |
when: datetime | None = None, |
| 299 |
author: str = f"Hypothesis {__version__} <[email protected]>", |
| 300 |
) -> str: |
| 301 |
"""Create a patch for (fname, before, after) triples.""" |
| 302 |
assert triples, "attempted to create empty patch" |
| 303 |
when = when or datetime.now(tz=timezone.utc) |
| 304 |
|
| 305 |
by_fname: dict[Path, list[tuple[str, str]]] = {} |
| 306 |
for fname, before, after in triples: |
| 307 |
by_fname.setdefault(Path(fname), []).append((before, after)) |
| 308 |
|
| 309 |
diffs = [HEADER.format(msg=msg, when=when, author=author)] |
| 310 |
for fname, changes in sorted(by_fname.items()): |
| 311 |
source_before = source_after = fname.read_text(encoding="utf-8") |
| 312 |
for before, after in changes: |
| 313 |
source_after = source_after.replace(before.rstrip(), after.rstrip(), 1) |
| 314 |
ud = difflib.unified_diff( |
| 315 |
source_before.splitlines(keepends=True), |
| 316 |
source_after.splitlines(keepends=True), |
| 317 |
fromfile=f"./{fname}", # git strips the first part of the path by default |
| 318 |
tofile=f"./{fname}", |
| 319 |
) |
| 320 |
diffs.append("".join(ud)) |
| 321 |
return "".join(diffs) |
| 322 |
|
| 323 |
|
| 324 |
def save_patch(patch: str, *, slug: str = "") -> Path: # pragma: no cover |
| 325 |
assert re.fullmatch(r"|[a-z]+-", slug), f"malformed {slug=}" |
| 326 |
now = date.today().isoformat() |
| 327 |
cleaned = re.sub(r"^Date: .+?$", "", patch, count=1, flags=re.MULTILINE) |
| 328 |
hash8 = hashlib.sha1(cleaned.encode()).hexdigest()[:8] |
| 329 |
patches_dir = storage_directory("patches") |
| 330 |
patches_dir.create_if_missing() |
| 331 |
p = patches_dir.path / f"{now}--{slug}{hash8}.patch" |
| 332 |
p.write_text(patch, encoding="utf-8") |
| 333 |
return p.relative_to(Path.cwd()) |
| 334 |
|
| 335 |
|
| 336 |
def gc_patches(slug: str = "") -> None: # pragma: no cover |
| 337 |
cutoff = date.today() - timedelta(days=7) |
| 338 |
for p in storage_directory("patches").path.glob( |
| 339 |
f"????-??-??--{slug}????????.patch" |
| 340 |
): |
| 341 |
if date.fromisoformat(p.stem.split("--")[0]) < cutoff: |
| 342 |
p.unlink() |