"""M01 목록이 마스터를 한 번만 읽는지 — `M01_MasterData_Store_Cache`. 목록(`/logics` · `/combos`)은 요청마다 마스터를 새로 읽지 않고 막힘도 미리 세어 둔 값을 씀. 여기서 보는 것 = ① 세어 둔 값이 줄마다 검사한 것과 같음 ② 파일이 바뀌면 바로 다시 읽음 ③ 저장 직후 목록에 바로 비침 ④ 다른 파일의 로직이 바뀌면 그것을 부르던 줄도 다시 셈 ⑤ 요소 저장 검사를 좁혀도 흠을 그대로 잡음(기초 셈 칸 고침 검사 = 문서 저장 몫 · 855 L3 ⓐ). """ from __future__ import annotations import json import shutil import time from pathlib import Path import pytest from fastapi import FastAPI from fastapi.testclient import TestClient from M01_MasterData import M01_MasterData_Parts as parts from M01_MasterData import M01_MasterData_Router as router_module from M01_MasterData import M01_MasterData_Store as store REAL = store.FOLDER CALLER = "GC000994" # 로직_건설품셈_01장_공통.json — 아래 로직을 부름 CALLEE = "GC000276" # 로직_건설품셈_08장_건설기계.json — 다른 파일에 있음 @pytest.fixture def client(tmp_path: Path, monkeypatch) -> TestClient: for path in REAL.glob("*.json"): 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) monkeypatch.setattr(store, "FOLDER", tmp_path) shutil.copytree(REAL / "수식문서", tmp_path / "수식문서") # 로직 목록 = 수식 문서(855 L2 ⓐ) monkeypatch.setattr(store._docs().ml, "FOLDER", tmp_path / "수식문서") app = FastAPI() app.include_router(router_module.router) return TestClient(app) def _mb(): import importlib return importlib.import_module("master_doc_block") def _logics(client: TestClient, **params) -> list[dict]: res = client.get("/api/m01/logics", params=params) assert res.status_code == 200, res.text return res.json()["logics"] def _write(file: str, change) -> None: """정본 파일을 손으로 고침(저장 길을 거치지 않음) — 바뀐 것을 알아채는지 보려고.""" path = store.FOLDER / file data = json.loads(path.read_text(encoding="utf-8")) change(data) path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8", newline="\n") def test_세어_둔_막힘이_줄마다_검사한_것과_같다(client: TestClient) -> None: listed = _logics(client) _, whole = store.loaded() docs = store._docs().docs() # 막힘 = 수식 문서 기준(master_doc_block · 855 2-B3) keys = {k for k in docs if k not in parts.parts()} # 부품 문서(813-2)는 목록에서 뺌 assert {x["키"] for x in listed} == keys for one in listed: reasons = _mb().reasons(one["키"], docs[one["키"]], docs, whole) assert one["reasons"] == reasons and one["blocked"] is bool(reasons) def test_거름이_그대로다(client: TestClient) -> None: whole = _logics(client) sub, detail = whole[0]["구분"], whole[0]["상세구분"] by_sub = _logics(client, sub=sub, detail=detail) assert by_sub == [x for x in whole if (x["구분"], x["상세구분"]) == (sub, detail)] assert _logics(client, blocked=1) == [x for x in whole if x["blocked"]] assert _logics(client, blocked=0) == [x for x in whole if not x["blocked"]] assert _logics(client, q=CALLER) == [x for x in whole if x["키"] == CALLER] def test_안_바뀌면_다시_읽지_않고_바뀌면_바로_읽는다(client: TestClient) -> None: files, whole = store.loaded() assert store.loaded() == (files, whole) # 같은 것을 그대로 씀 # 자국 = 요소 파일(로직 JSON 은 L3 에서 걷음) _write("인력.json", lambda d: d["줄"][0].update(비고="자국 바뀜")) fresh, _ = store.loaded() assert fresh is not files assert fresh["인력.json"]["줄"][0]["비고"] == "자국 바뀜" def test_로직을_저장하면_목록에_바로_비친다(client: TestClient) -> None: one = client.get("/api/m01/logic", params={"key": CALLER}).json() assert [x for x in _logics(client, q=CALLER)][0]["이름"] == one["logic"]["이름"] row = {**one["logic"], "이름": "저장 뒤 이름"} res = client.post( "/api/m01/save", json={ "files": [ { "file": one["file"], "version": one["version"], "changes": [{"op": "edit", "key": CALLER, "row": row}], } ], "개정확인": True, # 정본 줄 고침 = 개정 확인(713-1) }, ) assert res.status_code == 200, res.text listed = [x for x in _logics(client) if x["키"] == CALLER] assert listed and listed[0]["이름"] == "저장 뒤 이름" 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 / "수식문서" # 사본 = 준비(`client`)가 둠 doc_store._memo.clear() assert [x for x in _logics(client) if x["키"] == CALLER][0]["blocked"] is False 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"]) def _errors(res) -> list[str]: assert res.status_code == 422, res.text return res.json()["detail"]["errors"] def test_미리_읽어_두면_첫_목록이_기다리지_않는다(client: TestClient) -> None: store.cache.forget() thread = store.cache.warm(store.FOLDER) thread.join(120) assert not thread.is_alive() start = time.perf_counter() assert _logics(client) assert time.perf_counter() - start < 1.0 # 미리 안 읽으면 2~3초 def _plain(file: str) -> dict: """정본 파일 그대로(수는 글이 아닌 그대로) — 저장에 실어 보낼 줄을 꺼내려고.""" return json.loads((store.FOLDER / file).read_text(encoding="utf-8")) def _save_file(client: TestClient, file: str, changes: list[dict]): """정본 파일을 저장 길로 고침 — 요소·표 줄도 같은 길.""" return client.post( "/api/m01/save", json={ "files": [{"file": file, "version": store.read(file)[1], "changes": changes}], "개정확인": True, # 로직 정본 파일이면 개정 확인(713-1) · 요소 파일엔 상관없음 }, ) def test_쓰이는_요소를_지우면_저장이_막힌다(client: TestClient) -> None: """요소 저장도 좁혀 검사하지만 그 요소를 쓰던 로직은 그대로 걸림.""" _logics(client) # 미리 세어 둔 값이 선 평소 모양 res = _save_file(client, "인력.json", [{"op": "delete", "key": "LB000014"}]) assert any("LB000014" in x for x in _errors(res)) def test_요소를_고쳐_저장해도_막힘_표시가_전수와_같다(client: TestClient) -> None: """요소를 고친 뒤 다시 센 막힘이 줄마다 검사한 것과 같은지 — 좁혀 세는 길.""" was = _logics(client) raw = _plain("인력.json") row = {**next(r for r in raw["줄"] if str(r.get("키")) == "LB000014"), "비고": "저장 검사 시험"} res = _save_file(client, "인력.json", [{"op": "edit", "key": "LB000014", "row": row}]) assert res.status_code == 200, res.text listed = _logics(client) _, whole = store.loaded() docs = store._docs().docs() assert [x["키"] for x in listed] == [x["키"] for x in was] for one in listed: assert one["reasons"] == _mb().reasons(one["키"], docs[one["키"]], docs, whole) def test_요소_지도가_전수_검사와_같다(client: TestClient) -> None: """「어느 로직이 어느 요소를 보는지」 지도가 놓치는 자리가 없는지 — 인력 줄을 통째로 비우고 1,354 줄을 다 검사해, 달라진 줄이 지도 안에 드는지 봄.""" counts = store.cache.counted(store.FOLDER) files, _ = store.loaded() marks = set() for row in files["인력.json"]["줄"]: key = str(row.get("키")) marks |= {key, "#" + key[:2]} if row.get("원문번호"): marks.add(f"{key[:2]}:{row['원문번호']}") marked = {key for key, got in counts.items() if got[2] & marks} empty = {**files, "인력.json": {**files["인력.json"], "줄": []}} other = store.cm.mf.Master(empty) docs = store._docs().docs() changed = {k for k, d in docs.items() if _mb().reasons(k, d, docs, other) != counts[k][0]} assert changed and changed <= marked