test_smtp.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import smtplib
  2. try: # python 3
  3. from email.mime.text import MIMEText
  4. except ImportError: # python 2?
  5. from email.MIMEText import MIMEText
  6. from pytest_localserver import plugin, smtp
  7. def send_plain_email(to, from_, subject, txt, server=('localhost', 25)):
  8. """
  9. Sends a simple plain text message via SMTP.
  10. """
  11. if type(to) in (tuple, list):
  12. to = ', '.join(to)
  13. # Create a text/plain message
  14. msg = MIMEText(txt)
  15. msg['Subject'] = subject
  16. msg['From'] = from_
  17. msg['To'] = to
  18. host, port = server[:2]
  19. server = smtplib.SMTP(host, port)
  20. server.set_debuglevel(1)
  21. server.sendmail(from_, to, msg.as_string())
  22. server.quit()
  23. # define test fixture here again in order to run tests without having to
  24. # install the plugin anew every single time
  25. smtpserver = plugin.smtpserver
  26. def test_smtpserver_funcarg(smtpserver):
  27. assert isinstance(smtpserver, smtp.Server)
  28. assert smtpserver.is_alive()
  29. assert smtpserver.accepting and smtpserver.addr
  30. def test_server_is_killed(smtpserver):
  31. assert smtpserver.is_alive()
  32. smtpserver.stop()
  33. assert not smtpserver.is_alive()
  34. def test_server_is_deleted(smtpserver):
  35. assert smtpserver.is_alive()
  36. smtpserver.__del__() # need to call magic method here!
  37. assert not smtpserver.is_alive()
  38. def test_smtpserver_has_empty_outbox_at_startup(smtpserver):
  39. assert len(smtpserver.outbox) == 0
  40. def test_send_email(smtpserver):
  41. # send one e-mail
  42. send_plain_email(
  43. 'alice@example.com', 'webmaster@example.com',
  44. 'Your e-mail is getting there', 'Seems like this test actually works!',
  45. smtpserver.addr)
  46. msg = smtpserver.outbox[-1]
  47. assert msg['To'] == 'alice@example.com'
  48. assert msg['From'] == 'webmaster@example.com'
  49. assert msg['Subject'] == 'Your e-mail is getting there'
  50. assert msg.details.rcpttos == ['alice@example.com']
  51. assert msg.details.peer
  52. assert msg.details.mailfrom
  53. # send another e-mail
  54. send_plain_email(
  55. 'bob@example.com', 'webmaster@example.com',
  56. 'His e-mail too', 'Seems like this test actually works!',
  57. smtpserver.addr)
  58. msg = smtpserver.outbox[-1]
  59. assert msg['To'] == 'bob@example.com'
  60. assert msg['From'] == 'webmaster@example.com'
  61. assert msg['Subject'] == 'His e-mail too'
  62. # two mails are now in outbox
  63. assert len(smtpserver.outbox) == 2