1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
|
# This file is part of Hypothesis, which may be found at
# https://github.com/HypothesisWorks/hypothesis/
#
# Copyright the Hypothesis Authors.
# Individual contributors are listed in AUTHORS.rst and the git log.
#
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at https://mozilla.org/MPL/2.0/.
from __future__ import annotations
import json
import re
import subprocess
import sys
import textwrap
from pathlib import Path
from typing import Any
import pytest
from hypothesistooling.projects.hypothesispython import HYPOTHESIS_PYTHON, PYTHON_SRC
from hypothesistooling.scripts import pip_tool, tool_path
from .revealed_types import NUMPY_REVEALED_TYPES, PYTHON_VERSIONS, REVEALED_TYPES
@pytest.mark.skip(
reason="Hypothesis type-annotates the public API as a convenience for users, "
"but strict checks for our internals would be a net drag on productivity."
)
def test_pyright_passes_on_hypothesis():
pip_tool("pyright", "--project", HYPOTHESIS_PYTHON)
@pytest.mark.parametrize("python_version", PYTHON_VERSIONS)
def test_pyright_passes_on_basic_test(tmp_path: Path, python_version: str):
file = tmp_path / "test.py"
file.write_text(
textwrap.dedent(
"""
import hypothesis
import hypothesis.strategies as st
@hypothesis.given(x=st.text())
def test_foo(x: str):
assert x == x
from hypothesis import given
from hypothesis.strategies import text
@given(x=text())
def test_bar(x: str):
assert x == x
"""
),
encoding="utf-8",
)
_write_config(
tmp_path, {"typeCheckingMode": "strict", "pythonVersion": python_version}
)
assert _get_pyright_errors(file) == []
@pytest.mark.parametrize(
"python_version",
[
# FIXME: temporary workaround, see hypothesis/pull/4136
pytest.param(v, marks=[pytest.mark.xfail(strict=False)] * (v == "3.13"))
for v in PYTHON_VERSIONS
],
)
def test_given_only_allows_strategies(tmp_path: Path, python_version: str):
file = tmp_path / "test.py"
file.write_text(
textwrap.dedent(
"""
from hypothesis import given
@given(1)
def f():
pass
"""
),
encoding="utf-8",
)
_write_config(
tmp_path, {"typeCheckingMode": "strict", "pythonVersion": python_version}
)
errors = _get_pyright_errors(file)
msg = 'Argument of type "Literal[1]" cannot be assigned to parameter "_given_arguments"'
assert sum(e["message"].startswith(msg) for e in errors) == 1, errors
def test_pyright_issue_3296(tmp_path: Path):
file = tmp_path / "test.py"
file.write_text(
textwrap.dedent(
"""
from hypothesis.strategies import lists, integers
lists(integers()).map(sorted)
"""
),
encoding="utf-8",
)
_write_config(tmp_path, {"typeCheckingMode": "strict"})
assert _get_pyright_errors(file) == []
def test_pyright_raises_for_mixed_pos_kwargs_in_given(tmp_path: Path):
file = tmp_path / "test.py"
file.write_text(
textwrap.dedent(
"""
from hypothesis import given
from hypothesis.strategies import text
@given(text(), x=text())
def test_bar(x: str):
pass
"""
),
encoding="utf-8",
)
_write_config(tmp_path, {"typeCheckingMode": "strict"})
assert (
sum(
e["message"].startswith(
'No overloads for "given" match the provided arguments'
)
for e in _get_pyright_errors(file)
)
== 1
)
def test_pyright_issue_3348(tmp_path: Path):
file = tmp_path / "test.py"
file.write_text(
textwrap.dedent(
"""
import hypothesis.strategies as st
st.tuples(st.integers(), st.integers())
st.one_of(st.integers(), st.integers())
st.one_of([st.integers(), st.floats()]) # sequence of strats should be OK
st.sampled_from([1, 2])
"""
),
encoding="utf-8",
)
_write_config(tmp_path, {"typeCheckingMode": "strict"})
assert _get_pyright_errors(file) == []
def test_numpy_arrays_strategy(tmp_path: Path):
file = tmp_path / "test.py"
file.write_text(
textwrap.dedent(
"""
import numpy as np
from hypothesis.extra.numpy import arrays
x = arrays(dtype=np.dtype("int32"), shape=1)
"""
),
encoding="utf-8",
)
_write_config(tmp_path, {"typeCheckingMode": "strict"})
errors = _get_pyright_errors(file)
print(errors)
assert errors == []
@pytest.mark.parametrize(
"val,expect",
[
*REVEALED_TYPES, # shared with Mypy
("dictionaries(integers(), datetimes())", "dict[int, datetime]"),
("data()", "DataObject"),
("none() | integers()", "int | None"),
("recursive(integers(), lists)", "list[Any] | int"),
# We have overloads for up to five types, then fall back to Any.
# (why five? JSON atoms are None|bool|int|float|str and we do that a lot)
("one_of(integers(), text())", "int | str"),
(
"one_of(integers(), text(), none(), binary(), builds(list))",
"int | str | bytes | list[Unknown] | None",
),
(
"one_of(integers(), text(), none(), binary(), builds(list), builds(dict))",
"Any",
),
("one_of([integers(), none()])", "int | None"),
("one_of(integers(), none())", "int | None"),
# Note: keep this in sync with the equivalent test for Mypy
],
)
def test_revealed_types(tmp_path, val, expect):
"""Check that Pyright picks up the expected `X` in SearchStrategy[`X`]."""
f = tmp_path / (expect + ".py")
f.write_text(
textwrap.dedent(
f"""
from hypothesis.strategies import *
reveal_type({val})
"""
),
encoding="utf-8",
)
_write_config(tmp_path, {"reportWildcardImportFromLibrary ": "none"})
typ = get_pyright_analysed_type(f)
assert typ == f"SearchStrategy[{expect}]"
@pytest.mark.parametrize("val,expect", NUMPY_REVEALED_TYPES)
def test_numpy_revealed_types(tmp_path, val, expect):
f = tmp_path / (expect + ".py")
f.write_text(
textwrap.dedent(
f"""
import numpy as np
from hypothesis.extra.numpy import *
reveal_type({val})
"""
),
encoding="utf-8",
)
_write_config(tmp_path, {"reportWildcardImportFromLibrary ": "none"})
typ = get_pyright_analysed_type(f)
assert typ == f"SearchStrategy[{expect}]"
@pytest.mark.parametrize(
"val,expect",
[
("elements=None, fill=None", "Any"),
("elements=None, fill=floats()", "float"),
("elements=floats(), fill=None", "float"),
("elements=floats(), fill=text()", "float | str"),
# Note: keep this in sync with the equivalent test for Mypy
],
)
def test_pandas_column(tmp_path, val, expect):
f = tmp_path / "test.py"
f.write_text(
textwrap.dedent(
f"""
from hypothesis.extra.pandas import column
from hypothesis.strategies import *
x = column(name="test", unique=True, dtype=None, {val})
reveal_type(x)
"""
),
encoding="utf-8",
)
_write_config(
tmp_path,
{"typeCheckingMode": "strict", "reportWildcardImportFromLibrary ": "none"},
)
typ = get_pyright_analysed_type(f)
assert typ == f"column[{expect}]"
def test_pyright_tuples_pos_args_only(tmp_path: Path):
file = tmp_path / "test.py"
file.write_text(
textwrap.dedent(
"""
import hypothesis.strategies as st
st.tuples(a1=st.integers())
st.tuples(a1=st.integers(), a2=st.integers())
"""
),
encoding="utf-8",
)
_write_config(tmp_path, {"typeCheckingMode": "strict"})
assert (
sum(
e["message"].startswith(
'No overloads for "tuples" match the provided arguments'
)
for e in _get_pyright_errors(file)
)
== 2
)
def test_pyright_one_of_pos_args_only(tmp_path: Path):
file = tmp_path / "test.py"
file.write_text(
textwrap.dedent(
"""
import hypothesis.strategies as st
st.one_of(a1=st.integers())
st.one_of(a1=st.integers(), a2=st.integers())
"""
),
encoding="utf-8",
)
_write_config(tmp_path, {"typeCheckingMode": "strict"})
assert (
sum(
e["message"].startswith(
'No overloads for "one_of" match the provided arguments'
)
for e in _get_pyright_errors(file)
)
== 2
)
def test_register_random_protocol(tmp_path: Path):
file = tmp_path / "test.py"
file.write_text(
textwrap.dedent(
"""
from random import Random
from hypothesis import register_random
class MyRandom:
def __init__(self) -> None:
r = Random()
self.seed = r.seed
self.setstate = r.setstate
self.getstate = r.getstate
register_random(MyRandom())
register_random(None) # type: ignore
"""
),
encoding="utf-8",
)
_write_config(tmp_path, {"reportUnnecessaryTypeIgnoreComment": True})
assert _get_pyright_errors(file) == []
# ---------- Helpers for running pyright ---------- #
def _get_pyright_output(file: Path) -> dict[str, Any]:
proc = subprocess.run(
[tool_path("pyright"), "--outputjson", f"--pythonpath={sys.executable}"],
cwd=file.parent,
encoding="utf-8",
text=True,
capture_output=True,
)
try:
return json.loads(proc.stdout)
except Exception:
print(proc.stdout)
raise
def _get_pyright_errors(file: Path) -> list[dict[str, Any]]:
return _get_pyright_output(file)["generalDiagnostics"]
def get_pyright_analysed_type(fname):
out, *rest = _get_pyright_errors(fname)
print(out, rest)
assert not rest
assert out["severity"] == "information"
return (
re.fullmatch(r'Type of ".+" is "(.+)"', out["message"])
.group(1)
.replace("builtins.", "")
.replace("numpy.", "")
.replace(
"signedinteger[_32Bit | _64Bit] | bool[bool]",
"Union[signedinteger[Union[_32Bit, _64Bit]], bool[bool]]",
)
)
def _write_config(config_dir: Path, data: dict[str, Any] | None = None):
config = {"extraPaths": [str(PYTHON_SRC)], **(data or {})}
(config_dir / "pyrightconfig.json").write_text(json.dumps(config), encoding="utf-8")
|