aboutsummaryrefslogtreecommitdiffstats
path: root/test/mitmproxy/utils/test_typecheck.py
blob: a21c65c9cd868863b583919fe2f45eb2ebc7f9c7 (plain)
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
import io
import typing
from unittest import mock
import pytest

from mitmproxy.utils import typecheck


class TBase:
    def __init__(self, bar: int):
        pass


class T(TBase):
    def __init__(self, foo: str):
        super(T, self).__init__(42)


def test_get_arg_type_from_constructor_annotation():
    assert typecheck.get_arg_type_from_constructor_annotation(T, "foo") == str
    assert typecheck.get_arg_type_from_constructor_annotation(T, "bar") == int
    assert not typecheck.get_arg_type_from_constructor_annotation(T, "baz")


def test_check_type():
    typecheck.check_type("foo", 42, int)
    with pytest.raises(TypeError):
        typecheck.check_type("foo", 42, str)
    with pytest.raises(TypeError):
        typecheck.check_type("foo", None, str)
    with pytest.raises(TypeError):
        typecheck.check_type("foo", b"foo", str)


def test_check_union():
    typecheck.check_type("foo", 42, typing.Union[int, str])
    typecheck.check_type("foo", "42", typing.Union[int, str])
    with pytest.raises(TypeError):
        typecheck.check_type("foo", [], typing.Union[int, str])


def test_check_tuple():
    with pytest.raises(TypeError):
        typecheck.check_type("foo", None, typing.Tuple[int, str])
    with pytest.raises(TypeError):
        typecheck.check_type("foo", (), typing.Tuple[int, str])
    with pytest.raises(TypeError):
        typecheck.check_type("foo", (42, 42), typing.Tuple[int, str])
    with pytest.raises(TypeError):
        typecheck.check_type("foo", ("42", 42), typing.Tuple[int, str])
    typecheck.check_type("foo", (42, "42"), typing.Tuple[int, str])


def test_check_sequence():
    typecheck.check_type("foo", [10], typing.Sequence[int])
    with pytest.raises(TypeError):
        typecheck.check_type("foo", ["foo"], typing.Sequence[int])
    with pytest.raises(TypeError):
        typecheck.check_type("foo", [10, "foo"], typing.Sequence[int])
    with pytest.raises(TypeError):
        typecheck.check_type("foo", [b"foo"], typing.Sequence[str])
    with pytest.raises(TypeError):
        typecheck.check_type("foo", "foo", typing.Sequence[str])

    # Python 3.5.0 only defines __parameters__
    m = mock.Mock()
    m.__str__ = lambda self: "typing.Sequence"
    m.__parameters__ = (int,)
    typecheck.check_type("foo", [10], m)


def test_check_io():
    typecheck.check_type("foo", io.StringIO(), typing.IO[str])
    with pytest.raises(TypeError):
        typecheck.check_type("foo", "foo", typing.IO[str])