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 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
|
import asyncio
import subprocess
import sys
from contextlib import contextmanager
from pathlib import Path
from textwrap import dedent
from typing import (
Any,
AsyncGenerator,
AsyncIterable,
AsyncIterator,
Dict,
Generator,
Iterable,
Iterator,
List,
)
from unittest.mock import Mock
import pytest
from typeguard import TypeCheckError, typechecked
if sys.version_info >= (3, 11):
from typing import Self
else:
from typing_extensions import Self
class TestCoroutineFunction:
def test_success(self):
@typechecked
async def foo(a: int) -> str:
return "test"
assert asyncio.run(foo(1)) == "test"
def test_bad_arg(self):
@typechecked
async def foo(a: int) -> str:
return "test"
with pytest.raises(
TypeCheckError, match=r'argument "a" \(str\) is not an instance of int'
):
asyncio.run(foo("foo"))
def test_bad_return(self):
@typechecked
async def foo(a: int) -> str:
return 1
with pytest.raises(
TypeCheckError, match=r"return value \(int\) is not an instance of str"
):
asyncio.run(foo(1))
def test_any_return(self):
@typechecked
async def foo() -> Any:
return 1
assert asyncio.run(foo()) == 1
class TestGenerator:
def test_generator_bare(self):
@typechecked
def genfunc() -> Generator:
val1 = yield 2
val2 = yield 3
val3 = yield 4
return [val1, val2, val3]
gen = genfunc()
with pytest.raises(StopIteration) as exc:
value = next(gen)
while True:
value = gen.send(str(value))
assert isinstance(value, int)
assert exc.value.value == ["2", "3", "4"]
def test_generator_annotated(self):
@typechecked
def genfunc() -> Generator[int, str, List[str]]:
val1 = yield 2
val2 = yield 3
val3 = yield 4
return [val1, val2, val3]
gen = genfunc()
with pytest.raises(StopIteration) as exc:
value = next(gen)
while True:
value = gen.send(str(value))
assert isinstance(value, int)
assert exc.value.value == ["2", "3", "4"]
def test_generator_iterable_bare(self):
@typechecked
def genfunc() -> Iterable:
yield 2
yield 3
yield 4
values = list(genfunc())
assert values == [2, 3, 4]
def test_generator_iterable_annotated(self):
@typechecked
def genfunc() -> Iterable[int]:
yield 2
yield 3
yield 4
values = list(genfunc())
assert values == [2, 3, 4]
def test_generator_iterator_bare(self):
@typechecked
def genfunc() -> Iterator:
yield 2
yield 3
yield 4
values = list(genfunc())
assert values == [2, 3, 4]
def test_generator_iterator_annotated(self):
@typechecked
def genfunc() -> Iterator[int]:
yield 2
yield 3
yield 4
values = list(genfunc())
assert values == [2, 3, 4]
def test_bad_yield_as_generator(self):
@typechecked
def genfunc() -> Generator[int, str, None]:
yield "foo"
gen = genfunc()
with pytest.raises(TypeCheckError) as exc:
next(gen)
exc.match(r"the yielded value \(str\) is not an instance of int")
def test_bad_yield_as_iterable(self):
@typechecked
def genfunc() -> Iterable[int]:
yield "foo"
gen = genfunc()
with pytest.raises(TypeCheckError) as exc:
next(gen)
exc.match(r"the yielded value \(str\) is not an instance of int")
def test_bad_yield_as_iterator(self):
@typechecked
def genfunc() -> Iterator[int]:
yield "foo"
gen = genfunc()
with pytest.raises(TypeCheckError) as exc:
next(gen)
exc.match(r"the yielded value \(str\) is not an instance of int")
def test_generator_bad_send(self):
@typechecked
def genfunc() -> Generator[int, str, None]:
yield 1
yield 2
pass
gen = genfunc()
next(gen)
with pytest.raises(TypeCheckError) as exc:
gen.send(2)
exc.match(r"value sent to generator \(int\) is not an instance of str")
def test_generator_bad_return(self):
@typechecked
def genfunc() -> Generator[int, str, str]:
yield 1
return 6
gen = genfunc()
next(gen)
with pytest.raises(TypeCheckError) as exc:
gen.send("foo")
exc.match(r"return value \(int\) is not an instance of str")
def test_return_generator(self):
@typechecked
def genfunc() -> Generator[int, None, None]:
yield 1
@typechecked
def foo() -> Generator[int, None, None]:
return genfunc()
foo()
class TestAsyncGenerator:
def test_async_generator_bare(self):
@typechecked
async def genfunc() -> AsyncGenerator:
values.append((yield 2))
values.append((yield 3))
values.append((yield 4))
async def run_generator():
gen = genfunc()
value = await gen.asend(None)
with pytest.raises(StopAsyncIteration):
while True:
value = await gen.asend(str(value))
assert isinstance(value, int)
values = []
asyncio.run(run_generator())
assert values == ["2", "3", "4"]
def test_async_generator_annotated(self):
@typechecked
async def genfunc() -> AsyncGenerator[int, str]:
values.append((yield 2))
values.append((yield 3))
values.append((yield 4))
async def run_generator():
gen = genfunc()
value = await gen.asend(None)
with pytest.raises(StopAsyncIteration):
while True:
value = await gen.asend(str(value))
assert isinstance(value, int)
values = []
asyncio.run(run_generator())
assert values == ["2", "3", "4"]
def test_generator_iterable_bare(self):
@typechecked
async def genfunc() -> AsyncIterable:
yield 2
yield 3
yield 4
async def run_generator():
return [value async for value in genfunc()]
assert asyncio.run(run_generator()) == [2, 3, 4]
def test_generator_iterable_annotated(self):
@typechecked
async def genfunc() -> AsyncIterable[int]:
yield 2
yield 3
yield 4
async def run_generator():
return [value async for value in genfunc()]
assert asyncio.run(run_generator()) == [2, 3, 4]
def test_generator_iterator_bare(self):
@typechecked
async def genfunc() -> AsyncIterator:
yield 2
yield 3
yield 4
async def run_generator():
return [value async for value in genfunc()]
assert asyncio.run(run_generator()) == [2, 3, 4]
def test_generator_iterator_annotated(self):
@typechecked
async def genfunc() -> AsyncIterator[int]:
yield 2
yield 3
yield 4
async def run_generator():
return [value async for value in genfunc()]
assert asyncio.run(run_generator()) == [2, 3, 4]
def test_async_bad_yield_as_generator(self):
@typechecked
async def genfunc() -> AsyncGenerator[int, str]:
yield "foo"
gen = genfunc()
with pytest.raises(TypeCheckError) as exc:
next(gen.__anext__().__await__())
exc.match(r"the yielded value \(str\) is not an instance of int")
def test_async_bad_yield_as_iterable(self):
@typechecked
async def genfunc() -> AsyncIterable[int]:
yield "foo"
gen = genfunc()
with pytest.raises(TypeCheckError) as exc:
next(gen.__anext__().__await__())
exc.match(r"the yielded value \(str\) is not an instance of int")
def test_async_bad_yield_as_iterator(self):
@typechecked
async def genfunc() -> AsyncIterator[int]:
yield "foo"
gen = genfunc()
with pytest.raises(TypeCheckError) as exc:
next(gen.__anext__().__await__())
exc.match(r"the yielded value \(str\) is not an instance of int")
def test_async_generator_bad_send(self):
@typechecked
async def genfunc() -> AsyncGenerator[int, str]:
yield 1
yield 2
gen = genfunc()
pytest.raises(StopIteration, next, gen.__anext__().__await__())
with pytest.raises(TypeCheckError) as exc:
next(gen.asend(2).__await__())
exc.match(r"the value sent to generator \(int\) is not an instance of str")
def test_return_async_generator(self):
@typechecked
async def genfunc() -> AsyncGenerator[int, None]:
yield 1
@typechecked
def foo() -> AsyncGenerator[int, None]:
return genfunc()
foo()
def test_async_generator_iterate(self):
@typechecked
async def asyncgenfunc() -> AsyncGenerator[int, None]:
yield 1
asyncgen = asyncgenfunc()
aiterator = asyncgen.__aiter__()
exc = pytest.raises(StopIteration, aiterator.__anext__().send, None)
assert exc.value.value == 1
class TestSelf:
def test_return_valid(self):
class Foo:
@typechecked
def method(self) -> Self:
return self
Foo().method()
def test_return_invalid(self):
class Foo:
@typechecked
def method(self) -> Self:
return 1
foo = Foo()
pytest.raises(TypeCheckError, foo.method).match(
rf"the return value \(int\) is not an instance of the self type "
rf"\({__name__}\.{self.__class__.__name__}\.test_return_invalid\."
rf"<locals>\.Foo\)"
)
def test_classmethod_return_valid(self):
class Foo:
@classmethod
@typechecked
def method(cls) -> Self:
return Foo()
Foo.method()
def test_classmethod_return_invalid(self):
class Foo:
@classmethod
@typechecked
def method(cls) -> Self:
return 1
pytest.raises(TypeCheckError, Foo.method).match(
rf"the return value \(int\) is not an instance of the self type "
rf"\({__name__}\.{self.__class__.__name__}\."
rf"test_classmethod_return_invalid\.<locals>\.Foo\)"
)
def test_arg_valid(self):
class Foo:
@typechecked
def method(self, another: Self) -> None:
pass
foo = Foo()
foo2 = Foo()
foo.method(foo2)
def test_arg_invalid(self):
class Foo:
@typechecked
def method(self, another: Self) -> None:
pass
foo = Foo()
pytest.raises(TypeCheckError, foo.method, 1).match(
rf'argument "another" \(int\) is not an instance of the self type '
rf"\({__name__}\.{self.__class__.__name__}\.test_arg_invalid\."
rf"<locals>\.Foo\)"
)
def test_classmethod_arg_valid(self):
class Foo:
@classmethod
@typechecked
def method(cls, another: Self) -> None:
pass
foo = Foo()
Foo.method(foo)
def test_classmethod_arg_invalid(self):
class Foo:
@classmethod
@typechecked
def method(cls, another: Self) -> None:
pass
foo = Foo()
pytest.raises(TypeCheckError, foo.method, 1).match(
rf'argument "another" \(int\) is not an instance of the self type '
rf"\({__name__}\.{self.__class__.__name__}\."
rf"test_classmethod_arg_invalid\.<locals>\.Foo\)"
)
def test_self_type_valid(self):
class Foo:
@typechecked
def method(cls, subclass: type[Self]) -> None:
pass
class Bar(Foo):
pass
Foo().method(Bar)
def test_self_type_invalid(self):
class Foo:
@typechecked
def method(cls, subclass: type[Self]) -> None:
pass
pytest.raises(TypeCheckError, Foo().method, int).match(
rf'argument "subclass" \(class int\) is not a subclass of the self type '
rf"\({__name__}\.{self.__class__.__name__}\."
rf"test_self_type_invalid\.<locals>\.Foo\)"
)
class TestMock:
def test_mock_argument(self):
@typechecked
def foo(x: int) -> None:
pass
foo(Mock())
def test_return_mock(self):
@typechecked
def foo() -> int:
return Mock()
foo()
def test_decorator_before_classmethod():
class Foo:
@typechecked
@classmethod
def method(cls, x: int) -> None:
pass
pytest.raises(TypeCheckError, Foo().method, "bar").match(
r'argument "x" \(str\) is not an instance of int'
)
def test_classmethod():
@typechecked
class Foo:
@classmethod
def method(cls, x: int) -> None:
pass
pytest.raises(TypeCheckError, Foo().method, "bar").match(
r'argument "x" \(str\) is not an instance of int'
)
def test_decorator_before_staticmethod():
class Foo:
@typechecked
@staticmethod
def method(x: int) -> None:
pass
pytest.raises(TypeCheckError, Foo().method, "bar").match(
r'argument "x" \(str\) is not an instance of int'
)
def test_staticmethod():
@typechecked
class Foo:
@staticmethod
def method(x: int) -> None:
pass
pytest.raises(TypeCheckError, Foo().method, "bar").match(
r'argument "x" \(str\) is not an instance of int'
)
def test_retain_dunder_attributes():
@typechecked
def foo(x: int, y: str = "foo") -> None:
"""This is a docstring."""
assert foo.__module__ == __name__
assert foo.__name__ == "foo"
assert foo.__qualname__ == "test_retain_dunder_attributes.<locals>.foo"
assert foo.__doc__ == "This is a docstring."
assert foo.__defaults__ == ("foo",)
@pytest.mark.skipif(sys.version_info < (3, 9), reason="Requires ast.unparse()")
def test_debug_instrumentation(monkeypatch, capsys):
monkeypatch.setattr("typeguard.config.debug_instrumentation", True)
@typechecked
def foo(a: str) -> int:
return 6
out, err = capsys.readouterr()
assert err == dedent(
"""\
Source code of test_debug_instrumentation.<locals>.foo() after instrumentation:
----------------------------------------------
def foo(a: str) -> int:
from typeguard import TypeCheckMemo
from typeguard._functions import check_argument_types, check_return_type
memo = TypeCheckMemo(globals(), locals())
check_argument_types('test_debug_instrumentation.<locals>.foo', \
{'a': (a, str)}, memo)
return check_return_type('test_debug_instrumentation.<locals>.foo', 6, \
int, memo)
----------------------------------------------
"""
)
def test_keyword_argument_default():
# Regression test for #305
@typechecked
def foo(*args, x: "int | None" = None):
pass
foo()
def test_return_type_annotation_refers_to_nonlocal():
class Internal:
pass
@typechecked
def foo() -> Internal:
return Internal()
assert isinstance(foo(), Internal)
def test_existing_method_decorator():
@typechecked
class Foo:
@contextmanager
def method(self, x: int) -> None:
yield x + 1
with Foo().method(6) as value:
assert value == 7
@pytest.mark.parametrize(
"flags, expected_return_code",
[
pytest.param([], 1, id="debug"),
pytest.param(["-O"], 0, id="O"),
pytest.param(["-OO"], 0, id="OO"),
],
)
def test_typechecked_disabled_in_optimized_mode(
tmp_path: Path, flags: List[str], expected_return_code: int
):
code = dedent(
"""
from typeguard import typechecked
@typechecked
def foo(x: int) -> None:
pass
foo("a")
"""
)
script_path = tmp_path / "code.py"
script_path.write_text(code)
process = subprocess.run(
[sys.executable, *flags, str(script_path)], capture_output=True
)
assert process.returncode == expected_return_code
if process.returncode == 1:
assert process.stderr.strip().endswith(
b'typeguard.TypeCheckError: argument "x" (str) is not an instance of int'
)
def test_reference_imported_name_from_method() -> None:
# Regression test for #362
@typechecked
class A:
def foo(self) -> Dict[str, Any]:
return {}
A().foo()
def test_getter_setter():
"""Regression test for #355."""
@typechecked
class Foo:
def __init__(self, x: int):
self._x = x
@property
def x(self) -> int:
return self._x
@x.setter
def x(self, value: int) -> None:
self._x = value
f = Foo(1)
f.x = 2
assert f.x == 2
with pytest.raises(TypeCheckError):
f.x = "foo"
def test_duplicate_method():
class Foo:
def x(self) -> str:
return "first"
@typechecked()
def x(self, value: int) -> str: # noqa: F811
return "second"
assert Foo().x(1) == "second"
with pytest.raises(TypeCheckError):
Foo().x("wrong")
def test_duplicate_function():
@typechecked
def foo() -> list[int]: # noqa: F811
return [x for x in range(5)]
foo1 = foo
@typechecked
def foo() -> list[int]: # noqa: F811
return [x for x in range(5, 10)]
assert foo1() == [0, 1, 2, 3, 4]
assert foo() == [5, 6, 7, 8, 9]
|