52ca60df9a
- 설명란·세부 업무 목록·보드 카드에 파일을 놓으면 드라이브 프로젝트/섹션/업무/세부 업무 폴더에 올리고 설명에 "파일 이름.확장자" 링크(PROJECT_DRIVE_FOLDER_ID) - 설명에서 링크를 지우면 우리가 올린 파일만 드라이브 휴지통, 되살리면 복구 - 브라우저별 필터(localStorage)가 켜져 있으면 섹션 안 카드가 제자리로 돌아가던 버그 — 필터 중에도 순서 변경 허용, 숨은 업무는 제자리. 카드 속 이미지 끌기 오인 방지 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
166 lines
8.1 KiB
Python
166 lines
8.1 KiB
Python
"""업무 파일 → 구글 드라이브(2026-10-19) — 폴더 경로·업로드 API·설명 링크 append·링크 지우면 휴지통. DB·Google 없이 가짜로."""
|
|
import importlib
|
|
import tempfile
|
|
import unittest
|
|
from unittest.mock import MagicMock, patch
|
|
|
|
from fastapi import FastAPI
|
|
from fastapi.testclient import TestClient
|
|
|
|
from app.integrations import google_drive
|
|
|
|
api = importlib.import_module("app.modules.project.router")
|
|
ME = {"email": "me@test.local", "role": "user"}
|
|
|
|
|
|
class FakeDrive:
|
|
enabled = True
|
|
reason = ""
|
|
|
|
def __init__(self):
|
|
self.paths, self.uploads, self.trash = [], [], []
|
|
self.meta = {}
|
|
|
|
def ensure_folder_path(self, names, root=None):
|
|
self.paths.append(list(names))
|
|
return "FOLDER"
|
|
|
|
def upload(self, *, folder_id, name, stream, mimetype, task_id):
|
|
self.uploads.append({"folder": folder_id, "name": name, "data": stream.read(), "task_id": task_id})
|
|
fid = "F%dabcdefghij" % len(self.uploads)
|
|
return {"id": fid, "name": name, "url": google_drive.file_url(fid)}
|
|
|
|
def ours(self, file_id):
|
|
return self.meta.get(file_id)
|
|
|
|
def set_trashed(self, file_id, trashed):
|
|
self.trash.append((file_id, trashed))
|
|
|
|
|
|
class Store(MagicMock):
|
|
TASKS = {
|
|
1: {"id": 1, "project_id": 7, "project_name": "신제품", "stage_name": "기획", "title": "패키지 디자인",
|
|
"parent_task_id": None, "description": "<p>기존</p>"},
|
|
2: {"id": 2, "project_id": 7, "project_name": "신제품", "stage_name": None, "title": "시안 A",
|
|
"parent_task_id": 1, "description": ""},
|
|
}
|
|
|
|
def get_task(self, task_id):
|
|
t = self.TASKS.get(int(task_id))
|
|
return dict(t) if t else None
|
|
|
|
|
|
class Base(unittest.TestCase):
|
|
def setUp(self):
|
|
self.st = Store()
|
|
self.st.update_task.side_effect = lambda task_id, fields, actor, assignee_allowed=None: {
|
|
**self.st.get_task(task_id), **fields}
|
|
self.drive = FakeDrive()
|
|
app = FastAPI()
|
|
app.include_router(api.router)
|
|
app.state.project_store = self.st
|
|
app.state.data_dir = tempfile.mkdtemp(prefix="pj-drive-")
|
|
self.client = TestClient(app, raise_server_exceptions=False)
|
|
for p in (patch.object(api, "_require_user", return_value=ME), patch.object(api, "_db_or_503", return_value=self.st),
|
|
patch.object(api, "_require_task", return_value="full"),
|
|
patch.object(google_drive, "get_client", return_value=self.drive)):
|
|
p.start()
|
|
self.addCleanup(p.stop)
|
|
|
|
|
|
class HelperTests(unittest.TestCase):
|
|
def test_file_ids_in_description(self):
|
|
html = ('<p><a href="https://drive.google.com/file/d/AbC_12-xyz9/view" target="_blank">a.pdf</a> '
|
|
'<a href="https://example.com/file/d/zzzzzzzzzzzz/view">x</a></p>')
|
|
self.assertEqual(google_drive.file_ids_in(html), {"AbC_12-xyz9"})
|
|
self.assertEqual(google_drive.file_ids_in(""), set())
|
|
|
|
def test_folder_name_and_query_escape(self):
|
|
self.assertEqual(google_drive.folder_name(" 기획\n 2차 "), "기획 2차")
|
|
self.assertEqual(google_drive.folder_name(""), "(이름 없음)")
|
|
self.assertEqual(google_drive._q("A's \\ b"), "A\\'s \\\\ b")
|
|
|
|
def test_folder_path_project_section_task_subtask(self):
|
|
st = Store()
|
|
self.assertEqual(api._drive_folder_names(st, st.get_task(1)), ["신제품", "기획", "패키지 디자인"])
|
|
# 세부 업무 = 맨 위 업무의 섹션 + 업무 + 세부 업무
|
|
self.assertEqual(api._drive_folder_names(st, st.get_task(2)), ["신제품", "기획", "패키지 디자인", "시안 A"])
|
|
|
|
def test_link_html_escapes_name(self):
|
|
html = api.drive_link_html("https://drive.google.com/file/d/X1234567890/view", "<견적>.pdf")
|
|
self.assertIn("<견적>.pdf</a>", html)
|
|
self.assertIn('target="_blank"', html)
|
|
|
|
|
|
class UploadApiTests(Base):
|
|
def test_upload_returns_link_without_touching_description(self):
|
|
r = self.client.post("/project/api/tasks/1/drive-files", files={"file": ("도면 v2.dwg", b"abc", "application/acad")})
|
|
self.assertEqual(r.status_code, 201, r.text)
|
|
body = r.json()
|
|
self.assertEqual(body["file"]["name"], "도면 v2.dwg")
|
|
self.assertTrue(body["file"]["url"].startswith("https://drive.google.com/file/d/"))
|
|
self.assertEqual(self.drive.paths, [["신제품", "기획", "패키지 디자인"]])
|
|
self.assertEqual(self.drive.uploads[0]["data"], b"abc")
|
|
self.assertEqual(self.drive.uploads[0]["task_id"], 1)
|
|
self.st.update_task.assert_not_called()
|
|
|
|
def test_upload_append_adds_link_to_subtask_description(self):
|
|
r = self.client.post("/project/api/tasks/2/drive-files", files={"file": ("시안.png", b"png", "image/png")},
|
|
data={"append": "true"})
|
|
self.assertEqual(r.status_code, 201, r.text)
|
|
self.assertEqual(self.drive.paths, [["신제품", "기획", "패키지 디자인", "시안 A"]])
|
|
fields = self.st.update_task.call_args.kwargs["fields"]
|
|
self.assertIn('href="https://drive.google.com/file/d/F1abcdefghij/view"', fields["description"])
|
|
self.assertIn(">시안.png</a>", fields["description"])
|
|
self.assertEqual(r.json()["task"]["description"], fields["description"])
|
|
|
|
def test_empty_file_and_disabled_drive(self):
|
|
r = self.client.post("/project/api/tasks/1/drive-files", files={"file": ("a.txt", b"", "text/plain")})
|
|
self.assertEqual(r.status_code, 400)
|
|
self.drive.enabled = False
|
|
self.drive.reason = "Google 인증 미설정"
|
|
r = self.client.post("/project/api/tasks/1/drive-files", files={"file": ("a.txt", b"x", "text/plain")})
|
|
self.assertEqual(r.status_code, 503)
|
|
self.assertIn("Google 인증 미설정", r.json()["detail"])
|
|
|
|
def test_drive_error_is_502_with_message(self):
|
|
self.drive.ensure_folder_path = MagicMock(side_effect=google_drive.GoogleDriveError("업무 파일 폴더를 찾을 수 없습니다"))
|
|
r = self.client.post("/project/api/tasks/1/drive-files", files={"file": ("a.txt", b"x", "text/plain")})
|
|
self.assertEqual(r.status_code, 502)
|
|
self.assertIn("폴더", r.json()["detail"])
|
|
|
|
|
|
class LinkSyncTests(Base):
|
|
def test_removed_link_trashes_our_file_added_link_restores(self):
|
|
self.drive.meta = {"GONE1234567": {"trashed": False, "task_id": "1"},
|
|
"BACK1234567": {"trashed": True, "task_id": "1"},
|
|
"KEEP1234567": {"trashed": False, "task_id": "1"},
|
|
"OTHER123456": None}
|
|
self.st.description_mentions.side_effect = lambda text, exclude_task_id: text == "KEEP1234567"
|
|
api._sync_drive_links(self.st, 1, {"GONE1234567", "KEEP1234567", "OTHER123456"}, {"BACK1234567"})
|
|
self.assertIn(("GONE1234567", True), self.drive.trash)
|
|
self.assertIn(("BACK1234567", False), self.drive.trash)
|
|
# 다른 업무 설명에 남은 링크·우리가 올리지 않은 파일은 그대로
|
|
self.assertNotIn(("KEEP1234567", True), self.drive.trash)
|
|
self.assertNotIn(("OTHER123456", True), self.drive.trash)
|
|
|
|
def test_description_save_schedules_sync(self):
|
|
old = '<p><a href="https://drive.google.com/file/d/GONE1234567/view">a.pdf</a></p>'
|
|
self.st.TASKS = {1: {**Store.TASKS[1], "description": old}}
|
|
with patch.object(api, "_sync_drive_links") as sync, patch.object(api, "_record_mentions", return_value=[]):
|
|
r = self.client.put("/project/api/tasks/1", json={"description": "<p>링크 지움</p>"})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
sync.assert_called_once()
|
|
_, task_id, removed, added = sync.call_args.args
|
|
self.assertEqual((task_id, removed, added), (1, {"GONE1234567"}, set()))
|
|
|
|
def test_description_save_without_link_change_does_not_sync(self):
|
|
with patch.object(api, "_sync_drive_links") as sync, patch.object(api, "_record_mentions", return_value=[]):
|
|
r = self.client.put("/project/api/tasks/1", json={"description": "<p>글만 바뀜</p>"})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
sync.assert_not_called()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|