1 from __future__ import annotations

2

3 import typing

4

5 import pytest

6

7 from muutils.validate_type import validate_type

8

9

10@pytest.mark.parametrize(

11 "value, expected_type, expected_result",

12 [

13 (5, int | str, True), # type: ignore[operator]

14 ("hello", int | str, True), # type: ignore[operator]

15 (5.0, int | str, False), # type: ignore[operator]

16 (None, typing.Union[int, type(None)], True), # type: ignore[operator]

17 (None, typing.Union[int, str], False), # type: ignore[operator]

18 (None, int | str, False), # type: ignore[operator]

19 (42, int | None, True), # type: ignore[operator]

20 ("hello", int | None, False), # type: ignore[operator]

21 (3.14, int | None, False), # type: ignore[operator]

22 ([1], typing.List[int] | None, True), # type: ignore[operator]

23 (None, int | None, True), # type: ignore[operator]

24 (None, str | None, True), # type: ignore[operator]

25 (None, None | str, True), # type: ignore[operator]

26 (None, None | int, True), # type: ignore[operator]

27 (None, str | int, False), # type: ignore[operator]

28 (None, None | typing.List[typing.Dict[str, int]], True), # type: ignore[operator]

29 ],

30)

31 def test_validate_type_union(value, expected_type, expected_result):

32 try:

33 assert validate_type(value, expected_type) == expected_result

34 except Exception as e:

35 raise Exception(

36 f"{value = }, {expected_type = }, {expected_result = }, {e}"

37 ) from e

38

39

40@pytest.mark.parametrize(

41 "value, expected_type",

42 [

43 (42, list[int, str]), # type: ignore[misc]

44 ([1, 2, 3], list[int, str]), # type: ignore[misc]

45 ({"a": 1, "b": 2}, set[str, int]), # type: ignore[misc]

46 ({1: "a", 2: "b"}, set[int, str]), # type: ignore[misc]

47 ({"a": 1, "b": 2}, set[str, int, str]), # type: ignore[misc]

48 ({1: "a", 2: "b"}, set[int, str, int]), # type: ignore[misc]

49 ({1, 2, 3}, set[int, str]), # type: ignore[misc]

50 ({"a"}, set[int, str]), # type: ignore[misc]

51 (42, dict[int, str, bool]), # type: ignore[misc]

52 ],

53)

54 def test_validate_type_unsupported_generic_alias(value, expected_type):

55 with pytest.raises(TypeError):

56 validate_type(value, expected_type)

57 print(f"Failed to except: {value = }, {expected_type = }")