"""Redaksi Sub-CPMK tersesuaikan (sub_uraian_custom, dari OBE-Mapping) tidak hilang saat RPS dibuka, disimpan ulang, autosave, dan diunduh. Memakai DB hasil gladi migrasi (tests/migrasi.db).""" import io, os, re, sys from urllib.parse import urlencode os.environ["DB_PATH"] = os.path.join(os.path.dirname(os.path.abspath(__file__)), "migrasi.db") sys.path.insert(0, sys.argv[1]) from docx import Document from fastapi.testclient import TestClient from app import main, db, auth gagal = [] def cek(ok, pesan): print(("OK " if ok else "GAGAL"), pesan) if not ok: gagal.append(pesan) kode = next(r["mk_kode"] for r in db.get_conn().execute("SELECT mk_kode, data FROM rps") if len(__import__("json").loads(r["data"]).get("sub_uraian_custom") or {}) >= 2) lama = db.ambil_rps(kode)["data"] custom = lama["sub_uraian_custom"] koor = db.papan_kelas(db.tahun_aktif())[kode]["koordinator"] t = auth.token_baru(); db.buat_sesi(koor, t) c = TestClient(main.app); c.cookies.set("sesi", t) h = c.get(f"/rps/{kode}").text cek(all(teks in h for teks in custom.values()), f"{kode}: {len(custom)} redaksi tersesuaikan tampil di form") cek(h.count("disesuaikan") == len(custom), "penanda 'disesuaikan' muncul pada setiap Sub-CPMK yang diubah") # kirim ulang seluruh isi form apa adanya (seperti dosen menekan Simpan tanpa mengubah apa pun) from html.parser import HTMLParser class P(HTMLParser): def __init__(s): super().__init__(); s.isi = []; s.ta = None; s.sel = None def handle_starttag(s, tag, a): a = dict(a) if tag == "input" and a.get("name") and a.get("type") not in ("submit", "button", "file"): if a.get("type") in ("checkbox", "radio") and "checked" not in a: return s.isi.append((a["name"], a.get("value", ""))) elif tag == "textarea" and a.get("name"): s.ta = [a["name"], ""] elif tag == "select" and a.get("name"): s.sel = a["name"] elif tag == "option" and s.sel and "selected" in a: s.isi.append((s.sel, a.get("value", ""))) def handle_data(s, d): if s.ta: s.ta[1] += d def handle_endtag(s, tag): if tag == "textarea" and s.ta: s.isi.append(tuple(s.ta)); s.ta = None if tag == "select": s.sel = None p = P(); p.feed(h) isi = [(k, v) for k, v in p.isi if not k.startswith("_")] + [("aksi", "draft")] r = c.post(f"/rps/{kode}", content=urlencode(isi), follow_redirects=False, headers={"Content-Type": "application/x-www-form-urlencoded"}) baru = db.ambil_rps(kode)["data"] cek(baru.get("sub_uraian_custom") == custom, "simpan ulang: redaksi tersesuaikan utuh") cek(baru["minggu"] == lama["minggu"] and baru["komponen"] == lama["komponen"] and baru["identitas"] == lama["identitas"], "simpan ulang: rencana mingguan, komponen, identitas tidak berubah") # SEMUA RPS produksi: buka → simpan ulang tanpa perubahan → isi identik import json as _j for mk, in [tuple(r) for r in db.get_conn().execute("SELECT mk_kode FROM rps")]: if mk == kode: continue k_id = db.papan_kelas(db.tahun_aktif()).get(mk, {}).get("koordinator") or next( r[0] for r in db.get_conn().execute("SELECT id FROM pengguna WHERE role='kaprodi'")) tt = auth.token_baru(); db.buat_sesi(k_id, tt); c2 = TestClient(main.app); c2.cookies.set("sesi", tt) sebelum = db.ambil_rps(mk)["data"] pp = P(); pp.feed(c2.get(f"/rps/{mk}").text) kirim = [(k, v) for k, v in pp.isi if not k.startswith("_")] + [("aksi", "draft")] c2.post(f"/rps/{mk}", content=urlencode(kirim), follow_redirects=False, headers={"Content-Type": "application/x-www-form-urlencoded"}) sesudah = db.ambil_rps(mk)["data"] beda = [b for b in sebelum if _j.dumps(sebelum[b], sort_keys=True).replace("\r\n", "\n") != _j.dumps(sesudah.get(b), sort_keys=True).replace("\r\n", "\n")] cek(not beda, f"{mk}: buka + simpan ulang tanpa perubahan → isi identik {beda}") # kunci asing dipertahankan with db.get_conn() as conn: d = dict(baru); d["kunci_versi_lain"] = {"x": 1} conn.execute("UPDATE rps SET data=? WHERE mk_kode=? AND tahun=?", (__import__("json").dumps(d), kode, db.tahun_aktif())) c.post(f"/rps/{kode}", content=urlencode(isi), follow_redirects=False, headers={"Content-Type": "application/x-www-form-urlencoded"}) cek(db.ambil_rps(kode)["data"].get("kunci_versi_lain") == {"x": 1}, "kunci data dari versi lain dipertahankan saat simpan") # unduhan memakai redaksi tersesuaikan r = c.get(f"/rps/{kode}/unduh") teks = "\n".join(p.text for p in Document(io.BytesIO(r.content)).paragraphs) teks += "\n".join(cell.text for tb in Document(io.BytesIO(r.content)).tables for row in tb.rows for cell in row.cells) contoh = next(iter(custom.values())) cek(r.status_code == 200 and contoh[:60] in teks, "RPS unduhan memakai redaksi tersesuaikan") print("TOTAL GAGAL:", len(gagal)); sys.exit(1 if gagal else 0)