Files
Aislo/resources/tester/test_m01_combo.py
T
eomsangdonandClaude Opus 5.5 8c3801e707 refactor(853-1): M01 화면 0 서버 길 15 와 본체 걷음 — 묶음 ② 고친 파일(앞 커밋 654b75b5c 는 지운 파일만 담김)
- 길 지움(화면 TS · 다른 서버 모듈 · 시험 세 곳에서 다시 찾음 · /openapi.json 524 → 509 뜻한 15 만): GET /groups · /sections · /table/options · /logic/combos · POST /logic/new · /logic/edit · /logic/delete · /logic/draft · /logic/sheet · /logic/sheet/check · /logic/equation(+ preview · links · save) · /logic/doc/links
- 본체 지움: M01_MasterData_Sheet.py · Equation.read · preview · save · Store_Make.sections · _counts · table_options · logic_edit · logic_delete · _own_only · logic_draft · Store.groups · Store_Combo.combo_preview · scripts/master_draft.py(지운 /logic/draft 만 부름)
- 남김: Equation.export_row · edit_row · links(M02 Sangeun_Equation 이 부름) · Doc.candidates(M02 /doc/links) · Store_Make._all_sections(M02 Hopyo_Clause) · logic_new(복사 · 수식 저장이 씀) · combos_of_logic(Doc.users) · combo_inputs(알약 규칙 입구 · 시험) · master_combo.run(M02 시험 대조 값) · /alias/suggest(main.py 가 따로 끼움 · 승인 화면과 한 벌)
- 화면 입구 지움: Api_Fetch.fetchGroups · GroupInfo · fetchSubs · Logic_Api.draftLogic + Draft 타입 6
- 시험: test_m01_draft 지움(죽은 해석기 · 길만 봄) · test_794_1 시트 길 시험 지우고 /save 다시 셈 시험만 남김 · test_796_1 수식 길 시험 지움 · test_800_2 는 살아 있는 export_row · edit_row 로 같은 셈 · test_m01_make 는 죽은 길 대신 /save · logic_new 로 같은 결과 · test_m01_combo 미리 보기 시험 지움 · /logic/combos 는 combos_of_logic 로 · test_m01_api · test_802_3 · test_799_2 · test_717_1(+helper) 죽은 길 줄만 고침

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

290 lines
12 KiB
Python

"""일위대가 조합(PLAN 4-2 · 27-2a) — 담은 단가산출 로직 목록만 둠.
읽기 = M02 조합 저장소(`combos.one` · `combos.listing` · 서버 길은 없앰 732-1).
계약 `resources/master_data/_화면_계약.md` 9장 · 틀 `_틀.md` 10장 · 엔진 `scripts/master_combo.py`.
못박는 것
- 조합은 이름과 담은 로직 목록만 지님 — 수량·비율·계산 칸을 두지 않음.
- 검사 — 없는 로직 키 · 같은 로직 두 번 · 빈 조합 · 조합이 조합을 담음.
- 시험은 임시 사본에서 돌고, 사본의 조합 줄은 비워 시작 — 정본에 견본 조합이 있어도 없어도 같음.
"""
from __future__ import annotations
import json
import shutil
import sys
from pathlib import Path
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from common_util.common_util_auth import verify_session
from M01_MasterData import M01_MasterData_Router as router_module
from M01_MasterData import M01_MasterData_Store as store
from M01_MasterData import M01_MasterData_Store_Combo as combo_store
from M02_MasterTemplete import M02_MasterTemplete_Combo_Store as combos
from M02_MasterTemplete import M02_MasterTemplete_Store as m02
from M02_MasterTemplete.M02_MasterTemplete_Router_Combos import router as combos_router
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "master_data/scripts"))
import master_combo as mcb # noqa: E402
REAL = store.FOLDER
STACK = "GF000219" # 13-4-1 돌쌓기 메쌓기(인력)
LAYER = "GF000220" # 13-4-2 돌쌓기 메쌓기(장비)
GATHER = "GF000211" # 13-2-1 모래·자갈·약돌 채집(인력)
SAMPLE = (STACK, LAYER, GATHER) # 견본 조합 — 로직 셋
ADMIN = {"user_id": 1, "company_id": 1, "role": "SYSTEM_ADMIN", "is_master": False}
@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)
own = tmp_path / mcb.FILE # 정본의 견본 조합이 시험 줄 수에 끼지 않게 사본은 비워 시작
data = json.loads(own.read_text(encoding="utf-8"))
data["줄"] = []
data.pop("폴더", None) # 사용자가 화면으로 만든 빈 폴더 목록(정본 머리)도 안 물려받음
own.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
monkeypatch.setattr(store, "FOLDER", tmp_path)
app = FastAPI()
app.include_router(router_module.router)
app.include_router(combos_router)
app.dependency_overrides[verify_session] = lambda: ADMIN
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 _new(client: TestClient, body: dict, want: int = 200) -> dict:
"""옛 `/combo/new` 본문 `{combo, owner?}` → 마스터 조합 저장소(만들기 길은 은퇴 39-1d ·
소유는 줄 칸) · 옛 이름 `key` 도 붙임."""
combo = {**body["combo"], **({"소유": body["owner"]} if "owner" in body else {})}
try:
got = combos.create(combo)
except m02.StoreError as error:
assert error.status == want, error.detail
return {"detail": error.detail}
assert want == 200
return {"key": got.get("키"), **got}
def _one(client: TestClient, key: str) -> dict:
got = combos.one(key)
return {"version": got["판"], **got}
def _list(client: TestClient) -> list[dict]:
return combos.listing()["줄"]
def _edit(client: TestClient, key: str, version: str, row: dict, want: int = 200) -> dict:
"""조합 고치기 길(PUT)은 은퇴(39-1d) — 저장소 함수(실무문서 고치기)를 바로 부름."""
try:
done = combo_store.combo_edit(key, version, row, row.get("소유") or "")
except store.StoreError as error:
assert error.status == want, error.detail
return {"detail": error.detail}
assert want == 200
return done
def _make(client: TestClient, keys=SAMPLE, 이름="돌쌓기 한 벌", owner: str = "현장") -> dict:
body = {
"이름": 이름,
"구분": "자체",
"상세구분": "13장 구조물",
"단위": "㎡",
"담은로직": [{"로직": k, "메모": None} for k in keys],
}
return _new(client, {"combo": body, "owner": owner})
# ── 정본 파일 ─────────────────────────────────────────────────────────
def test_정본_조합_파일은_틀대로다() -> None:
"""줄 수는 못 박지 않음 — 견본이 있어도 없어도 됨 · 줄은 조합 키(UA)와 열 한 벌만."""
data = store.cm.load([mcb.FILE], folder=REAL)[mcb.FILE]
assert data["그룹"] == mcb.GROUP
assert all(row["키"].startswith("UA") and set(row) <= set(mcb.COLS) for row in data["줄"])
assert "원문" not in data # 관리자가 만드는 것이라 원문 근거가 없음
def test_조합_테이블ID_는_UA_이고_줄에_원문번호를_두지_않는다() -> None:
assert store.mk.table_id(mcb.GROUP, None) == "UA"
assert store.mk.GROUP_OF["UA"] == mcb.GROUP
assert "UA" in store.mk.NO_NUMBER
def test_조합은_요소_그룹이_아니다(client: TestClient) -> None:
"""조합은 제 길(`/combos`·`/combo`)로만 다룸 — 요소 길(`/groups/…/files`·`/rows`)에 끼지 않음.
끼우면 화면이 조합을 여느 요소 표처럼 `/rows` 로 펴 버림(줄 모양이 아주 다름).
"""
assert mcb.GROUP not in store.cm.mf.GROUPS
assert client.get("/api/m01/groups/일위대가조합/files").status_code == 404
# ── 만들기 · 읽기 ─────────────────────────────────────────────────────
def test_조합을_만들면_키를_서버가_주고_담은_로직에_이름이_붙는다(client: TestClient) -> None:
made = _make(client)
key = made["key"]
assert key.startswith("UA"), made
assert made["combo"]["소유"] == "현장"
assert tuple(made["combo"]) == mcb.COLS # 열 한 벌 · 차례까지
assert "원문번호" not in made["combo"]
got = _one(client, key)
assert [one["로직"] for one in got["줄"]] == list(SAMPLE) # 담은 차례 그대로
assert got["줄"][0]["이름"] == "돌쌓기 메쌓기(인력)"
assert got["줄"][0]["결과단위"] == "원/㎡"
assert got["blocked"] is False and got["reasons"] == []
# 수량·비율·계산은 조합에 두지 않음
assert set(got["combo"]["담은로직"][0]) == {"로직", "메모"}
def test_목록은_소유_담은_수_폴더를_준다(client: TestClient) -> None:
"""거르기(구분 · 소유 · 찾기)는 화면 몫 — 층 목록은 통째 · 폴더 = [구분, 상세구분]."""
_make(client, 이름="돌쌓기 한 벌")
_make(client, keys=(GATHER,), 이름="채집만", owner="공용")
got = combos.listing()
assert len(got["줄"]) == 2 and got["판"]
only = [c for c in got["줄"] if c["소유"] == "공용"]
assert [c["이름"] for c in only] == ["채집만"] and only[0]["count"] == 1
assert "담은로직" not in only[0]
assert got["폴더"] == [["자체"], ["자체", "13장 구조물"]]
def test_이_로직을_쓰는_조합을_거꾸로_본다(client: TestClient) -> None:
first = _make(client, 이름="돌쌓기 한 벌")["key"]
second = _make(client, keys=(STACK,), 이름="메쌓기만")["key"]
got = combo_store.combos_of_logic(STACK) # 로직 지우기 전 쓰는 곳(`Doc.users`)이 부름
assert [c["키"] for c in got["combos"]] == [first, second]
assert got["combos"][0]["차례"] == [1] # 그 조합 안 몇 번째인지
assert combo_store.combos_of_logic("GF000001")["combos"] == []
# ── 고치기 · 지우기 ───────────────────────────────────────────────────
def test_로직을_빼고_더하고_지울_수_있다(client: TestClient) -> None:
key = _make(client)["key"]
got = _one(client, key)
row = got["combo"]
row["담은로직"] = [{"로직": LAYER, "메모": "장비만 남김"}]
done = _edit(client, key, got["version"], row)
assert [one["로직"] for one in done["combo"]["담은로직"]] == [LAYER]
assert done["combo"]["담은로직"][0]["메모"] == "장비만 남김"
assert done["combo"]["키"] == key # 키는 안 바뀜
now = _one(client, key)
combos.delete(key, now["version"]) # 지우기 길은 은퇴(39-1d) — 저장소 함수로
assert _list(client) == []
def test_낡은_판본으로_고치면_409(client: TestClient) -> None:
key = _make(client)["key"]
row = _one(client, key)["combo"]
got = _edit(client, key, "낡은판본", row, want=409)
assert got["detail"] == {"stale": [mcb.FILE]}
# ── 검사 ──────────────────────────────────────────────────────────────
def test_없는_로직_키는_저장을_막는다(client: TestClient) -> None:
got = _new(
client,
{"combo": {"이름": "엉터리", "담은로직": [{"로직": "GF999999", "메모": None}]}},
want=422,
)
assert any("GF999999" in x for x in got["detail"]["errors"]), got
def test_같은_로직을_두_번_담으면_막는다(client: TestClient) -> None:
got = _new(
client,
{"combo": {"이름": "두 번", "담은로직": [{"로직": STACK}, {"로직": STACK}]}},
want=422,
)
assert any("두 번 담음" in x for x in got["detail"]["errors"]), got
def test_빈_조합은_막는다(client: TestClient) -> None:
got = _new(client, {"combo": {"이름": "빈 것", "담은로직": []}}, 422)
assert any("빈 조합" in x for x in got["detail"]["errors"]), got
def test_조합은_조합을_담지_못한다_1단만(client: TestClient) -> None:
key = _make(client)["key"]
got = _new(
client,
{"combo": {"이름": "겹친 것", "담은로직": [{"로직": key}]}},
want=422,
)
assert any("조합을 담지 못함" in x for x in got["detail"]["errors"]), got
def test_이름_없는_조합과_모르는_소유는_400(client: TestClient) -> None:
_new(client, {"combo": {"담은로직": [{"로직": STACK}]}}, want=400)
_new(
client,
{"combo": {"이름": "가", "담은로직": [{"로직": STACK}]}, "owner": "아무개"},
want=400,
)
def test_이름이_글자_아니면_400(client: TestClient) -> None:
"""재현: 이름 ["x"] 가 200 으로 저장됨(일감 24 어긋난 것 2) — 이제 400."""
_new(
client,
{"combo": {"이름": ["x"], "담은로직": [{"로직": STACK}]}},
want=400,
)
def test_이름이_너무_길면_막는다(client: TestClient) -> None:
got = _new(
client,
{"combo": {"이름": "가" * 61, "담은로직": [{"로직": STACK}]}},
want=422,
)
assert any("너무 김" in x for x in got["detail"]["errors"]), got
def test_같은_이름_두_번_담으면_막는다(client: TestClient) -> None:
_make(client, keys=(STACK,), 이름="돌쌓기 한 벌")
got = _new(
client,
{"combo": {"이름": "돌쌓기 한 벌", "담은로직": [{"로직": LAYER}]}},
want=422,
)
assert any("겹침" in x for x in got["detail"]["errors"]), got
def test_메모가_글자_아니면_막는다(client: TestClient) -> None:
"""재현: 메모 {"수량": 3} 이 200 으로 저장됨(일감 24 어긋난 것 1) — 이제 422."""
got = _new(
client,
{"combo": {"이름": "메모 흠", "담은로직": [{"로직": STACK, "메모": {"수량": 3}}]}},
want=422,
)
assert any("메모」 가 글자 아님" in x for x in got["detail"]["errors"]), got
def test_정본_로직은_조합을_만들어도_안_바뀐다(client: TestClient) -> None:
before = _get(client, "/api/m01/logic", key=STACK)
_make(client)
after = _get(client, "/api/m01/logic", key=STACK)
assert after["version"] == before["version"] and after["logic"] == before["logic"]