Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions backend/tests/utils/generic_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
from decimal import Decimal
from typing import Literal, Any
from jsonpath_ng.ext import parse
from datetime import datetime, date
from typing import Union, List


def load_json_data(filename: str):
Expand Down Expand Up @@ -91,3 +93,21 @@ def update_contained_resource_field(
{field_to_update: update_value}
)
return json_data

def format_date_types(dates: List[Union[date, datetime]], mode: str = "auto") -> List[str]:
"""
Accepts a list of date or datetime objects and returns them as strings:
- datetime → ISO 8601 string with timezone if present
- date → 'YYYY-MM-DD'
"""
formatted = []

for future_date in dates:
if mode == "datetime":
formatted.append(future_date.isoformat()) # full datetime with timezone
elif mode == "date":
formatted.append(future_date.strftime('%Y-%m-%d')) # just date
else:
raise TypeError(f"Unsupported type {type(future_date)}; expected date or datetime.")

return formatted
27 changes: 26 additions & 1 deletion backend/tests/utils/test_generic_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@

import unittest
from src.models.utils.generic_utils import form_json
from tests.utils.generic_utils import load_json_data
from tests.utils.generic_utils import load_json_data, format_date_types

import unittest
from datetime import datetime, date


class TestFormJson(unittest.TestCase):
Expand Down Expand Up @@ -70,3 +73,25 @@ def test_elements_whitespace_and_case_are_handled(self):
)
self.assertEqual(res["id"], self.response["id"])
self.assertEqual(res["meta"]["versionId"], self.response["version"])


class TestFormatFutureDates(unittest.TestCase):
def test_date_mode_formats_dates_and_datetimes(self):
inputs = [date(2100, 1, 2), datetime(2100, 1, 3, 12, 0, 0)]
expected = ["2100-01-02", "2100-01-03"]
self.assertEqual(format_date_types(inputs, mode="date"), expected)

def test_datetime_mode_formats_dates_and_datetimes(self):
inputs = [date(2100, 1, 2), datetime(2100, 1, 3, 12, 0, 0)]
expected = ["2100-01-02", "2100-01-03T12:00:00"]
self.assertEqual(format_date_types(inputs, mode="datetime"), expected)

def test_default_auto_mode_is_currently_unsupported(self):
# Current implementation raises TypeError when mode is not 'date' or 'datetime'
inputs = [date(2100, 1, 2)]
with self.assertRaises(TypeError):
format_date_types(inputs) # default mode is 'auto'


if __name__ == "__main__":
unittest.main()
16 changes: 11 additions & 5 deletions backend/tests/utils/values_for_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

from dataclasses import dataclass
from decimal import Decimal
from .generic_utils import format_date_types
from datetime import datetime, timedelta


# Lists of data types for 'invalid data type' testing
integers = [-1, 0, 1]
Expand Down Expand Up @@ -291,16 +294,20 @@ class InvalidValues:
"2000-02-30", # Invalid combination of month and day
]

for_future_dates = [
"2100-01-01", # Year in future
"2050-12-31", # Year in future
"2029-06-15", # Year in future
now = datetime.now()
sample_inputs = [
now + timedelta(days=1),
now + timedelta(days=365),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good set of test cases. Always preferred to mock datetime/now but in place of this, the approach used is fine.

now + timedelta(days=730)
]

for_future_dates = format_date_types(sample_inputs, mode = "date")

# Strings which are not in acceptable date time format
for_date_time_string_formats_for_relaxed_timezone = [
"", # Empty string
"invalid", # Invalid format
*format_date_types(sample_inputs, mode = "datetime"),
"20000101", # Date digits only (i.e. without hypens)
"20000101000000", # Date and time digits only
"200001010000000000", # Date, time and timezone digits only
Expand Down Expand Up @@ -392,4 +399,3 @@ class InvalidValues:
]

invalid_dose_quantity = {"value": 2, "unit": "ml", "code": "258773002"}

1 change: 0 additions & 1 deletion lambdas/id_sync/src/pds_details.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ def pds_get_patient_details(nhs_number: str) -> dict:
)
pds_service = PdsService(authenticator, pds_env)
patient = pds_service.get_patient_details(nhs_number)
logger.info("get patient details. response: %s", patient)
return patient
except Exception as e:
msg = f"Error getting PDS patient details for {nhs_number}"
Expand Down
1 change: 0 additions & 1 deletion lambdas/shared/src/common/pds_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ def get_patient_details(self, patient_id) -> dict | None:
response = requests.get(f"{self.base_url}/{patient_id}", headers=request_headers, timeout=5)

if response.status_code == 200:
logger.info(f"PDS. Response: {response.json()}")
return response.json()
elif response.status_code == 404:
logger.info(f"PDS. Patient not found for ID: {patient_id}")
Expand Down
Loading