|
1 | 1 | import unittest |
2 | 2 | from unittest import TestCase |
3 | 3 | import typing |
| 4 | +import collections.abc as cabc |
4 | 5 |
|
5 | 6 | from runtype.base_types import DataType, ContainerType, PhantomType |
6 | | -from runtype.pytypes import List, Dict, Int, Any, Constraint, String, Tuple, Iter |
| 7 | +from runtype.pytypes import cast_to_type, List, Dict, Int, Any, Constraint, String, Tuple, Iter |
7 | 8 | from runtype.typesystem import TypeSystem |
8 | 9 |
|
9 | 10 |
|
@@ -137,6 +138,51 @@ def test_pytypes(self): |
137 | 138 |
|
138 | 139 | assert List[int] == List[int] |
139 | 140 |
|
| 141 | + def test_canonize_pytypes(self): |
| 142 | + pytypes = [ |
| 143 | + int, str, list, dict, typing.Optional[int], |
| 144 | + typing.Sequence[int], |
| 145 | + |
| 146 | + # collections.abc |
| 147 | + cabc.Hashable, cabc.Sized, cabc.Callable, cabc.Iterable, cabc.Container, |
| 148 | + cabc.Collection, cabc.Iterator, cabc.Reversible, cabc.Generator, |
| 149 | + cabc.Sequence, cabc.MutableSequence, cabc.ByteString, |
| 150 | + cabc.Set, cabc.MutableSet, |
| 151 | + cabc.Mapping, cabc.MutableMapping, |
| 152 | + cabc.MappingView, cabc.ItemsView, cabc.KeysView, cabc.ValuesView, |
| 153 | + cabc.Awaitable, cabc.Coroutine, |
| 154 | + cabc.AsyncIterable, cabc.AsyncIterator, cabc.AsyncGenerator, |
| 155 | + |
| 156 | + typing.NoReturn |
| 157 | + ] |
| 158 | + for t in pytypes: |
| 159 | + a = cast_to_type(t) |
| 160 | + # assert a.kernel == t, (a,t) |
| 161 | + |
| 162 | + |
| 163 | + type_to_values = { |
| 164 | + cabc.Hashable: ([1, "a", frozenset()], [{}, set()]), |
| 165 | + cabc.Sized: ([(), {}], [10]), |
| 166 | + cabc.Callable: ([int, lambda:1], [3, "a"]), |
| 167 | + cabc.Iterable: ([(), {}, "", iter([])], [3]), |
| 168 | + cabc.Container: ([(), ""], [3]), |
| 169 | + cabc.Collection: ([(), ""], [iter([])]), |
| 170 | + cabc.Iterator: ([iter([])], [[]]), |
| 171 | + cabc.Reversible: ([[], ""], [iter([])]), |
| 172 | + cabc.Generator: ([(x for x in [])], [3, iter('')]), |
| 173 | + |
| 174 | + cabc.Set: ([set()], [{}]), |
| 175 | + cabc.ItemsView: ([{}.items()], [{}]) |
| 176 | + } |
| 177 | + |
| 178 | + for pyt, (good, bad) in type_to_values.items(): |
| 179 | + t = cast_to_type(pyt) |
| 180 | + for g in good: |
| 181 | + assert t.test_instance(g), (t, g) |
| 182 | + for b in bad: |
| 183 | + assert not t.test_instance(b), (t, b) |
| 184 | + |
| 185 | + |
140 | 186 |
|
141 | 187 |
|
142 | 188 |
|
|
0 commit comments