Unit testing and mocking email sender in Python with Google AppEngine

Posted by CVertex on Stack Overflow See other posts from Stack Overflow or by CVertex
Published on 2009-01-09T08:33:34Z Indexed on 2010/04/04 19:43 UTC
Read the original article Hit count: 326

I'm a newbie to python and the app engine.

I have this code that sends an email based on request params after some auth logic. in my Unit tests (i'm using GAEUnit), how do I confirm an email with specific contents were sent? - i.e. how do I mock the emailer with a fake emailer to verify send was called?

class EmailHandler(webapp.RequestHandler):
 def bad_input(self):
  self.response.set_status(400)
  self.response.headers['Content-Type'] = 'text/plain'
  self.response.out.write("<html><body>bad input </body></html>")

 def get(self):
  to_addr = self.request.get("to")
  subj = self.request.get("subject")
  msg = self.request.get("body")
  if not mail.is_email_valid(to_addr):
    # Return an error message...
    #   self.bad_input()
    pass

  # authenticate here

  message = mail.EmailMessage()
  message.sender = "[email protected]"
  message.to = to_addr
  message.subject = subj
  message.body = msg
  message.send()
  self.response.headers['Content-Type'] = 'text/plain'
  self.response.out.write("<html><body>success!</body></html>")

And the unit tests,

import unittest
from webtest import TestApp
from google.appengine.ext import webapp
from email import EmailHandler

class SendingEmails(unittest.TestCase):

  def setUp(self):
    self.application = webapp.WSGIApplication([('/', EmailHandler)], debug=True)

  def test_success(self):
    app = TestApp(self.application)
    response = app.get('http://localhost:8080/[email protected]&body=blah_blah_blah&subject=mySubject')
    self.assertEqual('200 OK', response.status)
    self.assertTrue('success' in response)
    # somehow, assert email was sent

© Stack Overflow or respective owner

Related posts about python

Related posts about google-app-engine