|
| 1 | +import collections |
| 2 | +import typing |
1 | 3 | from typing import Type
|
2 | 4 |
|
3 | 5 | import attr
|
@@ -43,3 +45,58 @@ class B(A):
|
43 | 45 |
|
44 | 46 | # This should still work, but using the new hook instead.
|
45 | 47 | assert converter.structure({"i": 1}, B) == B(2)
|
| 48 | + |
| 49 | + |
| 50 | +@pytest.mark.parametrize("converter_cls", [Converter, GenConverter]) |
| 51 | +@pytest.mark.parametrize( |
| 52 | + "typing_cls", [typing.Hashable, typing.Iterable, typing.Reversible] |
| 53 | +) |
| 54 | +def test_inherit_typing(converter_cls: Type[Converter], typing_cls): |
| 55 | + """Stuff from typing.* resolves to runtime to collections.abc.*. |
| 56 | +
|
| 57 | + Hence, typing.* are of a special alias type which we want to check if |
| 58 | + cattrs handles them correctly. |
| 59 | + """ |
| 60 | + converter = converter_cls() |
| 61 | + |
| 62 | + @attr.define |
| 63 | + class A(typing_cls): |
| 64 | + i: int = 0 |
| 65 | + |
| 66 | + def __hash__(self): |
| 67 | + return hash(self.i) |
| 68 | + |
| 69 | + def __iter__(self): |
| 70 | + return iter([self.i]) |
| 71 | + |
| 72 | + def __reversed__(self): |
| 73 | + return iter([self.i]) |
| 74 | + |
| 75 | + assert converter.structure({"i": 1}, A) == A(i=1) |
| 76 | + |
| 77 | + |
| 78 | +@pytest.mark.parametrize("converter_cls", [Converter, GenConverter]) |
| 79 | +@pytest.mark.parametrize( |
| 80 | + "collections_abc_cls", |
| 81 | + [collections.abc.Hashable, collections.abc.Iterable, collections.abc.Reversible], |
| 82 | +) |
| 83 | +def test_inherit_collections_abc( |
| 84 | + converter_cls: Type[Converter], collections_abc_cls |
| 85 | +): |
| 86 | + """As extension of test_inherit_typing, check if collections.abc.* work.""" |
| 87 | + converter = converter_cls() |
| 88 | + |
| 89 | + @attr.define |
| 90 | + class A(collections_abc_cls): |
| 91 | + i: int = 0 |
| 92 | + |
| 93 | + def __hash__(self): |
| 94 | + return hash(self.i) |
| 95 | + |
| 96 | + def __iter__(self): |
| 97 | + return iter([self.i]) |
| 98 | + |
| 99 | + def __reversed__(self): |
| 100 | + return iter([self.i]) |
| 101 | + |
| 102 | + assert converter.structure({"i": 1}, A) == A(i=1) |
0 commit comments