import base64 import io import json import unittest from email import policy from email.parser import BytesParser from urllib.error import HTTPError from urllib.parse import parse_qs from unittest.mock import patch from app.services import email class GmailDeliveryTests(unittest.TestCase): def setUp(self): self.enterContext(patch.multiple( email.settings, gmail_client_id="test-id", gmail_client_secret="test-secret", gmail_refresh_token="test-refresh", gmail_from_email="sender@example.com", )) self.http = self.enterContext(patch.object(email, "urlopen")) self.resend = self.enterContext(patch.object(email, "_send_resend_email")) self.smtp = self.enterContext(patch.object(email.smtplib, "SMTP")) def test_both_mail_types_refresh_and_send(self): for send, value in ( (email.send_email_verification_code, "123456"), (email.send_password_reset_email, "https://example.net/reset"), ): with self.subTest(send=send.__name__): self.http.reset_mock() self.http.side_effect = [ io.BytesIO(b'{"access_token":"test-access"}'), io.BytesIO(b'{"id":"test-message"}'), ] self.assertTrue(send("runner@example.net", value)) refresh, message = [call.args[0] for call in self.http.call_args_list] self.assertEqual(refresh.full_url, "https://oauth2.googleapis.com/token") self.assertEqual(parse_qs(refresh.data.decode("ascii")), { "client_id": ["test-id"], "client_secret": ["test-secret"], "refresh_token": ["test-refresh"], "grant_type": ["refresh_token"], }) self.assertEqual(message.full_url, "https://gmail.googleapis.com/gmail/v1/users/me/messages/send") self.assertEqual(message.get_header("Authorization"), "Bearer test-access") raw = base64.urlsafe_b64decode(json.loads(message.data)["raw"]) parsed = BytesParser(policy=policy.default).parsebytes(raw) self.assertEqual(parsed["From"].addresses[0].addr_spec, "sender@example.com") self.assertEqual(parsed["To"], "runner@example.net") self.assertIn(value, parsed.get_content()) self.resend.assert_not_called() self.smtp.assert_not_called() def test_refresh_rejection_never_sends_or_logs_credentials(self): self.http.side_effect = HTTPError( "https://oauth2.googleapis.com/token", 400, "test-secret", {}, None ) with self.assertLogs(email.logger, level="ERROR") as logs: self.assertFalse(email.send_email_verification_code("runner@example.net", "123456")) self.assertEqual(self.http.call_count, 1) self.assertNotIn("test-secret", "\n".join(logs.output)) self.resend.assert_not_called() self.smtp.assert_not_called() def test_incomplete_configuration_never_calls_provider(self): with patch.object(email.settings, "gmail_refresh_token", None): self.assertFalse(email.send_email_verification_code("runner@example.net", "123456")) self.http.assert_not_called() self.resend.assert_not_called() self.smtp.assert_not_called()