Skip to content

Commit

Permalink
added test for sending notitication
Browse files Browse the repository at this point in the history
  • Loading branch information
Jin-Sun-tts committed Dec 4, 2024
1 parent d1360ff commit c464a2c
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 40 deletions.
58 changes: 27 additions & 31 deletions harvester/harvest.py
Original file line number Diff line number Diff line change
Expand Up @@ -401,49 +401,45 @@ def report(self) -> None:
if hasattr(self, "notification_emails") and self.notification_emails:
self.send_notification_emails(actual_results_action)

def send_notification_emails(self, results: dict) -> str:
try:
job_url = f'{SMTP_CONFIG["base_url"]}/harvest_job/{self.job_id}'

subject = "Harvest Job Completed"
body = (
f"The harvest job ({self.job_id}) has been successfully completed.\n"
f"You can view the details here: {job_url}\n\n"
"Summary of the job:\n"
f"- Records Added: {results['create']}\n"
f"- Records Updated: {results['update']}\n"
f"- Records Deleted: {results['delete']}\n"
f"- Records Ignored: {results[None]}\n\n"
"====\n"
"You received this email because you subscribed to harvester updates.\n"
"Please do not reply to this email, as it is not monitored."
)
support_recipient = SMTP_CONFIG.get("recipient")
user_recipients = self.notification_emails
all_recipients = [support_recipient] + user_recipients
def send_notification_emails(self, results: dict) -> None:
job_url = f'{SMTP_CONFIG["base_url"]}/harvest_job/{self.job_id}'

subject = "Harvest Job Completed"
body = (
f"The harvest job ({self.job_id}) has been successfully completed.\n"
f"You can view the details here: {job_url}\n\n"
"Summary of the job:\n"
f"- Records Added: {results['create']}\n"
f"- Records Updated: {results['update']}\n"
f"- Records Deleted: {results['delete']}\n"
f"- Records Ignored: {results[None]}\n\n"
"====\n"
"You received this email because you subscribed to harvester updates.\n"
"Please do not reply to this email, as it is not monitored."
)
support_recipient = SMTP_CONFIG.get("recipient")
user_recipients = self.notification_emails
all_recipients = [support_recipient] + user_recipients

msg = MIMEMultipart()
msg["From"] = SMTP_CONFIG["default_sender"]
msg["Reply-To"] = "[email protected]"
msg["Subject"] = subject
msg.attach(MIMEText(body, "plain"))

try:
with smtplib.SMTP(SMTP_CONFIG["server"], SMTP_CONFIG["port"]) as server:
if SMTP_CONFIG["use_tls"]:
server.starttls()
server.login(SMTP_CONFIG["username"], SMTP_CONFIG["password"])

for recipient in all_recipients:
msg = MIMEMultipart()
msg["From"] = SMTP_CONFIG["default_sender"]
msg["To"] = recipient
msg["Reply-To"] = "[email protected]"
msg["Subject"] = subject
msg.attach(MIMEText(body, "plain"))

server.sendmail(SMTP_CONFIG["default_sender"], [recipient],
msg.as_string())
logger.info(f"Notification email sent to: {recipient}")
return "Emails sent successfully"

except Exception as e:
error_message = "Error preparing or sending notification emails"
logger.error(error_message + f": {e}")
return error_message
logger.error(f"Failed to send notification email: {e}")


@dataclass
Expand Down
22 changes: 13 additions & 9 deletions tests/integration/harvest/test_harvest_full_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,13 +162,16 @@ def test_validate_same_title(
assert kwargs["id"] == "5678"
assert kwargs["identifier"] == "cftc-dc2"

@patch("harvester.harvest.ckan")
@patch("harvester.harvest.smtplib.SMTP")
def test_harvest_send_notification_failure(
def test_send_notification_emails(
self,
mock_smtp,
CKANMock,
interface,
organization_data,
source_data_dcatus_single_record,
caplog
):
CKANMock.action.package_create.return_value = {"id": 1234}
CKANMock.action.package_update = "ok"
Expand All @@ -183,16 +186,17 @@ def test_harvest_send_notification_failure(
)
job_id = harvest_job.id
harvest_source = HarvestSource(job_id)
harvest_source.notification_emails = source_data_dcatus_single_record[
"notification_emails"
]
harvest_source.notification_emails = [source_data_dcatus_single_record[
"notification_emails"]]

results = {"create": 10, "update": 5, "delete": 3, None: 2}
mock_smtp.side_effect = Exception("SMTP connection failed")
error_message = harvest_source.send_notification_emails(results)

assert mock_smtp.side_effect is not None, "Mock SMTP side_effect was not set!"

assert error_message == "Error preparing or sending notification emails"
# Test Success Case
harvest_source.send_notification_emails(results)
assert "Notification email sent to" in caplog.text

# Test Failure Case
mock_smtp.side_effect = Exception("SMTP failed")
harvest_source.send_notification_emails(results)
assert "Failed to send notification email: SMTP failed" in caplog.text

1 comment on commit c464a2c

@github-actions
Copy link

Choose a reason for hiding this comment

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

Tests Skipped Failures Errors Time
2 0 💤 0 ❌ 0 🔥 8.429s ⏱️

Please sign in to comment.