| 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 |
This module provides codemods based on the :pypi:`LibCST` library, which can |
| 13 |
both detect *and automatically fix* issues with code that uses Hypothesis, |
| 14 |
including upgrading from deprecated features to our recommended style. |
| 15 |
|
| 16 |
You can run the codemods via our CLI:: |
| 17 |
|
| 18 |
$ hypothesis codemod --help |
| 19 |
Usage: hypothesis codemod [OPTIONS] PATH... |
| 20 |
|
| 21 |
`hypothesis codemod` refactors deprecated or inefficient code. |
| 22 |
|
| 23 |
It adapts `python -m libcst.tool`, removing many features and config |
| 24 |
options which are rarely relevant for this purpose. If you need more |
| 25 |
control, we encourage you to use the libcst CLI directly; if not this one |
| 26 |
is easier. |
| 27 |
|
| 28 |
PATH is the file(s) or directories of files to format in place, or "-" to |
| 29 |
read from stdin and write to stdout. |
| 30 |
|
| 31 |
Options: |
| 32 |
-h, --help Show this message and exit. |
| 33 |
|
| 34 |
Alternatively you can use ``python -m libcst.tool``, which offers more control |
| 35 |
at the cost of additional configuration (adding ``'hypothesis.extra'`` to the |
| 36 |
``modules`` list in ``.libcst.codemod.yaml``) and `some issues on Windows |
| 37 |
<https://github.com/Instagram/LibCST/issues/435>`__. |
| 38 |
|
| 39 |
.. autofunction:: refactor |
| 40 |
""" |
| 41 |
|
| 42 |
import functools |
| 43 |
import importlib |
| 44 |
from inspect import Parameter, signature |
| 45 |
from typing import ClassVar |
| 46 |
|
| 47 |
import libcst as cst |
| 48 |
import libcst.matchers as m |
| 49 |
from libcst.codemod import VisitorBasedCodemodCommand |
| 50 |
|
| 51 |
|
| 52 |
def refactor(code: str) -> str: |
| 53 |
"""Update a source code string from deprecated to modern Hypothesis APIs. |
| 54 |
|
| 55 |
This may not fix *all* the deprecation warnings in your code, but we're |
| 56 |
confident that it will be easier than doing it all by hand. |
| 57 |
|
| 58 |
We recommend using the CLI, but if you want a Python function here it is. |
| 59 |
""" |
| 60 |
context = cst.codemod.CodemodContext() |
| 61 |
mod = cst.parse_module(code) |
| 62 |
transforms: list[VisitorBasedCodemodCommand] = [ |
| 63 |
HypothesisFixPositionalKeywonlyArgs(context), |
| 64 |
HypothesisFixComplexMinMagnitude(context), |
| 65 |
HypothesisFixHealthCheckAll(context), |
| 66 |
HypothesisFixCharactersArguments(context), |
| 67 |
] |
| 68 |
for transform in transforms: |
| 69 |
mod = transform.transform_module(mod) |
| 70 |
return mod.code |
| 71 |
|
| 72 |
|
| 73 |
def match_qualname(name): |
| 74 |
# We use the metadata to get qualname instead of matching directly on function |
| 75 |
# name, because this handles some scope and "from x import y as z" issues. |
| 76 |
return m.MatchMetadataIfTrue( |
| 77 |
cst.metadata.QualifiedNameProvider, |
| 78 |
# If there are multiple possible qualnames, e.g. due to conditional imports, |
| 79 |
# be conservative. Better to leave the user to fix a few things by hand than |
| 80 |
# to break their code while attempting to refactor it! |
| 81 |
lambda qualnames: all(n.name == name for n in qualnames), |
| 82 |
) |
| 83 |
|
| 84 |
|
| 85 |
class HypothesisFixComplexMinMagnitude(VisitorBasedCodemodCommand): |
| 86 |
"""Fix a deprecated min_magnitude=None argument for complex numbers:: |
| 87 |
|
| 88 |
st.complex_numbers(min_magnitude=None) -> st.complex_numbers(min_magnitude=0) |
| 89 |
|
| 90 |
Note that this should be run *after* ``HypothesisFixPositionalKeywonlyArgs``, |
| 91 |
in order to handle ``st.complex_numbers(None)``. |
| 92 |
""" |
| 93 |
|
| 94 |
DESCRIPTION = "Fix a deprecated min_magnitude=None argument for complex numbers." |
| 95 |
METADATA_DEPENDENCIES = (cst.metadata.QualifiedNameProvider,) |
| 96 |
|
| 97 |
@m.call_if_inside( |
| 98 |
m.Call(metadata=match_qualname("hypothesis.strategies.complex_numbers")) |
| 99 |
) |
| 100 |
def leave_Arg(self, original_node, updated_node): |
| 101 |
if m.matches( |
| 102 |
updated_node, m.Arg(keyword=m.Name("min_magnitude"), value=m.Name("None")) |
| 103 |
): |
| 104 |
return updated_node.with_changes(value=cst.Integer("0")) |
| 105 |
return updated_node |
| 106 |
|
| 107 |
|
| 108 |
@functools.lru_cache |
| 109 |
def get_fn(import_path): |
| 110 |
mod, fn = import_path.rsplit(".", 1) |
| 111 |
return getattr(importlib.import_module(mod), fn) |
| 112 |
|
| 113 |
|
| 114 |
class HypothesisFixPositionalKeywonlyArgs(VisitorBasedCodemodCommand): |
| 115 |
"""Fix positional arguments for newly keyword-only parameters, e.g.:: |
| 116 |
|
| 117 |
st.fractions(0, 1, 9) -> st.fractions(0, 1, max_denominator=9) |
| 118 |
|
| 119 |
Applies to a majority of our public API, since keyword-only parameters are |
| 120 |
great but we couldn't use them until after we dropped support for Python 2. |
| 121 |
""" |
| 122 |
|
| 123 |
DESCRIPTION = "Fix positional arguments for newly keyword-only parameters." |
| 124 |
METADATA_DEPENDENCIES = (cst.metadata.QualifiedNameProvider,) |
| 125 |
|
| 126 |
kwonly_functions = ( |
| 127 |
"hypothesis.target", |
| 128 |
"hypothesis.find", |
| 129 |
"hypothesis.extra.lark.from_lark", |
| 130 |
"hypothesis.extra.numpy.arrays", |
| 131 |
"hypothesis.extra.numpy.array_shapes", |
| 132 |
"hypothesis.extra.numpy.unsigned_integer_dtypes", |
| 133 |
"hypothesis.extra.numpy.integer_dtypes", |
| 134 |
"hypothesis.extra.numpy.floating_dtypes", |
| 135 |
"hypothesis.extra.numpy.complex_number_dtypes", |
| 136 |
"hypothesis.extra.numpy.datetime64_dtypes", |
| 137 |
"hypothesis.extra.numpy.timedelta64_dtypes", |
| 138 |
"hypothesis.extra.numpy.byte_string_dtypes", |
| 139 |
"hypothesis.extra.numpy.unicode_string_dtypes", |
| 140 |
"hypothesis.extra.numpy.array_dtypes", |
| 141 |
"hypothesis.extra.numpy.nested_dtypes", |
| 142 |
"hypothesis.extra.numpy.valid_tuple_axes", |
| 143 |
"hypothesis.extra.numpy.broadcastable_shapes", |
| 144 |
"hypothesis.extra.pandas.indexes", |
| 145 |
"hypothesis.extra.pandas.series", |
| 146 |
"hypothesis.extra.pandas.columns", |
| 147 |
"hypothesis.extra.pandas.data_frames", |
| 148 |
"hypothesis.provisional.domains", |
| 149 |
"hypothesis.stateful.run_state_machine_as_test", |
| 150 |
"hypothesis.stateful.rule", |
| 151 |
"hypothesis.stateful.initialize", |
| 152 |
"hypothesis.strategies.floats", |
| 153 |
"hypothesis.strategies.lists", |
| 154 |
"hypothesis.strategies.sets", |
| 155 |
"hypothesis.strategies.frozensets", |
| 156 |
"hypothesis.strategies.iterables", |
| 157 |
"hypothesis.strategies.dictionaries", |
| 158 |
"hypothesis.strategies.characters", |
| 159 |
"hypothesis.strategies.text", |
| 160 |
"hypothesis.strategies.from_regex", |
| 161 |
"hypothesis.strategies.binary", |
| 162 |
"hypothesis.strategies.fractions", |
| 163 |
"hypothesis.strategies.decimals", |
| 164 |
"hypothesis.strategies.recursive", |
| 165 |
"hypothesis.strategies.complex_numbers", |
| 166 |
"hypothesis.strategies.shared", |
| 167 |
"hypothesis.strategies.uuids", |
| 168 |
"hypothesis.strategies.runner", |
| 169 |
"hypothesis.strategies.functions", |
| 170 |
"hypothesis.strategies.datetimes", |
| 171 |
"hypothesis.strategies.times", |
| 172 |
) |
| 173 |
|
| 174 |
def leave_Call(self, original_node, updated_node): |
| 175 |
"""Convert positional to keyword arguments.""" |
| 176 |
metadata = self.get_metadata(cst.metadata.QualifiedNameProvider, original_node) |
| 177 |
qualnames = {qn.name for qn in metadata} |
| 178 |
|
| 179 |
# If this isn't one of our known functions, or it has no posargs, stop there. |
| 180 |
if ( |
| 181 |
len(qualnames) != 1 |
| 182 |
or not qualnames.intersection(self.kwonly_functions) |
| 183 |
or not m.matches( |
| 184 |
updated_node, |
| 185 |
m.Call( |
| 186 |
func=m.DoesNotMatch(m.Call()), |
| 187 |
args=[m.Arg(keyword=None), m.ZeroOrMore()], |
| 188 |
), |
| 189 |
) |
| 190 |
): |
| 191 |
return updated_node |
| 192 |
|
| 193 |
# Get the actual function object so that we can inspect the signature. |
| 194 |
# This does e.g. incur a dependency on Numpy to fix Numpy-dependent code, |
| 195 |
# but having a single source of truth about the signatures is worth it. |
| 196 |
try: |
| 197 |
params = signature(get_fn(*qualnames)).parameters.values() |
| 198 |
except ModuleNotFoundError: |
| 199 |
return updated_node |
| 200 |
|
| 201 |
# st.floats() has a new allow_subnormal kwonly argument not at the end, |
| 202 |
# so we do a bit more of a dance here. |
| 203 |
if qualnames == {"hypothesis.strategies.floats"}: |
| 204 |
params = [p for p in params if p.name != "allow_subnormal"] |
| 205 |
|
| 206 |
if len(updated_node.args) > len(params): |
| 207 |
return updated_node |
| 208 |
|
| 209 |
# Create new arg nodes with the newly required keywords |
| 210 |
assign_nospace = cst.AssignEqual( |
| 211 |
whitespace_before=cst.SimpleWhitespace(""), |
| 212 |
whitespace_after=cst.SimpleWhitespace(""), |
| 213 |
) |
| 214 |
newargs = [ |
| 215 |
( |
| 216 |
arg |
| 217 |
if arg.keyword or arg.star or p.kind is not Parameter.KEYWORD_ONLY |
| 218 |
else arg.with_changes(keyword=cst.Name(p.name), equal=assign_nospace) |
| 219 |
) |
| 220 |
for p, arg in zip(params, updated_node.args, strict=False) |
| 221 |
] |
| 222 |
return updated_node.with_changes(args=newargs) |
| 223 |
|
| 224 |
|
| 225 |
class HypothesisFixHealthCheckAll(VisitorBasedCodemodCommand): |
| 226 |
"""Replace HealthCheck.all() with list(HealthCheck)""" |
| 227 |
|
| 228 |
DESCRIPTION = "Replace HealthCheck.all() with list(HealthCheck)" |
| 229 |
|
| 230 |
@m.leave(m.Call(func=m.Attribute(m.Name("HealthCheck"), m.Name("all")), args=[])) |
| 231 |
def replace_healthcheck(self, original_node, updated_node): |
| 232 |
return updated_node.with_changes( |
| 233 |
func=cst.Name("list"), |
| 234 |
args=[cst.Arg(value=cst.Name("HealthCheck"))], |
| 235 |
) |
| 236 |
|
| 237 |
|
| 238 |
class HypothesisFixCharactersArguments(VisitorBasedCodemodCommand): |
| 239 |
"""Fix deprecated white/blacklist arguments to characters:: |
| 240 |
|
| 241 |
st.characters(whitelist_categories=...) -> st.characters(categories=...) |
| 242 |
st.characters(blacklist_categories=...) -> st.characters(exclude_categories=...) |
| 243 |
st.characters(whitelist_characters=...) -> st.characters(include_characters=...) |
| 244 |
st.characters(blacklist_characters=...) -> st.characters(exclude_characters=...) |
| 245 |
|
| 246 |
Additionally, we drop `exclude_categories=` if `categories=` is present, |
| 247 |
because this argument is always redundant (or an error). |
| 248 |
""" |
| 249 |
|
| 250 |
DESCRIPTION = "Fix deprecated white/blacklist arguments to characters." |
| 251 |
METADATA_DEPENDENCIES = (cst.metadata.QualifiedNameProvider,) |
| 252 |
|
| 253 |
_replacements: ClassVar = { |
| 254 |
"whitelist_categories": "categories", |
| 255 |
"blacklist_categories": "exclude_categories", |
| 256 |
"whitelist_characters": "include_characters", |
| 257 |
"blacklist_characters": "exclude_characters", |
| 258 |
} |
| 259 |
|
| 260 |
@m.leave( |
| 261 |
m.Call( |
| 262 |
metadata=match_qualname("hypothesis.strategies.characters"), |
| 263 |
args=[ |
| 264 |
m.ZeroOrMore(), |
| 265 |
m.Arg(keyword=m.OneOf(*map(m.Name, _replacements))), |
| 266 |
m.ZeroOrMore(), |
| 267 |
], |
| 268 |
), |
| 269 |
) |
| 270 |
def fn(self, original_node, updated_node): |
| 271 |
# Update to the new names |
| 272 |
newargs = [] |
| 273 |
for arg in updated_node.args: |
| 274 |
kw = self._replacements.get(arg.keyword.value, arg.keyword.value) |
| 275 |
newargs.append(arg.with_changes(keyword=cst.Name(kw))) |
| 276 |
# Drop redundant exclude_categories, which is now an error |
| 277 |
if any(m.matches(arg, m.Arg(keyword=m.Name("categories"))) for arg in newargs): |
| 278 |
ex = m.Arg(keyword=m.Name("exclude_categories")) |
| 279 |
newargs = [a for a in newargs if m.matches(a, ~ex)] |
| 280 |
return updated_node.with_changes(args=newargs) |