Skip to content

Commit a5fec56

Browse files
authored
Merge pull request #9 from erezsh/aug12
Dispatch() can now be used in 'with'; more tests
2 parents 707ccba + d296bcc commit a5fec56

File tree

2 files changed

+51
-1
lines changed

2 files changed

+51
-1
lines changed

runtype/dispatch.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,11 @@ def dispatched_f(*args, **kw):
3838

3939
return dispatched_f
4040

41+
def __enter__(self):
42+
return self
4143

44+
def __exit__(self, exc_type, exc_value, exc_traceback):
45+
pass
4246

4347
class TypeTree:
4448
def __init__(self):

tests/test_types.py

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
import unittest
22
from unittest import TestCase
33
import typing
4+
import collections.abc as cabc
45

56
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
78
from runtype.typesystem import TypeSystem
89

910

@@ -137,6 +138,51 @@ def test_pytypes(self):
137138

138139
assert List[int] == List[int]
139140

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+
140186

141187

142188

0 commit comments

Comments
 (0)