From aecf17fef1a8d7db5217fc03d67aab17c0649c00 Mon Sep 17 00:00:00 2001 From: Rebecca Law Date: Wed, 13 May 2020 10:37:41 +0100 Subject: [PATCH] This morning we raise a ParseError for a bad date format for the DateReceived attribute on the /notifications/receive/mmg request. This PR tries to parse the date, if that throws an error return now as the datereceived. This will at least allow the message to be persisted. Typically the DateReceived, provider_date, and the created_at date in the inbound_sms table are within a second of each other. --- app/notifications/receive_notifications.py | 10 +++++++--- tests/app/notifications/test_receive_notification.py | 6 ++++++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/app/notifications/receive_notifications.py b/app/notifications/receive_notifications.py index abf92ca51..53a4cf8a0 100644 --- a/app/notifications/receive_notifications.py +++ b/app/notifications/receive_notifications.py @@ -1,3 +1,4 @@ +from datetime import datetime from urllib.parse import unquote import iso8601 @@ -115,9 +116,12 @@ def format_mmg_datetime(date): We expect datetimes in format 2017-05-21+11%3A56%3A11 - ie, spaces replaced with pluses, and URI encoded and in UTC """ - orig_date = format_mmg_message(date) - parsed_datetime = iso8601.parse_date(orig_date).replace(tzinfo=None) - return parsed_datetime + try: + orig_date = format_mmg_message(date) + parsed_datetime = iso8601.parse_date(orig_date).replace(tzinfo=None) + return parsed_datetime + except iso8601.ParseError: + return datetime.utcnow() def create_inbound_sms_object(service, content, from_number, provider_ref, date_received, provider_name): diff --git a/tests/app/notifications/test_receive_notification.py b/tests/app/notifications/test_receive_notification.py index e41cc9ef8..80eddd8af 100644 --- a/tests/app/notifications/test_receive_notification.py +++ b/tests/app/notifications/test_receive_notification.py @@ -4,6 +4,7 @@ from unittest.mock import call import pytest from flask import json +from freezegun import freeze_time from app.notifications.receive_notifications import ( format_mmg_message, @@ -216,6 +217,11 @@ def test_format_mmg_datetime(provider_date, expected_output): assert format_mmg_datetime(provider_date) == expected_output +@freeze_time('2020-05-14 14:30:00') +def test_format_mmg_datetime_returns_now_if_cannot_parse_date(): + assert format_mmg_datetime('13-05-2020 08%3A37%3A43') == datetime.utcnow() + + def test_create_inbound_mmg_sms_object(sample_service_full_permissions): data = { 'Message': 'hello+there+%F0%9F%93%A9',