mail4one/tests/test_smtp.py

81 lines
2.2 KiB
Python
Raw Normal View History

2023-06-12 21:15:21 -04:00
import asyncio
import logging
import unittest
import smtplib
import tempfile
2023-06-16 23:42:30 -04:00
import contextlib
2023-06-12 21:15:21 -04:00
import os
from pathlib import Path
2023-06-13 21:12:46 -04:00
from mail4one.smtp import create_smtp_server
2023-06-12 21:15:21 -04:00
2024-04-01 11:14:20 -04:00
TEST_MBOX = "foobar_mails"
2023-06-12 21:15:21 -04:00
MAILS_PATH: Path
def setUpModule() -> None:
global MAILS_PATH
logging.basicConfig(level=logging.CRITICAL)
td = tempfile.TemporaryDirectory(prefix="m41.smtp.")
unittest.addModuleCleanup(td.cleanup)
MAILS_PATH = Path(td.name)
os.mkdir(MAILS_PATH / TEST_MBOX)
2024-04-01 11:14:20 -04:00
for md in ("new", "cur", "tmp"):
2023-06-12 21:15:21 -04:00
os.mkdir(MAILS_PATH / TEST_MBOX / md)
class TestSMTP(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self) -> None:
2023-06-13 13:44:10 -04:00
smtp_server = await create_smtp_server(
2023-06-12 21:15:21 -04:00
host="127.0.0.1",
port=7996,
mails_path=MAILS_PATH,
2024-04-01 11:14:20 -04:00
mbox_finder=lambda addr: [TEST_MBOX],
ssl_context=None,
smtputf8=True,
2024-04-01 11:14:20 -04:00
)
2023-06-12 21:15:21 -04:00
self.task = asyncio.create_task(smtp_server.serve_forever())
async def test_send_mail(self) -> None:
msg = b"""From: foo@sender.com
To: "foo@bar.com"
Hello world
Byee
"""
msg = b"".join(l.strip() + b"\r\n" for l in msg.splitlines())
def send_mail():
2024-04-01 11:14:20 -04:00
with contextlib.closing(
smtplib.SMTP(host="127.0.0.1", port=7996)
) as client:
2023-06-16 23:42:30 -04:00
client.sendmail("foo@sender.com", "foo@bar.com", msg)
_, local_port = client.sock.getsockname()
return local_port
2023-06-12 21:15:21 -04:00
2023-06-16 23:42:30 -04:00
local_port = await asyncio.to_thread(send_mail)
2023-06-12 21:15:21 -04:00
expected = f"""From: foo@sender.com
To: "foo@bar.com"
X-Peer: ('127.0.0.1', {local_port})
X-MailFrom: foo@sender.com
X-RcptTo: foo@bar.com
X-SSL: Type: plain, STARTTLS: False
2023-06-12 21:15:21 -04:00
Hello world
Byee
"""
expected = "".join(l.strip() + "\r\n" for l in expected.splitlines())
2024-04-01 11:14:20 -04:00
mails = list((MAILS_PATH / TEST_MBOX / "new").glob("*"))
2023-06-12 21:15:21 -04:00
self.assertEqual(len(mails), 1)
self.assertEqual(mails[0].read_bytes(), expected.encode())
async def asyncTearDown(self) -> None:
logging.debug("at teardown")
self.task.cancel("test done")
if __name__ == "__main__":
unittest.main()