Juergen Edelbluth
08943cd8d5
This commit consolidates the SMTP mock code from some of my testing projects into a re-usable form. This package will be used later for realizing the upcoming pytest plugin.
75 lines
2.2 KiB
Python
75 lines
2.2 KiB
Python
"""
|
|
Tests for the SMTP Server Context
|
|
"""
|
|
from email.mime.multipart import MIMEMultipart
|
|
from email.mime.text import MIMEText
|
|
from smtplib import SMTP
|
|
|
|
import pytest
|
|
from hamcrest import assert_that, equal_to, greater_than_or_equal_to
|
|
|
|
from smtp_test_server.context import SmtpMockServer
|
|
from smtp_test_server.exceptions import AlreadyStartedError, NotProperlyInitializedError, NotStartedError
|
|
|
|
|
|
def test_server_context_smoke():
|
|
"""
|
|
Smoke Test
|
|
"""
|
|
with SmtpMockServer() as server:
|
|
assert_that(server.host, equal_to("127.0.0.1"))
|
|
assert_that(server.port, greater_than_or_equal_to(1024))
|
|
assert_that(server.messages, equal_to([]))
|
|
|
|
|
|
def test_send_simple_mail():
|
|
"""
|
|
Send a simple mail
|
|
"""
|
|
message = MIMEMultipart()
|
|
msg_to = "recipient@test.test"
|
|
msg_from = "sender@test.test"
|
|
msg_subject = "Test subject"
|
|
message["From"] = msg_from
|
|
message["To"] = msg_to
|
|
message["Subject"] = msg_subject
|
|
message.attach(MIMEText("Test Text"))
|
|
with SmtpMockServer() as server:
|
|
with SMTP(host=server.host, port=server.port) as smtp:
|
|
smtp.sendmail(msg_from, msg_to, message.as_string())
|
|
assert_that(len(server.messages), equal_to(1))
|
|
msg = server.messages[0]
|
|
assert_that(msg["From"], equal_to(msg_from))
|
|
assert_that(msg["To"], equal_to(msg_to))
|
|
assert_that(msg["Subject"], equal_to(msg_subject))
|
|
|
|
|
|
def test_illegal_access():
|
|
"""
|
|
Test an illegal access
|
|
"""
|
|
srv = SmtpMockServer()
|
|
with pytest.raises(NotProperlyInitializedError) as err:
|
|
_ = srv.messages
|
|
assert_that(err.value.args, equal_to(("accessed messages without starting the server",)))
|
|
|
|
|
|
def test_illegal_enter_state():
|
|
"""
|
|
Test an illegal enter state
|
|
"""
|
|
with SmtpMockServer() as srv:
|
|
with pytest.raises(AlreadyStartedError) as err:
|
|
srv.__enter__() # pylint: disable=unnecessary-dunder-call
|
|
assert_that(err.value.args, equal_to(("SMTP server already started",)))
|
|
|
|
|
|
def test_illegal_exit_state():
|
|
"""
|
|
Test an illegal exit statue
|
|
"""
|
|
with pytest.raises(NotStartedError) as err:
|
|
with SmtpMockServer() as srv:
|
|
srv.__exit__(None, None, None)
|
|
assert_that(err.value.args, equal_to(("SMTP server not started",)))
|