From 1b64234457838dec6ae16465c91b6e56c38f6411 Mon Sep 17 00:00:00 2001 From: Leandro Damascena Date: Wed, 13 Mar 2024 09:21:06 +0000 Subject: [PATCH] fix(event_handler): make decoded_body field optional in ApiGateway resolver (#3937) Making the field optional --- .../utilities/data_classes/common.py | 13 ++++++++----- tests/unit/test_data_classes.py | 14 -------------- 2 files changed, 8 insertions(+), 19 deletions(-) diff --git a/aws_lambda_powertools/utilities/data_classes/common.py b/aws_lambda_powertools/utilities/data_classes/common.py index 104993deae8..ffca15cc318 100644 --- a/aws_lambda_powertools/utilities/data_classes/common.py +++ b/aws_lambda_powertools/utilities/data_classes/common.py @@ -150,13 +150,16 @@ def body(self) -> Optional[str]: @cached_property def json_body(self) -> Any: """Parses the submitted body as json""" - return self._json_deserializer(self.decoded_body) + if self.decoded_body: + return self._json_deserializer(self.decoded_body) + + return None @cached_property - def decoded_body(self) -> str: - """Dynamically base64 decode body as a str""" - body: str = self["body"] - if self.is_base64_encoded: + def decoded_body(self) -> Optional[str]: + """Decode the body from base64 if encoded, otherwise return it as is.""" + body: Optional[str] = self.body + if self.is_base64_encoded and body: return base64.b64decode(body.encode()).decode() return body diff --git a/tests/unit/test_data_classes.py b/tests/unit/test_data_classes.py index c8f0c1fc932..393bcdf250e 100644 --- a/tests/unit/test_data_classes.py +++ b/tests/unit/test_data_classes.py @@ -324,13 +324,6 @@ def test_base_proxy_event_get_header_value_case_insensitive(): assert value is None -def test_base_proxy_event_json_body_key_error(): - event = BaseProxyEvent({}) - with pytest.raises(KeyError) as ke: - assert not event.json_body - assert str(ke.value) == "'body'" - - def test_base_proxy_event_json_body(): data = {"message": "Foo"} event = BaseProxyEvent({"body": json.dumps(data)}) @@ -338,13 +331,6 @@ def test_base_proxy_event_json_body(): assert event.json_body["message"] == "Foo" -def test_base_proxy_event_decode_body_key_error(): - event = BaseProxyEvent({}) - with pytest.raises(KeyError) as ke: - assert not event.decoded_body - assert str(ke.value) == "'body'" - - def test_base_proxy_event_decode_body_encoded_false(): data = "Foo" event = BaseProxyEvent({"body": data, "isBase64Encoded": False})