from __future__ import annotations import tempfile import unittest from pathlib import Path from backend.dto.common import ApiError, ErrorCode from backend.services.profile_service import ProfileService from core.audit_service import AuditService from core.identity import RequestContext from database.db_helper import Database, DatabaseSettings, SqliteSettings from database.repositories.profile_repository import ProfileRepository class ProfileServiceTests(unittest.TestCase): def setUp(self): self.tmp = tempfile.TemporaryDirectory() db_path = Path(self.tmp.name) / "imagestudio.db" self.database = Database(DatabaseSettings(sqlite=SqliteSettings(path=str(db_path)))) self.database.initialize() self.service = ProfileService( repository=ProfileRepository(self.database), audit_service=AuditService(self.database), ) self.ctx = RequestContext.from_astrbot( username="admin", user_id="user_001", permissions={"can_write"}, ) def tearDown(self): self.tmp.cleanup() def test_create_profile_writes_profile_and_audit_log(self): profile = self.service.create_profile( { "name": "莉娅", "description": "银白发少女", "appearance_prompt": "silver long hair, blue eyes", "default_model_route": "image_low", "metadata": {"source": "unit_test"}, }, self.ctx, ) self.assertTrue(profile.profile_id.startswith("profile_")) self.assertEqual(profile.name, "莉娅") self.assertEqual(profile.owner_user_id, "user_001") self.assertEqual(profile.metadata, {"source": "unit_test"}) conn = self.database.connect() try: audit = conn.execute( """ SELECT action, target_type, target_id FROM audit_logs WHERE target_id = ? """, (profile.profile_id,), ).fetchone() finally: conn.close() self.assertIsNotNone(audit) self.assertEqual(audit["action"], "create_profile") self.assertEqual(audit["target_type"], "character_profile") def test_update_profile_changes_fields_and_writes_audit_log(self): profile = self.service.create_profile({"name": "莉娅"}, self.ctx) updated = self.service.update_profile( profile.profile_id, { "name": "莉娅 Nova", "style_prompt": "anime impasto", }, self.ctx, ) self.assertEqual(updated.name, "莉娅 Nova") self.assertEqual(updated.style_prompt, "anime impasto") conn = self.database.connect() try: count = conn.execute( """ SELECT COUNT(*) AS total FROM audit_logs WHERE target_id = ? AND action = 'update_profile' """, (profile.profile_id,), ).fetchone()["total"] finally: conn.close() self.assertEqual(count, 1) def test_delete_profile_soft_deletes_and_hides_from_get(self): profile = self.service.create_profile({"name": "莉娅"}, self.ctx) deleted = self.service.delete_profile(profile.profile_id, self.ctx) self.assertEqual(deleted.status, "deleted") with self.assertRaises(ApiError) as raised: self.service.get_profile(profile.profile_id) self.assertEqual(raised.exception.error_code, ErrorCode.RESOURCE_NOT_FOUND) def test_list_profiles_is_scoped_to_actor(self): own = self.service.create_profile({"name": "莉娅"}, self.ctx) other_ctx = RequestContext.from_astrbot(username="guest", user_id="user_002") self.service.create_profile({"name": "诺亚"}, other_ctx) result = self.service.list_profiles(ctx=self.ctx) self.assertEqual(result.total, 1) self.assertEqual(result.items[0].profile_id, own.profile_id) def test_profile_owner_is_derived_from_context_and_cross_owner_access_is_hidden(self): profile = self.service.create_profile( {"name": "莉娅", "owner_user_id": "attacker_selected_owner"}, self.ctx, ) other_ctx = RequestContext.from_astrbot( username="guest", user_id="user_002", permissions={"can_write"}, ) self.assertEqual(profile.owner_user_id, "user_001") for operation in ( lambda: self.service.get_profile(profile.profile_id, other_ctx), lambda: self.service.update_profile(profile.profile_id, {"name": "stolen"}, other_ctx), lambda: self.service.delete_profile(profile.profile_id, other_ctx), ): with self.assertRaises(ApiError) as raised: operation() self.assertEqual(raised.exception.error_code, ErrorCode.RESOURCE_NOT_FOUND) def test_wildcard_permission_does_not_bypass_profile_ownership(self): profile = self.service.create_profile({"name": "莉娅"}, self.ctx) system_like_other_user = RequestContext.from_astrbot( username="root", user_id="user_999", permissions={"*"}, ) with self.assertRaises(ApiError) as raised: self.service.get_profile(profile.profile_id, system_like_other_user) self.assertEqual(raised.exception.error_code, ErrorCode.RESOURCE_NOT_FOUND) def test_profile_repository_pagination_is_normalized(self): for index in range(3): self.service.create_profile({"name": f"Nova {index}"}, self.ctx) zero_size = self.service.repository.list(owner_user_id=self.ctx.actor_id, page=0, page_size=0) huge_size = self.service.repository.list(owner_user_id=self.ctx.actor_id, page=1, page_size=999) self.assertEqual(zero_size.page, 1) self.assertEqual(zero_size.page_size, 1) self.assertEqual(len(zero_size.items), 1) self.assertEqual(huge_size.page_size, 100) self.assertEqual(huge_size.total, 3) def test_profile_list_reports_generation_kind_from_workflow_types(self): text_profile = self.service.create_profile({"name": "纯文本"}, self.ctx) quick_draft_profile = self.service.create_profile({"name": "快速档案文本"}, self.ctx) quick_profile = self.service.create_profile({"name": "快速角色"}, self.ctx) detailed_profile = self.service.create_profile({"name": "详细角色"}, self.ctx) fallback_quick_profile = self.service.create_profile({"name": "取消详细后快速"}, self.ctx) conn = self.database.connect() try: conn.executemany( """ INSERT INTO profile_workflows ( workflow_id, profile_id, workflow_type, display_name, status ) VALUES (?, ?, ?, ?, ?) """, [ ("workflow_quick_draft", quick_draft_profile.profile_id, "quick_profile", "Draft", "completed"), ("workflow_quick", quick_profile.profile_id, "character_fast", "Fast", "running"), ("workflow_detailed", detailed_profile.profile_id, "character_gradual", "Detailed", "draft"), ("workflow_cancelled", text_profile.profile_id, "character_gradual", "Cancelled", "cancelled"), ("workflow_cancelled_fast", text_profile.profile_id, "character_fast", "Cancelled fast", "cancelled"), ("workflow_fast_older", detailed_profile.profile_id, "character_fast", "Fast older", "completed"), ("workflow_cancelled_detailed", fallback_quick_profile.profile_id, "character_gradual", "Cancelled detailed", "cancelled"), ("workflow_fallback_fast", fallback_quick_profile.profile_id, "character_fast", "Fallback fast", "running"), ], ) conn.commit() finally: conn.close() kinds = { profile.profile_id: profile.generation_kind for profile in self.service.list_profiles(ctx=self.ctx).items } self.assertEqual(kinds[text_profile.profile_id], "ungenerated") self.assertEqual(kinds[quick_draft_profile.profile_id], "ungenerated") self.assertEqual(kinds[quick_profile.profile_id], "quick") self.assertEqual(kinds[detailed_profile.profile_id], "detailed") self.assertEqual(kinds[fallback_quick_profile.profile_id], "quick") self.assertEqual(self.service.get_profile(detailed_profile.profile_id).to_dict()["generation_kind"], "detailed") def test_create_profile_requires_name(self): with self.assertRaises(ApiError) as raised: self.service.create_profile({"name": " "}, self.ctx) self.assertEqual(raised.exception.error_code, ErrorCode.VALIDATION_FAILED) if __name__ == "__main__": unittest.main()