import os import unittest from datetime import datetime, timedelta from django.test import SimpleTestCase from django.test.utils import override_settings from anymail.exceptions import AnymailAPIError from anymail.message import AnymailMessage from .utils import AnymailTestMixin, sample_image_path, RUN_LIVE_TESTS SENDGRID_TEST_API_KEY = os.getenv('SENDGRID_TEST_API_KEY') SENDGRID_TEST_TEMPLATE_ID = os.getenv('SENDGRID_TEST_TEMPLATE_ID') @unittest.skipUnless(RUN_LIVE_TESTS, "RUN_LIVE_TESTS disabled in this environment") @unittest.skipUnless(SENDGRID_TEST_API_KEY, "Set SENDGRID_TEST_API_KEY environment variable " "to run SendGrid integration tests") @override_settings(ANYMAIL_SENDGRID_API_KEY=SENDGRID_TEST_API_KEY, ANYMAIL_SENDGRID_SEND_DEFAULTS={"esp_extra": { "mail_settings": {"sandbox_mode": {"enable": True}}, }}, EMAIL_BACKEND="anymail.backends.sendgrid.SendGridBackend") class SendGridBackendIntegrationTests(SimpleTestCase, AnymailTestMixin): """SendGrid v3 API integration tests These tests run against the **live** SendGrid API, using the environment variable `SENDGRID_TEST_API_KEY` as the API key If those variables are not set, these tests won't run. The SEND_DEFAULTS above force SendGrid's v3 sandbox mode, which avoids sending mail. (Sandbox sends also don't show in the activity feed, so disable that for live debugging.) The tests also use SendGrid's "sink domain" @sink.sendgrid.net for recipient addresses. https://support.sendgrid.com/hc/en-us/articles/201995663-Safely-Test-Your-Sending-Speed """ def setUp(self): super(SendGridBackendIntegrationTests, self).setUp() self.message = AnymailMessage('Anymail SendGrid integration test', 'Text content', 'from@example.com', ['to@sink.sendgrid.net']) self.message.attach_alternative('
HTML content
', "text/html") def test_simple_send(self): # Example of getting the SendGrid send status and message id from the message sent_count = self.message.send() self.assertEqual(sent_count, 1) anymail_status = self.message.anymail_status sent_status = anymail_status.recipients['to@sink.sendgrid.net'].status message_id = anymail_status.recipients['to@sink.sendgrid.net'].message_id self.assertEqual(sent_status, 'queued') # SendGrid always queues self.assertRegex(message_id, r'\<.+@example\.com\>') # should use from_email's domain self.assertEqual(anymail_status.status, {sent_status}) # set of all recipient statuses self.assertEqual(anymail_status.message_id, message_id) def test_all_options(self): send_at = datetime.now().replace(microsecond=0) + timedelta(minutes=2) message = AnymailMessage( subject="Anymail all-options integration test", body="This is the text body", from_email='"Test From, with comma"HTML: with link"
"and image: " % cid,
"text/html")
message.send()
self.assertEqual(message.anymail_status.status, {'queued'}) # SendGrid always queues
def test_merge_data(self):
message = AnymailMessage(
subject="Anymail merge_data test: %field%",
body="This body includes merge data: %field%",
from_email="Test From