Debian Codegraph @

hypothesis-python/src/hypothesis/extra/cli.py

raw
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 ::
13
14 $ hypothesis --help
15 Usage: hypothesis [OPTIONS] COMMAND [ARGS]...
16
17 Options:
18 --version Show the version and exit.
19 -h, --help Show this message and exit.
20
21 Commands:
22 codemod `hypothesis codemod` refactors deprecated or inefficient code.
23 fuzz [hypofuzz] runs tests with an adaptive coverage-guided fuzzer.
24 write `hypothesis write` writes property-based tests for you!
25
26 This module requires the :pypi:`click` package, and provides Hypothesis' command-line
27 interface, for e.g. :ref:`'ghostwriting' tests <ghostwriter>` via the terminal.
28 It's also where `HypoFuzz <https://hypofuzz.com/>`__ adds the :command:`hypothesis fuzz`
29 command (`learn more about that here <https://hypofuzz.com/docs/quickstart.html>`__).
30 """
31
32 import builtins
33 import importlib
34 import inspect
35 import sys
36 import types
37 from difflib import get_close_matches
38 from functools import partial
39 from multiprocessing import Pool
40 from pathlib import Path
41
42 try:
43 import pytest
44 except ImportError:
45 pytest = None # type: ignore
46
47 MESSAGE = """
48 The Hypothesis command-line interface requires the `{}` package,
49 which you do not have installed. Run:
50
51 python -m pip install --upgrade 'hypothesis[cli]'
52
53 and try again.
54 """
55
56 try:
57 import click
58 except ImportError:
59
60 def main():
61 """If `click` is not installed, tell the user to install it then exit."""
62 sys.stderr.write(MESSAGE.format("click"))
63 sys.exit(1)
64
65 else:
66 # Ensure that Python scripts in the current working directory are importable,
67 # on the principle that Ghostwriter should 'just work' for novice users. Note
68 # that we append rather than prepend to the module search path, so this will
69 # never shadow the stdlib or installed packages.
70 sys.path.append(".")
71
72 @click.group(context_settings={"help_option_names": ("-h", "--help")})
73 @click.version_option()
74 def main():
75 pass
76
77 def obj_name(s: str) -> object:
78 """This "type" imports whatever object is named by a dotted string."""
79 s = s.strip()
80 if "/" in s or "\\" in s:
81 raise click.UsageError(
82 "Remember that the ghostwriter should be passed the name of a module, not a path."
83 ) from None
84 try:
85 return importlib.import_module(s)
86 except ImportError:
87 pass
88 classname = None
89 if "." not in s:
90 modulename, module, funcname = "builtins", builtins, s
91 else:
92 modulename, funcname = s.rsplit(".", 1)
93 try:
94 module = importlib.import_module(modulename)
95 except ImportError as err:
96 try:
97 modulename, classname = modulename.rsplit(".", 1)
98 module = importlib.import_module(modulename)
99 except (ImportError, ValueError):
100 if s.endswith(".py"):
101 raise click.UsageError(
102 "Remember that the ghostwriter should be passed the name of a module, not a file."
103 ) from None
104 raise click.UsageError(
105 f"Failed to import the {modulename} module for introspection. "
106 "Check spelling and your Python import path, or use the Python API?"
107 ) from err
108
109 def describe_close_matches(
110 module_or_class: types.ModuleType, objname: str
111 ) -> str:
112 public_names = [
113 name for name in vars(module_or_class) if not name.startswith("_")
114 ]
115 matches = get_close_matches(objname, public_names)
116 if matches:
117 return f" Closest matches: {matches!r}"
118 else:
119 return ""
120
121 if classname is None:
122 try:
123 return getattr(module, funcname)
124 except AttributeError as err:
125 if funcname == "py":
126 # Likely attempted to pass a local file (Eg., "myscript.py") instead of a module name
127 raise click.UsageError(
128 "Remember that the ghostwriter should be passed the name of a module, not a file."
129 f"\n\tTry: hypothesis write {s[:-3]}"
130 ) from None
131 raise click.UsageError(
132 f"Found the {modulename!r} module, but it doesn't have a "
133 f"{funcname!r} attribute."
134 + describe_close_matches(module, funcname)
135 ) from err
136 else:
137 try:
138 func_class = getattr(module, classname)
139 except AttributeError as err:
140 raise click.UsageError(
141 f"Found the {modulename!r} module, but it doesn't have a "
142 f"{classname!r} class." + describe_close_matches(module, classname)
143 ) from err
144 try:
145 return getattr(func_class, funcname)
146 except AttributeError as err:
147 if inspect.isclass(func_class):
148 func_class_is = "class"
149 else:
150 func_class_is = "attribute"
151 raise click.UsageError(
152 f"Found the {modulename!r} module and {classname!r} {func_class_is}, "
153 f"but it doesn't have a {funcname!r} attribute."
154 + describe_close_matches(func_class, funcname)
155 ) from err
156
157 def _refactor(func, fname):
158 try:
159 oldcode = Path(fname).read_text(encoding="utf-8")
160 except (OSError, UnicodeError) as err:
161 # Permissions or encoding issue, or file deleted, etc.
162 return f"skipping {fname!r} due to {err}"
163
164 if "hypothesis" not in oldcode:
165 return # This is a fast way to avoid running slow no-op codemods
166
167 try:
168 newcode = func(oldcode)
169 except Exception as err:
170 from libcst import ParserSyntaxError
171
172 if isinstance(err, ParserSyntaxError):
173 from hypothesis.extra._patching import indent
174
175 msg = indent(str(err).replace("\n\n", "\n"), " ").strip()
176 return f"skipping {fname!r} due to {msg}"
177 raise
178
179 if newcode != oldcode:
180 Path(fname).write_text(newcode, encoding="utf-8")
181
182 @main.command() # type: ignore # Click adds the .command attribute
183 @click.argument("path", type=str, required=True, nargs=-1)
184 def codemod(path):
185 """`hypothesis codemod` refactors deprecated or inefficient code.
186
187 It adapts `python -m libcst.tool`, removing many features and config options
188 which are rarely relevant for this purpose. If you need more control, we
189 encourage you to use the libcst CLI directly; if not this one is easier.
190
191 PATH is the file(s) or directories of files to format in place, or
192 "-" to read from stdin and write to stdout.
193 """
194 try:
195 from libcst.codemod import gather_files
196
197 from hypothesis.extra import codemods
198 except ImportError:
199 sys.stderr.write(
200 "You are missing required dependencies for this option. Run:\n\n"
201 " python -m pip install --upgrade hypothesis[codemods]\n\n"
202 "and try again."
203 )
204 sys.exit(1)
205
206 # Special case for stdin/stdout usage
207 if "-" in path:
208 if len(path) > 1:
209 raise Exception(
210 "Cannot specify multiple paths when reading from stdin!"
211 )
212 print("Codemodding from stdin", file=sys.stderr)
213 print(codemods.refactor(sys.stdin.read()))
214 return 0
215
216 # Find all the files to refactor, and then codemod them
217 files = gather_files(path)
218 errors = set()
219 if len(files) <= 1:
220 errors.add(_refactor(codemods.refactor, *files))
221 else:
222 with Pool() as pool:
223 for msg in pool.imap_unordered(
224 partial(_refactor, codemods.refactor), files
225 ):
226 errors.add(msg)
227 errors.discard(None)
228 for msg in errors:
229 print(msg, file=sys.stderr)
230 return 1 if errors else 0
231
232 @main.command() # type: ignore # Click adds the .command attribute
233 @click.argument("func", type=obj_name, required=True, nargs=-1)
234 @click.option(
235 "--roundtrip",
236 "writer",
237 flag_value="roundtrip",
238 help="start by testing write/read or encode/decode!",
239 )
240 @click.option(
241 "--equivalent",
242 "writer",
243 flag_value="equivalent",
244 help="very useful when optimising or refactoring code",
245 )
246 @click.option(
247 "--errors-equivalent",
248 "writer",
249 flag_value="errors-equivalent",
250 help="--equivalent, but also allows consistent errors",
251 )
252 @click.option(
253 "--idempotent",
254 "writer",
255 flag_value="idempotent",
256 help="check that f(x) == f(f(x))",
257 )
258 @click.option(
259 "--binary-op",
260 "writer",
261 flag_value="binary_operation",
262 help="associativity, commutativity, identity element",
263 )
264 # Note: we deliberately omit a --ufunc flag, because the magic()
265 # detection of ufuncs is both precise and complete.
266 @click.option(
267 "--style",
268 type=click.Choice(["pytest", "unittest"]),
269 default="pytest" if pytest else "unittest",
270 help="pytest-style function, or unittest-style method?",
271 )
272 @click.option(
273 "-e",
274 "--except",
275 "except_",
276 type=obj_name,
277 multiple=True,
278 help="dotted name of exception(s) to ignore",
279 )
280 @click.option(
281 "--annotate/--no-annotate",
282 default=None,
283 help="force ghostwritten tests to be type-annotated (or not). "
284 "By default, match the code to test.",
285 )
286 def write(func, writer, except_, style, annotate): # \b disables autowrap
287 """`hypothesis write` writes property-based tests for you!
288
289 Type annotations are helpful but not required for our advanced introspection
290 and templating logic. Try running the examples below to see how it works:
291
292 \b
293 hypothesis write gzip
294 hypothesis write numpy.matmul
295 hypothesis write pandas.from_dummies
296 hypothesis write re.compile --except re.error
297 hypothesis write --equivalent ast.literal_eval eval
298 hypothesis write --roundtrip json.dumps json.loads
299 hypothesis write --style=unittest --idempotent sorted
300 hypothesis write --binary-op operator.add
301 """
302 # NOTE: if you want to call this function from Python, look instead at the
303 # ``hypothesis.extra.ghostwriter`` module. Click-decorated functions have
304 # a different calling convention, and raise SystemExit instead of returning.
305 kwargs = {"except_": except_ or (), "style": style, "annotate": annotate}
306 if writer is None:
307 writer = "magic"
308 elif writer == "idempotent" and len(func) > 1:
309 raise click.UsageError("Test functions for idempotence one at a time.")
310 elif writer == "roundtrip" and len(func) == 1:
311 writer = "idempotent"
312 elif "equivalent" in writer and len(func) == 1:
313 writer = "fuzz"
314 if writer == "errors-equivalent":
315 writer = "equivalent"
316 kwargs["allow_same_errors"] = True
317
318 try:
319 from hypothesis.extra import ghostwriter
320 except ImportError:
321 sys.stderr.write(MESSAGE.format("black"))
322 sys.exit(1)
323
324 code = getattr(ghostwriter, writer)(*func, **kwargs)
325 try:
326 from rich.console import Console
327 from rich.syntax import Syntax
328
329 from hypothesis.utils.terminal import guess_background_color
330 except ImportError:
331 print(code)
332 else:
333 try:
334 theme = "default" if guess_background_color() == "light" else "monokai"
335 code = Syntax(code, "python", background_color="default", theme=theme)
336 Console().print(code, soft_wrap=True)
337 except Exception:
338 print("# Error while syntax-highlighting code", file=sys.stderr)
339 print(code)