test_send.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. from email.message import EmailMessage
  2. import pytest
  3. from redmail import EmailSender, send_email
  4. class MockServer:
  5. def __init__(self, host, port):
  6. self.host = host
  7. self.port = port
  8. self.is_login = False
  9. def starttls(self):
  10. return
  11. def login(self, user=None, password=None):
  12. self.is_login = True
  13. self.user = user
  14. self.password = password
  15. return
  16. def send_message(self, msg):
  17. return
  18. def quit(self):
  19. return
  20. def test_send():
  21. email = EmailSender(host="localhost", port=0, cls_smtp=MockServer)
  22. assert email.connection is None
  23. msg = email.send(
  24. subject="An example",
  25. receivers=['me@example.com']
  26. )
  27. assert isinstance(msg, EmailMessage)
  28. assert email.connection is None
  29. def test_send_with_user():
  30. email = EmailSender(host="localhost", port=0, username="myuser", password="1234", cls_smtp=MockServer)
  31. assert email.connection is None
  32. assert email.username == "myuser"
  33. assert email.password == "1234"
  34. msg = email.send(
  35. subject="An example",
  36. receivers=['me@example.com']
  37. )
  38. assert isinstance(msg, EmailMessage)
  39. assert email.connection is None
  40. # Testing the server
  41. server = email.get_server()
  42. assert server.user == "myuser"
  43. assert server.password == "1234"
  44. def test_send_multi():
  45. email = EmailSender(host="localhost", port=0, cls_smtp=MockServer)
  46. assert email.connection is None
  47. with email:
  48. assert email.connection is not None
  49. msg = email.send(
  50. subject="An example",
  51. receivers=['me@example.com']
  52. )
  53. assert isinstance(msg, EmailMessage)
  54. assert email.connection is not None
  55. msg = email.send(
  56. subject="An example",
  57. receivers=['me@example.com']
  58. )
  59. assert isinstance(msg, EmailMessage)
  60. assert email.connection is not None
  61. assert email.connection is None
  62. def test_send_function():
  63. # This should fail but we test everything else goes through
  64. with pytest.raises(ConnectionRefusedError):
  65. send_email(host="localhost", port=0, subject="An example")