|
| 1 | +import functools |
1 | 2 | import typing |
2 | 3 | from copy import deepcopy |
3 | 4 | from functools import partial |
| 5 | +from typing import Any |
4 | 6 |
|
5 | 7 | import pytest |
6 | 8 | from attrs import define |
@@ -432,3 +434,42 @@ class Child1G(GenericParent[str]): |
432 | 434 | assert genconverter.structure({"p": 5, "c": 5}, GenericParent[str]) == Child1G( |
433 | 435 | "5", "5" |
434 | 436 | ) |
| 437 | + |
| 438 | + |
| 439 | +def test_parents_with_generics_tagged_union(genconverter: Converter): |
| 440 | + """Ensure proper handling of generic parents with configure_tagged_union, #682.""" |
| 441 | + |
| 442 | + @define |
| 443 | + class GenericParent(typing.Generic[T]): |
| 444 | + p: T |
| 445 | + |
| 446 | + @define |
| 447 | + class Child1G(GenericParent[str]): |
| 448 | + c: str |
| 449 | + |
| 450 | + @define |
| 451 | + class Child2G(GenericParent[int]): |
| 452 | + c: str |
| 453 | + |
| 454 | + union_strategy = functools.partial( |
| 455 | + configure_tagged_union, |
| 456 | + tag_generator=lambda cl: (typing.get_origin(cl) or cl).__name__, |
| 457 | + ) |
| 458 | + include_subclasses(GenericParent[Any], genconverter, union_strategy=union_strategy) |
| 459 | + |
| 460 | + assert genconverter.unstructure(Child1G("5", "5")) == { |
| 461 | + "p": "5", |
| 462 | + "c": "5", |
| 463 | + "_type": "Child1G", |
| 464 | + } |
| 465 | + assert genconverter.unstructure(Child2G(1, "5")) == { |
| 466 | + "p": 1, |
| 467 | + "c": "5", |
| 468 | + "_type": "Child2G", |
| 469 | + } |
| 470 | + assert genconverter.structure( |
| 471 | + {"p": "5", "c": "5", "_type": "Child1G"}, GenericParent[Any] |
| 472 | + ) == Child1G("5", "5") |
| 473 | + assert genconverter.structure( |
| 474 | + {"p": 1, "c": "5", "_type": "Child2G"}, GenericParent[Any] |
| 475 | + ) == Child2G(1, "5") |
0 commit comments