Skip to content

Commit 9a83030

Browse files
committed
dynamodb_client.transact_write_items
1 parent e46b182 commit 9a83030

File tree

3 files changed

+44
-40
lines changed

3 files changed

+44
-40
lines changed

lambdas/id_sync/src/ieds_db_operations.py

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from boto3.dynamodb.conditions import Key
22
from os_vars import get_ieds_table_name
33
from common.aws_dynamodb import get_dynamodb_table
4-
from common.clients import logger
4+
from common.clients import logger, dynamodb_client
55
from exceptions.id_sync_exception import IdSyncException
66

77
ieds_table = None
@@ -52,7 +52,7 @@ def ieds_update_patient_id(old_id: str, new_id: str) -> dict:
5252
old_patient_pk = f"Patient#{old_id}"
5353

5454
logger.info("Getting items to update in IEDS table...")
55-
items_to_update = get_items_to_update(old_patient_pk)
55+
items_to_update = get_items_from_patient_pk(old_patient_pk)
5656

5757
if not items_to_update:
5858
logger.warning(f"No items found to update for patient ID: {old_id}")
@@ -65,12 +65,13 @@ def ieds_update_patient_id(old_id: str, new_id: str) -> dict:
6565

6666
logger.info("loop through items to update...")
6767
logger.info(f"Items to update: {len(items_to_update)}")
68+
ieds_table_name = get_ieds_table_name()
6869
for item in items_to_update:
6970
logger.info("Update item")
7071
logger.info(f"Updating item: {item['PatientPK']}")
7172
transact_items.append({
7273
'Update': {
73-
'TableName': get_ieds_table_name(),
74+
'TableName': ieds_table_name,
7475
'Key': {
7576
'PK': {'S': item['PK']},
7677
},
@@ -92,7 +93,7 @@ def ieds_update_patient_id(old_id: str, new_id: str) -> dict:
9293
total_batches += 1
9394
logger.info(f"Transacting batch {total_batches} of size: {len(batch)}")
9495

95-
response = ieds_table.transact_write_items(TransactItems=batch)
96+
response = dynamodb_client.transact_write_items(TransactItems=batch)
9697
logger.info("Batch update complete. Response: %s", response)
9798

9899
# Check each batch response
@@ -119,13 +120,12 @@ def ieds_update_patient_id(old_id: str, new_id: str) -> dict:
119120

120121
except Exception as e:
121122
logger.exception("Error updating patient ID")
123+
logger.info("Error details: %s", e)
122124
raise IdSyncException(
123125
message=f"Error updating patient Id from :{old_id} to {new_id}",
124126
nhs_numbers=[old_id, new_id],
125127
exception=e
126128
)
127-
# ✅ Fix: Remove duplicate raise
128-
# raise e # Remove this line
129129

130130
# def test_ieds_insert_patient(patient_id: str) -> dict: # NOSONAR
131131
# """Test function for inserting patient ID."""
@@ -147,25 +147,25 @@ def ieds_update_patient_id(old_id: str, new_id: str) -> dict:
147147
# return result
148148

149149

150-
def get_items_to_update(old_patient_pk: str) -> list:
151-
"""Get items that need to be updated in the IEDS table."""
152-
logger.info(f"Getting items to update for old patient PK: {old_patient_pk}")
150+
def get_items_from_patient_pk(patient_pk: str) -> list:
151+
"""Get all items for patient PK."""
152+
logger.info(f"Getting items for patient PK: {patient_pk}")
153153
try:
154154
response = get_ieds_table().query(
155155
IndexName='PatientGSI', # query the GSI
156-
KeyConditionExpression=Key('PatientPK').eq(old_patient_pk),
156+
KeyConditionExpression=Key('PatientPK').eq(patient_pk),
157157
Limit=BATCH_SIZE
158158
)
159159

160160
if 'Items' not in response or not response['Items']:
161-
logger.warning(f"No items found for old patient PK: {old_patient_pk}")
161+
logger.warning(f"No items found for patient PK: {patient_pk}")
162162
return []
163163

164164
return response['Items']
165165
except Exception as e:
166-
logger.exception(f"Error querying items for old patient PK: {old_patient_pk}")
166+
logger.exception(f"Error querying items for patient PK: {patient_pk}")
167167
raise IdSyncException(
168-
message=f"Error querying items for old patient PK: {old_patient_pk}",
169-
nhs_numbers=[old_patient_pk],
168+
message=f"Error querying items for patient PK: {patient_pk}",
169+
nhs_numbers=[patient_pk],
170170
exception=e
171171
)

lambdas/id_sync/tests/test_ieds_db_operations.py

Lines changed: 29 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -415,12 +415,15 @@ def setUp(self):
415415
self.mock_table = MagicMock()
416416
self.mock_get_ieds_table_patcher.return_value = self.mock_table
417417

418+
self.mock_dynamodb_client = patch('ieds_db_operations.dynamodb_client')
419+
self.mock_dynamodb_client_patcher = self.mock_dynamodb_client.start()
420+
418421
# Mock transact_write_items (not update_item)
419-
self.mock_table.transact_write_items = MagicMock()
422+
self.mock_dynamodb_client_patcher.transact_write_items = MagicMock()
420423

421-
# Mock get_items_to_update
422-
self.get_items_to_update_patcher = patch('ieds_db_operations.get_items_to_update')
423-
self.mock_get_items_to_update = self.get_items_to_update_patcher.start()
424+
# Mock get_items_from_patient_pk
425+
self.get_items_from_patient_pk_patcher = patch('ieds_db_operations.get_items_from_patient_pk')
426+
self.mock_get_items_from_patient_pk = self.get_items_from_patient_pk_patcher.start()
424427

425428
# Mock get_ieds_table_name
426429
self.get_ieds_table_name_patcher = patch('ieds_db_operations.get_ieds_table_name')
@@ -438,27 +441,27 @@ def test_ieds_update_patient_id_success(self):
438441
{'PK': 'Patient#old-patient-123', 'PatientPK': 'Patient#old-patient-123'},
439442
{'PK': 'Patient#old-patient-123#record1', 'PatientPK': 'Patient#old-patient-123'}
440443
]
441-
self.mock_get_items_to_update.return_value = mock_items
444+
self.mock_get_items_from_patient_pk.return_value = mock_items
442445

443446
# Mock successful transact_write_items response
444447
mock_transact_response = {'ResponseMetadata': {'HTTPStatusCode': 200}}
445-
self.mock_table.transact_write_items.return_value = mock_transact_response
448+
self.mock_dynamodb_client_patcher.transact_write_items.return_value = mock_transact_response
446449

447450
# Act
448451
result = ieds_db_operations.ieds_update_patient_id(old_id, new_id)
449452

450-
# Assert - ✅ Fix: Update expected message to match actual implementation
453+
# Assert - Update expected message to match actual implementation
451454
expected_result = {
452455
"status": "success",
453456
"message": f"IEDS update, patient ID: {old_id}=>{new_id}. {len(mock_items)} updated 1."
454457
}
455458
self.assertEqual(result, expected_result)
456459

457-
# Verify get_items_to_update was called
458-
self.mock_get_items_to_update.assert_called_once_with(f"Patient#{old_id}")
460+
# Verify get_items_from_patient_pk was called
461+
self.mock_get_items_from_patient_pk.assert_called_once_with(f"Patient#{old_id}")
459462

460463
# Verify transact_write_items was called
461-
self.mock_table.transact_write_items.assert_called_once()
464+
self.mock_dynamodb_client_patcher.transact_write_items.assert_called_once()
462465

463466
# Verify table was retrieved
464467
self.mock_get_ieds_table_patcher.assert_called_once()
@@ -471,11 +474,11 @@ def test_ieds_update_patient_id_non_200_response(self):
471474

472475
# Mock items to update
473476
mock_items = [{'PK': 'Patient#old-patient-123', 'PatientPK': 'Patient#old-patient-123'}]
474-
self.mock_get_items_to_update.return_value = mock_items
477+
self.mock_get_items_from_patient_pk.return_value = mock_items
475478

476479
# ✅ Fix: Mock failed transact_write_items response (not update_item)
477480
mock_transact_response = {'ResponseMetadata': {'HTTPStatusCode': 400}}
478-
self.mock_table.transact_write_items.return_value = mock_transact_response
481+
self.mock_dynamodb_client_patcher.transact_write_items.return_value = mock_transact_response
479482

480483
# Act
481484
result = ieds_db_operations.ieds_update_patient_id(old_id, new_id)
@@ -488,7 +491,7 @@ def test_ieds_update_patient_id_non_200_response(self):
488491
self.assertEqual(result, expected_result)
489492

490493
# ✅ Fix: Verify transact_write_items was called (not update_item)
491-
self.mock_table.transact_write_items.assert_called_once()
494+
self.mock_dynamodb_client_patcher.transact_write_items.assert_called_once()
492495

493496
def test_ieds_update_patient_id_no_items_found(self):
494497
"""Test when no items are found to update"""
@@ -497,7 +500,7 @@ def test_ieds_update_patient_id_no_items_found(self):
497500
new_id = "new-patient-456"
498501

499502
# Mock empty items list
500-
self.mock_get_items_to_update.return_value = []
503+
self.mock_get_items_from_patient_pk.return_value = []
501504

502505
# Act
503506
result = ieds_db_operations.ieds_update_patient_id(old_id, new_id)
@@ -509,8 +512,8 @@ def test_ieds_update_patient_id_no_items_found(self):
509512
}
510513
self.assertEqual(result, expected_result)
511514

512-
# Verify get_items_to_update was called
513-
self.mock_get_items_to_update.assert_called_once_with(f"Patient#{old_id}")
515+
# Verify get_items_from_patient_pk was called
516+
self.mock_get_items_from_patient_pk.assert_called_once_with(f"Patient#{old_id}")
514517

515518
# Verify no transact operation was attempted
516519
self.mock_table.transact_write_items.assert_not_called()
@@ -582,10 +585,10 @@ def test_ieds_update_patient_id_update_exception(self):
582585

583586
# Mock items to update
584587
mock_items = [{'PK': 'Patient#old-patient-error', 'PatientPK': 'Patient#old-patient-error'}]
585-
self.mock_get_items_to_update.return_value = mock_items
588+
self.mock_get_items_from_patient_pk.return_value = mock_items
586589

587590
test_exception = Exception("DynamoDB transact failed")
588-
self.mock_table.transact_write_items.side_effect = test_exception
591+
self.mock_dynamodb_client_patcher.transact_write_items.side_effect = test_exception
589592

590593
# Act & Assert
591594
with self.assertRaises(Exception) as context:
@@ -598,7 +601,7 @@ def test_ieds_update_patient_id_update_exception(self):
598601
self.assertEqual(exception.inner_exception, test_exception)
599602

600603
# Verify transact was attempted
601-
self.mock_table.transact_write_items.assert_called_once()
604+
self.mock_dynamodb_client_patcher.transact_write_items.assert_called_once()
602605

603606
# Verify logger exception was called
604607
self.mock_logger.exception.assert_called_once_with("Error updating patient ID")
@@ -611,10 +614,10 @@ def test_ieds_update_patient_id_special_characters(self):
611614

612615
# Mock items to update
613616
mock_items = [{'PK': f'Patient#{old_id}', 'PatientPK': f'Patient#{old_id}'}]
614-
self.mock_get_items_to_update.return_value = mock_items
617+
self.mock_get_items_from_patient_pk.return_value = mock_items
615618

616619
mock_transact_response = {'ResponseMetadata': {'HTTPStatusCode': 200}}
617-
self.mock_table.transact_write_items.return_value = mock_transact_response
620+
self.mock_dynamodb_client_patcher.transact_write_items.return_value = mock_transact_response
618621

619622
# Act
620623
result = ieds_db_operations.ieds_update_patient_id(old_id, new_id)
@@ -624,7 +627,7 @@ def test_ieds_update_patient_id_special_characters(self):
624627
self.assertEqual(result["message"], f"IEDS update, patient ID: {old_id}=>{new_id}. {len(mock_items)} updated 1.")
625628

626629
# Verify transact_write_items was called with special characters
627-
self.mock_table.transact_write_items.assert_called_once()
630+
self.mock_dynamodb_client_patcher.transact_write_items.assert_called_once()
628631

629632

630633
class TestGetItemsToUpdate(TestIedsDbOperations):
@@ -640,7 +643,7 @@ def setUp(self):
640643
def tearDown(self):
641644
patch.stopall()
642645

643-
def test_get_items_to_update_success(self):
646+
def test_get_items_from_patient_pk_success(self):
644647
"""Test successful retrieval of items to update"""
645648
# Arrange
646649
patient_id = "test-patient-123"
@@ -654,15 +657,15 @@ def test_get_items_to_update_success(self):
654657
}
655658

656659
# Act
657-
result = ieds_db_operations.get_items_to_update(f"Patient#{patient_id}")
660+
result = ieds_db_operations.get_items_from_patient_pk(f"Patient#{patient_id}")
658661

659662
# Assert
660663
self.assertEqual(result, expected_items)
661664

662665
# Verify query was called with correct parameters
663666
self.mock_table.query.assert_called_once()
664667

665-
def test_get_items_to_update_no_records(self):
668+
def test_get_items_from_patient_pk_no_records(self):
666669
"""Test when no records are found for the patient ID"""
667670
# Arrange
668671
patient_id = "test-patient-no-records"
@@ -672,7 +675,7 @@ def test_get_items_to_update_no_records(self):
672675
}
673676

674677
# Act
675-
result = ieds_db_operations.get_items_to_update(f"Patient#{patient_id}")
678+
result = ieds_db_operations.get_items_from_patient_pk(f"Patient#{patient_id}")
676679

677680
# Assert
678681
self.assertEqual(result, [])

lambdas/shared/src/common/clients.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,4 @@
1919
# secretsmanager_client = boto3_client("secretsmanager", config=boto_config)
2020
secrets_manager_client = boto3_client("secretsmanager", region_name=REGION_NAME)
2121
dynamodb_resource = boto3.resource("dynamodb", region_name=REGION_NAME)
22+
dynamodb_client = boto3_client("dynamodb", region_name=REGION_NAME)

0 commit comments

Comments
 (0)