#!/usr/bin/env python3 """한땀 작업실 API 스모크 테스트 — 저장·커밋·되돌리기 왕복 검증.""" import json import sys import urllib.error import urllib.parse import urllib.request from pathlib import Path BASE = "http://127.0.0.1:8081" ROOT = Path.home() / "Projects/teamat" SLUG = "2026-10-whitework-tea-mat" MD = ROOT / "content/products" / f"{SLUG}.md" fails = [] def check(name, cond, extra=""): print(("OK " if cond else "FAIL ") + name + (f" {extra}" if extra and not cond else "")) if not cond: fails.append(name) def req(path, payload=None, raw=None, method=None): url = BASE + path data = None headers = {} if payload is not None: data = json.dumps(payload).encode() headers["Content-Type"] = "application/json" if raw is not None: data = raw headers["Content-Type"] = "application/octet-stream" request = urllib.request.Request(url, data=data, headers=headers, method=method or ("POST" if data else "GET")) try: with urllib.request.urlopen(request, timeout=120) as res: return res.status, json.loads(res.read().decode()) except urllib.error.HTTPError as error: body = error.read().decode() try: return error.code, json.loads(body) except json.JSONDecodeError: return error.code, {"raw": body} original = MD.read_text(encoding="utf-8") # 1. 목록 code, state = req("/api/state") check("GET /api/state", code == 200 and state["ok"] and state["count"] >= 3, str(code)) head0 = state["head"] # 2. 작품 열기 code, data = req(f"/api/product?slug={SLUG}") check("GET /api/product", code == 200 and data["product"]["fields"]["title"] == "목련 한 땀 티매트", str(code)) fields0 = data["product"]["fields"] body0 = data["product"]["body"] check("본문 읽힘", len(body0) > 50) check("추가 이미지 필드(빈 목록)", fields0["gallery"] == "") # 3. 변경 없이 저장 → 커밋하지 않아야 함 code, data = req("/api/product", {"slug": SLUG, "fields": fields0, "body": body0}) check("무변경 저장은 커밋 안 함", data["ok"] and data["changed"] is False, json.dumps(data)[:200]) # 4. 실제 수정 저장 (+ 추가 이미지 1장) fields = dict(fields0) fields["subtitle"] = "스모크 테스트 부제" fields["price"] = "59000" fields["gallery"] = "assets/img/2026-10-whitework-tea-mat/cover.jpg" code, data = req("/api/product", {"slug": SLUG, "fields": fields, "body": body0}) check("수정 저장 성공", data["ok"] and data.get("changed") is True, json.dumps(data)[:300]) sha = data.get("head", "") check("HEAD 이동", sha != head0, f"{head0} -> {sha}") text = MD.read_text(encoding="utf-8") check("파일 반영(subtitle)", "subtitle: 스모크 테스트 부제" in text) check("파일 반영(price 정수)", "price: 59000" in text, text[:400]) check("목록 형식 유지(gallery)", "gallery:\n- assets/img/2026-10-whitework-tea-mat/cover.jpg" in text, text[:600]) check("front matter 순서 유지", text.splitlines()[1].startswith("slug:"), text.splitlines()[1]) code, data = req("/api/history") check("이력에 수정 커밋", any("목련 한 땀 티매트" in row["subject"] for row in data["history"]), str(data["history"][:2])) # 5. 이미지 업로드 거부 (JPG 아님) code, data = req("/api/upload?name=x.png", raw=b"\x89PNG\r\n") check("PNG 업로드 거부", data["ok"] is False, json.dumps(data)) # 6. 잘못된 슬러그 code, data = req("/api/product?slug=../../etc/passwd") check("경로 조작 차단", code in (400, 404), str(code)) # 7. 되돌리기 code, data = req("/api/revert", {"sha": sha, "deploy": False}) check("되돌리기 성공", data["ok"] is True, json.dumps(data)[:300]) check("파일 원복", MD.read_text(encoding="utf-8") == original, "원본과 다름") # 8. 되돌린 뒤 무변경 저장은 다시 커밋하지 않아야 함 code, data = req(f"/api/product?slug={SLUG}") code, again = req("/api/product", {"slug": SLUG, "fields": data["product"]["fields"], "body": data["product"]["body"]}) check("원복 후 무변경", again["ok"] and again["changed"] is False, json.dumps(again)[:200]) print() print(f"{'실패 ' + str(len(fails)) + '건: ' + ', '.join(fails) if fails else '전부 통과'}") sys.exit(1 if fails else 0)