Files
dbx-main/tests/test_vacation_db.py
T
king a12a862c47 feat(vacation): 설정 화면·공휴일 설정 삭제 · 옵션 수정 = 관리자·승인자·통보자
- [설정] 버튼·설정 화면·공휴일 추가/삭제 삭제(예전 /vacation/settings 는 옵션으로), 쓰지 않는 CSS·db 공휴일 CRUD 정리
- 쉬는 날 = 국경일·대체공휴일 표(KR_HOLIDAYS)만 — vacation_holidays 는 남아 있지만 읽지 않음
- 옵션(승인자·통보자·잔여 연차) 수정 = ERP 관리자(수퍼 포함) + 지금 승인자 + 승인 통보자(_can_edit_options), 예전엔 관리자만
- 테스트: 실제 PG(국경일 표만), 실제 앱(통보자·승인자 수정 가능·그 밖 403, 설정 주소 없음·버튼 없음)

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

152 lines
9.4 KiB
Python

"""휴가 DB(vacation_db) — 옵션·메일 기록(마이그레이션 001, 2026-10-27) 실제 PostgreSQL 확인.
VACATION_TEST_DB_URL 이 localhost/127.0.0.1 일 때만 돈다(아니면 skip). 앱 계정(vacation_app)으로 접속해 권한(GRANT)까지 본다.
psql … -v app_password=… -f scripts/sql/vacation_db_init.sql
psql … -d vacation_db -f scripts/sql/vacation_db_001_options_mail.sql
VACATION_TEST_DB_URL=postgresql://vacation_app:<pw>@localhost:55432/vacation_db python -m pytest tests/test_vacation_db.py
"""
import os
import sys
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))
DSN = os.getenv("VACATION_TEST_DB_URL", "")
ENABLED = bool(DSN) and urlparse(DSN).hostname in ("localhost", "127.0.0.1")
@unittest.skipUnless(ENABLED, "VACATION_TEST_DB_URL(localhost) 미설정")
class VacationOptionsDBTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
from app.modules.vacation.db import VacationDBStore
cls.st = VacationDBStore(DSN)
@classmethod
def tearDownClass(cls):
cls.st.close()
def test_options_roundtrip(self):
self.assertTrue(self.st.options_ready())
saved = self.st.save_options(approvers=[" Lee@Test.local", "lee@test.local", "boss@test.local", "x"],
notifiers=["HR@test.local"], by="Admin@Test.local")
self.assertEqual(saved["approvers"], ["lee@test.local", "boss@test.local"]) # 소문자·중복·@ 없는 값 정리
self.assertEqual(saved["notifiers"], ["hr@test.local"])
self.assertEqual(saved["updated_by"], "admin@test.local")
self.assertTrue(saved["ready"] and saved["updated_at"])
again = self.st.save_options(approvers=[], notifiers=[], by="admin@test.local") # 덮어쓰기(키 하나)
self.assertEqual((again["approvers"], again["notifiers"]), ([], []))
def test_submit_approve_mail_log_end_to_end(self):
"""신청 → 제출 → 승인을 실제 DB 로, 메일은 가짜 SMTP — 기록이 상세 화면용 목록으로 나온다."""
from app.modules.vacation import notify
self.st.save_options(approvers=["lee@test.local"], notifiers=["hr@test.local"], by="admin@test.local")
owner = f"kim-{uuid.uuid4().hex[:6]}@test.local"
req = self.st.create_request(owner=owner, owner_name="김철수", status="작성중",
payload={"vacation_type": "연차", "start_date": "2026-11-02", "end_date": "2026-11-03",
"start_half": "full", "end_half": "full", "reason": "가족 행사"})
sub = self.st.submit(request_id=req["id"], owner=owner)
done = self.st.approve(request_id=req["id"], approver_email="lee@test.local")
users = [{"email": "lee@test.local", "name": "이팀장", "modules": {"vacation": True}}]
with patch("app.mail.send_email", return_value=True) as smtp, patch("app.mail.mail_enabled", return_value=True):
r1 = notify.deliver(self.st, None, event="submitted", req=sub, actor={"email": owner, "name": "김철수"},
users=users, link="https://erp.test/vacation/" + req["id"])
r2 = notify.deliver(self.st, None, event="approved", req=done, actor={"email": "lee@test.local", "name": "이팀장"},
users=users, link="https://erp.test/vacation/" + req["id"])
self.assertTrue(r1["ok"] and r2["ok"])
self.assertEqual(smtp.call_args_list[1].kwargs["to"], ["lee@test.local", "hr@test.local", owner])
log = self.st.list_mail_log(request_id=req["id"])
self.assertEqual([(m["event"], m["via"], m["ok"]) for m in log], [("submitted", "smtp", True), ("approved", "smtp", True)])
self.assertEqual(log[0]["sender"], owner)
self.assertEqual(log[1]["recipients"], f"lee@test.local, hr@test.local, {owner}")
self.assertIn("[휴가 승인] 김철수 · 연차", log[1]["subject"])
self.st.hard_delete(request_id=req["id"], user_email=owner, is_admin=True)
self.st.save_options(approvers=[], notifiers=[], by="admin@test.local")
@unittest.skipUnless(ENABLED, "VACATION_TEST_DB_URL(localhost) 미설정")
class VacationHolidayBalanceDBTests(unittest.TestCase):
"""2026-10-27 — 쉬는 날 = 국경일·대체공휴일 표, 연차 = 승인된 연차·반차만·해마다 나눠 셈, 잔여 연차 한꺼번에 저장."""
@classmethod
def setUpClass(cls):
from app.modules.vacation.db import VacationDBStore
cls.st = VacationDBStore(DSN)
@classmethod
def tearDownClass(cls):
cls.st.close()
def test_holiday_map_is_national_table_only(self):
"""쉬는 날 = 국경일·대체공휴일 표만(공휴일 설정 화면 삭제 — vacation_holidays 에 남은 줄은 읽지 않음)."""
st = self.st
m = st.holiday_map(date_from="2027-10-01", date_to="2027-10-31")
self.assertEqual(m, {"2027-10-03": "개천절", "2027-10-04": "개천절 대체", "2027-10-09": "한글날", "2027-10-11": "한글날 대체"})
self.assertEqual(st.holiday_map(date_from="2026-07-17", date_to="2026-07-17"), {"2026-07-17": "제헌절"}) # 예전 seed 에 없던 날
with st._pool.connection() as conn: # noqa: SLF001 — 예전 설정 화면이 남긴 줄을 흉내
conn.execute("INSERT INTO vacation_holidays (holiday_date, name, kind, is_red) VALUES ('2027-10-08', '창립기념일', 'company', TRUE), "
"('2027-10-11', '한글날 대체', 'substitute', FALSE) ON CONFLICT (holiday_date) DO NOTHING")
try:
self.assertEqual(st.holiday_map(date_from="2027-10-01", date_to="2027-10-31"), m) # 그대로
self.assertEqual(st.red_holiday_set(date_from="2027-10-01", date_to="2027-10-31"), set(m))
finally:
with st._pool.connection() as conn: # noqa: SLF001
conn.execute("DELETE FROM vacation_holidays WHERE holiday_date IN ('2027-10-08', '2027-10-11')")
def _approved(self, owner, vtype, start, end, sh="full", eh="full"):
req = self.st.create_request(owner=owner, owner_name="테스트", status="제출",
payload={"vacation_type": vtype, "start_date": start, "end_date": end,
"start_half": sh, "end_half": eh, "reason": ""})
self.st.approve(request_id=req["id"], approver_email="lee@test.local")
return req
def test_used_days_only_annual_types_and_split_by_year(self):
st = self.st
owner = f"bal-{uuid.uuid4().hex[:6]}@test.local"
made = [
self._approved(owner, "연차", "2026-11-02", "2026-11-03"), # 2
self._approved(owner, "오전반차", "2026-11-04", "2026-11-04"), # 0.5
self._approved(owner, "병가", "2026-11-05", "2026-11-06"), # 차감 안 함
self._approved(owner, "경조", "2026-11-09", "2026-11-09"), # 차감 안 함
self._approved(owner, "연차", "2026-12-30", "2027-01-04"), # 12/30·31 = 2, 1/4 = 1 (1/1 신정·주말 뺌)
]
st.create_request(owner=owner, owner_name="테스트", status="제출", # 제출(승인 전)은 차감 안 함
payload={"vacation_type": "연차", "start_date": "2026-11-10", "end_date": "2026-11-10",
"start_half": "full", "end_half": "full", "reason": ""})
try:
self.assertEqual(st.used_days(user_email=owner, year=2026), 4.5)
self.assertEqual(st.used_days(user_email=owner, year=2027), 1.0)
st.save_balances(year=2026, rows=[{"user_email": owner, "total_days": 15, "memo": "입사 2020"}])
s26 = st.balance_summary(user_email=owner, year=2026)
self.assertEqual((s26["total_days"], s26["used_days"], s26["remaining_days"]), (15.0, 4.5, 10.5))
s27 = st.balance_summary(user_email=owner, year=2027) # 다음 해로 넘어가지 않음(등록 전 = 0)
self.assertEqual((s27["total_days"], s27["remaining_days"]), (0.0, -1.0))
finally:
for r in st.list_for(owner):
st.hard_delete(request_id=r["id"], user_email=owner, is_admin=True)
def test_save_balances_validates_all_or_nothing(self):
st = self.st
a, b = f"a-{uuid.uuid4().hex[:6]}@test.local", f"b-{uuid.uuid4().hex[:6]}@test.local"
with self.assertRaises(ValueError):
st.save_balances(year=2031, rows=[{"user_email": a, "total_days": 15}, {"user_email": b, "total_days": 15.3}])
self.assertIsNone(st.get_balance(user_email=a, year=2031)) # 한 줄이라도 틀리면 전부 저장 안 함
self.assertEqual(st.save_balances(year=2031, rows=[{"user_email": a.upper(), "total_days": 15.5, "memo": " x "},
{"user_email": b, "total_days": 0}]), 2)
self.assertEqual((st.get_balance(user_email=a, year=2031)["total_days"], st.get_balance(user_email=a, year=2031)["memo"]),
(15.5, "x"))
st.save_balances(year=2031, rows=[{"user_email": a, "total_days": 20, "memo": ""}]) # 덮어쓰기
self.assertEqual(st.get_balance(user_email=a, year=2031)["total_days"], 20.0)
if __name__ == "__main__":
unittest.main()