Unit testing and mocking email sender in Python with Google AppEngine
- by CVertex
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