Files
dbx-main/tests/test_inout_web.py
T
king 12f1d455b9 fix(inout): 메일 창 — 연결 전 아래 줄 숨김, redirect_uri_mismatch 대비 등록할 주소 안내
- .io-dlg-footbar 의 display:flex 가 hidden 속성을 덮어써 연결 전에도 [메일 발송]·[연결 끊기]가 보이던 문제
  → .io/.io-dlg/.io-viewer 안의 [hidden] 은 늘 숨김.
- 구글이 redirect_uri_mismatch 로 막으면 ERP 로 돌아오지 않으므로, 연결 안내에 구글 클라우드
  "승인된 리디렉션 URI"에 넣을 정확한 주소(callback_url)를 미리 보여 준다.

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

293 lines
18 KiB
Python

"""입출고 관리 — 실제 앱(메뉴·권한·화면·폼)을 격리된 하위 프로세스에서 확인.
1) 등록·미설정: 메뉴·관리자 권한 칩·"설정 필요" 화면(DB 없이 늘 실행)
2) 전체 흐름(INOUT_TEST_DB_URL 이 localhost 일 때만): 옵션(공장·담당자) → 발주 담당 발주서 작성(코드표 단품만)
→ 입고 담당 분할 입고 → 초과 입고 확인 → 미입고 현황 → 잔량 종결, 그리고 권한(조회만·담당 아님 403).
코드표(itemcode_db)는 가짜 리더로 바꾼다. 운영 DSN·데이터는 쓰지 않는다.
"""
import os
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
from urllib.parse import urlparse
ROOT = Path(__file__).resolve().parents[1]
DSN = os.getenv("INOUT_TEST_DB_URL", "")
DB_ENABLED = bool(DSN) and urlparse(DSN).hostname in ("localhost", "127.0.0.1")
PRELUDE = '''
from unittest.mock import patch
from fastapi.testclient import TestClient
import app.main as main
def U(email, role="user", inout=True):
return {"email": email, "name": email.split("@")[0], "role": role, "is_super_admin": False,
"modules": {"inout": inout}}
who = {"u": None}
users = []
class Items:
enabled = True
reason = ""
NAMES = {"MT-A": "가 단품", "MT-B": "나 단품", "MT-C": "다 단품"}
def search(self, q, limit=30):
return [{"code": c, "name": n} for c, n in self.NAMES.items() if q.upper() in c or q in n]
def lookup(self, codes):
return {c: self.NAMES[c] for c in codes if c in self.NAMES}
def run(body):
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):
client = TestClient(main.app)
body(client)
'''
def _run(code: str, extra_env: dict[str, str] | None = None) -> subprocess.CompletedProcess:
env = dict(os.environ)
for key in ("ASSET", "CAFE24", "CUPANG", "VACATION", "PROJECT", "DISPATCH", "PERFORMANCE", "MALAYSIA_STOCK",
"ITEMCODE", "EXPENSE", "INOUT"):
env[key + "_DB_URL"] = ""
env.update(SESSION_SECRET_KEY="local-inout-test-only", SESSION_COOKIE_SECURE="false", PERFORMANCE_AUTO_SYNC="false")
env.update(extra_env or {})
with tempfile.TemporaryDirectory(prefix="inout-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=90)
class InoutWebTests(unittest.TestCase):
def test_registered_and_unconfigured(self):
res = _run('''
from app.store import MODULE_KEYS
admin = U("admin@test.local", role="admin")
users.append(admin)
who["u"] = admin
def body(c):
assert "inout" in MODULE_KEYS
assert main.MODULE_LABELS["inout"] == "입출고 관리"
assert any(x["key"] == "inout" and x["active"] for x in main.build_erp_nav(admin, active="inout"))
assert "입출고 관리" in c.get("/admin").text # 관리자 화면 권한 칩
r = c.get("/inout/")
assert r.status_code == 503 and "INOUT_DB_URL" in r.text, r.status_code # DB 미설정 = 설정 필요 안내
assert c.get("/inout/health").json() == {"status": "not_configured"}
who["u"] = U("nobody@test.local", inout=False)
assert c.get("/inout/").status_code == 403 # 모듈 권한 없음
print("OK")
run(body)
''')
self.assertEqual(res.returncode, 0, res.stdout + res.stderr)
self.assertIn("OK", res.stdout)
@unittest.skipUnless(DB_ENABLED, "INOUT_TEST_DB_URL(localhost) not set")
def test_full_flow(self):
res = _run('''
import re, uuid
from app.modules.inout.db import InoutDBStore
main.app.state.inout_store = InoutDBStore(__import__("os").environ["INOUT_TEST_DB_URL"])
main.app.state.inout_items = Items()
tag = uuid.uuid4().hex[:6]
admin, buyer, wh, viewer = (U("admin-%s@t.local" % tag, role="admin"), U("buyer-%s@t.local" % tag),
U("wh-%s@t.local" % tag), U("viewer-%s@t.local" % tag))
users.extend([admin, buyer, wh, viewer])
def body(c):
# ── 옵션(톱니 팝업): 공장·담당자(관리자만) ──
who["u"] = buyer
assert c.get("/inout/settings?panel=1").status_code == 403
assert 'id="io-options-btn"' not in c.get("/inout/").text # 관리자 아니면 톱니 없음
who["u"] = admin
lst = c.get("/inout/").text
assert 'id="io-options-btn"' in lst and 'id="io-options"' in lst and ">옵션</a>" not in lst # 탭 대신 톱니 + 팝업
r = c.get("/inout/settings", follow_redirects=False) # 예전 주소 = 목록으로 가서 팝업 열기
assert r.status_code == 303 and r.headers["location"] == "/inout/?options=1"
assert 'data-open="1"' in c.get("/inout/?options=1").text
panel = c.get("/inout/settings?panel=1").text
assert buyer["email"] in panel and "발주 담당" in panel and "<html" not in panel.lower() # 팝업 안 내용만
assert 'name="manager"' in panel and 'name="contact"' in panel # 담당자·연락처 따로
H = {"X-Inout-Options": "1"}
r = c.post("/inout/settings/factories", data={"name": "공장-" + tag, "manager": "김공장", "contact": "010-1", "email": "factory-%s@x.com" % tag,
"is_active": "1"}, headers=H)
assert r.status_code == 200 and r.json() == {"ok": True, "message": "공장을 저장했습니다."}
dup = c.post("/inout/settings/factories", data={"name": "공장-" + tag, "is_active": "1"}, headers=H)
assert dup.status_code == 400 and dup.json()["ok"] is False and "같은 이름" in dup.json()["message"]
r = c.post("/inout/settings/factories", data={"name": "폼-" + tag, "is_active": "1"}, follow_redirects=False)
assert r.status_code == 303 and r.headers["location"].startswith("/inout/?options=1&msg=") # 팝업이 아닌 제출 = 이동
fid = next(f["id"] for f in main.app.state.inout_store.list_factories() if f["name"] == "공장-" + tag)
f = next(x for x in main.app.state.inout_store.list_factories() if x["id"] == fid)
assert (f["manager"], f["contact"]) == ("김공장", "010-1")
assert c.post("/inout/settings/roles", data={"order_email": [buyer["email"]], "receive_email": [wh["email"]]},
headers=H).json()["ok"]
st = main.app.state.inout_store
assert st.roles_of(buyer["email"]) == {"order"} and st.roles_of(wh["email"]) == {"receive"}
# ── 조회만 하는 사람 ──
who["u"] = viewer
assert c.get("/inout/").status_code == 200
assert c.get("/inout/orders/new").status_code == 403
assert "조회만 가능" in c.get("/inout/").text
# ── 발주 담당: 발주서(코드표 단품만) ──
who["u"] = buyer
form = c.get("/inout/orders/new").text
assert "공장-" + tag in form and "새 발주서" in form
bad = c.post("/inout/orders/new", data={"factory_id": fid, "order_date": "2026-10-16", "due_date": "2026-10-20",
"item_code": ["MT-A", "ZZ-9"], "item_name": ["", ""], "qty": ["100", "5"], "line_memo": ["", ""]})
assert bad.status_code == 400 and "코드표 단품에 없는 제품입니다: ZZ-9" in bad.text and 'value="ZZ-9"' in bad.text
r = c.post("/inout/orders/new", data={"factory_id": fid, "order_date": "2026-10-16", "due_date": "2026-10-20",
"memo": "1차", "item_code": ["mt-a", "MT-B", ""], "item_name": ["", "", ""], "qty": ["1,00", "50", ""],
"line_memo": ["", "포장 주의", ""]}, follow_redirects=False)
assert r.status_code == 303, r.text[:300]
oid = int(re.search(r"/inout/orders/(\\d+)", r.headers["location"]).group(1))
detail = c.get(r.headers["location"]).text
assert "김공장 · 010-1" in detail # 공장 담당자·연락처
assert "가 단품" in detail and "포장 주의" in detail and "PO-261016-" in detail and "발주서 PO-261016-" in detail
assert "이번 입고" not in detail # 발주 담당은 입고 칸이 없다
assert c.post("/inout/orders/%d/receipts" % oid, data={"receipt_date": "2026-10-17"}).status_code == 403
# ── 입고 담당: 분할 입고 → 초과 확인 ──
who["u"] = wh
detail = c.get("/inout/orders/%d" % oid).text
ids = dict(zip(re.findall(r'aria-label="(MT-[AB]) 이번 입고', detail), re.findall(r'name="qty_(\\d+)"', detail)))
r = c.post("/inout/orders/%d/receipts" % oid, data={"receipt_date": "2026-10-17", "memo": "1차 트럭",
"qty_" + ids["MT-A"]: "60"}, follow_redirects=False)
assert r.status_code == 303
page = c.get("/inout/orders/%d" % oid).text
assert "부분입고" in page and "1차 트럭" in page
over = c.post("/inout/orders/%d/receipts" % oid, data={"receipt_date": "2026-10-18", "qty_" + ids["MT-A"]: "45",
"qty_" + ids["MT-B"]: "50"})
assert over.status_code == 409 and "초과 입고로 저장" in over.text and "+5" in over.text
assert 'value="45"' in over.text # 넣은 숫자는 그대로
assert st.get_order(oid)["summary"]["received"] == 60 # 확인 전엔 저장 안 됨
r = c.post("/inout/orders/%d/receipts" % oid, data={"receipt_date": "2026-10-18", "qty_" + ids["MT-A"]: "45",
"qty_" + ids["MT-B"]: "50", "confirm_over": "1"}, follow_redirects=False)
assert r.status_code == 303 and "%EC%B4%88%EA%B3%BC" in r.headers["location"] # "초과 입고 포함" 안내
got = st.get_order(oid)
assert (got["status"], got["summary"]["over"]) == ("over", 5)
pend = c.get("/inout/pending").text
assert "초과 입고" in pend and got["order_no"] in pend
# ── 두 번째 발주: 미입고 현황 → 잔량 종결 ──
who["u"] = buyer
r = c.post("/inout/orders/new", data={"factory_id": fid, "order_date": "2026-10-16", "item_code": ["MT-C"],
"item_name": [""], "qty": ["30"], "line_memo": [""]}, follow_redirects=False)
oid2 = int(re.search(r"/inout/orders/(\\d+)", r.headers["location"]).group(1))
pend = c.get("/inout/pending?q=MT-C").text
assert "다 단품" in pend and "30" in pend
assert "제품별 미입고 합계" in pend
lst = c.get("/inout/?status=active&q=MT-C").text
assert st.get_order(oid2)["order_no"] in lst
c.post("/inout/orders/%d/close" % oid2, data={"reason": "단종"})
assert st.get_order(oid2)["status"] == "closed"
assert st.get_order(oid2)["order_no"] not in c.get("/inout/pending?q=MT-C").text
assert st.get_order(oid2)["order_no"] in c.get("/inout/?status=closed&q=MT-C").text
# ── 003: 입고증 사진(입고와 함께 · 나중에 더하기 · 보기) ──
JPEG = b"\\xff\\xd8\\xff\\xe0" + b"7" * 300
who["u"] = wh
o3 = c.post("/inout/orders/new", data={"factory_id": fid, "order_date": "2026-10-16", "item_code": ["MT-A"],
"item_name": [""], "qty": ["10"], "line_memo": [""]}, follow_redirects=False)
assert o3.status_code == 403 # 입고 담당은 발주 못 함
who["u"] = buyer
o3 = c.post("/inout/orders/new", data={"factory_id": fid, "order_date": "2026-10-16", "item_code": ["MT-A"],
"item_name": [""], "qty": ["10"], "line_memo": [""]}, follow_redirects=False)
assert "mail=1" in o3.headers["location"] # 새 발주서 → 메일 미리보기 바로
oid3 = int(re.search(r"/inout/orders/(\\d+)", o3.headers["location"]).group(1))
assert 'data-open="1"' in c.get(o3.headers["location"]).text
who["u"] = wh
page = c.get("/inout/orders/%d" % oid3).text
assert 'enctype="multipart/form-data"' in page and 'name="photos"' in page and 'id="io-mail-btn"' not in page
lid = re.search(r'name="qty_(\\d+)"', page).group(1)
bad = c.post("/inout/orders/%d/receipts" % oid3, data={"receipt_date": "2026-10-20", "qty_" + lid: "3"},
files=[("photos", ("doc.pdf", b"%PDF-1.4 x", "application/pdf"))])
assert bad.status_code == 400 and "사진 파일" in bad.text and "다시 첨부" in bad.text
assert st.get_order(oid3)["summary"]["received"] == 0 # 사진이 틀리면 입고도 저장 안 함
r = c.post("/inout/orders/%d/receipts" % oid3, data={"receipt_date": "2026-10-20", "qty_" + lid: "3"},
files=[("photos", ("입고증1.jpg", JPEG, "image/jpeg")), ("photos", ("입고증2.jpg", JPEG, "image/jpeg"))],
follow_redirects=False)
assert r.status_code == 303, r.text[:300]
got = st.get_order(oid3)
pids = [p["id"] for p in got["receipts"][0]["photos"]]
assert len(pids) == 2 and got["summary"]["received"] == 3
img = c.get("/inout/photos/%d" % pids[0])
assert img.status_code == 200 and img.content == JPEG and img.headers["content-type"] == "image/jpeg"
assert img.headers["x-content-type-options"] == "nosniff" and "sandbox" in img.headers["content-security-policy"]
page = c.get("/inout/orders/%d" % oid3).text
assert 'data-photo="%d"' % pids[0] in page and 'src="/inout/photos/%d"' % pids[0] in page
rid3 = got["receipts"][0]["id"]
r = c.post("/inout/orders/%d/receipts/%d/photos" % (oid3, rid3), files=[("photos", ("추가.png", b"\\x89PNG\\r\\n\\x1a\\n" + b"1" * 50, "image/png"))],
follow_redirects=False)
assert r.status_code == 303 and len(st.get_order(oid3)["receipts"][0]["photos"]) == 3
who["u"] = viewer
assert c.get("/inout/photos/%d" % pids[0]).status_code == 200 # 모듈 권한이면 보기는 됨
assert c.post("/inout/orders/%d/photos/%d/delete" % (oid3, pids[0])).status_code == 403
who["u"] = U("nobody-%s@t.local" % tag, inout=False)
assert c.get("/inout/photos/%d" % pids[0]).status_code == 403
who["u"] = wh
c.post("/inout/orders/%d/photos/%d/delete" % (oid3, pids[0]))
assert len(st.get_order(oid3)["receipts"][0]["photos"]) == 2
# ── 003: 발주 메일(발주 담당 본인 Gmail) ──
import app.modules.inout.gmail as g
sent = []
g.send = lambda refresh, raw: (sent.append((refresh, raw)) or "gid-%d" % len(sent))
who["u"] = viewer
assert c.get("/inout/orders/%d/mail" % oid3).status_code == 403 # 발주 담당만
who["u"] = buyer
pv = c.get("/inout/orders/%d/mail" % oid3).json()
assert pv["connected"] is False and pv["connect_url"].startswith("/inout/gmail/connect?next=")
assert pv["callback_url"].endswith("/inout/gmail/callback") # 구글에 등록할 주소 안내
assert pv["to"] == "factory-%s@x.com" % tag and pv["subject"].startswith("[발주] ") and "가 단품" in pv["html"]
r = c.post("/inout/orders/%d/mail" % oid3, json={"to": pv["to"]})
assert r.status_code == 409 and r.json()["reconnect"] is True # 연결 전엔 못 보냄
# 연결 — 구글 콜백(가짜): 다른 계정이면 거절, 같은 계정이면 저장(암호문)
class FakeClient:
token = None
async def authorize_access_token(self, request):
return self.token
fake = FakeClient()
g.oauth_client = lambda: fake
fake.token = {"userinfo": {"email": "someone@gmail.com"}, "scope": "openid email " + g.GMAIL_SCOPE, "refresh_token": "1//x"}
r = c.get("/inout/gmail/callback", follow_redirects=False)
assert r.status_code == 303 and "%EB%8B%A4%EB%A5%B8" in r.headers["location"] # "다른 구글 계정"
assert st.gmail_token(buyer["email"]) is None
fake.token = {"userinfo": {"email": buyer["email"]}, "scope": "openid email " + g.GMAIL_SCOPE, "refresh_token": "1//buyer-refresh"}
c.get("/inout/gmail/callback", follow_redirects=False)
tok = st.gmail_token(buyer["email"])
assert tok is not None and "1//buyer-refresh" not in tok["refresh_token_enc"] # 원문은 DB 에 없음
assert c.get("/inout/orders/%d/mail" % oid3).json()["connected"] is True
bad_to = c.post("/inout/orders/%d/mail" % oid3, json={"to": "nope"})
assert bad_to.status_code == 400 and "받는 사람 형식" in bad_to.json()["detail"]
r = c.post("/inout/orders/%d/mail" % oid3, json={"to": pv["to"], "cc": "boss@x.com"})
assert r.status_code == 200 and r.json()["ok"], r.text
refresh, raw = sent[-1]
assert refresh == "1//buyer-refresh" and b"factory-" in raw and b"boss@x.com" in raw
again = c.post("/inout/orders/%d/mail" % oid3, json={"to": pv["to"]})
assert again.status_code == 409 and again.json()["resend_needed"] is True and len(sent) == 1 # 실수로 두 번 안 감
assert c.post("/inout/orders/%d/mail" % oid3, json={"to": pv["to"], "resend": True}).json()["ok"] and len(sent) == 2
detail = c.get("/inout/orders/%d" % oid3).text
assert "모두 2번" in detail and "발주 메일 다시 보내기" in detail
# 구글이 연결을 끊었으면(invalid_grant) 토큰을 지우고 다시 연결 안내
def gone(refresh, raw):
raise g.GmailNotConnected("Gmail 연결이 끊겼습니다 — 다시 연결하세요.")
g.send = gone
r = c.post("/inout/orders/%d/mail" % oid3, json={"to": pv["to"], "resend": True})
assert r.status_code == 409 and r.json()["reconnect"] and st.gmail_token(buyer["email"]) is None
# ── 단품 검색 API ──
assert c.get("/inout/api/items?q=MT-").json()["items"][0]["code"] == "MT-A"
print("OK")
run(body)
''', {"INOUT_TEST_DB_URL": DSN, "APP_ENCRYPTION_KEY": "22" * 32, "GOOGLE_CLIENT_ID": "cid", "GOOGLE_CLIENT_SECRET": "sec"})
self.assertEqual(res.returncode, 0, res.stdout + res.stderr)
self.assertIn("OK", res.stdout)
if __name__ == "__main__":
unittest.main()