Files
Aislo/resources/tester/test_m01_make.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

221 lines
10 KiB
Python

"""M01 「만들기」 — 절로 표 거르기 · 소유 거름 · 자체 로직(만들기 · 본뜨기 · `/save` 고치기 · 지우기) · 끝수.
계약 `resources/master_data/_화면_계약.md` 2장·5장·6장. 임시 폴더 사본에서 씀.
"""
from __future__ import annotations
import shutil
from decimal import Decimal
from pathlib import Path
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
import helper_855_old_engine_routes as old_engine # noqa: E402 — 옛 셈 길 몸(855 2-E1 · 시험 전용)
from M01_MasterData import M01_MasterData_Store_Make as make
REAL = store.FOLDER
LABOR = "LB000002" # 보통인부
SAMPLE = "GF000219" # 산림 13-4-1 메쌓기(인력)
@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)
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)
app.include_router(old_engine.router)
return TestClient(app)
def _get(client: TestClient, url: str, **params) -> dict:
res = client.get(url, params=params)
assert res.status_code == 200, res.text
return res.json()
def _post(client: TestClient, url: str, body: dict, want: int = 200) -> dict:
res = client.post(url, json=body)
assert res.status_code == want, res.text
return res.json()
def _draft(끝수=None) -> dict:
"""보통인부 1/7 인 한 줄짜리 초안 — 저장 안 함."""
return {
"원문번호": "",
"이름": "시험 초안",
"결과단위": "원/㎡",
"출처": "자체",
"소유": "현장",
"입력": [],
"중간": [],
"호표": [
{
"종류": "인력",
"요소": LABOR,
"이름": "보통인부",
"단위": "인",
"수량": "1 / 7",
"비목": "노무비",
}
],
"덧줄": [],
"끝수": 끝수,
}
def _new(owner: str) -> dict:
"""새 자체 로직 — 화면 길(`/logic/copy` · `/logic/formula/save`)이 함께 쓰는 `logic_new`."""
return make.logic_new(_draft(), owner)
def _own_save(client: TestClient, change: dict, version: str, want: int = 200) -> dict:
"""자체 로직 고치기 · 지우기 = M01 [저장](`/save`) 한 길."""
body = {"files": [{"file": make.OWN, "version": version, "changes": [change]}]}
return _post(client, "/api/m01/save", body, want)
# ── 끝수 ──────────────────────────────────────────────────────────────
def test_끝수_묶음이_계에_붙고_글자는_안_붙는다(client: TestClient) -> None:
plain = _post(client, "/api/m01/calc", {"key": "", "inputs": {}, "row": _draft()})
assert plain["ok"] is True, plain
raw = Decimal(str(plain["sums"]["계"]))
assert raw == 24581 # 172068 / 7 = 24,581.14 → 줄 0.1 원 · 소계 1 원 버림(751-3 · 품셈 1-2-2)
cut = _post(
client,
"/api/m01/calc",
{"key": "", "inputs": {}, "row": _draft({"대상": "계", "자리": -1, "방법": "올림"})},
)
assert Decimal(str(cut["sums"]["계"])) == 24590 # 로직 끝수 묶음 = 1-2-2 버림 뒤 한 번 더
assert cut["sums"]["노무비"] == cut["sums"]["계"] # 비목 합마다 끊고 계 = 그 합
text = _post(client, "/api/m01/calc", {"key": "", "inputs": {}, "row": _draft("원 미만 버림")})
assert Decimal(str(text["sums"]["계"])) == raw # 글자 끝수는 설명일 뿐
def test_끝수_묶음_모양을_검사가_잡는다() -> None:
bad = {"키": "GX000001", "원문번호": "", "호표": [], "끝수": {"대상": "줄", "방법": "내림"}}
found = store.cm.mf.check_logic(store.cm.master(REAL), bad)[0]
assert any("대상" in x for x in found) and any("방법" in x for x in found)
# ── 절 거르기 ─────────────────────────────────────────────────────────
def test_절로_표_거르기(client: TestClient) -> None:
hits = _get(client, "/api/m01/tables", group="소요량", section="13-4", size=500)["tables"]
assert hits and all(store.in_section(t["원문번호"], "13-4") for t in hits)
assert not store.in_section("13-40", "13-4") and store.in_section("13-4", "13-4")
def test_로직_목록을_소유로_거른다(client: TestClient) -> None:
every = _get(client, "/api/m01/logics")["logics"]
assert all("소유" in x for x in every)
only = _get(client, "/api/m01/logics", owner="공용")["logics"]
assert only and all(x["소유"] == "공용" for x in only)
assert _get(client, "/api/m01/logics", owner="현장")["logics"] == []
# ── 자체 로직 ─────────────────────────────────────────────────────────
def test_자체_로직_만들기_본뜨기_고치기_지우기(client: TestClient) -> None:
made = _new("현장")
assert made["key"].startswith("GX") and made["file"] == make.OWN
assert made["logic"]["구분"] == "자체" and made["logic"]["소유"] == "현장"
assert (store.FOLDER / make.OWN).is_file()
again = _new("현장")
assert again["key"] != made["key"] # 원문번호가 같아도 키는 하나씩
copied = _post(client, "/api/m01/logic/copy", {"key": SAMPLE, "이름": "메쌓기 본뜸"})
assert copied["key"] != SAMPLE and f"{SAMPLE} 를 본뜸" in copied["logic"]["비고"]
assert copied["logic"]["이름"] == "메쌓기 본뜸" and copied["logic"]["소유"] == "현장"
assert copied["logic"]["상세구분"] == "13장 구조물"
fixed = dict(copied["logic"], 이름="고친 이름")
change = {"op": "edit", "key": copied["key"], "row": fixed}
_own_save(client, change, copied["version"])
done = _get(client, "/api/m01/logic", key=copied["key"])
assert done["logic"]["이름"] == "고친 이름" and done["logic"]["키"] == copied["key"]
_own_save(client, change, copied["version"], want=409) # 옛 판
gone = _own_save(client, {"op": "delete", "key": copied["key"]}, done["version"])
assert gone["files"][0]["file"] == make.OWN
assert client.get("/api/m01/logic", params={"key": copied["key"]}).status_code == 404
def test_모르는_소유는_400(client: TestClient) -> None:
with pytest.raises(store.StoreError) as caught:
make.logic_new(_draft(), "남의것")
assert caught.value.status == 400
def test_만든_자체_로직은_빈_문서로_열리고_목록에_든다(client: TestClient) -> None:
"""855 L3 ⓐ — 새 기초 셈은 문서(줄 쌓기) 몫 · 받은 줄의 셈 칸은 안 씀(옛 「시험 계산에 돈다」 걷음)."""
made = _new("공용")
got = _get(client, "/api/m01/logic/doc", key=made["key"])
assert (
got["새"] is False
and got["파일"] == "수식_자체.json"
and got["문서"]["이름"] == "시험 초안"
)
listed = _get(client, "/api/m01/logics", owner="공용")["logics"]
assert made["key"] in [x["키"] for x in listed]
def test_일위대가가_담은_로직은_못_지운다(client: TestClient, tmp_path: Path, monkeypatch) -> None:
"""39-1d — 로직 지우기 검사 = 모든 층(마스터 · 회사 · 개인) labor 담은로직 + 실무문서(마스터
일위대가 조합) · 쓰는 곳을 알림 · 다 빼면 지워짐(임시 storage · 임시 마스터)."""
import json
from config import config_system
from M02_MasterTemplete import M02_Template_Layers as layers
system, storage = tmp_path / "system", tmp_path / "storage"
monkeypatch.setattr(layers, "SYSTEM_ROOT", system)
monkeypatch.setattr(config_system, "STORAGE_BASE_DIR", str(storage))
made = _new("현장")
key = made["key"]
docs = {
"회사 3": storage / "3/templates/labor/item1.json",
"개인 3/15": storage / "3/15/templates/labor/item2.json",
"마스터": system / "labor/item3.json",
}
for at, path in enumerate(docs.values()):
path.parent.mkdir(parents=True)
doc = {"일위대가번": f"SU-00000{at}", "담은로직": [{"로직": SAMPLE}, {"로직": key}]}
path.write_text(json.dumps(doc, ensure_ascii=False), encoding="utf-8")
combos = store.FOLDER / store.mcb.FILE
raw = json.loads(combos.read_text(encoding="utf-8"))
raw["줄"].append({**raw["줄"][0], "키": "UA999999", "담은로직": [{"로직": key, "메모": None}]})
combos.write_text(json.dumps(raw, ensure_ascii=False), encoding="utf-8")
def delete(want: int) -> dict:
version = _get(client, "/api/m01/logic", key=key)["version"]
return _own_save(client, {"op": "delete", "key": key}, version, want)
errors = " ".join(delete(422)["detail"]["errors"])
for where in docs:
assert f"일위대가 {where} 「SU-" in errors and key in errors # 어디서 쓰는지 알림
assert store.mcb.FILE in errors # 실무문서(마스터 일위대가 조합)
for path in docs.values(): # 일위대가에서 뺌 — 실무문서만 남음
path.write_text(json.dumps({"담은로직": [{"로직": SAMPLE}]}), encoding="utf-8")
assert "일위대가 " not in " ".join(delete(422)["detail"]["errors"])
raw["줄"].pop()
combos.write_text(json.dumps(raw, ensure_ascii=False), encoding="utf-8")
assert delete(200)["files"][0]["file"] == make.OWN # 쓰는 곳 0 = 지워짐