"""안내문 발송(outreach, 2026-10-27).
1) store — 주소 판별(메일/인스타), 붙여넣기 해석, {이름}·(광고)·끝 문구, 메일 HTML(escape·굵게·링크·사진), DM 글.
2) send.send_batch — 본인 Gmail 로 한 사람에 한 통, 이름 없음·연결 끊김·한 사람 실패 처리(가짜 Gmail).
3) 실제 앱(격리된 하위 프로세스, 가짜 저장소) — 메뉴·권한·설정 필요 안내·화면·API·Gmail 없을 때 409.
4) 실제 PostgreSQL(OUTREACH_TEST_DB_URL 이 localhost 일 때만) — 추가·중복·두 번 눌러도 한 번(claim)·기록·설정·사진.
"""
import os
import subprocess
import sys
import tempfile
import unittest
import uuid
from pathlib import Path
from unittest.mock import patch
from urllib.parse import urlparse
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from app.modules.outreach import send, store # noqa: E402
DSN = os.getenv("OUTREACH_TEST_DB_URL", "")
DB_ENABLED = bool(DSN) and urlparse(DSN).hostname in ("localhost", "127.0.0.1")
class DetectParseTests(unittest.TestCase):
def test_detect(self):
ok = {"Kim@Miras.co.kr": ("email", "kim@miras.co.kr"), "mailto:a@b.com": ("email", "a@b.com"),
"@mira.kitchen": ("instagram", "mira.kitchen"), "mira_kitchen": ("instagram", "mira_kitchen"),
"https://www.instagram.com/Lee_S/?hl=ko": ("instagram", "lee_s"), "instagram.com/park.j": ("instagram", "park.j"),
"ig.me/m/hong": ("instagram", "hong"), "https://instagr.am/choi": ("instagram", "choi")}
for a, (k, h) in ok.items():
d = store.detect(a)
self.assertEqual((d["kind"], d["handle"]), (k, h), a)
for bad in ("", "홍길동", "a@b", "bad..name", ".dot", "instagram.com/p/abc123", "https://instagram.com/reel/x", "12345", "a" * 31):
self.assertIsNone(store.detect(bad)["kind"], bad)
def test_parse_bulk(self):
rows = store.parse_bulk("kim@miras.co.kr, 김철수\n홍길동\t@hong.gd\n\n# 주석\nhttps://instagram.com/lee_s 이수진\n"
"@hong.gd 홍길동 또\n박지성 park_js\n주소없음 홍\n")
got = [(r["kind"], r["handle"], r["name"], r["dup"]) for r in rows]
self.assertEqual(got, [("email", "kim@miras.co.kr", "김철수", False), ("instagram", "hong.gd", "홍길동", False),
("instagram", "lee_s", "이수진", False), ("instagram", "hong.gd", "홍길동 또", True),
("instagram", "park_js", "박지성", False), (None, "", "홍", False)])
self.assertEqual([r["line"] for r in rows], [1, 2, 5, 6, 7, 8])
class RenderTests(unittest.TestCase):
T = store.normalize_template({"subject": "{이름}님께 제안", "body": "안녕하세요, {이름}님.\n**미라네주방**입니다.\nhttps://miras.co.kr/",
"footer": "수신 거부는 회신", "ad_label": True, "sender_name": "미라네주방"})
def test_default_template_is_users_text(self):
d = store.DEFAULT_TEMPLATE
self.assertEqual(d["subject"], "누적매출 300억. 800만개 판매 신화 미라클통 '미라네주방'입니다.")
self.assertTrue(d["body"].startswith("안녕하세요, {이름}님.\n주방의 본질을 지키며"))
self.assertTrue(d["body"].rstrip().endswith("미라네주방 팀 드림\nhttps://miras.co.kr/"))
self.assertEqual(d["body"].count("{이름}"), 6)
self.assertTrue(store.needs_name(d))
def test_subject_text_html_dm(self):
self.assertEqual(store.subject_for(self.T, "김철수"), "(광고) 김철수님께 제안")
self.assertEqual(store.plain_text(self.T, "김철수"), "안녕하세요, 김철수님.\n미라네주방입니다.\nhttps://miras.co.kr/\n\n수신 거부는 회신")
h = store.html_body(self.T, "", ["c1@dbx", "c2@dbx"])
self.assertIn("<script>x</script>님", h)
self.assertNotIn("
안녕하세요, {이름}님.
빨강
' '', h) # 메일 프로그램 문단 여백 0 for bad in ("")[0]) # noqa: E731 assert "기본 문구(아직 저장 안 함)" in s and "정보통신망법" in s and 'id="otr-body-editor"' in s and "/static/vendor/quill/quill.js" in s assert cur(s)["body"].startswith("
안녕하세요, {이름}님.
주방의 본질을 지키며"), cur(s) r = c.post("/outreach/settings", data={"subject": "{이름}님 제안", "body": "안녕하세요 {이름}님", "sender_name": "미라네주방", "footer": "수신 거부: 회신", "ad_label": "1"}) assert r.status_code == 303 and st.saved == "me@miras.co.kr" and st.t["ad_label"] is True assert c.post("/outreach/settings", data={"subject": "", "body": "x"}).status_code == 400 # 붙여넣기 미리보기 → 추가 text = "kim@miras.co.kr, 김철수\\n@mira.kitchen 미라\\n홍길동\\n@nobody\\n" p = c.post("/outreach/api/recipients/parse", json={"text": text}).json()["rows"] assert [x["kind_label"] for x in p] == ["메일", "DM", "오류", "DM"], p a = c.post("/outreach/api/recipients", json={"text": text}).json() assert (a["added"], a["invalid"]) == (3, 1), a p2 = c.post("/outreach/api/recipients/parse", json={"text": "kim@miras.co.kr"}).json()["rows"] assert p2[0]["exists"] is True rows = c.get("/outreach/api/recipients").json()["rows"] kim, mira, nobody = rows assert mira["dm_link"] == "https://ig.me/m/mira.kitchen" and "안녕하세요 미라님" in mira["dm_text"] assert nobody["needs_name"] is True and kim["needs_name"] is False # 미리보기 — 제목 (광고)·이름 pv = c.get(f"/outreach/api/recipients/{kim['id']}/preview").json() assert pv["subject"] == "(광고) 김철수님 제안" and "안녕하세요 김철수님" in pv["html"] and "수신 거부: 회신" in pv["text"] # 이름 고치기 assert c.put(f"/outreach/api/recipients/{nobody['id']}", json={"name": "노바디"}).json()["row"]["needs_name"] is False # 인스타 DM 문구 — 저장하면 DM 줄 글·미리보기가 그 문구로(메일은 그대로) assert "인스타 DM 문구" in s and 'name="dm_body"' in s and 'id="otr-dm-editor"' in s r = c.post("/outreach/settings", data={"subject": "{이름}님 제안", "body": "안녕하세요 {이름}님", "footer": "수신 거부: 회신", "dm_body": "{이름}님, **DM** 문구입니다"}) assert r.status_code == 303 and st.t["dm_body"] == "{이름}님, **DM** 문구입니다" mira2 = next(x for x in c.get("/outreach/api/recipients").json()["rows"] if x["id"] == mira["id"]) assert mira2["dm_text"] == "미라님, DM 문구입니다", mira2 assert c.get(f"/outreach/api/recipients/{mira['id']}/preview").json()["text"] == "미라님, DM 문구입니다" assert "수신 거부: 회신" in c.get(f"/outreach/api/recipients/{kim['id']}/preview").json()["text"] assert cur(c.get("/outreach/settings").text)["dm_body"] == "{이름}님, **DM** 문구입니다" # DM 수동 보내기 탭(2026-10-30) — {이름} 을 그대로 둔 DM 문구(별표 뺌)를 화면 데이터로 d = c.get("/outreach/dm").text dm_data = __import__("json").loads(d.split('id="otr-data">')[1].split("")[0]) assert 'id="otr-dm-names"' in d and "DM 수동 보내기" in d and dm_data == {"dm_template": "{이름}님, DM 문구입니다"}, dm_data # 서식 편집기 본문(fmt=html) — 서버가 정리해 저장, 메일 미리보기에 서식·이름 r = c.post("/outreach/settings", data={"subject": "{이름}님 제안", "fmt": "html", "dm_body": "", "body": '
안녕 {이름}님
'}) assert r.status_code == 303 and st.t["body"] == '안녕 {이름}님
', st.t["body"] pv = c.get(f"/outreach/api/recipients/{kim['id']}/preview").json() assert '김철수님' in pv["html"] and pv["text"].startswith("안녕 김철수님"), pv assert c.get("/outreach/").text.count("안녕 {이름}님") == 1 # 리스트 화면 '보낼 내용' = 글로 assert c.post("/outreach/settings", data={"subject": "x", "fmt": "html", "body": "