britney2-ubuntu/tests/mock_smtpd.py
Iain Lane 8350694348 email: Add tests that send email through a mocked SMTP server
I want to fix two bugs in interactions between other parts of britney
and the email policy. It's not currently easy to do so because we just
run the policy itself manually by creating some fake excuses.

Steal part of the machinery from the autopkgtest tests, and run a few
tests through britney completely. Use a fake SMTP server to record which
emails we sent.

(The port is hardcoded - that might not be so smart.)
2017-03-22 16:59:50 +00:00

46 lines
1.3 KiB
Python

#!/usr/bin/python3
# (C) 2017 Canonical Ltd.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
from collections import defaultdict
import asyncore
import smtpd
import threading
class FakeSMTPServer(smtpd.SMTPServer):
"""A fake smtp server"""
def __init__(self, host, port):
# ((localhost, port), remoteaddr
# remoteaddr is an address to relay to, which isn't relevant for us
super().__init__((host, port), None, decode_data=False)
# to -> (from, data)
self.emails = defaultdict(list)
def process_message(self, peer, mailfrom, rcpttos, data, **kwargs):
#print('received email: %s, %s, %s' % (mailfrom, rcpttos, data))
for rcpt in rcpttos:
self.emails[rcpt].append(data)
pass
def get_emails(self):
'''Get a list of the people that were emailed'''
return list(self.emails.keys())
def run(self):
self.thread = threading.Thread(target=asyncore.loop,kwargs = {'timeout':1} )
self.thread.start()
# support standalone running
if __name__ == "__main__":
smtp_server = FakeSMTPServer('localhost', 1337)
smtp_server.run()