From 1054787846e3b50ccfd39f8bb910f7186265dc9d Mon Sep 17 00:00:00 2001 From: YokiiroBW Date: Mon, 6 Jul 2026 04:12:43 +0800 Subject: [PATCH] =?UTF-8?q?S116=20PG=E8=BF=81=E7=A7=BB=E7=83=9F=E6=B5=8B?= =?UTF-8?q?=E8=84=9A=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/__init__.py | 1 + scripts/imagestudio_pg_smoke.py | 77 +++++++++++++++++++++++++++++++ tests/test_pg_smoke.py | 81 +++++++++++++++++++++++++++++++++ 3 files changed, 159 insertions(+) create mode 100644 scripts/__init__.py create mode 100644 scripts/imagestudio_pg_smoke.py create mode 100644 tests/test_pg_smoke.py diff --git a/scripts/__init__.py b/scripts/__init__.py new file mode 100644 index 0000000..6b164c9 --- /dev/null +++ b/scripts/__init__.py @@ -0,0 +1 @@ +"""Operational scripts for ImageStudio.""" diff --git a/scripts/imagestudio_pg_smoke.py b/scripts/imagestudio_pg_smoke.py new file mode 100644 index 0000000..d242e80 --- /dev/null +++ b/scripts/imagestudio_pg_smoke.py @@ -0,0 +1,77 @@ +"""PostgreSQL migration smoke entrypoint. + +The script intentionally prints only redacted configuration state. It can be +used as a dry-run plan in unit tests, or pointed at a real PG config for a live +migration and seed smoke. +""" + +from __future__ import annotations + +import argparse +import json +import os +import sys +from pathlib import Path +from typing import Any + +REPO_ROOT = Path(__file__).resolve().parents[1] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +from database.db_helper import Database, load_database_settings +from database.seed import seed_default_material_categories + + +def build_pg_smoke_plan(config_path: str | Path = "config.yaml") -> dict[str, Any]: + settings = load_database_settings(config_path) + pg = settings.postgresql + return { + "config_path": "***PATH***", + "selected_backend": settings.selected_backend, + "postgresql_configured": pg.is_configured, + "postgresql_enabled": pg.enabled, + "connection_mode": "dsn" if pg.dsn else "host", + "host_set": bool(pg.host), + "database_set": bool(pg.database), + "user_set": bool(pg.user), + "password_set": bool(pg.password), + } + + +def run_pg_smoke(config_path: str | Path = "config.yaml", *, dry_run: bool = False) -> dict[str, Any]: + plan = build_pg_smoke_plan(config_path) + if dry_run: + return {"ok": True, "dry_run": True, "plan": plan} + if plan["selected_backend"] != "postgresql" or not plan["postgresql_configured"]: + raise RuntimeError("PostgreSQL smoke requires a configured PostgreSQL backend") + database = Database(load_database_settings(config_path)) + database.initialize() + seed_result = seed_default_material_categories(database) + conn = database.connect() + try: + migrations = conn.execute("SELECT COUNT(*) AS total FROM schema_migrations").fetchone()["total"] + categories = conn.execute("SELECT COUNT(*) AS total FROM material_categories").fetchone()["total"] + finally: + conn.close() + return { + "ok": True, + "dry_run": False, + "plan": plan, + "migrations_applied": int(migrations), + "seed": seed_result, + "material_categories": int(categories), + } + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Run ImageStudio PostgreSQL migration smoke.") + parser.add_argument("--config", default=os.environ.get("IMAGESTUDIO_CONFIG", "config.yaml")) + parser.add_argument("--dry-run", action="store_true") + args = parser.parse_args(argv) + result = run_pg_smoke(args.config, dry_run=args.dry_run) + print(json.dumps(result, ensure_ascii=False, sort_keys=True)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/test_pg_smoke.py b/tests/test_pg_smoke.py new file mode 100644 index 0000000..de61b2c --- /dev/null +++ b/tests/test_pg_smoke.py @@ -0,0 +1,81 @@ +from __future__ import annotations + +import os +import tempfile +import unittest +from pathlib import Path + +from scripts.imagestudio_pg_smoke import build_pg_smoke_plan, run_pg_smoke + + +class PostgresSmokeTests(unittest.TestCase): + def test_pg_smoke_plan_redacts_config_and_reports_connection_shape(self): + with tempfile.TemporaryDirectory() as tmp: + config_path = Path(tmp) / "config.yaml" + config_path.write_text( + """ +database: + backend: postgresql + postgresql: + enabled: true + host: localhost + port: 5432 + database: imagestudio_test + user: imagestudio + password: super-secret +""", + encoding="utf-8", + ) + + plan = build_pg_smoke_plan(config_path) + + self.assertEqual(plan["config_path"], "***PATH***") + self.assertEqual(plan["selected_backend"], "postgresql") + self.assertTrue(plan["postgresql_configured"]) + self.assertEqual(plan["connection_mode"], "host") + self.assertTrue(plan["password_set"]) + self.assertNotIn("super-secret", str(plan)) + self.assertNotIn(str(config_path), str(plan)) + + def test_pg_smoke_dry_run_does_not_connect(self): + with tempfile.TemporaryDirectory() as tmp: + config_path = Path(tmp) / "config.yaml" + config_path.write_text( + """ +database: + backend: sqlite +""", + encoding="utf-8", + ) + + result = run_pg_smoke(config_path, dry_run=True) + + self.assertTrue(result["ok"]) + self.assertTrue(result["dry_run"]) + self.assertEqual(result["plan"]["selected_backend"], "sqlite") + + @unittest.skipUnless(os.environ.get("IMAGESTUDIO_TEST_PG_DSN"), "IMAGESTUDIO_TEST_PG_DSN is not set") + def test_live_pg_smoke_from_env_dsn(self): + with tempfile.TemporaryDirectory() as tmp: + config_path = Path(tmp) / "config.yaml" + config_path.write_text( + f""" +database: + backend: postgresql + postgresql: + enabled: true + dsn: "{os.environ["IMAGESTUDIO_TEST_PG_DSN"]}" +""", + encoding="utf-8", + ) + + result = run_pg_smoke(config_path) + + self.assertTrue(result["ok"]) + self.assertFalse(result["dry_run"]) + self.assertGreaterEqual(result["migrations_applied"], 1) + self.assertGreaterEqual(result["material_categories"], 1) + + +if __name__ == "__main__": + unittest.main()