from __future__ import annotations from email.message import EmailMessage from typing import Any, cast import pytest from server.services import contact as contact_service # noqa: E402 pylint: disable=wrong-import-position @pytest.fixture def patched_settings(monkeypatch): original = contact_service.settings.SMTP_SETTINGS.copy() patched = original.copy() monkeypatch.setattr(contact_service.settings, "SMTP_SETTINGS", patched) return patched def test_send_notification_returns_false_when_unconfigured(monkeypatch, patched_settings): patched_settings.update({"host": None, "recipients": []}) # Ensure we do not accidentally open a socket if called monkeypatch.setattr(contact_service.smtplib, "SMTP", pytest.fail) submission = contact_service.ContactSubmission( name="Test", email="test@example.com", company=None, message="Hello", timeline=None, ) assert contact_service.send_notification(submission) is False def test_send_notification_sends_email(monkeypatch, patched_settings): patched_settings.update( { "host": "smtp.example.com", "port": 2525, "sender": "sender@example.com", "username": "user", "password": "secret", "use_tls": True, "recipients": ["owner@example.com"], } ) smtp_calls: dict[str, Any] = {} class DummySMTP: def __init__(self, host, port, timeout=None): smtp_calls["init"] = (host, port, timeout) def __enter__(self): return self def __exit__(self, exc_type, exc, tb): return False def starttls(self): smtp_calls["starttls"] = True def login(self, username, password): smtp_calls["login"] = (username, password) def send_message(self, message): smtp_calls["message"] = message monkeypatch.setattr(contact_service.smtplib, "SMTP", DummySMTP) submission = contact_service.ContactSubmission( name="Alice", email="alice@example.com", company="Example Co", message="Hello there", timeline="Soon", ) assert contact_service.send_notification(submission) is True assert smtp_calls["init"] == ( patched_settings["host"], patched_settings["port"], 15, ) assert smtp_calls["starttls"] is True assert smtp_calls["login"] == ( patched_settings["username"], patched_settings["password"]) message = cast(EmailMessage, smtp_calls["message"]) assert message["Subject"] == "Neue Kontaktanfrage von Alice" assert message["To"] == "owner@example.com" assert "Hello there" in message.get_content()