Files
dbx-main/tests/test_outreach.py
king 48cd7f0878 feat(안내문 발송): DM 수동 보내기 — 이름 지우기·본문 편집·저장한 본문 목록
- 이름 목록: × 한 명씩 빼기·[전체 삭제], 이름 넣기는 목록에 더함
- 본문: 바로 고침(plaintext-only), {이름} 자리 = 분홍 칩, 이름 누르면 고친 글 + 이름 복사
- 저장한 본문(본문 오른쪽): 설정 DM 문구 + 저장한 것, 고르기·[저장]·[새 본문으로 저장]·× 지우기
- outreach_db 마이그레이션 002 outreach_dm_bodies + POST/PUT/DELETE /outreach/api/dm-bodies
  (002 미적용이면 목록 안내만, API 503)
- 캐시 버전 20261030c, 단위·API·실제 PG·브라우저 테스트

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 16:51:10 +09:00

561 lines
33 KiB
Python

"""안내문 발송(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, "<script>x</script>", ["c1@dbx", "c2@dbx"])
self.assertIn("&lt;script&gt;x&lt;/script&gt;님", h)
self.assertNotIn("<script>", h)
self.assertIn("<strong>미라네주방</strong>", h)
self.assertIn('<a href="https://miras.co.kr/"', h)
self.assertEqual(h.count('src="cid:'), 2)
self.assertEqual(store.dm_link("mira.kitchen"), "https://ig.me/m/mira.kitchen")
def test_legacy_text_body_becomes_html(self):
# 예전 저장 글·기본 문구(fmt 없음) = 줄마다 문단, 빈 줄 유지, **굵게**·주소 변환 — 글로 되돌리면 별표만 빠진 원래 글
self.assertEqual(self.T["fmt"], "html")
self.assertEqual(self.T["body"], '<p>안녕하세요, {이름}님.</p><p><strong>미라네주방</strong>입니다.</p>'
'<p><a href="https://miras.co.kr/">https://miras.co.kr/</a></p>')
d = store.normalize_template(None)
self.assertEqual(store.html_to_text(d["body"]), store.DEFAULT_TEMPLATE["body"].replace("**", "").rstrip())
self.assertEqual(store.normalize_template({"body": d["body"], "fmt": "html"})["body"], d["body"]) # 다시 정리해도 같음
def test_editor_html_sanitized(self):
# 설정 편집기(Quill getSemanticHTML) HTML — 서식은 남기고 위험한 것은 뺀다, &nbsp; → 띄어쓰기, 빈 문단 = <br>
raw = ('<p>안녕하세요,&nbsp;<span class="otr-nametag-on">{이름}</span>님.</p><p></p>'
'<p style="text-align: center;"><span style="color: rgb(230, 0, 0); font-size: 20px; position: fixed;">빨강</span>'
'<script>alert(1)</script><img src=x onerror="alert(1)"><iframe src="//x"></iframe></p>'
'<ul><li><strong>하나</strong></li><li><em><u><s>둘</s></u></em></li></ul>'
'<p><a href="javascript:alert(1)" onclick="x">나쁜</a> <a href="https://a.com/?x=1&amp;y=2" target="_blank">좋은</a>'
'<span style="background-color: url(x)">배경</span>{<strong>이</strong>름}<div>안</div></p>')
t = store.normalize_template({"body": raw, "fmt": "html"})
self.assertEqual(t["body"],
'<p>안녕하세요, <span>{이름}</span>님.</p><p><br></p>'
'<p style="text-align: center"><span style="color: rgb(230, 0, 0); font-size: 20px">빨강</span></p>'
'<ul><li><strong>하나</strong></li><li><em><u><s>둘</s></u></em></li></ul>'
'<p><a>나쁜</a> <a href="https://a.com/?x=1&amp;y=2">좋은</a><span>배경</span>{<strong>이</strong>름}안</p>')
self.assertEqual(store.html_to_text(t["body"]), "안녕하세요, {이름}님.\n\n빨강\n- 하나\n- 둘\n나쁜 좋은배경{이름}안")
self.assertTrue(store.needs_name(t))
h = store.html_body(t, "<김>")
self.assertIn("안녕하세요, <span>&lt;김&gt;</span>님.", h)
self.assertIn("배경</span>&lt;김&gt;<strong></strong>안", h) # 글자마다 서식이 달라도 {이름} 을 바꾼다
self.assertIn('<p style="margin:0;text-align: center">', h) # 메일 프로그램 문단 여백 0
for bad in ("<script", "onerror", "javascript:", "<iframe", "position", "url(", "<img src=x", "class="):
self.assertNotIn(bad, h)
# 서식 포함 너무 긴 본문 = 저장 안 됨(정리 후 길이)
self.assertGreater(len(store.normalize_template({"body": "<p>" + "가" * (store.BODY_MAX + 10) + "</p>", "fmt": "html"})["body"]),
store.BODY_MAX)
def test_dm_body(self):
# DM 문구가 비면 메일 글(본문 + 끝 문구), 있으면 그것만 — 별표만 빼고 {이름}, 끝 문구·제목 없이
self.assertEqual(store.dm_text(self.T, "김철수"), store.plain_text(self.T, "김철수"))
self.assertEqual(store.DEFAULT_TEMPLATE["dm_body"], "")
t = store.normalize_template({**self.T, "dm_body": " {이름}님, **미라네주방**입니다!\r\n메일 주소 알려주세요 "})
self.assertEqual(store.dm_text(t, "미라"), "미라님, 미라네주방입니다!\n메일 주소 알려주세요")
self.assertEqual(len(store.normalize_template({"dm_body": "가" * 5000})["dm_body"]), store.DM_MAX)
# 이름 필요 = 그 구분으로 갈 글 기준
no_name_dm = store.normalize_template({"subject": "{이름}님", "body": "{이름}", "dm_body": "안녕하세요"})
self.assertTrue(store.needs_name(no_name_dm, "email"))
self.assertFalse(store.needs_name(no_name_dm, "instagram"))
self.assertTrue(store.needs_name(t, "instagram"))
self.assertTrue(store.needs_name(store.normalize_template({"body": "x", "footer": "{이름}"}), "instagram"))
class FakeDB:
def __init__(self, template=None, images=()):
self.t = store.normalize_template(template)
self.images = list(images)
self.done = []
def get_template(self):
return dict(self.t)
def list_images(self, with_data=False):
return self.images
def finish_send(self, rid, *, ok, via, by, subject, error=""):
self.done.append((rid, ok, via, by, subject, error))
class FakeInout:
def __init__(self, connected=True):
self.tok = {"me@miras.co.kr": {"refresh_token_enc": "enc"}} if connected else {}
self.deleted, self.marked = [], []
def gmail_token(self, email):
return self.tok.get(email)
def delete_gmail_token(self, email):
self.deleted.append(email)
def mark_gmail(self, email, error=""):
self.marked.append(email)
class SendBatchTests(unittest.TestCase):
USER = {"email": "me@miras.co.kr", "name": "나"}
ROWS = [{"id": 1, "handle": "a@x.com", "name": "에이"}, {"id": 2, "handle": "b@x.com", "name": ""},
{"id": 3, "handle": "c@x.com", "name": "씨"}]
def _run(self, db, inout, fail_on=None, exc=None):
from app.modules.inout import gmail
sent = []
def fake_send(refresh, raw):
text = raw.decode("utf-8", "replace")
to = next(r["handle"] for r in self.ROWS if r["handle"] in text.split("Subject:")[0])
if fail_on and to == fail_on:
raise exc
sent.append((refresh, to, raw))
return "gid"
with patch.object(gmail, "decrypt_token", return_value="R"), patch.object(gmail, "send", side_effect=fake_send):
res = send.send_batch(db, inout, rows=[dict(r) for r in self.ROWS], user=self.USER, gap=0)
return res, sent
def test_sends_one_each_skips_no_name(self):
import email as em
import email.policy # noqa: F401
db = FakeDB(images=[{"id": 9, "data": b"\xff\xd8jpeg"}])
res, sent = self._run(db, FakeInout())
self.assertEqual(res, {"sent": 2, "failed": 1})
self.assertEqual([s[1] for s in sent], ["a@x.com", "c@x.com"])
msg = em.message_from_bytes(sent[0][2], policy=em.policy.default)
self.assertIn("me@miras.co.kr", msg["From"])
self.assertEqual(msg["To"], "a@x.com")
html = next(p for p in msg.walk() if p.get_content_type() == "text/html").get_content()
self.assertIn("안녕하세요, 에이님.", html)
self.assertIn("cid:outreach-9@dbx", html)
self.assertTrue(any(p.get("Content-ID") == "<outreach-9@dbx>" for p in msg.walk()))
self.assertEqual([(d[0], d[1]) for d in db.done], [(1, True), (2, False), (3, True)])
self.assertIn("이름 없음", db.done[1][5])
def test_not_connected_fails_all(self):
db = FakeDB()
res, sent = self._run(db, FakeInout(connected=False))
self.assertEqual((res, sent), ({"sent": 0, "failed": 3}, []))
self.assertTrue(all(not d[1] and "Gmail 이 연결되지" in d[5] for d in db.done))
def test_disconnect_midway_stops_rest_and_one_bad_address_continues(self):
from app.modules.inout import gmail
db, inout = FakeDB({"body": "본문"}), FakeInout()
res, _ = self._run(db, inout, fail_on="a@x.com", exc=gmail.GmailNotConnected("끊김"))
self.assertEqual(res, {"sent": 0, "failed": 3})
self.assertEqual(inout.deleted, ["me@miras.co.kr"])
db2 = FakeDB({"body": "본문"})
res2, sent2 = self._run(db2, FakeInout(), fail_on="a@x.com", exc=gmail.GmailError("주소 오류"))
self.assertEqual(res2, {"sent": 2, "failed": 1}) # {이름} 없는 본문 = 이름 없어도 보냄
self.assertEqual([s[1] for s in sent2], ["b@x.com", "c@x.com"])
# ── 실제 앱 ─────────────────────────────────────────────
PRELUDE = '''
from unittest.mock import patch
from fastapi.testclient import TestClient
import app.main as main
from app.modules.outreach import store as ostore
from app.modules.outreach import send as osend
def U(email, role="user", outreach=True):
return {"email": email, "name": email.split("@")[0], "role": role, "is_super_admin": False, "modules": {"outreach": outreach}}
who = {"u": None}
me, other = U("me@miras.co.kr"), U("x@miras.co.kr", outreach=False)
users = [me, other]
batches = []
class Store:
def __init__(self):
self.t = ostore.normalize_template(None); self.rows = []; self.seq = 0; self.saved = None
def get_template(self):
return {**self.t, "updated_by": "", "updated_at": "", "is_default": self.saved is None}
def save_template(self, value, by): # db.save_template 과 같은 검사
t = ostore.normalize_template(value)
if not t["subject"] or not ostore.html_to_text(t["body"]).strip(): raise ValueError("메일 제목·본문을 쓰세요.")
self.t = t; self.saved = by; return self.get_template()
def list_images(self, with_data=False): return []
def list_logs(self, limit=200): return []
dm_bodies = []
def list_dm_bodies(self): return [dict(b) for b in reversed(self.dm_bodies)]
def save_dm_body(self, body, by, body_id=None):
title, text = ostore.dm_saved_body(body)
if body_id is None:
self.seq += 1; self.dm_bodies.append({"id": self.seq, "title": title, "body": text, "created_by": by, "updated_by": by, "updated_at": ""})
return self.seq
b = next((x for x in self.dm_bodies if x["id"] == body_id), None)
if b is None: raise KeyError(body_id)
b.update(title=title, body=text, updated_by=by); return body_id
def delete_dm_body(self, body_id): self.dm_bodies = [b for b in self.dm_bodies if b["id"] != body_id]
def list_recipients(self): return [dict(r) for r in self.rows]
def get_recipient(self, rid): return next((dict(r) for r in self.rows if r["id"] == rid), None)
def add_recipients(self, rows, by):
out = {"added": 0, "existed": 0, "invalid": 0}
for r in rows:
d = ostore.detect(r["address"])
if not d["kind"]: out["invalid"] += 1; continue
if any(x["kind"] == d["kind"] and x["handle"] == d["handle"] for x in self.rows): out["existed"] += 1; continue
self.seq += 1
self.rows.append({"id": self.seq, "kind": d["kind"], "handle": d["handle"], "address": r["address"], "name": r["name"],
"memo": "", "status": "대기", "sent_at": "", "sent_by": "", "sent_via": "", "last_error": ""})
out["added"] += 1
return out
def update_recipient(self, rid, name=None, memo=None, status=None):
r = next(x for x in self.rows if x["id"] == rid)
if name is not None: r["name"] = name
if status is not None: r["status"] = status
return dict(r)
def delete_recipients(self, ids):
n = len(self.rows); self.rows = [r for r in self.rows if r["id"] not in ids]; return n - len(self.rows)
def claim_for_send(self, ids):
got = [r for r in self.rows if r["id"] in ids and r["kind"] == "email" and r["status"] in ("대기", "실패")]
for r in got: r["status"] = "발송중"
return [dict(r) for r in got]
def mark_dm_sent(self, rid, by, subject):
r = next(x for x in self.rows if x["id"] == rid)
if r["kind"] != "instagram": raise ValueError("메일 줄은 [일괄 발송]으로 보냅니다.")
r.update(status="보냄", sent_via="dm", sent_by=by); return dict(r)
class Inout:
def __init__(self, on): self.on = on
def gmail_token(self, email): return {"refresh_token_enc": "x"} if self.on else None
st = Store()
def run(body, connected=False, configured=True):
main.app.state.outreach_store = st if configured else None
main.app.state.inout_store = Inout(connected)
with patch.object(main, "get_current_user_record", side_effect=lambda r: who["u"]), \\
patch.object(main, "get_session_user", side_effect=lambda r: who["u"]), \\
patch.object(main.user_store, "get", side_effect=lambda e: who["u"]), \\
patch.object(main.user_store, "list_all", side_effect=lambda: users), \\
patch.object(osend, "send_batch", side_effect=lambda *a, **kw: batches.append([r["id"] for r in kw["rows"]])), \\
patch("app.modules.inout.gmail.configured", return_value=True):
body(TestClient(main.app, follow_redirects=False))
'''
def _run(code: str) -> subprocess.CompletedProcess:
env = dict(os.environ)
for key in ("ASSET", "CAFE24", "CUPANG", "VACATION", "PROJECT", "DISPATCH", "PERFORMANCE", "MALAYSIA_STOCK",
"ITEMCODE", "EXPENSE", "INOUT", "OUTREACH"):
env[key + "_DB_URL"] = ""
env.update(SESSION_SECRET_KEY="local-outreach-test-only", SESSION_COOKIE_SECURE="false", PERFORMANCE_AUTO_SYNC="false",
PYTHONIOENCODING="utf-8")
with tempfile.TemporaryDirectory(prefix="outreach-web-") as directory:
env["DATA_DIR"] = directory
return subprocess.run([sys.executable, "-c", PRELUDE + code], cwd=ROOT, env=env, capture_output=True,
text=True, encoding="utf-8", timeout=120)
class OutreachWebTests(unittest.TestCase):
def test_registered_permission_and_unconfigured(self):
res = _run('''
from app.store import MODULE_KEYS
def body(c):
assert "outreach" in MODULE_KEYS and main.MODULE_LABELS["outreach"] == "안내문 발송"
who["u"] = me
assert any(x["key"] == "outreach" for x in main.build_erp_nav(me, active="outreach"))
r = c.get("/outreach/")
assert r.status_code == 503 and "OUTREACH_DB_URL" in r.text, r.status_code
assert c.get("/outreach/health").json() == {"status": "not_configured"}
who["u"] = other
assert c.get("/outreach/").status_code == 403
assert c.post("/outreach/api/recipients", json={"text": "a@b.com"}).status_code == 403
print("OK")
run(body, configured=False)
''')
self.assertEqual(res.returncode, 0, res.stdout + res.stderr)
self.assertIn("OK", res.stdout)
def test_flow(self):
res = _run('''
def body(c):
who["u"] = me
t = c.get("/outreach/").text
assert "안내문 발송" in t and "누적매출 300억" in t and "Gmail 연결" in t and "고른 메일 보내기" in t
# 설정 — 기본 문구, 저장, (광고)
s = c.get("/outreach/settings").text
cur = lambda s: __import__("json").loads(s.split('id="otr-current-data">')[1].split("</script>")[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("<p>안녕하세요, {이름}님.</p><p>주방의 본질을 지키며"), 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("</script>")[0])
assert 'id="otr-dm-names"' in d and "DM 수동 보내기" in d and dm_data == {"dm_template": "{이름}님, DM 문구입니다",
"dm_bodies": [], "dm_max": 1000}, dm_data
# 저장한 본문 — 새로 저장(제목 = 첫 줄)·고치기·없는 것 404·빈 글/너무 김 400·지우기
r = c.post("/outreach/api/dm-bodies", json={"body": "\\n 첫 줄 제목\\n{이름}님 안녕하세요"})
assert r.status_code == 200 and r.json()["items"][0]["title"] == "첫 줄 제목", r.text
bid = r.json()["id"]
assert c.put(f"/outreach/api/dm-bodies/{bid}", json={"body": "바꾼 제목\\n본문"}).json()["items"][0]["body"] == "바꾼 제목\\n본문"
assert c.put("/outreach/api/dm-bodies/99999", json={"body": "x"}).status_code == 404
assert c.post("/outreach/api/dm-bodies", json={"body": " "}).status_code == 400
assert c.post("/outreach/api/dm-bodies", json={"body": "가" * 1001}).status_code == 400
assert c.delete(f"/outreach/api/dm-bodies/{bid}").json()["items"] == []
# 서식 편집기 본문(fmt=html) — 서버가 정리해 저장, 메일 미리보기에 서식·이름
r = c.post("/outreach/settings", data={"subject": "{이름}님 제안", "fmt": "html", "dm_body": "",
"body": '<p>안녕&nbsp;<span style="color: rgb(230, 0, 0)" onclick="x">{이름}</span>님</p><script>x</script>'})
assert r.status_code == 303 and st.t["body"] == '<p>안녕 <span style="color: rgb(230, 0, 0)">{이름}</span>님</p>', st.t["body"]
pv = c.get(f"/outreach/api/recipients/{kim['id']}/preview").json()
assert '<span style="color: rgb(230, 0, 0)">김철수</span>님' 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": "<p></p><p><br></p>"}).status_code == 400
# 메일 보내기 — Gmail 없음 = 409(재연결 안내)
r = c.post("/outreach/api/send", json={"ids": [kim["id"]]})
assert r.status_code == 409 and r.json()["reconnect"] is True
# DM 보냄 — 인스타 줄만
assert c.post(f"/outreach/api/recipients/{kim['id']}/dm-sent").status_code == 400
assert c.post(f"/outreach/api/recipients/{mira['id']}/dm-sent").json()["row"]["status"] == "보냄"
print("OK1")
run(body)
def body2(c):
who["u"] = me
kim = st.rows[0]
r = c.post("/outreach/api/send", json={"ids": [r["id"] for r in st.rows]})
assert r.status_code == 202 and r.json()["queued"] == 1, r.text # 메일 줄만(DM 은 빠짐)
assert batches == [[kim["id"]]], batches
assert c.post("/outreach/api/send", json={"ids": [kim["id"]]}).status_code == 409 # 이미 발송중 — 두 번 안 보냄
assert c.post("/outreach/api/send", json={"ids": []}).status_code == 400
assert "보내는 메일: <b>me@miras.co.kr</b>" in c.get("/outreach/").text
assert c.post("/outreach/api/recipients/delete", json={"ids": [st.rows[1]["id"]]}).json()["deleted"] == 1
print("OK2")
run(body2, connected=True)
''')
self.assertEqual(res.returncode, 0, res.stdout + res.stderr)
self.assertIn("OK2", res.stdout)
def test_gmail_callback_outreach_origin(self):
"""안내문 발송에서 시작한 Gmail 연결 — 입출고 콜백이 outreach 권한으로 처리하고 안내문 화면으로."""
res = _run('''
from app.modules.inout import gmail
from starlette.requests import Request
class Inout2(Inout):
saved = []
def save_gmail_token(self, email, refresh_token_enc, scopes): self.saved.append(email)
class Client:
async def authorize_access_token(self, request):
return {"userinfo": {"email": "me@miras.co.kr"}, "scope": "openid email " + gmail.GMAIL_SCOPE, "refresh_token": "R"}
@main.app.get("/__mark")
def mark(request: Request):
request.session["_gmail_origin"] = "outreach"; request.session["_gmail_next"] = "/outreach/"; return {}
def body(c):
inout = Inout2(False)
main.app.state.inout_store = inout
who["u"] = me
with patch.object(gmail, "oauth_client", return_value=Client()), patch.object(gmail, "encrypt_token", return_value="enc"):
c.get("/__mark")
r = c.get("/inout/gmail/callback")
assert r.status_code == 303 and r.headers["location"].startswith("/outreach/?msg="), (r.status_code, r.headers.get("location"))
assert inout.saved == ["me@miras.co.kr"]
who["u"] = other # 안내문 권한 없으면 거절
c.get("/__mark")
assert c.get("/inout/gmail/callback").status_code == 403
print("OK")
run(body)
''')
self.assertEqual(res.returncode, 0, res.stdout + res.stderr)
self.assertIn("OK", res.stdout)
class DmSavedBodyTests(unittest.TestCase):
def test_title_is_first_line_and_limits(self):
from app.modules.outreach import store as ostore
self.assertEqual(ostore.dm_saved_body("\r\n\n 안녕 {이름}님 \r\n둘째"), ("안녕 {이름}님", "안녕 {이름}님 \n둘째"))
self.assertEqual(ostore.dm_saved_body("가" * 50)[0], "가" * 40 + "…")
for bad in ("", " \n ", "가" * (ostore.DM_MAX + 1)):
with self.assertRaises(ValueError):
ostore.dm_saved_body(bad)
@unittest.skipUnless(DB_ENABLED, "OUTREACH_TEST_DB_URL(localhost) 미설정")
class OutreachDBTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
from app.modules.outreach.db import OutreachDBStore
cls.st = OutreachDBStore(DSN)
@classmethod
def tearDownClass(cls):
cls.st.close()
def test_dm_bodies(self):
st = self.st
tag = uuid.uuid4().hex[:6]
a = st.save_dm_body(f"제목{tag}\n{{이름}}님", by="Me@X.com")
b = st.save_dm_body(f"둘째{tag}", by="me@x.com")
items = [x for x in st.list_dm_bodies() if tag in x["title"]]
self.assertEqual([x["id"] for x in items], [b, a]) # 새로 고친 것부터
self.assertEqual((items[1]["body"], items[1]["created_by"]), (f"제목{tag}\n{{이름}}님", "me@x.com"))
st.save_dm_body(f"고침{tag}", by="me@x.com", body_id=a)
self.assertEqual([x["title"] for x in st.list_dm_bodies() if tag in x["title"]][0], f"고침{tag}")
with self.assertRaises(KeyError):
st.save_dm_body("x", by="me@x.com", body_id=-1)
st.delete_dm_body(a)
st.delete_dm_body(b)
self.assertFalse([x for x in st.list_dm_bodies() if tag in x["title"]])
def test_recipients_claim_finish_logs(self):
import threading
st = self.st
tag = uuid.uuid4().hex[:6]
res = st.add_recipients([{"address": f"Kim{tag}@miras.co.kr", "name": "김"}, {"address": f"@mira{tag}", "name": ""},
{"address": "홍길동", "name": "x"}, {"address": f"kim{tag}@MIRAS.co.kr", "name": "다른 이름"}], by="me@x.com")
self.assertEqual(res, {"added": 2, "existed": 1, "invalid": 1})
rows = {r["handle"]: r for r in st.list_recipients() if tag in r["handle"]}
kim, mira = rows[f"kim{tag}@miras.co.kr"], rows[f"mira{tag}"]
self.assertEqual((kim["kind"], kim["name"], mira["kind"]), ("email", "김", "instagram")) # 이미 있는 이름은 그대로
st.add_recipients([{"address": f"@mira{tag}", "name": "미라"}], by="me@x.com") # 빈 이름은 채움
self.assertEqual(st.get_recipient(mira["id"])["name"], "미라")
# 동시에 두 번 잡아도 한 번만
got = []
ts = [threading.Thread(target=lambda: got.append(st.claim_for_send([kim["id"], mira["id"]]))) for _ in range(4)]
[t.start() for t in ts]
[t.join() for t in ts]
self.assertEqual(sorted(len(g) for g in got), [0, 0, 0, 1])
self.assertEqual(st.get_recipient(kim["id"])["status"], "발송중")
self.assertEqual(st.delete_recipients([kim["id"]]), 0) # 보내는 중엔 못 지움
st.finish_send(kim["id"], ok=False, via="gmail", by="me@x.com", subject="제목", error="오류")
self.assertEqual((st.get_recipient(kim["id"])["status"], st.get_recipient(kim["id"])["last_error"]), ("실패", "오류"))
self.assertEqual(len(st.claim_for_send([kim["id"]])), 1) # 실패는 다시 잡힘
st.finish_send(kim["id"], ok=True, via="gmail", by="me@x.com", subject="제목")
k = st.get_recipient(kim["id"])
self.assertEqual((k["status"], k["sent_via"], k["last_error"], bool(k["sent_at"])), ("보냄", "gmail", "", True))
self.assertEqual(st.claim_for_send([kim["id"]]), []) # 보낸 줄은 안 잡힘
self.assertEqual(st.mark_dm_sent(mira["id"], by="me@x.com", subject="s")["status"], "보냄")
with self.assertRaises(ValueError):
st.mark_dm_sent(kim["id"], by="me@x.com", subject="s")
logs = [l for l in st.list_logs() if tag in l["address"].lower()]
self.assertEqual(sorted((l["kind"], l["ok"]) for l in logs), [("email", False), ("email", True), ("instagram", True)])
self.assertEqual(st.update_recipient(kim["id"], status="대기")["status"], "대기")
with self.assertRaises(ValueError):
st.update_recipient(kim["id"], status="보냄")
# 서버가 보내던 중 멈춘 줄 → 실패
st.claim_for_send([kim["id"]])
self.assertGreaterEqual(st.release_stuck(), 1)
self.assertEqual(st.get_recipient(kim["id"])["status"], "실패")
self.assertEqual(st.delete_recipients([kim["id"], mira["id"]]), 2)
def test_template_and_images(self):
st = self.st
t = st.get_template()
self.assertTrue(t["subject"])
saved = st.save_template({"subject": "제목 {이름}", "body": "본문", "ad_label": True, "sender_name": "미라네",
"dm_body": "{이름}님 DM"}, by="Me@X.com")
self.assertEqual((saved["subject"], saved["ad_label"], saved["updated_by"], saved["is_default"]), ("제목 {이름}", True, "me@x.com", False))
self.assertEqual(st.get_template()["dm_body"], "{이름}님 DM")
with self.assertRaises(ValueError):
st.save_template({"subject": "", "body": "x"}, by="me")
ids = [st.add_image(filename=f"{i}.jpg", data=b"\xff\xd8" + bytes([i]), width=10, height=10, by="me") for i in range(2)]
try:
self.assertEqual([im["id"] for im in st.list_images() if im["id"] in ids], ids)
st.move_image(ids[1], -1)
self.assertEqual([im["id"] for im in st.list_images() if im["id"] in ids], [ids[1], ids[0]])
self.assertEqual(bytes(st.get_image(ids[0])["data"]), b"\xff\xd8\x00")
self.assertEqual(st.list_images(with_data=True)[0].keys() >= {"data"}, True)
finally:
for i in ids:
st.delete_image(i)
st.save_template(dict(store.DEFAULT_TEMPLATE), by="me")
if __name__ == "__main__":
unittest.main()