Skip to content

Commit 9a9229c

Browse files
authored
recasting might happen on already cast objects (re-invokes) (#94)
1 parent 92b87c3 commit 9a9229c

File tree

2 files changed

+10
-6
lines changed

2 files changed

+10
-6
lines changed

src/cloudformation_cli_python_lib/recast.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33

44
from .exceptions import InvalidRequest
55

6+
PRIMITIVES = (str, bool, int, float)
7+
68

79
# CloudFormation recasts all primitive types as strings, this tries to set them back to
810
# the types in the type hints
@@ -22,7 +24,7 @@ def recast_object(
2224
json_data[k] = _recast_lists(cls, k, v, classes)
2325
elif isinstance(v, set):
2426
json_data[k] = _recast_sets(cls, k, v, classes)
25-
elif isinstance(v, str):
27+
elif isinstance(v, PRIMITIVES):
2628
dest_type = _field_to_type(cls.__dataclass_fields__[k].type, k, classes)
2729
json_data[k] = _recast_primitive(dest_type, k, v)
2830
else:
@@ -47,7 +49,7 @@ def _recast_sets(cls: Any, k: str, v: Set[Any], classes: Dict[str, Any]) -> Set[
4749

4850

4951
def cast_sequence_item(cls: Any, k: str, item: Any, classes: Dict[str, Any]) -> Any:
50-
if isinstance(item, str):
52+
if isinstance(item, PRIMITIVES):
5153
return _recast_primitive(cls, k, item)
5254
if isinstance(item, list):
5355
return _recast_lists(cls, k, item, classes)
@@ -59,12 +61,12 @@ def cast_sequence_item(cls: Any, k: str, item: Any, classes: Dict[str, Any]) ->
5961
raise InvalidRequest(f"Unsupported type: {type(item)} for {k}")
6062

6163

62-
def _recast_primitive(cls: Any, k: str, v: str) -> Any:
64+
def _recast_primitive(cls: Any, k: str, v: Any) -> Any:
6365
if cls == typing.Any:
6466
# If the type is Any, we cannot guess what the original type was, so we leave
6567
# it as a string
6668
return v
67-
if cls == bool:
69+
if cls == bool and isinstance(v, str):
6870
if v.lower() == "true":
6971
return True
7072
if v.lower() == "false":

tests/lib/recast_test.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -79,8 +79,10 @@ def test_recast_complex_object():
7979
],
8080
}
8181
model = ComplexResourceModel._deserialize(payload)
82-
assert expected == payload
83-
assert expected == model._serialize()
82+
assert payload == expected
83+
assert model._serialize() == expected
84+
# re-invocations should not fail because they already type-cast payloads
85+
assert ComplexResourceModel._deserialize(payload)._serialize() == expected
8486

8587

8688
def test_recast_object_invalid_json_type():

0 commit comments

Comments
 (0)