iro/test_helpers/smtp_helper.py
changeset 302 3f4bdea2abbf
parent 294 0e75bd39767d
equal deleted inserted replaced
90:eb04ac3a8327 302:3f4bdea2abbf
       
     1 # Copyright (c) 2012 netzguerilla.net <iro@netzguerilla.net>
       
     2 # 
       
     3 # This file is part of Iro.
       
     4 # 
       
     5 # Permission is hereby granted, free of charge, to any person obtaining a copy of
       
     6 # this software and associated documentation files (the "Software"), to deal in
       
     7 # the Software without restriction, including without limitation the rights to use,
       
     8 # copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
       
     9 # #Software, and to permit persons to whom the Software is furnished to do so,
       
    10 # subject to the following conditions:
       
    11 # 
       
    12 # The above copyright notice and this permission notice shall be included in
       
    13 # all copies or substantial portions of the Software.
       
    14 # 
       
    15 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
       
    16 # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
       
    17 # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
       
    18 # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
       
    19 # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
       
    20 # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
       
    21 
       
    22 """
       
    23 A helper class which allows test code to intercept and store sent email.
       
    24 (from: http://lakin.weckers.net/thoughts/twisted/part1/threaded/)
       
    25 """
       
    26 import smtpd
       
    27 import asyncore
       
    28 
       
    29 class TestSMTPServer(smtpd.SMTPServer):
       
    30     """
       
    31     An SMTP Server used to allow integration tests which ensure email is sent.
       
    32     """
       
    33 
       
    34     def __init__(self, localaddr):
       
    35         self.rcvd = []
       
    36         smtpd.SMTPServer.__init__(self, localaddr, None)
       
    37 
       
    38     def start(self):
       
    39         import threading
       
    40         self.poller = threading.Thread(target=asyncore.loop,
       
    41                 kwargs={'timeout':0.1, 'use_poll':True})
       
    42         self.poller.start()
       
    43 
       
    44     def process_message(self, peer, mailfrom, rcpttos, data):
       
    45         self.rcvd.append((mailfrom, rcpttos, data))
       
    46 
       
    47     def close(self):
       
    48         smtpd.SMTPServer.close(self)
       
    49         self.poller.join()