| 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 |
import ast |
| 12 |
import itertools |
| 13 |
import json |
| 14 |
import operator |
| 15 |
import re |
| 16 |
import subprocess |
| 17 |
import sys |
| 18 |
|
| 19 |
import pytest |
| 20 |
|
| 21 |
from hypothesis import settings, strategies as st |
| 22 |
from hypothesis.errors import StopTest |
| 23 |
from hypothesis.extra.ghostwriter import ( |
| 24 |
binary_operation, |
| 25 |
equivalent, |
| 26 |
fuzz, |
| 27 |
idempotent, |
| 28 |
magic, |
| 29 |
roundtrip, |
| 30 |
) |
| 31 |
from hypothesis.internal.reflection import get_pretty_function_description |
| 32 |
|
| 33 |
pytestmark = pytest.mark.skipif( |
| 34 |
settings.get_current_profile_name() == "threading", |
| 35 |
reason="ghostwriter is not thread safe", |
| 36 |
) |
| 37 |
|
| 38 |
|
| 39 |
def run(cmd, *, cwd=None): |
| 40 |
return subprocess.run( |
| 41 |
cmd, capture_output=True, shell=True, text=True, cwd=cwd, encoding="utf-8" |
| 42 |
) |
| 43 |
|
| 44 |
|
| 45 |
@pytest.mark.parametrize( |
| 46 |
"cli,code", |
| 47 |
[ |
| 48 |
# Passing one argument falls back to one-argument tests |
| 49 |
("--equivalent re.compile", lambda: fuzz(re.compile)), |
| 50 |
("--roundtrip sorted", lambda: idempotent(sorted)), |
| 51 |
# For multiple arguments, they're equivalent to the function call |
| 52 |
( |
| 53 |
"--equivalent eval ast.literal_eval", |
| 54 |
lambda: equivalent(eval, ast.literal_eval), |
| 55 |
), |
| 56 |
( |
| 57 |
"--roundtrip json.loads json.dumps --except ValueError", |
| 58 |
lambda: roundtrip(json.loads, json.dumps, except_=ValueError), |
| 59 |
), |
| 60 |
# Imports submodule (importlib.import_module passes; __import__ fails) |
| 61 |
pytest.param( |
| 62 |
"hypothesis.strategies", |
| 63 |
lambda: magic(st), |
| 64 |
marks=pytest.mark.skipif(sys.version_info[:2] != (3, 10), reason="varies"), |
| 65 |
), |
| 66 |
# We can write tests for classes even without classmethods or staticmethods |
| 67 |
("hypothesis.errors.StopTest", lambda: fuzz(StopTest)), |
| 68 |
# Search for identity element does not print e.g. "You can use @seed ..." |
| 69 |
("--binary-op operator.add", lambda: binary_operation(operator.add)), |
| 70 |
# Annotations are passed correctly |
| 71 |
("sorted --annotate", lambda: fuzz(sorted, annotate=True)), |
| 72 |
("sorted --no-annotate", lambda: fuzz(sorted, annotate=False)), |
| 73 |
], |
| 74 |
ids=get_pretty_function_description, |
| 75 |
) |
| 76 |
def test_cli_python_equivalence(cli, code): |
| 77 |
result = run("hypothesis write " + cli) |
| 78 |
result.check_returncode() |
| 79 |
cli_output = result.stdout.strip() |
| 80 |
assert cli == "hypothesis.strategies" or not result.stderr |
| 81 |
code_output = code().strip() |
| 82 |
assert code_output == cli_output |
| 83 |
|
| 84 |
|
| 85 |
@pytest.mark.parametrize( |
| 86 |
"cli,err_msg", |
| 87 |
[ |
| 88 |
("--idempotent sorted sorted", "Test functions for idempotence one at a time."), |
| 89 |
( |
| 90 |
"xxxx", |
| 91 |
"Found the 'builtins' module, but it doesn't have a 'xxxx' attribute.", |
| 92 |
), |
| 93 |
( |
| 94 |
"re.srch", |
| 95 |
"Found the 're' module, but it doesn't have a 'srch' attribute. " |
| 96 |
"Closest matches: ['search']", |
| 97 |
), |
| 98 |
( |
| 99 |
"re.fmatch", |
| 100 |
"Found the 're' module, but it doesn't have a 'fmatch' attribute. " |
| 101 |
"Closest matches: ['match', 'fullmatch'", |
| 102 |
# Python >= 3.7 has 'Match' objects too |
| 103 |
), |
| 104 |
], |
| 105 |
) |
| 106 |
def test_cli_too_many_functions(cli, err_msg): |
| 107 |
# Supplying multiple functions to writers that only cope with one |
| 108 |
result = run("hypothesis write " + cli) |
| 109 |
assert result.returncode == 2 |
| 110 |
assert "Error: " + err_msg in result.stderr |
| 111 |
assert ("Closest matches" in err_msg) == ("Closest matches" in result.stderr) |
| 112 |
|
| 113 |
|
| 114 |
CODE_TO_TEST = """ |
| 115 |
from typing import Sequence, List |
| 116 |
|
| 117 |
def sorter(seq: Sequence[int]) -> List[int]: |
| 118 |
return sorted(seq) |
| 119 |
""" |
| 120 |
|
| 121 |
|
| 122 |
def test_can_import_from_scripts_in_working_dir(tmp_path): |
| 123 |
(tmp_path / "mycode.py").write_text(CODE_TO_TEST, encoding="utf-8") |
| 124 |
result = run("hypothesis write mycode.sorter", cwd=tmp_path) |
| 125 |
assert result.returncode == 0 |
| 126 |
assert "Error: " not in result.stderr |
| 127 |
|
| 128 |
|
| 129 |
CLASS_CODE_TO_TEST = """ |
| 130 |
from typing import Sequence, List |
| 131 |
|
| 132 |
def my_func(seq: Sequence[int]) -> List[int]: |
| 133 |
return sorted(seq) |
| 134 |
|
| 135 |
class MyClass: |
| 136 |
|
| 137 |
@staticmethod |
| 138 |
def my_staticmethod(seq: Sequence[int]) -> List[int]: |
| 139 |
return sorted(seq) |
| 140 |
|
| 141 |
@classmethod |
| 142 |
def my_classmethod(cls, seq: Sequence[int]) -> List[int]: |
| 143 |
return sorted(seq) |
| 144 |
""" |
| 145 |
|
| 146 |
|
| 147 |
@pytest.mark.parametrize("func", ["my_staticmethod", "my_classmethod"]) |
| 148 |
def test_can_import_from_class(tmp_path, func): |
| 149 |
(tmp_path / "mycode.py").write_text(CLASS_CODE_TO_TEST, encoding="utf-8") |
| 150 |
result = run(f"hypothesis write mycode.MyClass.{func}", cwd=tmp_path) |
| 151 |
assert result.returncode == 0 |
| 152 |
assert "Error: " not in result.stderr |
| 153 |
|
| 154 |
|
| 155 |
@pytest.mark.parametrize( |
| 156 |
"classname,thing,kind", |
| 157 |
[ |
| 158 |
("XX", "", "class"), |
| 159 |
("MyClass", " and 'MyClass' class", "attribute"), |
| 160 |
("my_func", " and 'my_func' attribute", "attribute"), |
| 161 |
], |
| 162 |
) |
| 163 |
def test_error_import_from_class(tmp_path, classname, thing, kind): |
| 164 |
(tmp_path / "mycode.py").write_text(CLASS_CODE_TO_TEST, encoding="utf-8") |
| 165 |
result = run(f"hypothesis write mycode.{classname}.XX", cwd=tmp_path) |
| 166 |
msg = f"Error: Found the 'mycode' module{thing}, but it doesn't have a 'XX' {kind}." |
| 167 |
assert result.returncode == 2 |
| 168 |
assert msg in result.stderr |
| 169 |
|
| 170 |
|
| 171 |
def test_magic_discovery_from_module(tmp_path): |
| 172 |
(tmp_path / "mycode.py").write_text(CLASS_CODE_TO_TEST, encoding="utf-8") |
| 173 |
result = run("hypothesis write mycode", cwd=tmp_path) |
| 174 |
assert result.returncode == 0 |
| 175 |
assert "my_func" in result.stdout |
| 176 |
assert "MyClass.my_staticmethod" in result.stdout |
| 177 |
assert "MyClass.my_classmethod" in result.stdout |
| 178 |
|
| 179 |
|
| 180 |
ROUNDTRIP_CODE_TO_TEST = """ |
| 181 |
from typing import Union |
| 182 |
import json |
| 183 |
|
| 184 |
def to_json(json: Union[dict,list]) -> str: |
| 185 |
return json.dumps(json) |
| 186 |
|
| 187 |
def from_json(json: str) -> Union[dict,list]: |
| 188 |
return json.loads(json) |
| 189 |
|
| 190 |
class MyClass: |
| 191 |
|
| 192 |
@staticmethod |
| 193 |
def to_json(json: Union[dict,list]) -> str: |
| 194 |
return json.dumps(json) |
| 195 |
|
| 196 |
@staticmethod |
| 197 |
def from_json(json: str) -> Union[dict,list]: |
| 198 |
return json.loads(json) |
| 199 |
|
| 200 |
class OtherClass: |
| 201 |
|
| 202 |
@classmethod |
| 203 |
def to_json(cls, json: Union[dict,list]) -> str: |
| 204 |
return json.dumps(json) |
| 205 |
|
| 206 |
@classmethod |
| 207 |
def from_json(cls, json: str) -> Union[dict,list]: |
| 208 |
return json.loads(json) |
| 209 |
""" |
| 210 |
|
| 211 |
|
| 212 |
def test_roundtrip_correct_pairs(tmp_path): |
| 213 |
(tmp_path / "mycode.py").write_text(ROUNDTRIP_CODE_TO_TEST, encoding="utf-8") |
| 214 |
result = run("hypothesis write mycode", cwd=tmp_path) |
| 215 |
assert result.returncode == 0 |
| 216 |
for scope1, scope2 in itertools.product( |
| 217 |
["mycode.MyClass", "mycode.OtherClass", "mycode"], repeat=2 |
| 218 |
): |
| 219 |
round_trip_code = f"""value0 = {scope1}.to_json(json=json) |
| 220 |
value1 = {scope2}.from_json(json=value0)""" |
| 221 |
if scope1 == scope2: |
| 222 |
assert round_trip_code in result.stdout |
| 223 |
else: |
| 224 |
assert round_trip_code not in result.stdout |
| 225 |
|
| 226 |
|
| 227 |
def test_empty_module_is_not_error(tmp_path): |
| 228 |
(tmp_path / "mycode.py").write_text("# Nothing to see here\n", encoding="utf-8") |
| 229 |
result = run("hypothesis write mycode", cwd=tmp_path) |
| 230 |
assert result.returncode == 0 |
| 231 |
assert "Error: " not in result.stderr |
| 232 |
assert "# Found no testable functions" in result.stdout |