Files
Aislo/resources/tester/test_855_b09_golden.py
T
eomsangdonandClaude Opus 5.5 f6d7fd14f1 test(855-F): B9-0 B08 · B09 답 지문 — 임시 층 견본 · 사본 지금 길 · 손 줄 · 다르면 실패
- test_855_b09_golden + golden_855_b09.json: 개인 층 견본(SK 바탕 · 율 더한줄 · 형제 · 따로 · 가져온 식 · 기계 · 재료 / SC 참조 · 고정 · 로직 + 자재) → 구조물 사본(labor_doc_rows · price_bundle) · B09 서고 사본(import_copy) · 설계내역서 손 줄(율 · 고른 재료 · 입력 · 운반공 거리 채움)
- 지문 갈래 15: calc_user · daega_inputs · 단가 수요 키 · 산근(관급 있음 · 없음 · 값 / 글 따로) · logic_preview 손 줄마다(값 / 글) · B08 snapshot_units
- 다르면 실패 + 다시 뜨기(--write) 글 · 세 번 돌려 같음 · 제품 코드 고침 0

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 17:22:41 +09:00

265 lines
12 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.
# ruff: noqa: F811, E402 — 임시 층 fixture(world)를 test_m02_labor_ref 에서 받아 씀 · `--write` 때 길을 먼저 둠
"""855-F B9-0 — B08 · B09 답 지문(옛 엔진 부름을 걷는 걸음 B9-1 ~ B9-6 의 「다름 0」 자).
임시 storage(개인 층 7/42) · 견본을 시험이 지음 → 사본 만들기(지금 길) → 답 지문:
- 층 견본 — 단가산출(SK): 바탕 로직 · 율 더한줄 · 형제(바탕 참조) · 「따로」 · 가져온 식 · 기계 · 재료 /
일위대가(SC): SK 참조 · 고정 · 로직 줄 + 자재
- 구조물 사본 = 일위대가 열 문서(위 참조 + 로직 · 고른 재료 · 자재) → `labor_doc_rows` · `price_bundle`
· B09 서고 사본 = `Bill_Library.import_copy`(SK 따로 · SK 가져온 식 · SC)
- 손 줄 = 설계내역서 로직 줄(율 · 고른 재료 · 입력) + 운반공(거리 채움)
- 답 = B09 `calc_user` · `daega_inputs` · 단가 수요 키(`_demand`) · 산근(`Sangeun.build` · 관급 있음 · 없음)
· `logic_preview`(손 줄마다) · B08 `snapshot_units` — 갈래마다 지문(값 · 글 따로).
지문 = `golden_855_b09.json` · 다르면 실패 — 뜻대로 금액 · 글을 바꾼 걸음만 다시 뜸:
`./venv/Scripts/python.exe resources/tester/test_855_b09_golden.py --write`(바뀐 갈래를 커밋 글에).
"""
from __future__ import annotations
import asyncio
import copy
import hashlib
import json
import os
import re
import sys
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parents[2]
if str(ROOT) not in sys.path: # `--write` 로 바로 돌릴 때
sys.path.insert(0, str(ROOT))
from B08_Quantity import B08_Quantity_Router_Material as b08
from B09_Estimation import B09_Estimation_Bill_Library as library
from B09_Estimation import B09_Estimation_Router as b09
from B09_Estimation import B09_Estimation_Sangeun as sangeun
from B09_Estimation import B09_Estimation_Store as b09_store
from B09_Estimation.B09_Estimation_Labor_Source import daega_inputs
from M02_MasterTemplete import M02_Doc_Sk_Path as sk_path
from M02_MasterTemplete import M02_Item_Snapshot as snapshots
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 M02_MasterTemplete import M02_Sangeun_Imported as imported
from resources.tester.test_145_2_b09_labor_calc import _item, _project
from resources.tester.test_793_2_sangeun_imported import _bonghwa
from resources.tester.test_m02_labor_ref import MINE, world # noqa: F401 — 같은 임시 층
HERE = Path(__file__).resolve().parent
FILE = HERE / "golden_855_b09.json"
REDO = "./venv/Scripts/python.exe resources/tester/test_855_b09_golden.py --write"
WRITE = os.environ.get("S855B09_WRITE") == "1"
OWNER = "7/42"
FORM = "GC000211" # 합판거푸집 — 옵션 · 재료 · 인력
PCT = "GC001109" # 인력 둘 + 「노무비 * 3 / 100」 덧줄(율)
SUB = "GC000999" # 원/주 · 고소작업차 로직 줄 + 덧줄 공구손료 %
NET = "GC000337" # 낙석방지망 — 노무 · 크레인(중기) · 자재 셋
NET_IN = {"구분": "기계식", "방지망": "포켓식", "지역": "전국평균", "크레인": "2104-0010"}
DIG = "GF000089" # 토사깍기(기계) — 굴착기 시간당
STONE = "GF000219" # 돌쌓기 메쌓기(인력)
TWO_MATS = "GC000565" # 재료 줄 둘(고른 재료 열쇠)
HAUL = "GF000134" # 골재운반(운반공 · 거리로 입력 채움)
FIXED = {
"고정": {
"이름": "sub6임시 손 단가",
"규격": "",
"단위": "식",
"단가": {"노무비": 12000, "재료비": 3000, "경비": 500},
"이음": {"노임": "LB000002", "자재": None, "기계": None, "유가": None},
},
"수량": {"손": 2},
}
RATE = {
"고정": {"이름": "공구손료", "단가": {}, "이음": {}, "비율": {"기준": "인력", "비목": "경비"}}
}
def _sk(**doc) -> str:
return refs.create("sangeun", {"이름": "sub6임시", "단위": "㎡", "더한줄": [], **doc})["이름"]
def _layer_samples(me: Path) -> dict[str, str]:
"""개인 층 견본 — {갈래: 키}."""
with store.at(me):
keys = {
"바탕": _sk(바탕={"로직": FORM}, 입력값={"유형": "복잡", "사용횟수": "3회"}),
"율": _sk(바탕={"로직": SUB}, 단위="주", 더한줄=[{**RATE, "수량": 2}]),
"기계": _sk(바탕={"로직": DIG}, 단위="㎥"),
"재료": _sk(바탕={"로직": NET}, 입력값=NET_IN),
}
keys["형제"] = _sk(바탕={"참조": {**MINE, "키": keys["바탕"]}})
keys["따로"] = _sk(바탕={"로직": PCT})
read = sk_path.read(keys["따로"])
twice = copy.deepcopy(read["문서"])
twice["금액"][0]["수량"] = f"({twice['금액'][0].get('수량') or 1}) × 2"
sk_path.save(keys["따로"], {"문서": twice, "판": read["판"]})
row, src = _bonghwa()
keys["가져온"] = imported.create(row, src, "sub6임시 가져온")["이름"]
sc = {
"이름": "sub6임시 일위대가",
"단위": "㎡",
"담은로직": [
{"참조": {**MINE, "키": keys["바탕"]}, "수량": {"손": 1}},
FIXED,
{"로직": STONE, "입력값": {}, "수량": {"손": 1}},
],
"자재": [{"코드": "MT003810", "수량": {"손": 2}}],
}
keys["일위대가"] = refs.create("precombo", sc)["이름"]
return keys
def _structure(world, keys: dict[str, str], root: Path) -> None:
"""구조물 사본(pipe@100.0) — 일위대가 열 문서를 지금 사본 길(`labor_doc_rows` · `price_bundle`)로."""
me = world["personal"]
lines = [
{"참조": {**MINE, "키": keys[k]}, "수량": {"손": q}}
for k, q in (("바탕", 2), ("율", 1), ("형제", 1), ("따로", 1), ("가져온", 1), ("기계", 3))
]
lines += [
{"참조": {**MINE, "키": keys["재료"]}, "수량": {"손": 1}},
{"참조": {**MINE, "키": keys["일위대가"]}, "수량": {"손": 1}},
{"로직": STONE, "입력값": {}, "수량": {"손": 1}},
{"로직": TWO_MATS, "수량": {"손": 1}},
]
with store.at(me):
doc = labor.clean(
{"열": "rv", "담은로직": lines, "자재": [{"코드": "MT003810", "수량": {"손": 2}}]}
)
rows = source.labor_doc_rows(doc)
files = {
source.LABOR_FILE: rows,
source.PRICE_FILE: source.price_bundle(rows, me),
snapshots.VALUES_FILE: {STONE: {"높이": {"값": 1.5}}},
snapshots.PICKS_FILE: {TWO_MATS: {"1": "MT003196", "2": "MT003173"}},
snapshots.MANIFEST_NAME: {"원본": {**_item("SS000901"), "경로": ["x"]}},
}
folder = snapshots.structures_dir(root) / snapshots.folder_name("pipe@100.0")
folder.mkdir(parents=True)
for name, data in files.items():
text = json.dumps(data, ensure_ascii=False, default=str)
(folder / name).write_text(text, encoding="utf-8")
HAND = [
{"key": "hand:rate", "section": "1.1", "after": "", "spec": "", "name": "율 줄", "unit": "㎡", "qty": 2,
"ref": {"tab": "logic", "code": PCT, "given": {}, "rate": None, "picks": None}},
{"key": "hand:pick", "section": "1.1", "after": "hand:rate", "spec": "", "name": "고른 재료", "unit": "㎡", "qty": 1,
"ref": {"tab": "logic", "code": TWO_MATS, "given": {}, "rate": None, "picks": {"1": "MT003196", "2": "MT003173"}}},
{"key": "hand:net", "section": "1.1", "after": "hand:pick", "spec": "", "name": "입력", "unit": "㎡", "qty": 3,
"ref": {"tab": "logic", "code": NET, "given": NET_IN, "rate": 90, "picks": None}},
] # fmt: skip
HAUL_REF = {"tab": "logic", "code": HAUL, "name": "골재운반", "given": {"Cm": 1}, "cycle": {}}
USER = {
"bill": {"qty": {}, "rows": HAND},
"haul_refs": {"haul:r-u1": HAUL_REF},
"haul_dist": {"haul:r-u1": {"L1": 25.1, "L2": 0.8}},
}
def _clean(value, root: Path):
"""지문 꼴 — 임시 경로 · 때(날짜 · 시각)는 지움 · 수는 글로."""
text = json.dumps(value, ensure_ascii=False, sort_keys=True, default=str)
text = text.replace(str(root).replace("\\", "\\\\"), "<root>").replace(str(root), "<root>")
return re.sub(
r"\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?", "<때>", text
)
def _split_text(value):
"""(값, 글) — 산출근거 글(`text` · `head` · `foot` · `lines` 글 목록)을 따로 떼어 지문을 나눔."""
words = []
def walk(v):
if isinstance(v, dict):
out = {}
for k, x in v.items():
if k in ("text", "head", "foot"):
words.append(x)
else:
out[k] = walk(x)
return out
if isinstance(v, list):
return [walk(x) for x in v]
return v
return walk(value), words
def answers(world, tmp_path) -> dict[str, object]:
keys = _layer_samples(world["personal"])
root = _project(tmp_path / "proj", [(100, "SS000901")])
_structure(world, keys, root)
for kind, key in (
("sangeun", keys["따로"]),
("sangeun", keys["가져온"]),
("precombo", keys["일위대가"]),
):
library.import_copy(root, kind, "personal", OWNER, key)
b09_store.write_user(root, USER)
haul = {k: USER[k] for k in ("haul_refs", "haul_dist")} # 운반 연결 = 셈 때 거리이정표에서 붙음
user = {**b09_store.read_user(root), **haul}
out: dict[str, object] = {"키": keys}
out["calc_user"] = b09.calc_user(root)
out["daega_inputs"] = daega_inputs(root)
out["수요"] = asyncio.run(b09._demand(root))
for name, supply in (("산근", None), ("산근 관급", lambda _k: "관급")):
sg = sangeun.build(root, user, None, supply)
out[f"{name} 값"], out[f"{name} 글"] = _split_text(sg)
for row in HAND:
ref = row["ref"]
body = b09.PreviewBody(
code=ref["code"], given=ref["given"], rate=ref["rate"], picks=ref["picks"]
)
got = b09.logic_preview(root, body)
got, words = _split_text(got)
out[f"미리보기 {row['key']} 값"] = {k: v for k, v in got.items() if k != "lines"}
out[f"미리보기 {row['key']} 글"] = [got.get("lines"), words]
linked = snapshots.linked_snapshots(root)
summary = {
"linked": linked,
"sources": [["rv:x", 12.0, folder, ["system||SS000901"]] for folder in sorted(linked)],
"total": {"rv:x": 12.0},
}
out["B08 단위수량"] = b08.snapshot_units(root, summary)
return {k: _clean(v, root) for k, v in out.items()}
def _hash(text: str) -> str:
return hashlib.sha256(text.encode("utf-8")).hexdigest()[:16]
@pytest.fixture(autouse=True)
def _manual(monkeypatch):
"""자동 따라옴 끔 — 저장본 그대로(층 꼴만 봄 · 자동은 test_836_2)."""
from M02_MasterTemplete import M02_Sk_AutoRenew as renew
monkeypatch.setattr(renew, "on", lambda: False)
def test_B08_B09_답_지문_같음(world, tmp_path):
got = {k: _hash(v) for k, v in answers(world, tmp_path).items()}
if WRITE:
body = {"판": 1, "지문": got}
FILE.write_text(json.dumps(body, ensure_ascii=False, indent=1) + "\n", "utf-8")
want = json.loads(FILE.read_text("utf-8"))["지문"]
bad = sorted(k for k in want.keys() | got.keys() if want.get(k) != got.get(k))
assert not bad, (
f"B08 · B09 답 지문 다름 — {bad}\n"
f"뜻대로 금액 · 글을 바꾼 걸음이면 다시 뜸: {REDO} (아니면 고친 코드를 되짚음)"
)
if __name__ == "__main__":
if "--write" not in sys.argv:
sys.exit(f"다시 뜨기 = {REDO}")
os.environ["S855B09_WRITE"] = "1"
import tempfile
temp = str(Path(tempfile.gettempdir()) / "s855b09_pt") # 공용 임시 폴더 권한 막힘 피함
sys.exit(pytest.main([__file__, "-q", "-p", "no:cacheprovider", "--basetemp", temp]))