Files
Aislo/resources/tester/test_719_1_sk_freeze.py
T
eomsangdonandClaude Opus 5.5 56146d5f4a refactor(855-F B9-6): 프로젝트 사본에서 M01 로직 줄 걷음 — 단가.json 로직 파일 · 일위대가.json 로직 사본 0 · 셈 = 수식.json
앞 커밋 296ec60ee(auto · 앞 세션 결제 오류로 멈춘 미커밋을 싱크가 올림)의 설명 + 그 뒤 시험 고침.
- M02_Item_Source: logic_rows 가 로직 줄 안 실음(빠진로직 = M01 수식 문서에 없는 키) · formula_docs(사본 수식 문서 닫힌 묶음) ·
  price_bundle = 새 M02_Item_Bundle.collect(문서 변수 연결을 훑어 자원 · 표 줄만 · 로직 줄 없음) · build_source 가 수식.json 붙임
- M02_Item_Bundle(새): 문서 연결 훑기 모음 · 셈 색인 Index(문서 이름표 + docs) · load
- M02_Doc_B09.build = formula_docs(단가 묶음 안 읽음 · logic_keys 걷음) · M02_Doc_Copy.doc_of = 색인이 실어 온 사본 문서 먼저
- M02_Item_Snapshot.source_files 원본판에 수식.json 듦 · Item_Prices.calc 색인 = 묶음 + 문서
- B08 Router_Material · B09 Sangeun · Labor_Source · Linked · Doc_Run · Bill_Library(서고 사본 수식 · 원본판 = 일위대가 + 수식 문서) = 같은 색인
- B09 Daega_Personal 단가산출 [내 자료집] = 수식 문서 꼴(옛 칸 덮개 · 원본 · 정체 안 씀 · 고침 = 수식 길 저장)
- 시험: 사본 셈 견본이 수식.json 을 같이 넘김(실제 Item_Copy.calc 길) — test_719_1 셋 · 848_1 · 848_10 ·
  795_4 · 145_1 · 145_2 · 719_2 · 802_4a · 841_1 · item_copy_complete · m02_item_labor · structures_summary_snapshot · 855_b09_golden
- 세기(골든 견본 사본 8): 단가.json 로직 파일 22 → 0 · 로직 줄 28 → 0 · 일위대가.json 로직 사본 4 → 0
- 검증: 관련 + 핵심 + 143 + 855_2d_frozen 898 중 실패 = 703(같은 내용 지문 4 ↔ 4.0 · 고치기 전 코드도 같음) ·
  713_1 · 804_7(M01 cce57c298 몫) 뿐 · 실제 B09 프로젝트 답 해시 같음 · 빌더 --check 같음 · typecheck 0

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

180 lines
8.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""719-1 · 855-F B9-5 프로젝트 사본 — M02 단가산출(SK) 수식 문서 사본(`M02_Item_Sangeun` ·
`M02_Item_Source` · `M02_Item_Prices` · `B09_Estimation_Bill_Library`) — 임시 storage(견본 층 ·
실제 M01 읽기만).
사본 SK = 원래 SK 문서 + `수식` 따로 사본(덮음 · 고친 문서 반영) · 굳힌 로직 줄(옛 GX9 ·
`로직_단가산출.json`) 없음 · 구조물 사본 · B09 서고 사본 셈 = M02 층 SK 셈 · 원본 SK 를 지우거나
M02 에서 고쳐도 사본 값 그대로([재생성] = 새 값) · 원본 층 지문 그대로 · 서고 원본판 = 다시 모아도
같음 · SK 고치면 다름 · 수식 사본을 못 짓는 SK(옛 칸) = 그대로(M02 처럼 못 셈).
"""
# ruff: noqa: F811 — 임시 층 fixture `world` 를 들여 씀
import copy
import hashlib
import json
import pytest
from B09_Estimation import B09_Estimation_Bill_Library as library
from M02_MasterTemplete import M02_Doc_Sk_Path as sk_path
from M02_MasterTemplete import M02_Item_Prices as prices
from M02_MasterTemplete import M02_Item_Sangeun as sk
from M02_MasterTemplete import M02_Item_Source as source
from M02_MasterTemplete import M02_Labor_Doc as labor
from M02_MasterTemplete import M02_Labor_Ref as refs
from M02_MasterTemplete import M02_MasterTemplete_Store as store
from resources.tester.test_715_sangeun_store import PCT, _sk
from resources.tester.test_m02_labor_ref import MINE, world # noqa: F401 — 같은 임시 층
def _print(folder):
"""층 폴더 지문 — 파일 이름 · 바이트."""
out = hashlib.sha256()
for path in sorted(p for p in folder.rglob("*") if p.is_file()):
out.update(str(path.relative_to(folder)).encode() + path.read_bytes())
return out.hexdigest()
def _top(ref, qty=2):
with store.at(ref["folder"]):
doc = labor.clean({"열": "rv", "담은로직": [{"참조": ref["ref"], "수량": {"손": qty}}]})
return doc, labor.calc(doc, {})["줄"][0]
def edit(folder, key, times=2):
"""M02 수식 길에서 SK 문서를 고침(따로) — 첫 금액 줄 수량 × times."""
with store.at(folder):
read = sk_path.read(key)
doc = copy.deepcopy(read["문서"])
doc["금액"][0]["수량"] = f"({doc['금액'][0].get('수량') or 1}) × {times}"
sk_path.save(key, {"문서": doc, "판": read["판"]})
def _mine(world):
"""SK = 바탕 로직 + M02 에서 고친 문서(따로)."""
key = _sk(world["personal"], 바탕={"로직": PCT})
edit(world["personal"], key)
return key, {"folder": world["personal"], "ref": {**MINE, "키": key}}
def _rows(bundle):
return [
row
for part in bundle.values()
if isinstance(part, dict)
for row in part.get("줄") or part.get("표") or []
if isinstance(row, dict)
]
def test_구조물_사본_수식_사본_값_같음_원본_지우고_고쳐도(world):
key, ref = _mine(world)
doc, live = _top(ref)
assert not live["까닭"] and live["기준"]["계"] > 0
before = _print(world["personal"])
rows = source.labor_doc_rows(doc)
bundle = source.price_bundle(rows, world["personal"])
assert _print(world["personal"]) == before # 원본 층 안 건드림
frozen = rows["참조사본"][refs.ref_id(ref["ref"])]
assert (
frozen["바탕"] == {"로직": PCT}
and frozen["수식"]["따로"] is True
and frozen["수식"][sk.LOCK]
)
assert "굳힌줄" not in frozen and "원본" not in frozen
assert "로직_단가산출.json" not in bundle
assert not [r for r in _rows(bundle) if str(r.get("키")).startswith("GX9")]
json.dumps(rows["참조사본"], ensure_ascii=False) # 사본 파일로 쓸 수 있는 꼴(Decimal 없음)
saved = json.loads(json.dumps(bundle, ensure_ascii=False))
formula = {"문서": source.formula_docs(rows)} # 사본 수식.json(855-F B9-6 · 로직 몫)
edit(world["personal"], key, 3) # M02 에서 다시 고침 → 사본 그대로
(world["personal"] / "sangeun" / f"{key}.json").unlink() # 원본이 사라져도 사본만 봄
got = prices.calc(rows, saved, {}, {}, None, formula)
line = got["줄"][0]
assert not line["까닭"]
for part in ("노무비", "재료비", "경비", "계"):
assert line["기준"][part] == pytest.approx(live["기준"][part], rel=1e-9)
assert line["반영"]["계"] == pytest.approx(live["반영"]["계"], rel=1e-9)
def test_재생성은_M02_새_값(world):
key, ref = _mine(world)
doc, _ = _top(ref)
first = source.labor_doc_rows(doc)
edit(world["personal"], key, 3)
_, live = _top(ref)
again = source.labor_doc_rows(doc)
bundle = source.price_bundle(again, world["personal"])
formula = {"문서": source.formula_docs(again)}
got = prices.calc(
again, json.loads(json.dumps(bundle, ensure_ascii=False)), {}, {}, None, formula
)
assert got["줄"][0]["기준"]["계"] == pytest.approx(live["기준"]["계"], rel=1e-9)
rid = refs.ref_id(ref["ref"])
assert first["참조사본"][rid]["수식"]["문서"] != again["참조사본"][rid]["수식"]["문서"]
def test_B09_서고_사본_값_같음_원본판(world, tmp_path):
key, ref = _mine(world)
with store.at(world["personal"]):
sc = refs.create(
"precombo",
{"이름": "조합", "단위": "㎡", "담은로직": [{"참조": ref["ref"], "수량": {"손": 2}}]},
)["이름"]
# 742-1 = SC 안 줄 수량(손 2) 저장 → 사본 = 저장 2 · 쓰는 쪽 알약 값(2)이 앞섬(층 · 사본 같은 값)
pill = f"{refs.ref_id({**MINE, '키': sc})}#0"
with store.at(world["personal"]):
top = labor.clean(
{"열": "rv", "담은로직": [{"참조": {**MINE, "키": sc}, "수량": {"손": 1}}]}
)
live = labor.calc(top, {pill: 2})["줄"][0]
area = {"시트": [{"id": "s", "칸": {"A1": {"값": 2}}, "연결": [{"칸": "A1", "키": pill}]}]}
before = _print(world["personal"])
root = tmp_path / "proj"
made = library.import_copy(root, "precombo", "personal", "7/42", sc)
assert made["만듦"] and _print(world["personal"]) == before
folder = library.library_dir(root) / made["폴더"]
read = {p.name: json.loads(p.read_text(encoding="utf-8")) for p in folder.glob("*.json")}
labor_file, price_file, formula = (
read[source.LABOR_FILE],
read[source.PRICE_FILE],
read["수식.json"],
)
bare = prices.calc(labor_file, price_file, {}, {}, None, formula)["줄"][0]
assert bare["기준"]["계"] == pytest.approx(
live["기준"]["계"], rel=1e-9
) # 이은 값 없음 = 저장 2
got = prices.calc(labor_file, price_file, {}, {}, area, formula)["줄"][0]
assert not got["까닭"] and not live["까닭"]
assert got["기준"]["계"] == pytest.approx(live["기준"]["계"], rel=1e-9)
mark = read["manifest.json"]["원본판"]
built = library._build("precombo", "personal", "7/42", sc)[0]
assert library.source_version(built) == mark # 다시 모아도 같은 판
again = library.import_copy(root, "precombo", "personal", "7/42", sc)
assert again == {"폴더": made["폴더"], "만듦": False}
edit(
world["personal"], key, 3
) # 811-1 SC 안 SK = 참조 한 행 → SK 고치면 원본판 바뀜 = [재생성] 대상
assert library.source_version(library._build("precombo", "personal", "7/42", sc)[0]) != mark
def test_SK_없는_사본_그대로():
"""SK 없는 참조사본 = 받은 묶음 그대로(기존 사본 · 공사 금액 전후 같음)."""
copies = {"x": {"종류": "사전조합", "담은로직": []}}
assert sk.freeze(copies) is copies and sk.bundle_keys(copies) == ([], [])
def test_옛_칸_SK_는_그대로_못_셈(world):
"""수식 사본을 못 짓는 SK(옛 칸 덮개 · 855 2-C1) = 그대로 · 사본 셈 = M02 처럼 까닭."""
key = _sk(world["personal"], 바탕={"로직": PCT}, 덮개={"labor:LB000036#0": {"qty": 0.5}})
ref = {"folder": world["personal"], "ref": {**MINE, "키": key}}
doc, live = _top(ref)
rows = source.labor_doc_rows(doc)
frozen = rows["참조사본"][refs.ref_id(ref["ref"])]
assert not (frozen.get("수식") or {}).get("따로")
bundle = json.loads(
json.dumps(source.price_bundle(rows, world["personal"]), ensure_ascii=False)
)
got = prices.calc(rows, bundle, {}, {}, None)["줄"][0]
assert live["까닭"] and got["까닭"] and got["기준"] is None