|
| 1 | +import typing as ty |
| 2 | + |
| 3 | +from typecats import Cat, register_unstruc_hook_func |
| 4 | + |
| 5 | + |
| 6 | +@Cat |
| 7 | +class Container: |
| 8 | + one: ty.Any |
| 9 | + many: ty.List[ty.Any] |
| 10 | + |
| 11 | + |
| 12 | +@Cat |
| 13 | +class SecondContainer: |
| 14 | + thing: ty.Any |
| 15 | + |
| 16 | + |
| 17 | +@Cat |
| 18 | +class SomeCat: |
| 19 | + field: str |
| 20 | + |
| 21 | + |
| 22 | +class HasUnstrucHook: |
| 23 | + def __init__(self, unstruc_field): |
| 24 | + self.unstruc_field = unstruc_field |
| 25 | + |
| 26 | + |
| 27 | +class WithoutUnstrucHook: |
| 28 | + def __init__(self, some_field): |
| 29 | + self.some_field = some_field |
| 30 | + |
| 31 | + |
| 32 | +def test_unstruc_cat_types_in_any_fields(): |
| 33 | + container = Container( |
| 34 | + one=SecondContainer( |
| 35 | + thing=SomeCat(field="a"), |
| 36 | + ), |
| 37 | + many=[ |
| 38 | + SecondContainer( |
| 39 | + thing=SomeCat(field="b"), |
| 40 | + ), |
| 41 | + SomeCat(field="c"), |
| 42 | + ], |
| 43 | + ) |
| 44 | + |
| 45 | + expected = { |
| 46 | + "one": {"thing": {"field": "a"}}, |
| 47 | + "many": [{"thing": {"field": "b"}}, {"field": "c"}], |
| 48 | + } |
| 49 | + |
| 50 | + assert container.unstruc() == expected |
| 51 | + |
| 52 | + |
| 53 | +def test_unstruc_of_non_cat_in_any_field_with_unstruc_hook(): |
| 54 | + register_unstruc_hook_func( |
| 55 | + lambda t: t == HasUnstrucHook, lambda x: {"unstruc_field": x.unstruc_field} |
| 56 | + ) |
| 57 | + |
| 58 | + # This has no unstruc hook registered and should therefore be returned as-is |
| 59 | + no_unstruc = WithoutUnstrucHook("some_str_0") |
| 60 | + |
| 61 | + container = Container( |
| 62 | + one=HasUnstrucHook("some_str_1"), |
| 63 | + many=[no_unstruc, HasUnstrucHook("some_str_2")], |
| 64 | + ) |
| 65 | + |
| 66 | + expected = { |
| 67 | + "one": {"unstruc_field": "some_str_1"}, |
| 68 | + "many": [no_unstruc, {"unstruc_field": "some_str_2"}], |
| 69 | + } |
| 70 | + |
| 71 | + assert container.unstruc() == expected |
0 commit comments