unit testing a routine that sends mail

Phlip phlip2005 at gmail.com
Thu Feb 18 15:16:03 EST 2010


commander_coder wrote:

> I have a routine that sends an email (this is how a Django view
> notifies me that an event has happened).  I want to unit test that
> routine.

Are you opening SMTP and POP3 sockets??

If you are not developing that layer itself, just use Django's built-
in mock system. Here's my favorite assertion for it:

    def assert_mail(self, funk):
        from django.core import mail
        previous_mails = len(mail.outbox)
        funk()
        mails = mail.outbox[ previous_mails : ]
        assert [] != mails, 'the called block should produce emails'
        if len(mails) == 1:  return mails[0]
        return mails

You call it a little bit like this:

        missive = self.assert_mail( lambda:
mark_order_as_shipped(order) )

Then you can use assert_contains on the missive.body, to see what mail
got generated. That's what you are actually developing, so your tests
should skip any irrelevant layers, and only test the layers where you
yourself might add bugs.

--
  Phlip
  http://penbird.tumblr.com/



More information about the Python-list mailing list