180 lines
8.2 KiB
Python
180 lines
8.2 KiB
Python
"""셀 이동의 실제 저장소/라우터 로직을 트랜잭션 대역으로 검증(실제 PostgreSQL 테스트는 test_project_module.py)."""
|
|
import copy
|
|
import importlib
|
|
import json
|
|
import unittest
|
|
from contextlib import contextmanager
|
|
from types import SimpleNamespace
|
|
from unittest.mock import patch
|
|
|
|
from fastapi import FastAPI
|
|
from fastapi.testclient import TestClient
|
|
|
|
from app.modules.project import store
|
|
from app.modules.project.db import ProjectStore
|
|
|
|
api_module = importlib.import_module("app.modules.project.router")
|
|
|
|
|
|
class Rows:
|
|
def __init__(self, rows=()):
|
|
self.rows = list(rows)
|
|
|
|
def fetchall(self):
|
|
return self.rows
|
|
|
|
def fetchone(self):
|
|
return self.rows[0] if self.rows else None
|
|
|
|
|
|
class Connection:
|
|
def __init__(self):
|
|
self.rows = {10: {"id": 10, "area_id": 2, "year": 2026}, 20: {"id": 20, "area_id": 1, "year": 2026}}
|
|
self.cells = {(10, 1): "original", (20, 2): "existing"}
|
|
self.calls, self.commits, self.rollbacks = [], 0, 0
|
|
self.fail_delete = False
|
|
self.transaction_depth = 0
|
|
|
|
@contextmanager
|
|
def transaction(self):
|
|
before = copy.deepcopy(self.cells)
|
|
self.transaction_depth += 1
|
|
try:
|
|
yield self
|
|
except Exception:
|
|
self.cells = before
|
|
self.rollbacks += 1
|
|
raise
|
|
else:
|
|
self.commits += 1
|
|
finally:
|
|
self.transaction_depth -= 1
|
|
|
|
def execute(self, sql, params):
|
|
self.calls.append((sql, params))
|
|
if sql.startswith("SELECT r.id, r.area_id, a.year"):
|
|
return Rows(self.rows[r] for r in set(params[0]) if r in self.rows)
|
|
if sql.startswith("SELECT id FROM goal_areas"):
|
|
return Rows({"id": a} for a in params[0])
|
|
if sql.startswith("SELECT id, area_id FROM goal_rows"):
|
|
return Rows(self.rows[r] for r in sorted(set(params[0])) if r in self.rows)
|
|
if sql.startswith("SELECT row_id, month, body"):
|
|
keys = [(params[0], params[1]), (params[2], params[3])]
|
|
return Rows({"row_id": r, "month": m, "body": self.cells[r, m]} for r, m in keys if (r, m) in self.cells)
|
|
if sql.startswith("INSERT INTO goal_cells"):
|
|
assert self.transaction_depth > 0, "Cell writes must hold the area lock until commit"
|
|
self.cells[params[0], params[1]] = params[2]
|
|
return Rows()
|
|
if sql.startswith("DELETE FROM goal_cells"):
|
|
assert self.transaction_depth > 0, "Cell writes must hold the area lock until commit"
|
|
if self.fail_delete:
|
|
raise RuntimeError("simulated delete failure")
|
|
self.cells.pop((params[0], params[1]), None)
|
|
return Rows()
|
|
if sql.startswith("SELECT a.id AS area_id"):
|
|
assert self.transaction_depth > 0, "Autocommit releases the area lock before the write"
|
|
row = self.rows.get(params[0])
|
|
return Rows([{"area_id": row["area_id"]}] if row else [])
|
|
raise AssertionError("Unexpected SQL: " + sql)
|
|
|
|
|
|
class GoalMoveTests(unittest.TestCase):
|
|
def setUp(self):
|
|
self.conn = Connection()
|
|
@contextmanager
|
|
def connection():
|
|
yield self.conn
|
|
self.st = ProjectStore.__new__(ProjectStore)
|
|
self.st._pool = SimpleNamespace(connection=connection)
|
|
self.st._table_exists = lambda conn, name: True
|
|
self.st._goal_quarters = lambda conn: True
|
|
self.merges = {}
|
|
self.st._area_geometry = lambda conn, area: (
|
|
[r for r in self.conn.rows if self.conn.rows[r]["area_id"] == area], self.merges.get(area, []), True)
|
|
self.payload = dict(source_row=10, source_month=1, target_row=20, target_month=2,
|
|
source_body="original", target_body="existing", body="original", updated_by="ADMIN@TEST.LOCAL")
|
|
|
|
def move(self, **changes):
|
|
return self.st.move_goal_cell(**(self.payload | changes))
|
|
|
|
def test_move_preserves_all_explicit_formats_and_locks_in_order(self):
|
|
rich = store.validate_goal_text(store.GOAL_RICH_PREFIX + json.dumps([
|
|
{"text": "formatted", "bold": True, "italic": True, "underline": True, "size": 24, "color": "#ff0000"}]))
|
|
self.conn.cells[10, 1] = rich
|
|
self.assertEqual(self.move(source_body=rich, body=rich), rich)
|
|
self.assertNotIn((10, 1), self.conn.cells)
|
|
self.assertEqual(self.conn.cells[20, 2], rich)
|
|
self.assertEqual(self.conn.commits, 1)
|
|
self.assertTrue(any("goal_areas" in sql and "FOR UPDATE" in sql and p == ([1, 2],) for sql, p in self.conn.calls))
|
|
|
|
def test_failure_after_target_write_rolls_back_both_cells(self):
|
|
before = dict(self.conn.cells)
|
|
self.conn.fail_delete = True
|
|
with self.assertRaises(RuntimeError):
|
|
self.move()
|
|
self.assertEqual(self.conn.cells, before)
|
|
self.assertEqual(self.conn.rollbacks, 1)
|
|
|
|
def test_concurrent_change_in_either_cell_aborts_without_writes(self):
|
|
for key in ((10, 1), (20, 2)):
|
|
with self.subTest(key=key):
|
|
self.setUp()
|
|
self.conn.cells[key] = "another user's edit"
|
|
before = dict(self.conn.cells)
|
|
with self.assertRaises(store.GoalCellConflict):
|
|
self.move()
|
|
self.assertEqual(self.conn.cells, before)
|
|
|
|
def test_lost_response_retry_succeeds_without_writing_again(self):
|
|
self.move()
|
|
count = len([sql for sql, _ in self.conn.calls if sql.startswith(("INSERT", "DELETE"))])
|
|
self.assertEqual(self.move(), "original")
|
|
self.assertEqual(len([sql for sql, _ in self.conn.calls if sql.startswith(("INSERT", "DELETE"))]), count)
|
|
|
|
def test_empty_target_and_defaults_become_explicit_styles(self):
|
|
self.conn.cells.pop((20, 2))
|
|
rich = store.GOAL_RICH_PREFIX + json.dumps([{"text": "original", "bold": False, "size": 14, "color": "#050505"}])
|
|
result = self.move(target_body="", body=rich)
|
|
self.assertEqual(store.goal_text_plain(result), "original")
|
|
self.assertIn('"bold":false', result)
|
|
|
|
def test_bad_content_missing_rows_wrong_year_and_hidden_merge_cell(self):
|
|
for changes, error in [({"body": "different"}, ValueError), ({"target_row": 999}, KeyError),
|
|
({"target_month": 17}, ValueError), ({"target_row": 10, "target_month": 1}, ValueError)]:
|
|
with self.subTest(changes=changes), self.assertRaises(error):
|
|
self.move(**changes)
|
|
self.conn.rows[20]["year"] = 2027
|
|
with self.assertRaises(ValueError):
|
|
self.move()
|
|
self.conn.rows[20]["year"] = 2026
|
|
self.merges[1] = [{"r0": 0, "r1": 0, "c0": 1, "c1": 2}]
|
|
with self.assertRaises(store.GoalCellConflict):
|
|
self.move()
|
|
|
|
def test_normal_save_uses_the_same_area_lock(self):
|
|
self.st.set_goal_cell(row_id=10, month=1, body="new")
|
|
self.assertIn("FOR UPDATE OF a", self.conn.calls[0][0])
|
|
self.assertEqual(self.conn.cells[10, 1], "new")
|
|
self.assertEqual(self.conn.commits, 1)
|
|
|
|
def test_http_admin_permissions_validation_and_conflict_status(self):
|
|
app = FastAPI()
|
|
app.include_router(api_module.router)
|
|
app.state.project_store = self.st
|
|
client = TestClient(app)
|
|
payload = {k: v for k, v in self.payload.items() if k != "updated_by"}
|
|
with patch.object(api_module, "_require_user", return_value={"email": "a@test.local", "role": "user"}):
|
|
self.assertEqual(client.post("/project/api/goals/cells/move", json=payload).status_code, 403)
|
|
with patch.object(api_module, "_require_user", return_value={"email": "a@test.local", "role": "admin"}):
|
|
self.assertEqual(client.post("/project/api/goals/cells/move", json=payload | {"source_body": None}).status_code, 400)
|
|
self.conn.cells[20, 2] = "changed"
|
|
self.assertEqual(client.post("/project/api/goals/cells/move", json=payload).status_code, 409)
|
|
self.conn.cells[20, 2] = "existing"
|
|
result = client.post("/project/api/goals/cells/move", json=payload)
|
|
self.assertEqual(result.status_code, 200)
|
|
self.assertEqual(result.json(), {"ok": True, "body": "original"})
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|