import os import unittest import warnings from datetime import datetime, timedelta from django.test import SimpleTestCase, override_settings, tag from anymail.exceptions import AnymailAPIError from anymail.message import AnymailMessage from .utils import AnymailTestMixin, sample_image_path SPARKPOST_TEST_API_KEY = os.getenv('SPARKPOST_TEST_API_KEY') @tag('sparkpost', 'live') @unittest.skipUnless(SPARKPOST_TEST_API_KEY, "Set SPARKPOST_TEST_API_KEY environment variable " "to run SparkPost integration tests") @override_settings(ANYMAIL_SPARKPOST_API_KEY=SPARKPOST_TEST_API_KEY, EMAIL_BACKEND="anymail.backends.sparkpost.EmailBackend") class SparkPostBackendIntegrationTests(AnymailTestMixin, SimpleTestCase): """SparkPost API integration tests These tests run against the **live** SparkPost API, using the environment variable `SPARKPOST_TEST_API_KEY` as the API key If that variable is not set, these tests won't run. SparkPost doesn't offer a test mode -- it tries to send everything you ask. To avoid stacking up a pile of undeliverable @example.com emails, the tests use SparkPost's "sink domain" @*.sink.sparkpostmail.com. https://www.sparkpost.com/docs/faq/using-sink-server/ SparkPost also doesn't support arbitrary senders (so no from@example.com). We've set up @test-sp.anymail.info as a validated sending domain for these tests. """ def setUp(self): super().setUp() self.message = AnymailMessage('Anymail SparkPost integration test', 'Text content', 'test@test-sp.anymail.info', ['to@test.sink.sparkpostmail.com']) self.message.attach_alternative('
HTML content
', "text/html") # The SparkPost Python package uses requests directly, without managing sessions, and relies # on GC to close connections. This leads to harmless (but valid) warnings about unclosed # ssl.SSLSocket during cleanup: https://github.com/psf/requests/issues/1882 # There's not much we can do about that, short of switching from the SparkPost package # to our own requests backend implementation (which *does* manage sessions properly). # Unless/until we do that, filter the warnings to avoid test noise. # Filter in TestCase.setUp because unittest resets the warning filters for each test. # https://stackoverflow.com/a/26620811/647002 from anymail.backends.base_requests import AnymailRequestsBackend from anymail.backends.sparkpost import EmailBackend as SparkPostBackend assert not issubclass(SparkPostBackend, AnymailRequestsBackend) # else this filter can be removed warnings.filterwarnings("ignore", message=r"unclosedHTML: with link"
"and image: " % cid,
"text/html")
message.send()
self.assertEqual(message.anymail_status.status, {'queued'}) # SparkPost always queues
def test_merge_data(self):
message = AnymailMessage(
subject="Anymail merge_data test: {{ value }}",
body="This body includes merge data: {{ value }}\n"
"And global merge data: {{ global }}",
from_email="Test From