Skip to content

Commit

Permalink
Remove the 'no cover' pragma and fix a real bug
Browse files Browse the repository at this point in the history
  • Loading branch information
matthiask committed Oct 30, 2018
1 parent 6726f02 commit 4bc74fd
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 7 deletions.
4 changes: 2 additions & 2 deletions spark/spark_mails/api.py
Expand Up @@ -14,8 +14,8 @@ def process_mail_events(iterable, *, defaults=None, fail_silently=False):
if e["group"] in mails:
# TODO What about invalid templates? (They should not be saveable, but...)
subject, body = mails[e["group"]].render(e["context"])
if subject: # pragma: no cover (unlikely)
if subject:
kwargs["subject"] = subject
if body: # pragma: no cover (unlikely)
if body:
kwargs["body"] = body
EmailMessage(**kwargs).send(fail_silently=fail_silently)
13 changes: 8 additions & 5 deletions spark/spark_mails/models.py
Expand Up @@ -39,9 +39,12 @@ def render(self, context):
for line in self.template.render(Context(context)).splitlines()
)
subject = ""
while True:
line = next(lines)
if line:
subject = line
break
try:
while True:
line = next(lines)
if line:
subject = line
break
except StopIteration: # if lines is empty
pass
return subject, "\n".join(lines).strip("\n")
29 changes: 29 additions & 0 deletions tests/testapp/test_mails.py
Expand Up @@ -57,6 +57,7 @@ def test_mails(self):
self.assertEqual(len(mail.outbox), 1)
sent = mail.outbox[0]
self.assertEqual(sent.to, [user.email])
self.assertEqual(sent.subject, "Dear test")

def test_invalid_mail(self):
m = Mail(event_group="test", template_source="""{{ Bla.21342._"*32424 }}""")
Expand Down Expand Up @@ -108,3 +109,31 @@ def test_admin(self):
m = Mail.objects.create(event_group="stuff_mail", template_source=MAIL)
response = client.get("/admin/spark_mails/mail/{}/change/".format(m.pk))
self.assertContains(response, "Best regards</code></div>")

def test_empty_template(self):
Mail.objects.create(event_group="stuff_mail", template_source="")
user = User.objects.create(username="test", email="test@example.com")
stuff = Stuff.objects.create(key="asdf")
events = [
{
"group": "stuff_mail",
"key": "stuff_mail_2",
"context": {
"key": stuff.key,
"key_length": len(stuff.key),
"user": user,
"spark_mail": {
"to": [user.email],
"subject": "Would be overridden if template had content",
},
},
},
{"group": "stuff_stuff", "key": "stuff_stuff_1", "context": {}},
]
api.process_mail_events(only_new_events(events))
api.process_mail_events(only_new_events(events)) # Twice.

self.assertEqual(len(mail.outbox), 1)
sent = mail.outbox[0]
self.assertEqual(sent.to, [user.email])
self.assertEqual(sent.subject, "Would be overridden if template had content")

0 comments on commit 4bc74fd

Please sign in to comment.