|
| 1 | +from dataclasses import dataclass |
| 2 | +from datetime import datetime |
| 3 | +from typing import Generic, TypeVar |
| 4 | + |
| 5 | +import pytest |
| 6 | + |
| 7 | +from dataclasses_json import dataclass_json |
| 8 | + |
| 9 | +S = TypeVar("S") |
| 10 | +T = TypeVar("T") |
| 11 | + |
| 12 | + |
| 13 | +@dataclass_json |
| 14 | +@dataclass |
| 15 | +class Bar: |
| 16 | + value: int |
| 17 | + |
| 18 | + |
| 19 | +@dataclass_json |
| 20 | +@dataclass |
| 21 | +class Foo(Generic[T]): |
| 22 | + bar: T |
| 23 | + |
| 24 | + |
| 25 | +@dataclass_json |
| 26 | +@dataclass |
| 27 | +class Baz(Generic[T]): |
| 28 | + foo: Foo[T] |
| 29 | + |
| 30 | + |
| 31 | +@pytest.mark.parametrize( |
| 32 | + "instance_of_t, decodes_successfully", |
| 33 | + [ |
| 34 | + pytest.param(1, True, id="literal"), |
| 35 | + pytest.param([1], True, id="literal_list"), |
| 36 | + pytest.param({"a": 1}, True, id="map_of_literal"), |
| 37 | + pytest.param(datetime(2021, 1, 1), False, id="extended_type"), |
| 38 | + pytest.param(Bar(1), False, id="object"), |
| 39 | + ] |
| 40 | +) |
| 41 | +def test_dataclass_with_generic_dataclass_field(instance_of_t, decodes_successfully): |
| 42 | + foo = Foo(bar=instance_of_t) |
| 43 | + baz = Baz(foo=foo) |
| 44 | + decoded = Baz[type(instance_of_t)].from_json(baz.to_json()) |
| 45 | + assert decoded.foo == Foo.from_json(foo.to_json()) |
| 46 | + if decodes_successfully: |
| 47 | + assert decoded == baz |
| 48 | + else: |
| 49 | + assert decoded != baz |
| 50 | + |
| 51 | + |
| 52 | +@dataclass_json |
| 53 | +@dataclass |
| 54 | +class Foo2(Generic[T, S]): |
| 55 | + bar1: T |
| 56 | + bar2: S |
| 57 | + |
| 58 | + |
| 59 | +@dataclass_json |
| 60 | +@dataclass |
| 61 | +class Baz2(Generic[T, S]): |
| 62 | + foo2: Foo2[T, S] |
| 63 | + |
| 64 | + |
| 65 | +@pytest.mark.parametrize( |
| 66 | + "instance_of_t, decodes_successfully", |
| 67 | + [ |
| 68 | + pytest.param(1, True, id="literal"), |
| 69 | + pytest.param([1], True, id="literal_list"), |
| 70 | + pytest.param({"a": 1}, True, id="map_of_literal"), |
| 71 | + pytest.param(datetime(2021, 1, 1), False, id="extended_type"), |
| 72 | + pytest.param(Bar(1), False, id="object"), |
| 73 | + ] |
| 74 | +) |
| 75 | +def test_dataclass_with_multiple_generic_dataclass_fields(instance_of_t, decodes_successfully): |
| 76 | + foo2 = Foo2(bar1=instance_of_t, bar2=instance_of_t) |
| 77 | + baz = Baz2(foo2=foo2) |
| 78 | + decoded = Baz2[type(instance_of_t), type(instance_of_t)].from_json(baz.to_json()) |
| 79 | + assert decoded.foo2 == Foo2.from_json(foo2.to_json()) |
| 80 | + if decodes_successfully: |
| 81 | + assert decoded == baz |
| 82 | + else: |
| 83 | + assert decoded != baz |
0 commit comments