Merge branch 'sub_laptop_5' of C:/Aislo_wt/sub_laptop_5 into main_laptop_1
This commit is contained in:
@@ -0,0 +1,168 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""수식 문서 막힘 검사(PLAN 855 · 걸음 2-B3) — 옛 `master_formula.check_logic` 대신 문서 기준.
|
||||
|
||||
막힘 = 문서 검사 표지(`master_doc.check`) + 부름 닫힘(단가산출 연결 키가 저장 문서에 있음) +
|
||||
요소 닫힘(요소 · 표 키 · `{선택}` 구멍을 그 목록으로 편 키 · 재료 고르기 후보 — 마스터 색인) ·
|
||||
저장 검사는 문서 사이 부름 순환까지. 기본 입력으로 셈이 안 되는 것은 막힘 아님(사용자 확정 · 지금 그대로).
|
||||
문서 없는 로직 = 막힘 아님(지금 그대로 · 로직 줄 뒤에 문서를 지음) · 저장 검사도 문서 없는 키를 안 봄.
|
||||
일위대가 조합 줄 검사(`combo_row`) = 옛 `master_combo.check_row` 와 같은 글 · 로직이 있는지는 문서로.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import master_doc as md
|
||||
import master_formula as mf # 마스터 색인(`Master.get`) — 없는 키 = FormulaError
|
||||
import master_keys as mk
|
||||
import master_material as mm # 재료 고르기 조건 검사(`check_pick`)
|
||||
|
||||
COMBO = "UA" # 일위대가 조합 키 머리(`master_combo.TID`)
|
||||
COMBO_ITEM = ("로직", "메모") # 조합 담은 로직 줄 칸(`master_combo.ITEM_COLS`)
|
||||
|
||||
|
||||
def calls(doc: dict) -> set[str]:
|
||||
"""문서가 부르는 단가산출 키(키 구멍 `{…}` 부름은 셈 때 정해져 뺌)."""
|
||||
out = set()
|
||||
for v in doc.get("변수") or []:
|
||||
link = v.get("연결") or {}
|
||||
if link.get("갈래") == "단가산출" and link.get("키") and "{" not in str(link["키"]):
|
||||
out.add(str(link["키"]))
|
||||
return out
|
||||
|
||||
|
||||
def _refs(doc: dict, text) -> list[str] | None:
|
||||
"""요소 · 표 키 글 → 실제 키 — `{구멍}` 은 그 선택 변수 목록으로 폄 · 못 펴면 None."""
|
||||
out = [str(text)]
|
||||
for hole in dict.fromkeys(md.holes(text)):
|
||||
var = next(
|
||||
(
|
||||
v
|
||||
for v in doc.get("변수") or []
|
||||
if hole in (v.get("이름"), v.get("열쇠"), md.var_id(v))
|
||||
),
|
||||
None,
|
||||
)
|
||||
link = (var or {}).get("연결") or {}
|
||||
if link.get("갈래") != "선택" or not isinstance(link.get("목록"), list):
|
||||
return None
|
||||
out = [t.replace("{" + hole + "}", str(c)) for t in out for c in link["목록"]]
|
||||
return out
|
||||
|
||||
|
||||
def _element_links(doc: dict):
|
||||
"""(변수, 연결, 키 글) — 요소 · 표 연결의 키 자리."""
|
||||
for v in doc.get("변수") or []:
|
||||
link = v.get("연결") or {}
|
||||
slot = {"요소": "키", "표": "표"}.get(link.get("갈래"))
|
||||
if slot and link.get(slot):
|
||||
yield v, link, link[slot]
|
||||
|
||||
|
||||
def seen(doc: dict) -> set[str]:
|
||||
"""문서가 보는 요소 · 표 키(구멍은 편 키 · 못 펴면 그 묶음 「#ID」) ·
|
||||
재료 고르기 조건이면 자재품목 묶음 통째(「#MT」)."""
|
||||
out = set()
|
||||
for _, _, text in _element_links(doc):
|
||||
refs = _refs(doc, text)
|
||||
out |= set(refs) if refs is not None else {"#" + str(text)[:2]}
|
||||
if any((v.get("연결") or {}).get("재료") for v in doc.get("변수") or []):
|
||||
out.add("#" + mm.MARKET)
|
||||
return out
|
||||
|
||||
|
||||
def closure(key: str, doc: dict, whole) -> list[str]:
|
||||
"""요소 닫힘 — 연결이 부르는 요소 · 표가 마스터에 있음 · 재료 고르기 후보가 있음."""
|
||||
out = []
|
||||
for v, link, text in _element_links(doc):
|
||||
for ref in _refs(doc, text) or []:
|
||||
try:
|
||||
whole.get(ref)
|
||||
except mf.FormulaError as e:
|
||||
out.append(f"{key} 연결 {md.var_id(v)} · {e}")
|
||||
for v in doc.get("변수") or []:
|
||||
cond = (v.get("연결") or {}).get("재료")
|
||||
if isinstance(cond, dict):
|
||||
out += mm.check_pick(whole, f"{key} 연결 {md.var_id(v)}", cond)
|
||||
return out
|
||||
|
||||
|
||||
def _text(key: str, mark: dict) -> str:
|
||||
where = f" {mark['자리']}" if mark.get("자리") else ""
|
||||
return f"{key}{where} · {mark['갈래']} — {mark['글']}"
|
||||
|
||||
|
||||
def reasons(key: str, doc: dict | None, have, whole=None) -> list[str]:
|
||||
"""그 로직의 막힘 까닭 — 표지 + 부름 닫힘(`have` = 있는 문서 키 묶음) + 요소 닫힘(`whole` 을 주면)."""
|
||||
if doc is None: # 막힘 기준 = 지금 그대로(사용자 확정) — 문서 없는 새 줄은 막힘 아님
|
||||
return []
|
||||
out = [_text(key, m) for m in md.check(doc)]
|
||||
out += [f"{key} · 부르는 단가산출 「{k}」 없음" for k in sorted(calls(doc) - set(have))]
|
||||
out += _passed(key, doc, have)
|
||||
return out + (closure(key, doc, whole) if whole is not None else [])
|
||||
|
||||
|
||||
def _passed(key: str, doc: dict, have) -> list[str]:
|
||||
"""단가산출 부름이 넘기는 입력 이름 = 부르는 문서의 입력 변수 열쇠(옛 「입력 이름」 검사 몫)."""
|
||||
out = []
|
||||
for v in doc.get("변수") or []:
|
||||
link = v.get("연결") or {}
|
||||
callee = have.get(str(link.get("키"))) if link.get("갈래") == "단가산출" else None
|
||||
if callee is None or not isinstance(have, dict):
|
||||
continue
|
||||
ins = {
|
||||
x.get("열쇠")
|
||||
for x in callee.get("변수") or []
|
||||
if (x.get("연결") or {}).get("갈래") in ("입력", "선택", "숫자")
|
||||
}
|
||||
for name in sorted(set(link.get("입력") or {}) - ins):
|
||||
out.append(f"{key} 연결 {md.var_id(v)} · 「{link['키']}」 에 입력 「{name}」 없음")
|
||||
return out
|
||||
|
||||
|
||||
def check_docs(docs: dict[str, dict], keys=None, whole=None) -> list[str]:
|
||||
"""저장 검사 몫 — `keys`(없으면 전부)의 막힘 까닭 + 문서 사이 부름 순환(전체)."""
|
||||
out = [
|
||||
x
|
||||
for k in sorted(docs if keys is None else set(keys) & set(docs))
|
||||
for x in reasons(k, docs[k], docs, whole)
|
||||
]
|
||||
graph = {k: sorted(calls(d)) for k, d in docs.items()}
|
||||
out += [f"돌고 도는 참조 · {' → '.join([*loop, loop[0]])}" for loop in md.loops(graph)]
|
||||
return out
|
||||
|
||||
|
||||
def combo_row(row: dict, docs) -> list[str]:
|
||||
"""일위대가 조합 한 줄 — 빈 조합 · 없는 로직 · 같은 로직 두 번 · 조합을 담음 · 메모 모양."""
|
||||
where = f"{row.get('키')} {row.get('이름') or ''}".strip()
|
||||
got = row.get("담은로직")
|
||||
items = got if isinstance(got, list) else []
|
||||
out = [] if items else [f"{where} · 빈 조합 — 담은 로직이 없음"]
|
||||
if got is not None and not isinstance(got, list):
|
||||
out.append(f"{where} · 「담은로직」 이 목록 아님")
|
||||
picked: set[str] = set()
|
||||
for at, one in enumerate(items, start=1):
|
||||
if not isinstance(one, dict):
|
||||
out.append(f"{where} 줄{at} · 담은 로직 줄이 묶음 아님 「{one}」")
|
||||
continue
|
||||
extra = set(one) - set(COMBO_ITEM)
|
||||
if extra:
|
||||
out.append(f"{where} 줄{at} · 모르는 칸 {sorted(extra)}")
|
||||
memo = one.get("메모")
|
||||
if memo is not None and not isinstance(memo, str):
|
||||
out.append(f"{where} 줄{at} · 「메모」 가 글자 아님 「{memo}」 — 수량·계산은 두지 않음")
|
||||
key = str(one.get("로직") or "")
|
||||
if not mk.KEY.fullmatch(key):
|
||||
out.append(f"{where} 줄{at} · 로직 키 모양 아님 「{key}」")
|
||||
continue
|
||||
if mk.id_of(key) == COMBO:
|
||||
out.append(f"{where} 줄{at} · 조합은 조합을 담지 못함 「{key}」 — 단가산출 로직만")
|
||||
continue
|
||||
if mk.GROUP_OF.get(mk.id_of(key)) != "로직":
|
||||
out.append(f"{where} 줄{at} · 로직 아님 「{key}」")
|
||||
continue
|
||||
if key not in docs:
|
||||
out.append(f"{where} 줄{at} · 없는 요소 「{key}」")
|
||||
continue
|
||||
if key in picked:
|
||||
out.append(f"{where} 줄{at} · 같은 로직을 두 번 담음 「{key}」")
|
||||
picked.add(key)
|
||||
return out
|
||||
@@ -31,3 +31,76 @@ def test_틀린_식은_옛_새_모두_막힘():
|
||||
bad_doc["금액"][0]["수량"] = "없는기호 × 2"
|
||||
assert h.mf.check_logic(whole, bad_row)[0]
|
||||
assert md.check(bad_doc)
|
||||
|
||||
|
||||
def test_화면_답이_문서_막힘_길을_씀(monkeypatch):
|
||||
"""2-B3 뒤 — M01 `/logic` 막힘 · 목록 막힘 · 일위대가 조합 막힘이 수식 문서 기준(`master_doc_block`).
|
||||
문서 하나를 틀리게(사본) 하면 로직 줄은 그대로인데 화면 답이 막힘으로 바뀜 · 문서가 빠지면 조합도 막힘."""
|
||||
import copy
|
||||
|
||||
from M01_MasterData import M01_MasterData_Doc as doc_store
|
||||
from M01_MasterData import M01_MasterData_Store as store
|
||||
from M01_MasterData import M01_MasterData_Store_Combo as combo_store
|
||||
|
||||
real = doc_store.docs()
|
||||
key = next(k for k, d in real.items() if d.get("금액"))
|
||||
assert not store.logic(key)["blocked"] and not store.blocks()[key]
|
||||
bad = copy.deepcopy(real[key])
|
||||
bad["금액"][0]["수량"] = "없는기호 × 2"
|
||||
monkeypatch.setattr(doc_store, "docs", lambda: {**real, key: bad})
|
||||
got = store.logic(key)
|
||||
assert got["blocked"] and any("없는기호" in x for x in got["reasons"])
|
||||
assert store.blocks()[key] == got["reasons"]
|
||||
|
||||
row = {"키": "UA999999", "이름": "시험", "담은로직": [{"로직": key}]}
|
||||
assert combo_store.problems_of(row) == []
|
||||
monkeypatch.setattr(doc_store, "docs", lambda: {k: d for k, d in real.items() if k != key})
|
||||
assert combo_store.problems_of(row) == [f"UA999999 시험 줄1 · 없는 요소 「{key}」"]
|
||||
assert store.logic(key)["reasons"] == [] # 문서 없는 줄 = 막힘 아님(지금 그대로)
|
||||
|
||||
|
||||
def test_저장_검사_부름_닫힘_순환():
|
||||
"""저장 검사 로직 몫(`master_doc_block.check_docs`) — 부르는 단가산출이 빠지면 막힘 · 문서 사이 순환."""
|
||||
mb = importlib.import_module("master_doc_block")
|
||||
_, _, docs, _ = h.world()
|
||||
caller = next(k for k, d in docs.items() if mb.calls(d))
|
||||
called = sorted(mb.calls(docs[caller]))[0]
|
||||
assert not mb.check_docs(docs, {caller})
|
||||
gone = {k: d for k, d in docs.items() if k != called}
|
||||
assert any(f"「{called}」 없음" in x for x in mb.check_docs(gone, {caller}))
|
||||
a = {"꼴": "수식문서", "키": "GX900001", "변수": [{"열쇠": "b", "기호": "b", "연결": {"갈래": "단가산출", "키": "GX900002"}}]} # fmt: skip
|
||||
b = {**a, "키": "GX900002", "변수": [{"열쇠": "a", "기호": "a", "연결": {"갈래": "단가산출", "키": "GX900001"}}]} # fmt: skip
|
||||
assert any("돌고 도는 참조" in x for x in mb.check_docs({"GX900001": a, "GX900002": b}, set()))
|
||||
|
||||
|
||||
def test_요소_닫힘_쓰이는_요소가_없으면_막힘():
|
||||
"""요소 닫힘 — 문서가 부르는 요소 · 표가 마스터에 없으면 막힘(쓰이는 요소를 지우면 저장이 막는 지금 동작 지킴) ·
|
||||
단가산출에 넘기는 입력 이름이 부르는 문서에 없으면 막힘."""
|
||||
import copy
|
||||
|
||||
mb = importlib.import_module("master_doc_block")
|
||||
_, whole, docs, _ = h.world()
|
||||
key, doc = next(
|
||||
(k, d)
|
||||
for k, d in docs.items()
|
||||
if any(
|
||||
(v.get("연결") or {}).get("갈래") == "요소"
|
||||
and str((v.get("연결") or {}).get("키") or "").startswith("LB0")
|
||||
for v in d.get("변수") or []
|
||||
)
|
||||
)
|
||||
assert not mb.reasons(key, doc, docs, whole)
|
||||
gone = copy.deepcopy(doc)
|
||||
link = next(
|
||||
v["연결"]
|
||||
for v in gone["변수"]
|
||||
if str((v.get("연결") or {}).get("키") or "").startswith("LB0")
|
||||
)
|
||||
link["키"] = "LB999999"
|
||||
assert any("LB999999" in x for x in mb.reasons(key, gone, docs, whole))
|
||||
|
||||
caller = next(k for k, d in docs.items() if mb.calls(d))
|
||||
bad = copy.deepcopy(docs[caller])
|
||||
call = next(v["연결"] for v in bad["변수"] if (v.get("연결") or {}).get("갈래") == "단가산출")
|
||||
call["입력"] = {**(call.get("입력") or {}), "없는입력": "1"}
|
||||
assert any("없는입력" in x for x in mb.reasons(caller, bad, docs, whole))
|
||||
|
||||
@@ -107,16 +107,26 @@ def test_로직을_저장하면_목록에_바로_비친다(client: TestClient) -
|
||||
assert listed and listed[0]["이름"] == "저장 뒤 이름"
|
||||
|
||||
|
||||
def test_부르는_로직이_바뀌면_다른_파일의_줄도_다시_센다(client: TestClient) -> None:
|
||||
def test_부르는_로직이_바뀌면_다른_파일의_줄도_다시_센다(
|
||||
client: TestClient, tmp_path: Path, monkeypatch
|
||||
) -> None:
|
||||
"""목록 막힘 = 수식 문서 기준(855 2-B3) — 부른 쪽 문서가 깨지면(넘겨받던 입력 변수를 지움)
|
||||
다른 파일의 부르는 줄도 다시 세어 막힘."""
|
||||
from M01_MasterData import M01_MasterData_Doc as doc_store
|
||||
|
||||
docs = tmp_path / "수식문서"
|
||||
shutil.copytree(REAL / "수식문서", docs)
|
||||
monkeypatch.setattr(doc_store.ml, "FOLDER", docs)
|
||||
doc_store._memo.clear()
|
||||
assert [x for x in _logics(client) if x["키"] == CALLER][0]["blocked"] is False
|
||||
|
||||
def add_input(data: dict) -> None:
|
||||
row = next(r for r in data["줄"] if r["키"] == CALLEE)
|
||||
row["입력"] = [*row.get("입력", []), {"이름": "새입력", "종류": "수"}]
|
||||
|
||||
_write("로직_건설품셈_08장_건설기계.json", add_input) # 부르는 쪽 파일은 그대로
|
||||
path = docs / "수식_건설품셈_08장_건설기계.json" # 부르는 쪽 문서 파일은 그대로
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
callee = next(d for d in data["줄"] if d["키"] == CALLEE)
|
||||
callee["변수"] = [v for v in callee["변수"] if v.get("열쇠") != "지역"]
|
||||
path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
caller = [x for x in _logics(client) if x["키"] == CALLER][0]
|
||||
assert caller["blocked"] is True and any("새입력" in x for x in caller["reasons"])
|
||||
assert caller["blocked"] is True and any("입력 「지역」" in x for x in caller["reasons"])
|
||||
|
||||
|
||||
def _save(client: TestClient, key: str, spoil) -> object:
|
||||
|
||||
@@ -13,6 +13,7 @@ import pytest
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from M01_MasterData import M01_MasterData_Doc as doc_store
|
||||
from M01_MasterData import M01_MasterData_Router as router_module
|
||||
from M01_MasterData import M01_MasterData_Store as store
|
||||
from M01_MasterData import M01_MasterData_Store_Make as make
|
||||
@@ -28,7 +29,12 @@ def client(tmp_path: Path, monkeypatch) -> TestClient:
|
||||
if not path.name.startswith("_") or path.name == store.mk.BOOK.name:
|
||||
shutil.copy(path, tmp_path / path.name)
|
||||
shutil.copytree(REAL / "기계", tmp_path / "기계") # 기계 = 폴더(826-2)
|
||||
shutil.copytree(
|
||||
REAL / "수식문서", tmp_path / "수식문서"
|
||||
) # 막힘 · 조합 검사 = 문서 기준(855 2-B3)
|
||||
monkeypatch.setattr(store, "FOLDER", tmp_path)
|
||||
monkeypatch.setattr(doc_store.ml, "FOLDER", tmp_path / "수식문서")
|
||||
doc_store._memo.clear()
|
||||
app = FastAPI()
|
||||
app.include_router(router_module.router)
|
||||
return TestClient(app)
|
||||
|
||||
Reference in New Issue
Block a user