Files
Aislo/resources/tester/test_m01_cache.py
T
eomsangdonandClaude Opus 5.5 7e6190f8d3 refactor(855-E L3ⓐ): M01 기초 저장 · 검사 · 막힘 세기 = 수식 문서 기준 · 로직 줄 쓰기 = Store_Logic.mirror 한 자리
앞 세션 auto 커밋 cce57c298(Store_Logic 새 길 · /logic 답 머리만 · 판 = 문서 파일 지문 · 개정 = 문서 머리 대조 · 별칭 · 기계 등록 · [신규] · [삭제])에 이어
- Store_Cache: 막힘 세기(blocks · counted)를 문서 파일마다 · 저장 검사 logic_errors = 키 겹침 · 대장(요소 + 문서 키) · 연결 · 문서 막힘(check_logics 로직 줄 검사 걷음) · _docs_of = 문서 전부 · narrow 로직 갈래 걷음 · check_saved(부름 0) 지움
- Store_Save: 기초(로직 파일) 받지 않음(400) · gone · labor_errors(whole) 갈래 걷음
- Store_Logic: 정본 파일에도 새 기초(그 파일 표 키 — 옛 /save 와 같음) · 지움 검사에 조합 · 지운 기초를 부르던 문서 더함(옛 422 그대로) · 쓰는 곳 409 는 Doc.remove 로(옛 자리)
- 시험(옛 /save 로 로직 줄 셈 칸 고침 · /logic 답 셈 칸을 붙든 것 = 죽은 길): 새 test_855_l3_doc_only(로직 파일 없음 + 같이 쓰기 끔 = 켬과 답 같음 · 목록 · 상세 · 저장 · 개정 409 · 판 409 · 별칭 · 신규 · 복사 · 삭제 · 기계 등록)
  · test_m01_cache 셈 칸 /save 검사 셋 · test_794_1 식 고침 /save 422 걷음(셈 칸 고침 = 문서 저장 몫 · /save 는 머리만 씀)
  · test_m01_make 「시험 계산에 돈다」 → 빈 문서로 열림 · test_m01_api · test_m01_text 옛 셈 길 시험은 로직 줄 사본에서 읽음
  · test_854_2_m01_key_book 대장 끊김 = 인력 줄 + 기초 문서 쓰기 · test_794_1b · test_804_7 판 = 문서 파일 · test_802_3 문서 없는 키 = 404(빈 문서 안 지음)
  · test_826_2 좁힌 검사 = 판정만 견줌(기초 흠 글이 문서 꼴) · 로직 갈래 셋 뺌 · test_m01_copy 옛 시트 길 걷고 master_copy 왕복만 · test_854_2_m01_copy_doc 식 복사 → 기본정보 고친 복사
  · test_713_1 · test_796_1 row_print 줄 뺌(row_print 지움)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 08:37:53 +09:00

206 lines
9.3 KiB
Python

"""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 _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)
files, whole = store.loaded()
rows = {
str(r.get("키")): r for _, d in files.items() if d.get("그룹") == "로직" for r in d["줄"]
}
for key in parts.parts(): # 부품 문서(813-2)는 목록에서 뺌 — 키로 열기 · 셈은 그대로
rows.pop(key, None)
assert len(listed) == len(rows)
for one in listed:
reasons = store.cm.mf.check_logic(whole, rows[one["키"]])[0]
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) # 같은 것을 그대로 씀
_write("로직_건설품셈_01장_공통.json", lambda d: d["줄"][0].update(비고="자국 바뀜"))
fresh, _ = store.loaded()
assert fresh is not files
assert fresh["로직_건설품셈_01장_공통.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)
files, whole = store.loaded()
rows = {
str(r.get("키")): r for _, d in files.items() if d.get("그룹") == "로직" for r in d["줄"]
}
assert [x["키"] for x in listed] == [x["키"] for x in was]
for one in listed:
assert one["reasons"] == store.cm.mf.check_logic(whole, rows[one["키"]])[0]
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)
rows = {
str(r.get("키")): r for _, d in files.items() if d.get("그룹") == "로직" for r in d["줄"]
}
changed = {k for k, r in rows.items() if store.cm.mf.check_logic(other, r)[0] != counts[k][0]}
assert changed and changed <= marked