class SmtpTestCase(HookTestCase): """SvnHook Test Case with SMTP Server""" def setUp(self, repoid, host='localhost', port=8025, *args, **kwargs): # Initialize the base test case. super(SmtpTestCase, self).setUp(repoid, *args, **kwargs) # Construct the SMTP server. self.smtphost = host self.smtpport = port self.smtpserver = SmtpSink(host=host, port=port) # Start the SMTP server thread. self.smtpserver.start() # Make sure the SMTP server is always shut down. self.addCleanup(self.__class__._stopSmtpServer, self) def _stopSmtpServer(self): # Stop the SMTP server thread. self.smtpserver.stop() def getMailbox(self): """Get the Unix mailbox object containing received messages.""" # Load the mailbox contents into an IO object. mailboxFile = StringIO.StringIO( self.smtpserver.getMailboxContents()) # Construct a mailbox object from the contents. return mailbox.PortableUnixMailbox( mailboxFile, email.message_from_file) def getMessage(self, subject): """Get the first email message with a matching subject line. Throws a KeyError, when a matching message not found. Args: subject: Subject line of message. Returns: Message object for the matching message. """ # Look at the received message subject lines. for msgsubject in [ message.get('Subject') for message in self.getMailbox()]: if msgsubject == subject: return message # A matching message wasn't found. raise KeyError('Message with subject not found: ' + subject) def assertFromAddress(self, message, fromaddr, msg=None): """Assert that a message has proper From address. Args: message: Message to be checked. fromaddr: Expected sender email address. msg: Optional message to use on failure. """ self.assertEquals(message.get('From'), fromaddr, msg) def assertToAddress(self, message, toaddr, msg=None): """Assert that a message has proper To address. Args: message: Message to be checked. toaddr: Expected recipient email address. msg: Optional message to use on failure. """ self.assertIn(toaddr, message.get_all('To'), msg) def assertBody(self, message, body, msg=None): """Assert that a message has the correct body. Args: message: Message to be checked. body: Expected body of the email message. msg: Optional message to use on failure. """ # Assert against the decoded, non-multipart, content. Trim off # the terminal whitespace (two linefeeds). self.assertEquals( message.get_payload(None, True).rstrip(), body.rstrip(), msg) def assertBodyRegexp(self, message, regexp, msg=None): """Assert that a message body matches a regular expression. Args: message: Message to be checked. regexp: Regular expression to match against the message body. msg: Optional message to use on failure. """ # Assert against the decoded, non-multipart, content. Trim off # the terminal whitespace (two linefeeds). self.assertRegexpMatches( message.get_payload(None, True).rstrip(), regexp, msg)