Skip to content

Commit

Permalink
Add support for Mock and MagicMock types. (#105)
Browse files Browse the repository at this point in the history
These are analogous to Any, except for values instead of arguments.
Any accepts any value. MagicMock can pretend to be any type.
  • Loading branch information
prescod committed Apr 6, 2020
1 parent 7507ca9 commit 4d5dc39
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
19 changes: 19 additions & 0 deletions tests/test_typeguard.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from concurrent.futures import ThreadPoolExecutor
from functools import wraps, partial, lru_cache
from io import StringIO, BytesIO
from unittest.mock import Mock, MagicMock
from typing import (
Any, Callable, Dict, List, Set, Tuple, Union, TypeVar, Sequence, NamedTuple, Iterable,
Container, Generic, BinaryIO, TextIO, Generator, Iterator, SupportsInt, AbstractSet)
Expand Down Expand Up @@ -38,6 +39,11 @@ def method(self, a: int):
pass


@pytest.fixture(params=[Mock, MagicMock], ids=['mock', 'magicmock'])
def mock_class(request):
return request.param


@pytest.mark.parametrize('inputval, expected', [
(qualified_name, 'function'),
(Child(), 'test_typeguard.Child'),
Expand Down Expand Up @@ -83,6 +89,12 @@ def foo(a: Any):

foo('aa')

def test_mock_value(self, mock_class):
def foo(a: str, b: int, c: dict, d: Any) -> int:
assert check_argument_types()

foo(mock_class(), mock_class(), mock_class(), mock_class())

def test_callable_exact_arg_count(self):
def foo(a: Callable[[int, str], int]):
assert check_argument_types()
Expand Down Expand Up @@ -722,6 +734,13 @@ def foo() -> None:
exc = pytest.raises(TypeError, foo)
assert str(exc.value) == 'type of the return value must be NoneType; got str instead'

def test_return_type_magicmock(self, mock_class):
@typechecked
def foo() -> str:
return mock_class()

foo()

@pytest.mark.parametrize('typehint', [
Callable[..., int],
Callable
Expand Down
3 changes: 2 additions & 1 deletion typeguard/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
Callable, Any, Union, Dict, List, TypeVar, Tuple, Set, Sequence, get_type_hints, TextIO,
Optional, IO, BinaryIO, Type, Generator, overload, Iterable, AsyncIterable, Iterator,
AsyncIterator, AbstractSet)
from unittest.mock import Mock
from warnings import warn
from weakref import WeakKeyDictionary, WeakValueDictionary

Expand Down Expand Up @@ -552,7 +553,7 @@ def check_type(argname: str, value, expected_type, memo: Optional[_CallMemo] = N
:param expected_type: a class or generic type instance
"""
if expected_type is Any:
if expected_type is Any or isinstance(value, Mock):
return

if expected_type is None:
Expand Down

0 comments on commit 4d5dc39

Please sign in to comment.