Files
dbx-main/tests/test_inout_mail_photo.py
T
king 0ba6192e95 feat(입출고): 대성화학·인천공장 발주 메일 표를 간단하게
공장 이름에 대성화학·인천공장이 들어가면 품목 표를 번호·제품 코드·
제품명·수량·박스당 수량·박스 수·비고로 만들고, 요약 표와 글 본문에서도
금액·무게·PP·은을 뺀다. 박스 값은 메일을 만들 때의 상품 정보로 계산한다.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 15:43:19 +09:00

308 lines
18 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""입출고 003 — 발주 메일(본문·받는 주소·Gmail 연결 검사·토큰·보내기)과 입고증 사진 검사. DB·구글 없이(가짜 구글 서버)."""
import base64
import email
import json
import re
import unittest
from datetime import date
from email import policy
from unittest.mock import patch
import httpx
from app.modules.inout import gmail
from app.modules.inout import store as s
JPEG = b"\xff\xd8\xff\xe0" + b"0" * 64
PNG = b"\x89PNG\r\n\x1a\n" + b"0" * 64
def _order(**over):
o = {"order_no": "PO-261016-01", "factory_name": "엘리화학", "factory_manager": "이석준", "order_date": date(2026, 10, 16),
"due_date": date(2026, 10, 30), "memo": "박스당 24개<포장>",
"lines": [{"item_code": "MT-0320", "item_name": "미라클 통 320ml", "qty": 5000, "memo": ""},
{"item_code": "MT-0500", "item_name": "<b>뚜껑</b>", "qty": 1200, "memo": "흰색"}]}
o.update(over)
return o
class RotateTests(unittest.TestCase):
"""입고증 사진 돌리기(2026-11-02) — 시계 방향·형식 유지·EXIF 반영."""
@staticmethod
def _image(fmt, size=(40, 20), **save):
from io import BytesIO
from PIL import Image
im = Image.new("RGB", size, (255, 0, 0))
im.paste((0, 0, 255), (0, 0, size[0] // 2, size[1] // 2)) # 왼쪽 위만 파랑
buf = BytesIO()
im.save(buf, format=fmt, **save)
return buf.getvalue()
@staticmethod
def _open(data):
from io import BytesIO
from PIL import Image
return Image.open(BytesIO(data))
def test_right_and_left_turn_corner_the_right_way(self):
right = self._open(s.rotate_image(self._image("PNG"), 90))
self.assertEqual(right.size, (20, 40))
self.assertEqual(right.convert("RGB").getpixel((19, 0)), (0, 0, 255)) # 왼쪽 위 → 시계 방향이면 오른쪽 위
left = self._open(s.rotate_image(self._image("PNG"), 270))
self.assertEqual(left.convert("RGB").getpixel((0, 39)), (0, 0, 255)) # 반시계면 왼쪽 아래
def test_keeps_format(self):
for fmt, kind in (("JPEG", "image/jpeg"), ("PNG", "image/png"), ("WEBP", "image/webp"), ("GIF", "image/gif")):
with self.subTest(fmt=fmt):
out = s.rotate_image(self._image(fmt), 90)
self.assertEqual(s.sniff_image(out), kind)
self.assertEqual(self._open(out).size, (20, 40))
def test_phone_exif_is_applied_then_dropped(self):
"""휴대폰 사진(EXIF 회전 6 = 화면에선 세로) — 돌린 결과는 화면에 보이던 모습 기준이어야 하고 EXIF 회전이 남으면 안 된다."""
from PIL import Image
exif = Image.Exif()
exif[0x0112] = 6
out = self._open(s.rotate_image(self._image("JPEG", exif=exif.tobytes()), 90))
self.assertEqual(out.size, (40, 20)) # 화면 20×40 → 오른쪽으로 돌려 40×20
self.assertNotEqual(out.getexif().get(0x0112), 6)
def test_refuses_what_cannot_be_turned(self):
for bad, msg in ((b"....ftypheic" + b"0" * 20, "HEIC"), (JPEG, "돌릴 수 없")):
with self.subTest(msg=msg), self.assertRaisesRegex(ValueError, msg):
s.rotate_image(bad, 90)
with self.assertRaisesRegex(ValueError, "왼쪽·오른쪽"):
s.rotate_image(self._image("PNG"), 45)
from io import BytesIO
from PIL import Image
buf = BytesIO()
Image.new("RGB", (4, 4), (255, 0, 0)).save(buf, format="GIF", save_all=True, append_images=[Image.new("RGB", (4, 4), (0, 0, 255))])
with self.assertRaisesRegex(ValueError, "움직이는"):
s.rotate_image(buf.getvalue(), 90)
class MailContentTests(unittest.TestCase):
def test_parse_emails(self):
self.assertEqual(s.parse_emails("a@x.com, B@y.co.kr; a@X.com\nc@z.kr"), ["a@x.com", "B@y.co.kr", "c@z.kr"])
self.assertEqual(s.parse_emails(""), [])
for bad in ("abc", "a@b", "a@@b.com", "a b@c.com"):
with self.subTest(bad=bad), self.assertRaises(ValueError):
s.parse_emails(bad)
with self.assertRaisesRegex(ValueError, "입력하세요"):
s.parse_emails(" ", label="받는 사람", required=True)
with self.assertRaisesRegex(ValueError, "10개"):
s.parse_emails(",".join(f"u{i}@x.com" for i in range(11)))
def test_order_mail_summary_and_escaping(self):
m = s.order_mail(_order(), sender_name="King", sender_email="king@dbxcorp.co.kr")
self.assertEqual(m["subject"], "[발주] PO-261016-01 · 엘리화학 · 미라클 통 320ml 외 1종")
for part in ("이석준님, 안녕하세요.", "발주번호: PO-261016-01", "발주일: 2026.10.16(금)", "입고 예정일: 2026.10.30(금)", "2종 · 총 6,200개",
"1. MT-0320 미라클 통 320ml — 5,000개", "(흰색)", "발주 담당: King (king@dbxcorp.co.kr)"):
self.assertIn(part, m["text"])
h = m["html"]
self.assertIn("&lt;b&gt;뚜껑&lt;/b&gt;", h) # 제품 이름·메모의 HTML 은 글자로
self.assertIn("박스당 24개&lt;포장&gt;", h)
self.assertNotIn("<b>뚜껑</b>", h)
self.assertIn("6,200", h) and self.assertIn("5,000", h)
m2 = s.order_mail(_order(due_date=None, factory_manager="", memo="", lines=_order()["lines"][:1]),
sender_name="", sender_email="k@x.com")
self.assertEqual(m2["subject"], "[발주] PO-261016-01 · 엘리화학 · 미라클 통 320ml")
self.assertIn("입고 예정일: 협의", m2["text"])
self.assertTrue(m2["text"].startswith("안녕하세요."))
self.assertNotIn("요청 사항", m2["text"])
def test_order_mail_simple_factories(self):
"""대성화학·인천공장 — 표는 번호·제품 코드·제품명·수량·박스당 수량·박스 수·비고만, 단가·금액·무게·은은 어디에도 없음. 다른 공장은 그대로."""
from decimal import Decimal as D
priced = [{"item_code": "MT-0320", "item_name": "통", "qty": 100, "memo": "흰색", "unit_price": D("7777"),
"weight_g": D("50"), "silver_pct": D("3")}]
for name in ("대성화학", "(주)대성화학", "인천공장", "인천 공장"):
with self.subTest(name=name):
m = s.order_mail(_order(factory_name=name, lines=priced), sender_name="K", sender_email="k@x.com")
head = m["html"][m["html"].index("<thead>"):m["html"].index("</thead>")]
self.assertEqual(re.findall(r"<th[^>]*>([^<]*)</th>", head), ["번호", "제품 코드", "제품명", "수량", "박스당 수량", "박스 수", "비고"])
row = m["html"][m["html"].index("<tbody>"):m["html"].index("</tbody>")]
self.assertEqual(row.count("<td"), 7)
self.assertEqual(m["html"][m["html"].index("<tfoot>"):].count("<th"), 5) # 합계(3칸 합침)·수량·박스당 빈칸·박스·비고
for part in (m["html"], m["text"]):
self.assertNotRegex(part, "단가|금액|무게|PP|은\\(|7,777|777,700")
self.assertIn("1. MT-0320 통 — 100개 (흰색)", m["text"])
self.assertIn("발주번호", m["html"])
other = s.order_mail(_order(lines=[dict(priced[0], body_per_box=30)]), sender_name="K", sender_email="k@x.com")
for part in ("단가(원)", "금액(원)", "전체 무게(kg)", "PP 사용량(kg)", "은(Ag) 함유량", "7,777"):
self.assertIn(part, other["html"])
self.assertIn(">No</th>", other["html"])
self.assertIn("단가 7,777", other["text"])
self.assertNotIn("박스", other["html"].replace("박스당 24개", "")) # 다른 공장엔 박스 칸 없음(요청 사항 글 제외)
def test_order_mail_simple_boxes(self):
"""박스당 수량·박스 수(올림) — 뚜껑 있으면 통·뚜껑 따로, 입수 없으면 '-', 합계는 있는 줄만."""
self.assertEqual(s.line_boxes({"qty": 100, "body_per_box": 30}), {"per": "30개", "count": "4박스", "total": 4})
self.assertEqual(s.line_boxes({"qty": 90, "body_per_box": 30})["total"], 3)
self.assertEqual(s.line_boxes({"qty": 1000, "body_per_box": 120, "lid_per_box": 500}),
{"per": "통 120개 · 뚜껑 500개", "count": "통 9 · 뚜껑 2박스", "total": 11})
self.assertEqual(s.line_boxes({"qty": 5}), {"per": "-", "count": "-", "total": None})
lines = [{"item_code": "A", "item_name": "봉투", "qty": 2600, "memo": "", "body_per_box": 100, "lid_per_box": None},
{"item_code": "B", "item_name": "통", "qty": 1000, "memo": "흰색", "body_per_box": 120, "lid_per_box": 500},
{"item_code": "C", "item_name": "없음", "qty": 5, "memo": ""}]
m = s.order_mail(_order(factory_name="대성화학", memo="", lines=lines), sender_name="K", sender_email="k@x.com")
self.assertIn(">100개</td>", m["html"])
self.assertIn(">26박스</td>", m["html"])
self.assertIn("통 9 · 뚜껑 2박스", m["html"])
self.assertIn("37박스 (미설정 1종 제외)", m["html"])
self.assertIn("1. A 봉투 — 2,600개 · 박스당 100개 · 26박스", m["text"])
self.assertIn("2. B 통 — 1,000개 · 박스당 통 120개 · 뚜껑 500개 · 통 9 · 뚜껑 2박스 (흰색)", m["text"])
self.assertIn("3. C 없음 — 5개", m["text"])
def test_build_message_utf8_and_alternative(self):
raw = gmail.build_message(sender_name="킹", sender_email="king@dbxcorp.co.kr", to=["a@x.com", "b@y.com"], cc=["c@z.com"],
subject="[발주] 테스트 · 한글", text="본문", html="<p>본문</p>")
msg = email.message_from_bytes(raw, policy=policy.default)
self.assertEqual(msg["Subject"], "[발주] 테스트 · 한글")
self.assertEqual((msg["To"], msg["Cc"]), ("a@x.com, b@y.com", "c@z.com"))
self.assertIn("king@dbxcorp.co.kr", msg["From"])
self.assertEqual([p.get_content_type() for p in msg.iter_parts()], ["text/plain", "text/html"])
class PhotoTests(unittest.TestCase):
def test_sniff(self):
self.assertEqual(s.sniff_image(JPEG), "image/jpeg")
self.assertEqual(s.sniff_image(PNG), "image/png")
self.assertEqual(s.sniff_image(b"RIFF\x00\x00\x00\x00WEBPVP8 "), "image/webp")
self.assertEqual(s.sniff_image(b"GIF89a..."), "image/gif")
self.assertEqual(s.sniff_image(b"\x00\x00\x00\x18ftypheic...."), "image/heic")
self.assertIsNone(s.sniff_image(b"%PDF-1.4"))
self.assertIsNone(s.sniff_image(b"<svg xmlns=...")) # SVG(스크립트 가능)는 받지 않는다
def test_validate(self):
out = s.validate_photos([("C:\\폰\\IMG_1.jpg", JPEG), ("empty.jpg", b""), ("b.png", PNG)])
self.assertEqual([(x["filename"], x["content_type"]) for x in out], [("IMG_1.jpg", "image/jpeg"), ("b.png", "image/png")])
with self.assertRaisesRegex(ValueError, "사진 파일"):
s.validate_photos([("x.pdf", b"%PDF-1.4")])
with self.assertRaisesRegex(ValueError, "너무 큽니다"):
s.validate_photos([("big.jpg", JPEG + b"0" * s.MAX_PHOTO_BYTES)])
with self.assertRaisesRegex(ValueError, "10장"):
s.validate_photos([("a.jpg", JPEG)] * 3, existing=8)
class GmailTests(unittest.TestCase):
def test_check_grant(self):
ok = {"userinfo": {"email": "King@dbxcorp.co.kr"}, "scope": f"openid email {gmail.GMAIL_SCOPE}", "refresh_token": "1//r"}
self.assertEqual(gmail.check_grant(ok, expected_email="king@dbxcorp.co.kr"), ("1//r", ok["scope"]))
with self.assertRaisesRegex(gmail.GmailError, "다른 구글 계정"):
gmail.check_grant({**ok, "userinfo": {"email": "me@gmail.com"}}, expected_email="king@dbxcorp.co.kr")
with self.assertRaisesRegex(gmail.GmailError, "gmail.send"):
gmail.check_grant({**ok, "scope": "openid email"}, expected_email="king@dbxcorp.co.kr")
with self.assertRaisesRegex(gmail.GmailError, "갱신 토큰"):
gmail.check_grant({**ok, "refresh_token": ""}, expected_email="king@dbxcorp.co.kr")
def test_token_encryption_roundtrip_and_aad(self):
env = {"APP_ENCRYPTION_KEY": "11" * 32, "APP_ENCRYPTION_KEY_VERSION": "1"}
with patch.dict("os.environ", env):
enc = gmail.encrypt_token("King@x.com", "1//refresh-secret")
self.assertNotIn("refresh-secret", enc)
self.assertEqual(gmail.decrypt_token("king@x.com", enc), "1//refresh-secret")
with self.assertRaises(gmail.GmailNotConnected): # 남의 이메일 이름으로는 못 푼다(AAD)
gmail.decrypt_token("other@x.com", enc)
with patch.dict("os.environ", {"APP_ENCRYPTION_KEY": ""}), self.assertRaisesRegex(gmail.GmailError, "암호화 키"):
gmail.encrypt_token("k@x.com", "r")
def _fake(self, handler):
return patch.object(gmail, "_http", lambda: httpx.Client(transport=httpx.MockTransport(handler)))
def test_send_refreshes_and_posts_raw(self):
seen = []
def handler(req):
seen.append(req)
if req.url.host == "oauth2.googleapis.com":
return httpx.Response(200, json={"access_token": "ya29.A", "expires_in": 3600})
return httpx.Response(200, json={"id": "18f-msg", "threadId": "t"})
with self._fake(handler), patch("app.main.env", side_effect=lambda k, d="": {"GOOGLE_CLIENT_ID": "cid", "GOOGLE_CLIENT_SECRET": "sec"}.get(k, d)):
gid = gmail.send("1//r", b"Subject: x\r\n\r\nbody")
self.assertEqual(gid, "18f-msg")
form = dict(x.split("=", 1) for x in seen[0].content.decode().split("&"))
self.assertEqual((form["grant_type"], form["refresh_token"], form["client_id"]), ("refresh_token", "1%2F%2Fr", "cid"))
self.assertEqual(seen[1].headers["Authorization"], "Bearer ya29.A")
self.assertEqual(base64.urlsafe_b64decode(json.loads(seen[1].content)["raw"]), b"Subject: x\r\n\r\nbody")
def test_errors(self):
env = patch("app.main.env", side_effect=lambda k, d="": {"GOOGLE_CLIENT_ID": "c", "GOOGLE_CLIENT_SECRET": "s"}.get(k, d))
revoked = lambda req: httpx.Response(400, json={"error": "invalid_grant", "error_description": "Token has been expired or revoked."}) # noqa: E731
with self._fake(revoked), env, self.assertRaisesRegex(gmail.GmailNotConnected, "끊겼습니다"):
gmail.send("1//r", b"x")
def no_api(req):
if req.url.host == "oauth2.googleapis.com":
return httpx.Response(200, json={"access_token": "a"})
return httpx.Response(403, json={"error": {"message": "Gmail API has not been used in project 1 before or it is disabled."}})
with self._fake(no_api), env, self.assertRaisesRegex(gmail.GmailError, "Gmail API 가 꺼져"):
gmail.send("1//r", b"x")
def scope(req):
if req.url.host == "oauth2.googleapis.com":
return httpx.Response(200, json={"access_token": "a"})
return httpx.Response(403, json={"error": {"message": "Request had insufficient authentication scopes."}})
with self._fake(scope), env, self.assertRaises(gmail.GmailNotConnected):
gmail.send("1//r", b"x")
def down(req):
raise httpx.ConnectError("x")
with self._fake(down), env, self.assertRaisesRegex(gmail.GmailError, "ConnectError"):
gmail.send("1//r", b"x")
class MailPriceTests(unittest.TestCase):
"""004 — 메일 본문에 금액(수량 × 단가)·전체 무게(kg)·PP 사용량(kg)·은(Ag) 함유량(%·kg)과 합계(2026-10-19)."""
def test_order_mail_prices(self):
from decimal import Decimal as D
o = _order()
o["lines"][0].update(unit_price=D("85.5"), weight_g=D("24.5"), silver_pct=D("0.5"))
m = s.order_mail(o, sender_name="K", sender_email="k@x.com")
# 5,000개 × 24.5g = 122.5kg, 은 = 122.5kg × 0.5% = 0.6125kg, PP 사용량 = 122.5 − 0.6125 = 121.8875 → 121.888
for part in ("발주 금액: 427,500원 (단가 미입력 1종 제외)", "전체 무게: 122.5 kg", "PP 사용량: 121.888 kg", "은(Ag) 총량: 0.6125 kg",
"단가 85.5 · 금액 427,500 · 전체 무게 122.5kg · PP 사용량 121.888kg · 은 0.5% (0.6125kg)",
"단가 - · 금액 - · 전체 무게 - · PP 사용량 - · 은 -"):
self.assertIn(part, m["text"])
h = m["html"]
for part in ("단가(원)", "금액(원)", "전체 무게(kg)", "PP 사용량(kg)", "은(Ag) 함유량", "427,500", "0.5% (0.6125kg)",
">122.5<", ">121.888<", "0.6125 kg"):
self.assertIn(part, h)
self.assertNotIn("PP(g/개)", h)
# 합계 줄(2026-10-21) — 금액 " 원", 무게 " kg"(소수 첫째 자리에서 반올림): 122.5 → 123, 121.8875 → 122, 0.6125 → 1
foot = h.split("<tfoot>", 1)[1]
for part in (">427,500 원<", ">123 kg<", ">122 kg<", ">1 kg<"):
self.assertIn(part, foot)
self.assertLess(h.index("PP 사용량(kg)"), h.index("은(Ag) 함유량")) # PP 사용량 열은 은 함유량 왼쪽
# 첫 요약 표 = 4열(항목·값 두 쌍씩), 8칸 → 4줄. 요청 사항은 맨 아래 한 줄 전체(colspan 3)
import re
facts_tbl = h.split("</table>", 1)[0]
rows = re.findall(r"<tr>(.*?)</tr>", facts_tbl)
body = [r for r in rows if "요청 사항" not in r]
self.assertEqual(len(body), 4)
self.assertTrue(all(r.count("<th") == 2 and r.count("<td") == 2 for r in body))
self.assertIn("발주번호</th>", body[0]) and self.assertIn("발주일</th>", body[0])
self.assertIn("PP 사용량</th>", body[3]) and self.assertIn("은(Ag) 총량</th>", body[3])
memo_rows = [r for r in rows if "요청 사항" in r]
self.assertEqual(len(memo_rows), 1 if o.get("memo") else 0)
if memo_rows:
self.assertIn('colspan="3"', memo_rows[0])
o2 = _order() # 단가가 하나도 없으면 금액 줄은 "-"
t2 = s.order_mail(o2, sender_name="K", sender_email="k@x.com")["text"]
self.assertNotIn("전체 무게:", t2)
if __name__ == "__main__":
unittest.main()