|
| 1 | +import re |
| 2 | +from email.header import decode_header, make_header |
| 3 | + |
| 4 | +import pytest |
| 5 | +from core.external_apis.__interface__ import SendParameters |
| 6 | +from core.external_apis.smtp_email import email_client |
| 7 | +from django.core import mail |
| 8 | + |
| 9 | +_MAX_ENCODED_WORD_LENGTH = 75 # RFC 2047, 구분자 포함 |
| 10 | + |
| 11 | +_LONG_KOREAN_SUBJECT = ( |
| 12 | + "[파이콘 한국] 행사 일주일 전 꼭 확인해 주세요. / [PyCon Korea] One week to go — please check before you come" |
| 13 | +) |
| 14 | + |
| 15 | + |
| 16 | +def _params(**overrides) -> SendParameters: |
| 17 | + return SendParameters( |
| 18 | + payload=overrides.pop("payload", {"title": "제목", "body": "<p>본문</p>"}), |
| 19 | + send_to=overrides.pop("send_to", "to@example.com"), |
| 20 | + sent_from=overrides.pop("sent_from", "from@example.com"), |
| 21 | + template_code=overrides.pop("template_code", ""), |
| 22 | + ) |
| 23 | + |
| 24 | + |
| 25 | +def _sent_subject_header() -> str: |
| 26 | + head = mail.outbox[0].message().as_bytes().split(b"\r\n\r\n")[0].decode() |
| 27 | + return re.search(r"^Subject:(.*?)(?=^\S+:)", head + "\nX:", re.S | re.M).group(1) |
| 28 | + |
| 29 | + |
| 30 | +@pytest.mark.parametrize( |
| 31 | + "subject", [_LONG_KOREAN_SUBJECT, "파이콘 한국 티켓 결제가 완료되었습니다!", "ASCII only subject"] |
| 32 | +) |
| 33 | +def test_send_message_subject_encoded_words_are_rfc2047_compliant(subject): |
| 34 | + email_client.send_message(data=_params(payload={"title": subject, "body": "<p>본문</p>"})) |
| 35 | + |
| 36 | + header = _sent_subject_header() |
| 37 | + encoded_words = [word for word in header.split() if word.startswith("=?")] |
| 38 | + assert all(len(word) <= _MAX_ENCODED_WORD_LENGTH for word in encoded_words) |
| 39 | + assert len({word.split("?")[2] for word in encoded_words}) <= 1 # base64/quoted-printable 혼용 금지 |
| 40 | + assert str(make_header(decode_header(header.strip()))) == subject |
| 41 | + |
| 42 | + |
| 43 | +def test_send_message_sends_html_body(): |
| 44 | + email_client.send_message(data=_params(payload={"title": "제목", "body": "<p>본문</p>"})) |
| 45 | + |
| 46 | + message = mail.outbox[0] |
| 47 | + assert message.content_subtype == "html" |
| 48 | + assert message.body == "<p>본문</p>" |
| 49 | + assert message.to == ["to@example.com"] |
| 50 | + |
| 51 | + |
| 52 | +def test_send_message_requires_title(): |
| 53 | + with pytest.raises(ValueError, match="title"): |
| 54 | + email_client.send_message(data=_params(payload={"body": "<p>본문</p>"})) |
| 55 | + |
| 56 | + |
| 57 | +def test_send_message_requires_sent_from(): |
| 58 | + with pytest.raises(ValueError, match="sent_from"): |
| 59 | + email_client.send_message(data=_params(sent_from="")) |
0 commit comments