From 9b1291e7808dbe35ac292aec4ecc521af9e6ac3a Mon Sep 17 00:00:00 2001 From: Will Holmes Date: Tue, 4 Jul 2023 10:36:51 -0400 Subject: [PATCH] Remove fractions from timestamp during response parsing to fix rare bug caused by timestamps with no fractions --- src/pyspeedinsights/api/response.py | 5 ++++- tests/api/test_response.py | 12 +++++++++--- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/src/pyspeedinsights/api/response.py b/src/pyspeedinsights/api/response.py index cdf6a68..b083324 100644 --- a/src/pyspeedinsights/api/response.py +++ b/src/pyspeedinsights/api/response.py @@ -126,6 +126,9 @@ def _get_timestamp(json_resp: dict) -> str: A str in format year-month-day_hour.minute.second. """ timestamp = json_resp["analysisUTCTimestamp"] - dt_object = datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S.%fZ") + ts_no_fractions = timestamp.split(".")[0] # Remove fraction + if ts_no_fractions[-1] != "Z": + ts_no_fractions += "Z" # Add Z back after fraction removal + dt_object = datetime.strptime(ts_no_fractions, "%Y-%m-%dT%H:%M:%SZ") date = dt_object.strftime("%Y-%m-%d_%H.%M.%S") return date diff --git a/tests/api/test_response.py b/tests/api/test_response.py index 910ae33..710cbbf 100644 --- a/tests/api/test_response.py +++ b/tests/api/test_response.py @@ -11,7 +11,7 @@ class TestProcessExcel: def _get_json_resp(self, all_metrics, category="performance"): return { - "analysisUTCTimestamp": "2023-02-26T17:36:18.266Z", + "analysisUTCTimestamp": "2023-02-26T17:36:18", "lighthouseResult": { "configSettings": {"formFactor": "desktop"}, "categories": {category: {"score": 1}}, @@ -88,7 +88,7 @@ def test_process_excel_non_performance_without_metrics(self, all_metrics): def test_parse_metadata(): json_resp = { - "analysisUTCTimestamp": "2023-02-26T17:36:18.266Z", + "analysisUTCTimestamp": "2023-02-26T17:36:18Z", "lighthouseResult": { "configSettings": {"formFactor": "desktop"}, "categories": {"performance": {"score": 1}}, @@ -162,6 +162,12 @@ def test_get_audits_base(): def test_get_timestamp(): - json_resp = {"analysisUTCTimestamp": "2023-02-26T17:36:18.266Z"} + json_resp = {"analysisUTCTimestamp": "2023-02-26T17:36:18Z"} + timestamp = _get_timestamp(json_resp) + assert timestamp == "2023-02-26_17.36.18" + + +def test_get_timestamp_fraction_removed(): + json_resp = {"analysisUTCTimestamp": "2023-02-26T17:36:18.123Z"} timestamp = _get_timestamp(json_resp) assert timestamp == "2023-02-26_17.36.18"