from __future__ import annotations import tempfile import unittest from pathlib import Path from backend.dto.common import ErrorCode, error_response, success_response from core.audit_service import AuditService from core.identity import RequestContext from database.db_helper import Database, DatabaseSettings, PostgresSettings, SqliteSettings class CommonDtoTests(unittest.TestCase): def test_success_response_matches_contract(self): response = success_response({"ready": True}, request_id="req_test") self.assertEqual( response, { "ok": True, "data": {"ready": True}, "warnings": [], "request_id": "req_test", }, ) def test_error_response_matches_contract(self): response = error_response( error_code=ErrorCode.VALIDATION_FAILED, message="缺少字段", details={"field": "name"}, request_id="req_test", ) self.assertEqual(response["ok"], False) self.assertEqual(response["error_code"], "VALIDATION_FAILED") self.assertEqual(response["message"], "缺少字段") self.assertEqual(response["details"], {"field": "name"}) self.assertEqual(response["request_id"], "req_test") class DatabaseSettingsTests(unittest.TestCase): def test_sqlite_is_default_backend(self): settings = DatabaseSettings() self.assertEqual(settings.selected_backend, "sqlite") def test_postgres_is_selected_when_configured(self): settings = DatabaseSettings( backend="auto", postgresql=PostgresSettings( enabled=True, host="localhost", database="imagestudio", user="imagestudio", ), ) self.assertEqual(settings.selected_backend, "postgresql") def test_forced_sqlite_ignores_configured_postgres(self): settings = DatabaseSettings( backend="sqlite", postgresql=PostgresSettings(enabled=True, dsn="postgresql://example"), ) self.assertEqual(settings.selected_backend, "sqlite") class AuditServiceTests(unittest.TestCase): def test_record_writes_audit_log_to_sqlite(self): with tempfile.TemporaryDirectory() as tmp: db_path = Path(tmp) / "imagestudio.db" settings = DatabaseSettings(sqlite=SqliteSettings(path=str(db_path))) database = Database(settings) database.initialize() ctx = RequestContext.system() record = AuditService(database).record( ctx=ctx, action="unit_test", target_type="test_target", target_id="target_001", after_snapshot={"ok": True}, ) conn = database.connect() try: row = conn.execute( "SELECT action, target_type, target_id FROM audit_logs WHERE audit_id = ?", (record.audit_id,), ).fetchone() finally: conn.close() self.assertIsNotNone(row) self.assertEqual(row["action"], "unit_test") self.assertEqual(row["target_type"], "test_target") self.assertEqual(row["target_id"], "target_001") if __name__ == "__main__": unittest.main()