Files
Aislo/resources/tester/test_342_2_confirm_fingerprint.py
eomsangdonandClaude Opus 5.5 11c75f022a refactor(767-1): 안 쓰는 지면 필터 · 서피스 지움 — 필터 넷(CSF · 격자 최저 · PMF · RANSAC) · 표현 셋(TIN + Taubin 평활 · NURBS · meshfree) · 수치지형도 비교 방식 다섯 · 안 부르는 길 정리
- 필터 = 업체 분류 · 점진 TIN · 둘의 다듬기 판만 · 분석 허용 목록 = Ground 등록부(available_filters) 한 벌
- 표현 = DTM · implicit 만 · 평활 = DTM 만 · config 기본 목록 · PRECOMPUTE · 설정 사전 맞춤(설정 지문 바뀜 — 768 에서 다시 지음)
- 등고선 = 격자 · 굳힌 격자만(삼각망 굽기 · 외곽 맞춤 · implicit RBF 폴백 걷음) · 표본기 · 경로 찾기 tin · nurbs · meshfree 갈래 걷음
- 수치지형도 = 라플라스만(TIN 둘 · TPS · ANUDEM형 · 다중해상도 걷음) · B04 단추 하나
- 안 부르는 길 — B04 JSON 점군 GET · ground-stats GET + TS · B07 옛 계획평면도(라이다) 짓기 · lidar_source · LIDAR_ID · plan_lidar 종류 이름 · SOURCE_FILTER_LABELS · MODEL_METHODS(py) · MESH_* 설정
- 옛 manifest 의 지운 갈래 줄은 DB 로 되살리지 않음 · 옛 csf 행은 미리보기 · 등고선 그대로 열림 · 지운 이름 요청 = 400
- 낡은 글 — Ground · Pipeline 머리 · WF1 「없으면 csf」 · B07 음영 기본 「csf」 → 빈 값 · 등고선 폴백 「csf」 → 404 · B04 3D 보기 처음값 · B05 Schema · B06 Prebuild · 씨닝 설명
- 시험 지움 2 — test_b04_contour_raster · test_b04_contour_equivalence(지운 삼각망 굽기 · 없는 프로젝트를 봐 건너뛰던 것)
- 시험 덜어냄 — test_b04_ground_filters CSF · 격자 최저 네 경우(지운 필터)
- 시험 고침 — 허용 목록 · 형 검사에 걸린 csf · tin · grid_min_z · meshfree · tin_sheet 견본을 ptd · implicit · laplace 로(54_22 · 238_1 · 443 · 342_2 · 346_3 · 351_1 · 442_2 · 271 + helper · 344_1 · 133_1 · 343_2 · 637 · 754_1 · 763_1 깨진 tin → 깨진 implicit · 763_3 · b05 둘 · b06 · sheet_surface TIN(도엽선) 경우 지움) · 이름만 바꿈(273_2 · 343_1 · 343_3 · 624_1)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 16:35:12 +09:00

274 lines
9.6 KiB
Python

# -*- 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(payload):
calls.append(payload)
return {"areas": [], "mass_haul": {"total": len(calls)}}
monkeypatch.setattr(prebuild, "NODE_BUNDLE", bundle)
monkeypatch.setattr(prebuild, "_run_node", 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_node", 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": "ptd", "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(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_node", 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 # 유토곡선 같은 값 — 안 씀