tests/smtp_helper.py
branchdevel
changeset 164 b634a8fed51f
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/tests/smtp_helper.py	Tue Feb 14 21:27:51 2012 +0100
@@ -0,0 +1,28 @@
+"""
+A helper class which allows test code to intercept and store sent email.
+(from: http://lakin.weckers.net/thoughts/twisted/part1/threaded/)
+"""
+import smtpd
+import asyncore
+
+class TestSMTPServer(smtpd.SMTPServer):
+    """
+    An SMTP Server used to allow integration tests which ensure email is sent.
+    """
+
+    def __init__(self, localaddr):
+        self.rcvd = []
+        smtpd.SMTPServer.__init__(self, localaddr, None)
+
+    def start(self):
+        import threading
+        self.poller = threading.Thread(target=asyncore.loop,
+                kwargs={'timeout':0.1, 'use_poll':True})
+        self.poller.start()
+
+    def process_message(self, peer, mailfrom, rcpttos, data):
+        self.rcvd.append((mailfrom, rcpttos, data))
+
+    def close(self):
+        smtpd.SMTPServer.close(self)
+        self.poller.join()