Files
dbx-main/tests/test_notice.py
king c7cc94a09c fix: 2026-10-15 코드 검토 F01~F10 — 수집 실패 전파·트랜잭션 경계·저장 실패·공지 버전/확인 조건·테스트 체계
- F01 쿠팡: HTTP 200 비JSON·data 목록 없음은 수집 실패(기간 교체 안 함), 정상 빈 목록과 구분
- F02 회의록 [적용]: 업무 INSERT 와 줄 연결을 한 연결·한 트랜잭션(_insert_task), 확인은 잠그기 전·알림/메일은 커밋 뒤, 줄 바뀜 409
- F03 업무 등록 표: persist 실패 전파, 미저장이면 [적용] 중단, 초안 유지·다시 저장·이탈 경고
- F04 인증정보 변경 시 내부 토큰 삭제 + 네이버·토스 토큰을 발급 인증정보 지문(SHA-256)에 묶음, GS샵 방식 캐시도 키 지문 기준
- F05 쪽 수 상한·커서 반복 = 실패(쿠팡은 구간을 하루까지 나눠 재시도), 네이버·카카오·토스·GS샵 동일 기준
- F06 [중지] 확인과 저장 시작을 같은 잠금(begin_saving), 저장 시작 뒤 중지 불가
- F07/F08 긴급 공지: 내용 version·고친 공지 다시 그리기·확인에 version(409), 확인은 행 잠금 트랜잭션에서 수신자·표시 시각·취소 검증
- F09 쇼핑몰 연결 테스트도 clear 처리·저장 안 한 시험은 상태 유지(광고 테스트와 같은 계약)
- F10 DB 테스트 skip·가짜 app.main/time.sleep 파일 범위 fixture, 오래된 기대값 갱신, pytest.ini·requirements-dev·tests/js/package.json·docs/TESTING.md
- 결과·후속 과제: docs/CODE_REVIEW_2026-10-15_RESULT.md (마이그레이션·환경변수 변경 없음)

Python 440 passed/63 skipped(DB 없음), 503 passed(로컬 PostgreSQL), jsdom 7종·Edge 6종 통과

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 18:41:42 +09:00

180 lines
9.1 KiB
Python

"""긴급 공지 — 검증(본문 정리·이미지 형식·시각·받는 사람)과 API 권한(수퍼관리자만 만들기, 받는 사람만 확인·이미지). DB 없이."""
import importlib
import sys
import types
import unittest
from datetime import datetime, timedelta
from unittest.mock import patch
from fastapi import FastAPI
from fastapi.testclient import TestClient
from app.modules.notice import store
from app.store import SUPER_ADMIN_EMAIL
from app.timezone import KST
api = importlib.import_module("app.modules.notice.router")
SUPER = {"email": SUPER_ADMIN_EMAIL, "name": "King", "is_super_admin": True}
ADMIN = {"email": "admin@test.local", "role": "admin"}
BOB = {"email": "bob@test.local"}
PNG = b"\x89PNG\r\n\x1a\n" + b"0" * 20
class ValidationTests(unittest.TestCase):
def test_body_keeps_only_notice_images(self):
html = ('<p>점검 <b>안내</b></p><img src="/notice/images/7" alt="a"><img src="https://evil.example/x.png">'
'<img src="data:image/png;base64,AAAA"><script>alert(1)</script><a href="javascript:alert(1)">x</a>')
out = store.sanitize_body(html)
self.assertIn('/notice/images/7', out)
self.assertNotIn("evil.example", out)
self.assertNotIn("data:image", out)
self.assertNotIn("<script", out)
self.assertNotIn("javascript:", out)
self.assertIn("<b>안내</b>", out)
self.assertEqual(store.image_ids_in(out), [7])
def test_title_targets_time(self):
with self.assertRaises(ValueError):
store.validate_title(" ")
with self.assertRaises(ValueError):
store.validate_title("x" * 201)
self.assertEqual(store.validate_targets(True, ["a@b"]), (True, []))
self.assertEqual(store.validate_targets(False, ["A@Test.local", "a@test.local", "nope"]), (False, ["a@test.local"]))
with self.assertRaises(ValueError):
store.validate_targets(False, [])
d = store.parse_show_at("2026-10-12T18:30")
self.assertEqual((d.hour, d.minute, d.utcoffset()), (18, 30, timedelta(hours=9))) # 화면 입력 = 한국시간
self.assertEqual(store.parse_show_at("2026-10-12T09:30:00Z").astimezone(KST).hour, 18)
self.assertLess(abs((store.parse_show_at("") - datetime.now(KST)).total_seconds()), 5)
with self.assertRaises(ValueError):
store.parse_show_at("내일")
def test_image_sniffing(self):
self.assertEqual(store.sniff_image(PNG), "image/png")
self.assertEqual(store.sniff_image(b"\xff\xd8\xff\xe0abc"), "image/jpeg")
self.assertEqual(store.sniff_image(b"RIFF\x00\x00\x00\x00WEBPVP8 "), "image/webp")
for bad in (b"", b"<svg onload=alert(1)>", b"<html>", b"\x89PNG" + b"0" * (store.IMAGE_MAX_BYTES)):
with self.assertRaises(ValueError):
store.sniff_image(bad)
class FakeStore:
def __init__(self):
now = datetime.now(KST)
self.notices = {
1: {"id": 1, "title": "전체 공지", "body_html": "<p>x</p>", "show_at": now.isoformat(), "to_all": True,
"created_by": SUPER_ADMIN_EMAIL, "cancelled_at": "", "targets": []},
2: {"id": 2, "title": "일부", "body_html": "", "show_at": now.isoformat(), "to_all": False,
"created_by": SUPER_ADMIN_EMAIL, "cancelled_at": "", "targets": ["carol@test.local"]},
3: {"id": 3, "title": "예약", "body_html": "", "show_at": (now + timedelta(hours=1)).isoformat(), "to_all": True,
"created_by": SUPER_ADMIN_EMAIL, "cancelled_at": "", "targets": []},
}
self.images = {5: {"id": 5, "notice_id": 2, "content_type": "image/png", "data": PNG, "uploaded_by": SUPER_ADMIN_EMAIL},
6: {"id": 6, "notice_id": 3, "content_type": "image/png", "data": PNG, "uploaded_by": SUPER_ADMIN_EMAIL}}
self.acked, self.created = [], []
def enabled(self):
return True
def pending_for(self, email):
return [n for n in self.notices.values() if self.is_recipient(notice=n, email=email)]
def get_notice(self, notice_id):
return self.notices.get(notice_id)
def is_recipient(self, notice, email):
return notice["to_all"] or email in notice["targets"]
def ack(self, notice_id, email, version=None):
"""저장소 계약(검토 F07·F08) — 받는 사람·표시 시각·취소·내용 버전은 저장소가 판단(실제 판단은 test_notice_db)."""
n = self.notices.get(notice_id)
if n is None or n["cancelled_at"] or not self.is_recipient(notice=n, email=email) \
or datetime.fromisoformat(n["show_at"]) > datetime.now(KST):
return "denied"
if version and version != n.get("version", ""):
return "stale"
self.acked.append((notice_id, email))
return "acked"
def list_notices(self):
return [{**n, "acks": {}} for n in self.notices.values()]
def create_notice(self, **kw):
self.created.append(kw)
store.validate_title(kw["title"])
return {"id": 9, **kw}
def get_image(self, image_id):
return self.images.get(image_id)
def add_image(self, data, filename, by):
return {"id": 10, "url": "/notice/images/10", "content_type": store.sniff_image(data)}
class NoticeApiTests(unittest.TestCase):
def setUp(self):
app = FastAPI()
app.include_router(api.router)
self.st = FakeStore()
app.state.notice_store = self.st
self.client = TestClient(app)
def as_(self, who):
fake = types.ModuleType("app.main")
fake.get_current_user_record = lambda request: who
return patch.dict(sys.modules, {"app.main": fake})
def test_only_super_admin_manages(self):
body = {"title": "t", "body_html": "", "to_all": True}
for who in (ADMIN, BOB):
with self.as_(who):
self.assertEqual(self.client.post("/notice/api/notices", json=body).status_code, 403)
self.assertEqual(self.client.get("/notice/api/notices").status_code, 403)
self.assertEqual(self.client.post("/notice/api/images", files={"file": ("a.png", PNG, "image/png")}).status_code, 403)
with self.as_(SUPER):
self.assertEqual(self.client.post("/notice/api/notices", json=body).status_code, 201)
self.assertEqual(self.client.post("/notice/api/notices", json={"title": ""}).status_code, 400)
r = self.client.post("/notice/api/images", files={"file": ("a.png", PNG, "image/png")})
self.assertEqual((r.status_code, r.json()["image"]["url"]), (201, "/notice/images/10"))
self.assertEqual(self.client.post("/notice/api/images", files={"file": ("x.svg", b"<svg/>", "image/svg+xml")}).status_code, 400)
with self.as_(None):
self.assertEqual(self.client.get("/notice/api/pending").status_code, 401)
def test_pending_hides_admin_fields_and_ack_only_for_recipients(self):
with self.as_(BOB):
out = self.client.get("/notice/api/pending").json()["notices"]
self.assertEqual(sorted(n["id"] for n in out), [1, 3]) # 시각 판단은 저장소(실제 DB 테스트)
# 받는 사람 목록·확인 현황 없음, 내용 버전(version)은 보낸다(고친 공지를 다시 그리게, 검토 F07)
self.assertEqual(set(out[0]), {"id", "title", "body_html", "show_at", "created_by", "version"})
self.assertEqual(self.client.post("/notice/api/1/ack").status_code, 200)
self.assertEqual(self.client.post("/notice/api/2/ack").status_code, 404) # 받는 사람 아님
self.assertEqual(self.client.post("/notice/api/3/ack").status_code, 404) # 띄울 시각 전(예약) — 검토 F08
self.assertEqual(self.client.post("/notice/api/99/ack").status_code, 404)
self.st.notices[1]["version"] = "v2"
r = self.client.post("/notice/api/1/ack", json={"version": "v1"}) # 고치기 전 내용을 읽고 누름
self.assertEqual(r.status_code, 409)
self.assertIn("수정", r.json()["detail"])
self.st.notices[1]["cancelled_at"] = "2026-10-15T10:00+09:00"
self.assertEqual(self.client.post("/notice/api/1/ack").status_code, 404) # 취소된 공지
self.assertEqual(self.st.acked, [(1, "bob@test.local")])
def test_image_access(self):
with self.as_(BOB):
self.assertEqual(self.client.get("/notice/images/5").status_code, 404) # 받는 사람이 아닌 공지
self.assertEqual(self.client.get("/notice/images/6").status_code, 404) # 아직 띄울 시각 전
with self.as_({"email": "carol@test.local"}):
r = self.client.get("/notice/images/5")
self.assertEqual((r.status_code, r.headers["content-type"], r.headers["x-content-type-options"]), (200, "image/png", "nosniff"))
with self.as_(SUPER):
self.assertEqual(self.client.get("/notice/images/6").status_code, 200)
def test_not_configured_is_503(self):
self.client.app.state.notice_store = None
with self.as_(BOB):
self.assertEqual(self.client.get("/notice/api/pending").status_code, 503)
if __name__ == "__main__":
unittest.main()