diff --git a/.gitignore b/.gitignore index 3a3c72a..6339aeb 100644 --- a/.gitignore +++ b/.gitignore @@ -137,4 +137,5 @@ doc/dist # IDE files .idea -.vscode +.vscode/* +!.vscode/settings.json diff --git a/.vscode/settings.json b/.vscode/settings.json index 97aef07..22791a0 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -12,5 +12,10 @@ "python.linting.lintOnSave": true, "python.linting.mypyEnabled": true, "mypy.dmypyExecutable": "${workspaceFolder}/venv/bin/dmypy", - "files.autoSave": "afterDelay" + "files.autoSave": "afterDelay", + "python.testing.pytestArgs": [ + "tests" + ], + "python.testing.unittestEnabled": false, + "python.testing.pytestEnabled": true } diff --git a/src/firebase_functions/pubsub_fn.py b/src/firebase_functions/pubsub_fn.py index 4647a1b..ebac90e 100644 --- a/src/firebase_functions/pubsub_fn.py +++ b/src/firebase_functions/pubsub_fn.py @@ -105,6 +105,13 @@ def _message_handler( data = event_dict["data"] message_dict = data["message"] + # if no microseconds are present, we should set them to 0 to prevent parsing from failing + if "." not in event_dict["time"]: + event_dict["time"] = event_dict["time"].replace("Z", ".000000Z") + if "." not in message_dict["publish_time"]: + message_dict["publish_time"] = message_dict["publish_time"].replace( + "Z", ".000000Z") + time = _dt.datetime.strptime( event_dict["time"], "%Y-%m-%dT%H:%M:%S.%f%z", diff --git a/tests/test_pubsub_fn.py b/tests/test_pubsub_fn.py index c0b9665..74ae72e 100644 --- a/tests/test_pubsub_fn.py +++ b/tests/test_pubsub_fn.py @@ -129,3 +129,32 @@ def init(): _message_handler(func, raw_event) self.assertEqual("world", hello) + + def test_datetime_without_mircroseconds_doesnt_throw(self): + time = "2023-03-11T13:25:37Z" + raw_event = _CloudEvent( + attributes={ + "id": "test-message", + "source": "https://example.com/pubsub", + "specversion": "1.0", + "time": time, + "type": "com.example.pubsub.message", + }, + data={ + "message": { + "attributes": { + "key": "value" + }, + "data": "eyJ0ZXN0IjogInZhbHVlIn0=", + "message_id": "message-id-123", + "publish_time": time, + }, + "subscription": "my-subscription", + }, + ) + try: + _message_handler(lambda _: None, raw_event) + # pylint: disable=broad-except + except Exception: + self.fail( + "Datetime without microseconds should not throw an exception")