# -*- coding: utf-8 -*- """342-2 [확정] · [저장] 서버 재계산 — 입력 지문 · 바뀐 행만 · 행 읽기 한 번(부록 4 R23). ① 지문 = Node 에 넘기는 입력 **전부** + 번들 판 — 같은 입력이면 Node 를 다시 안 돌림 · 입력 어느 칸(깊은 칸 · 문맥 · 번들)이 바뀌어도 다시 돌림. ② Node 에 가는 입력과 지문이 같은 한 벌 — 지문 밖으로 새는 입력 길이 없음. ③ 행 쓰기 = 읽기 한 번 · 바뀐 행만 한 문장 · 앞 벌이 만든 새 행을 뒤 벌이 찾음. ④ 같은 입력으로 두 번 = 두 번째는 Node 0 번 · 행 쓰기 0 · 유토곡선 쓰기 0. """ from __future__ import annotations import asyncio import copy import json import os import sys from pathlib import Path from types import SimpleNamespace from uuid import uuid4 import pytest ROOT = Path(__file__).resolve().parents[2] if str(ROOT) not in sys.path: sys.path.insert(0, str(ROOT)) import B06_Section.B06_Section_Router as b06_router # noqa: E402 import B06_Section.B06_Section_Router_Design as b06_design # noqa: E402 import B06_Section.B06_Section_Server_Calc_Prebuild as prebuild # noqa: E402 from B06_Section.B06_Section_Repository_Bulk import ( # noqa: E402 merge_cross_section_design_batches, ) DETAIL = { "longitudinal": {"length_m": 40.0, "stations": [{"chainage_m": 0.0}]}, "cross_sections": [ {"chainage_m": 0.0, "design": {"ground_type": "soil", "slope": {"cut": 1.0}}}, {"chainage_m": 20.0, "design": {"ground_type": "rock"}}, ], } CONTEXT = {"earthwork_conversion": {"soil": {"L": 1.25, "C": 0.9}}, "haul_equipment_limits": []} @pytest.fixture def node(monkeypatch, tmp_path): bundle = tmp_path / "bundle.js" bundle.write_text("//", encoding="utf-8") calls: list = [] def fake_run(path, script, payload): calls.append(payload) return {"areas": [], "mass_haul": {"total": len(calls)}} monkeypatch.setattr(prebuild, "BUNDLE", bundle) monkeypatch.setattr(prebuild, "run_bundle_json", fake_run) monkeypatch.setattr(prebuild, "bundle_stale", lambda path: False) monkeypatch.setattr(prebuild, "_NODE_CACHE", {}) return SimpleNamespace(calls=calls, bundle=bundle) def _input(): return {"detail": copy.deepcopy(DETAIL), "context": copy.deepcopy(CONTEXT)} def test_같은_입력이면_Node_한_번(node): first = prebuild._node_output(_input()) second = prebuild._node_output(_input()) assert len(node.calls) == 1 assert first == second @pytest.mark.parametrize( "change", [ lambda data: data["detail"]["cross_sections"][0]["design"]["slope"].update(cut=1.5), lambda data: data["detail"]["cross_sections"].append({"chainage_m": 40.0}), lambda data: data["detail"]["longitudinal"].update(length_m=40.5), lambda data: data["context"]["earthwork_conversion"]["soil"].update(C=0.85), lambda data: data.update(context={**data["context"], "structure_spoil_m3": 3.0}), ], ids=["깊은 설계 칸", "측점 더함", "종단", "환산계수", "문맥 새 칸"], ) def test_입력_어느_칸이_바뀌어도_다시(node, change): prebuild._node_output(_input()) changed = _input() change(changed) prebuild._node_output(changed) assert len(node.calls) == 2 def test_번들이_바뀌면_다시(node): prebuild._node_output(_input()) stat = node.bundle.stat() os.utime(node.bundle, ns=(stat.st_atime_ns, stat.st_mtime_ns + 10_000_000)) prebuild._node_output(_input()) assert len(node.calls) == 2 def test_TS_가_번들보다_새로우면_다시(node, monkeypatch): prebuild._node_output(_input()) monkeypatch.setattr(prebuild, "bundle_stale", lambda path: True) prebuild._node_output(_input()) assert len(node.calls) == 2 def test_실패는_기억_안_함(node, monkeypatch): monkeypatch.setattr(prebuild, "run_bundle_json", lambda *a: node.calls.append(a) or None) assert prebuild._node_output(_input()) is None assert prebuild._node_output(_input()) is None assert len(node.calls) == 2 # ── ③ 행 쓰기 ────────────────────────────────────────────────────────────── class _Cursor: def __init__(self, log, rows): self.log, self.rows = log, rows async def __aenter__(self): return self async def __aexit__(self, *exc): return False async def execute(self, sql, params=None): self.log.append((" ".join(sql.split()), list(params or []))) async def fetchall(self): return self.rows class _Connection: def __init__(self, rows): self.log: list = [] self.rows = rows def cursor(self, *args): return _Cursor(self.log, self.rows) async def begin(self): return None async def commit(self): return None async def rollback(self): return None def _rows(): return [ (1, 0.0, {"design": {"ground_type": "soil", "cut_area_m2": 2.0}}), (2, 20.0, json.dumps({"design": {"ground_type": "rock"}})), ] def _kinds(log): return [sql.split()[0] for sql, _ in log] def test_읽기_한_번_바뀐_행만(tmp_path): connection = _Connection(_rows()) written = asyncio.run( merge_cross_section_design_batches( connection, route_id=7, batches=[ ([(0.0, {"ground_type": "soil", "cut_area_m2": 2.0})], True, None), # 그대로 ([(20.0, {"cut_area_m2": 3.0})], False, None), # 바뀜 ([(40.0, {"ground_type": "soil"})], True, uuid4()), # 새 행 ([(40.0, {"cut_area_m2": 1.0})], False, None), # 앞 벌의 새 행에 얹음 ], ) ) assert _kinds(connection.log) == ["SELECT", "UPDATE", "INSERT"] update = connection.log[1][1] assert update[0] == 2 and json.loads(update[1])["design"] == { "ground_type": "rock", "cut_area_m2": 3.0, } insert = connection.log[2][1] assert json.loads(insert[3]) == {"design": {"ground_type": "soil", "cut_area_m2": 1.0}} assert written == 2 def test_모두_그대로면_쓰기_없음(): connection = _Connection(_rows()) written = asyncio.run( merge_cross_section_design_batches( connection, route_id=7, batches=[ ([(0.0, {"cut_area_m2": 2.0})], False, None), ([(20.0, {"ground_type": "rock"})], True, None), ], ) ) assert _kinds(connection.log) == ["SELECT"] assert written == 0 # ── ②④ 재계산 두 번 ────────────────────────────────────────────────────────── class _Pool: def __init__(self, connection): self.connection = connection def acquire(self): connection = self.connection class _Acquire: async def __aenter__(self): return connection async def __aexit__(self, *exc): return False return _Acquire() def test_같은_입력_두_번이면_Node_0_쓰기_0(node, monkeypatch, tmp_path): rows = [(1, 0.0, {"design": DETAIL["cross_sections"][0]["design"]})] connection = _Connection(rows) stored = {"data": {"mass_haul": None}} written_haul: list = [] async def detail(project_id, route_id): return SimpleNamespace(model_dump=lambda mode: copy.deepcopy(DETAIL)) async def run_with(fn, *args): if fn is prebuild.get_longitudinal_section: return copy.deepcopy(stored) if fn is prebuild.get_project_storage_relative_path: return "p" return {"source_filter": "csf", "method": "dtm", "smooth": False} async def write_haul(connection, *, route_id, data_patch): written_haul.append(data_patch) stored["data"]["mass_haul"] = data_patch["mass_haul"] def fake_run(path, script, payload): node.calls.append(payload) # Node 에 간 입력이 곧 지문 입력 — 다른 입력 길 없음 assert set(payload) == {"detail", "context"} return {"areas": [{"chainage_m": 0.0, "cut_area_m2": 5.0}], "mass_haul": {"total": 9.0}} monkeypatch.setattr(prebuild, "run_bundle_json", fake_run) monkeypatch.setattr(b06_router, "get_section_detail", detail) monkeypatch.setattr(prebuild, "run_with_connection", run_with) monkeypatch.setattr(prebuild, "resolve_stored_project_path", lambda path: str(tmp_path)) monkeypatch.setattr(prebuild, "get_db_pool", lambda: _Pool(connection)) monkeypatch.setattr(prebuild, "merge_longitudinal_section_data", write_haul) monkeypatch.setattr(prebuild, "quantity_settings", lambda root: {}) monkeypatch.setattr(prebuild, "mixed_conversion_factors", lambda settings: CONTEXT) monkeypatch.setattr(prebuild, "haul_equipment_limits", lambda settings: []) monkeypatch.setattr(b06_design, "enforce_design_lines", lambda *a: None) monkeypatch.setattr(prebuild, "_enforce_stored_designs", lambda *a: None) asyncio.run(prebuild.recompute_server_side(uuid4(), 3)) assert len(node.calls) == 1 assert _kinds(connection.log) == ["SELECT", "UPDATE"] assert len(written_haul) == 1 # 첫 번째가 쓴 값을 행에 반영(가짜 DB) — 두 번째는 같은 입력 rows[0] = (1, 0.0, json.loads(connection.log[1][1][1])) connection.log.clear() asyncio.run(prebuild.recompute_server_side(uuid4(), 3)) assert len(node.calls) == 1 # Node 다시 안 돎 assert _kinds(connection.log) == ["SELECT"] # 바뀐 행 없음 — 쓰기 0 assert len(written_haul) == 1 # 유토곡선 같은 값 — 안 씀