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
from collections.abc import Callable, Generator
from typing import Literal, Any

import pytest
from testlib.utils import is_value_of_type


def test_list_type_valid():
    assert is_value_of_type([1, 2, 3], list[int])


def test_list_type_valid_multi_type():
    assert is_value_of_type([1, "a", 2], list[int | str])
    assert is_value_of_type([1, "a", 2], set[str | int] | list[int | str])


def test_list_type_invalid_single_fail():
    assert not is_value_of_type([1, 2, "a"], list[int])


def test_list_type_invalid_all_wrong():
    assert not is_value_of_type([1, 2, 3], list[str])


def test_list_type_nested():
    assert is_value_of_type([[1], [2, 3], [4]], list[list[int]])


def test_list_type_nested_single_invalid():
    assert not is_value_of_type([[1], [2, 3], ["a"]], list[list[int]])


def test_none_type():
    assert is_value_of_type(None, None)


def test_none_type_union():
    assert is_value_of_type(None, int | None)


def test_weird_type_valid():
    assert is_value_of_type(42, Literal[42])


def test_type_type():
    class Foo: ...

    assert is_value_of_type(Foo, type[Foo])


def test_type_doesnt_allow_generator():
    def foo():
        yield 1

    with pytest.raises(ValueError, match=r"Unsupported expected_type.+"):
        is_value_of_type(foo, Generator[int, None, None])


def test_type_doesnt_allow_callable():
    def foo(a):  # noqa: ANN001, ANN202 # dummy stuff within testing, nothing external
        return "a" + str(a)

    with pytest.raises(ValueError, match=r"Unsupported expected_type.+"):
        is_value_of_type(foo, Callable[[int], str])


def test_type_allows_none():
    assert is_value_of_type(None, type[None])


def test_doesnt_allow_generic():
    class X[T]: ...

    with pytest.raises(ValueError, match=r"Unsupported expected_type.+"):
        is_value_of_type(0, X[int])


def test_type_dict_checks_valid():
    d = {"a": 1, "b": 2}
    assert is_value_of_type(d, dict[str, int])


def test_type_dict_key_invalid():
    d = {"a": 1, 1: 2}
    assert not is_value_of_type(d, dict[str, int])


def test_type_dict_value_invalid():
    d = {"a": 1, "b": "2"}
    assert not is_value_of_type(d, dict[str, int])


def test_type_allows_any():
    assert is_value_of_type(1, Any)
    assert is_value_of_type("a", Any)
    assert is_value_of_type(lambda x: x, Any)