diff --git a/alembic/versions/7707cef3421c_add_shout_field_to_draft_model.py b/alembic/versions/7707cef3421c_add_shout_field_to_draft_model.py deleted file mode 100644 index b8e910f1..00000000 --- a/alembic/versions/7707cef3421c_add_shout_field_to_draft_model.py +++ /dev/null @@ -1,30 +0,0 @@ -"""Add shout field to Draft model - -Revision ID: 7707cef3421c -Revises: -Create Date: 2025-08-21 12:10:35.621695 - -""" -from alembic import op -import sqlalchemy as sa - - -# revision identifiers, used by Alembic. -revision = '7707cef3421c' -down_revision = None -branch_labels = None -depends_on = None - - -def upgrade() -> None: - # ### commands auto generated by Alembic - please adjust! ### - op.add_column('draft', sa.Column('shout', sa.Integer(), nullable=True)) - op.create_foreign_key(None, 'draft', 'shout', ['shout'], ['id']) - # ### end Alembic commands ### - - -def downgrade() -> None: - # ### commands auto generated by Alembic - please adjust! ### - op.drop_constraint(None, 'draft', type_='foreignkey') - op.drop_column('draft', 'shout') - # ### end Alembic commands ### diff --git a/ci_server.py b/ci_server.py index bfb8518f..2d06f384 100755 --- a/ci_server.py +++ b/ci_server.py @@ -364,10 +364,10 @@ def initialize_test_database(): logger.info("🗄️ Инициализируем тестовую базу данных...") # Создаем файл базы если его нет - db_file = Path("database.db") + db_file = Path("test_e2e.db") # Используем ту же БД что и в e2e тестах if not db_file.exists(): db_file.touch() - logger.info("✅ Создан файл базы данных") + logger.info("✅ Создан файл базы данных test_e2e.db") # Импортируем и создаем таблицы logger.info("✅ Engine импортирован успешно") diff --git a/tests/conftest.py b/tests/conftest.py index 325e9139..e52dac9f 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -18,6 +18,19 @@ try: # Create a fake Redis instance fake_redis = fakeredis.aioredis.FakeRedis() + # Add the execute method that our Redis service needs + async def execute_method(command: str, *args): + """Добавляем метод execute для совместимости с RedisService""" + cmd_method = getattr(fake_redis, command.lower(), None) + if cmd_method is not None: + if hasattr(cmd_method, '__call__'): + return await cmd_method(*args) + else: + return cmd_method + return None + + fake_redis.execute = execute_method + # Patch Redis at module level import storage.redis diff --git a/tests/test_community_delete_e2e_browser.py b/tests/test_community_delete_e2e_browser.py index e38e0ada..6db09c30 100644 --- a/tests/test_community_delete_e2e_browser.py +++ b/tests/test_community_delete_e2e_browser.py @@ -58,8 +58,47 @@ class TestCommunityDeleteE2EAPI: print("✅ Сообщество найдено в базе") print(f" ID: {test_community['id']}, Название: {test_community['name']}") else: - print("⚠️ Сообщество не найдено, пропускаем тест...") - pytest.skip("Тестовое сообщество не найдено, пропускаем тест") + print("⚠️ Сообщество не найдено, создаем новое...") + # Создаем новое тестовое сообщество + create_response = requests.post( + f"{api_base_url}", + json={ + "query": """ + mutation CreateCommunity($input: CommunityInput!) { + create_community(input: $input) { + success + community { + id + name + slug + } + error + } + } + """, + "variables": { + "input": { + "name": "Test Community for Delete", + "slug": community_slug, + "desc": "Test community for deletion testing" + } + } + }, + headers=headers, + timeout=10 + ) + + if create_response.status_code == 200: + create_data = create_response.json() + if create_data.get("data", {}).get("create_community", {}).get("success"): + test_community = create_data["data"]["create_community"]["community"] + print(f"✅ Создано новое сообщество: {test_community['name']}") + else: + print("❌ Не удалось создать тестовое сообщество") + pytest.skip("Не удалось создать тестовое сообщество") + else: + print("❌ Ошибка при создании сообщества") + pytest.skip("Ошибка API при создании сообщества") except Exception as e: print(f"❌ Ошибка при проверке сообщества: {e}") diff --git a/tests/test_community_rbac.py b/tests/test_community_rbac.py index 74f72bc4..beeeb474 100644 --- a/tests/test_community_rbac.py +++ b/tests/test_community_rbac.py @@ -93,9 +93,9 @@ class TestCommunityRoleInheritance: has_permission = await user_has_permission(user.id, perm, community.id) assert has_permission, f"Author должен иметь разрешение {perm}" - def test_community_editor_role_inheritance(self, session, unique_email, unique_slug): + @pytest.mark.asyncio + async def test_community_editor_role_inheritance(self, session, unique_email, unique_slug): """Тест наследования ролей для editor в сообществе""" - pytest.skip("Community RBAC тесты временно отключены из-за проблем с Redis") # Создаем тестового пользователя user = Author( email=unique_email, @@ -118,7 +118,7 @@ class TestCommunityRoleInheritance: session.add(community) session.flush() - initialize_community_permissions(community.id) + await initialize_community_permissions(community.id) # Создаем CommunityAuthor с ролью editor ca = CommunityAuthor( @@ -132,24 +132,24 @@ class TestCommunityRoleInheritance: # Проверяем что editor наследует разрешения author author_permissions = ["draft:create", "shout:create", "collection:create"] for perm in author_permissions: - has_permission = user_has_permission(user.id, perm, community.id) + has_permission = await user_has_permission(user.id, perm, community.id) assert has_permission, f"Editor должен наследовать разрешение {perm} от author" # Проверяем что editor наследует разрешения reader через author reader_permissions = ["shout:read", "topic:read", "collection:read"] for perm in reader_permissions: - has_permission = user_has_permission(user.id, perm, community.id) + has_permission = await user_has_permission(user.id, perm, community.id) assert has_permission, f"Editor должен наследовать разрешение {perm} от reader через author" # Проверяем специфичные разрешения editor editor_permissions = ["shout:delete_any", "shout:update_any", "topic:create", "community:create"] for perm in editor_permissions: - has_permission = user_has_permission(user.id, perm, community.id) + has_permission = await user_has_permission(user.id, perm, community.id) assert has_permission, f"Editor должен иметь разрешение {perm}" - def test_community_admin_role_inheritance(self, session, unique_email, unique_slug): + @pytest.mark.asyncio + async def test_community_admin_role_inheritance(self, session, unique_email, unique_slug): """Тест наследования ролей для admin в сообществе""" - pytest.skip("Community RBAC тесты временно отключены из-за проблем с Redis") # Создаем тестового пользователя user = Author( email=unique_email, @@ -172,7 +172,7 @@ class TestCommunityRoleInheritance: session.add(community) session.flush() - initialize_community_permissions(community.id) + await initialize_community_permissions(community.id) # Создаем CommunityAuthor с ролью admin ca = CommunityAuthor( @@ -192,12 +192,12 @@ class TestCommunityRoleInheritance: ] for perm in all_role_permissions: - has_permission = user_has_permission(user.id, perm, community.id) + has_permission = await user_has_permission(user.id, perm, community.id) assert has_permission, f"Admin должен иметь разрешение {perm} через наследование" - def test_community_expert_role_inheritance(self, session, unique_email, unique_slug): + @pytest.mark.asyncio + async def test_community_expert_role_inheritance(self, session, unique_email, unique_slug): """Тест наследования ролей для expert в сообществе""" - pytest.skip("Community RBAC тесты временно отключены из-за проблем с Redis") # Создаем тестового пользователя user = Author( email=unique_email, @@ -220,7 +220,7 @@ class TestCommunityRoleInheritance: session.add(community) session.flush() - initialize_community_permissions(community.id) + await initialize_community_permissions(community.id) # Создаем CommunityAuthor с ролью expert ca = CommunityAuthor( @@ -234,24 +234,24 @@ class TestCommunityRoleInheritance: # Проверяем что expert наследует разрешения reader reader_permissions = ["shout:read", "topic:read", "collection:read"] for perm in reader_permissions: - has_permission = user_has_permission(user.id, perm, community.id) + has_permission = await user_has_permission(user.id, perm, community.id) assert has_permission, f"Expert должен наследовать разрешение {perm} от reader" # Проверяем специфичные разрешения expert expert_permissions = ["reaction:create:PROOF", "reaction:create:DISPROOF", "reaction:create:AGREE"] for perm in expert_permissions: - has_permission = user_has_permission(user.id, perm, community.id) + has_permission = await user_has_permission(user.id, perm, community.id) assert has_permission, f"Expert должен иметь разрешение {perm}" # Проверяем что expert НЕ имеет разрешения author author_permissions = ["draft:create", "shout:create"] for perm in author_permissions: - has_permission = user_has_permission(user.id, perm, community.id) + has_permission = await user_has_permission(user.id, perm, community.id) assert not has_permission, f"Expert НЕ должен иметь разрешение {perm}" - def test_community_artist_role_inheritance(self, session, unique_email, unique_slug): + @pytest.mark.asyncio + async def test_community_artist_role_inheritance(self, session, unique_email, unique_slug): """Тест наследования ролей для artist в сообществе""" - pytest.skip("Community RBAC тесты временно отключены из-за проблем с Redis") # Создаем тестового пользователя user = Author( email=unique_email, @@ -274,7 +274,7 @@ class TestCommunityRoleInheritance: session.add(community) session.flush() - initialize_community_permissions(community.id) + await initialize_community_permissions(community.id) # Создаем CommunityAuthor с ролью artist ca = CommunityAuthor( @@ -288,24 +288,24 @@ class TestCommunityRoleInheritance: # Проверяем что artist наследует разрешения author author_permissions = ["draft:create", "shout:create", "collection:create"] for perm in author_permissions: - has_permission = user_has_permission(user.id, perm, community.id) + has_permission = await user_has_permission(user.id, perm, community.id) assert has_permission, f"Artist должен наследовать разрешение {perm} от author" # Проверяем что artist наследует разрешения reader через author reader_permissions = ["shout:read", "topic:read", "collection:read"] for perm in reader_permissions: - has_permission = user_has_permission(user.id, perm, community.id) + has_permission = await user_has_permission(user.id, perm, community.id) assert has_permission, f"Artist должен наследовать разрешение {perm} от reader через author" # Проверяем специфичные разрешения artist artist_permissions = ["reaction:create:CREDIT", "reaction:read:CREDIT", "reaction:update:CREDIT"] for perm in artist_permissions: - has_permission = user_has_permission(user.id, perm, community.id) + has_permission = await user_has_permission(user.id, perm, community.id) assert has_permission, f"Artist должен иметь разрешение {perm}" - def test_community_multiple_roles_inheritance(self, session, unique_email, unique_slug): + @pytest.mark.asyncio + async def test_community_multiple_roles_inheritance(self, session, unique_email, unique_slug): """Тест множественных ролей с наследованием в сообществе""" - pytest.skip("Community RBAC тесты временно отключены из-за проблем с Redis") # Создаем тестового пользователя user = Author( email=unique_email, @@ -328,7 +328,7 @@ class TestCommunityRoleInheritance: session.add(community) session.flush() - initialize_community_permissions(community.id) + await initialize_community_permissions(community.id) # Создаем CommunityAuthor с несколькими ролями ca = CommunityAuthor( @@ -342,24 +342,24 @@ class TestCommunityRoleInheritance: # Проверяем разрешения от роли author author_permissions = ["draft:create", "shout:create", "collection:create"] for perm in author_permissions: - has_permission = user_has_permission(user.id, perm, community.id) + has_permission = await user_has_permission(user.id, perm, community.id) assert has_permission, f"Пользователь с ролями author,expert должен иметь разрешение {perm} от author" # Проверяем разрешения от роли expert expert_permissions = ["reaction:create:PROOF", "reaction:create:DISPROOF", "reaction:create:AGREE"] for perm in expert_permissions: - has_permission = user_has_permission(user.id, perm, community.id) + has_permission = await user_has_permission(user.id, perm, community.id) assert has_permission, f"Пользователь с ролями author,expert должен иметь разрешение {perm} от expert" # Проверяем общие разрешения от reader (наследуются обеими ролями) reader_permissions = ["shout:read", "topic:read", "collection:read"] for perm in reader_permissions: - has_permission = user_has_permission(user.id, perm, community.id) + has_permission = await user_has_permission(user.id, perm, community.id) assert has_permission, f"Пользователь с ролями author,expert должен иметь разрешение {perm} от reader" - def test_community_roles_have_permission_inheritance(self, session, unique_email, unique_slug): + @pytest.mark.asyncio + async def test_community_roles_have_permission_inheritance(self, session, unique_email, unique_slug): """Тест функции roles_have_permission с наследованием в сообществе""" - pytest.skip("Community RBAC тесты временно отключены из-за проблем с Redis") # Создаем тестового пользователя user = Author( email=unique_email, @@ -382,27 +382,27 @@ class TestCommunityRoleInheritance: session.add(community) session.flush() - initialize_community_permissions(community.id) + await initialize_community_permissions(community.id) # Проверяем что editor имеет разрешения author через наследование - has_author_permission = roles_have_permission(["editor"], "draft:create", community.id) + has_author_permission = await roles_have_permission(["editor"], "draft:create", community.id) assert has_author_permission, "Editor должен иметь разрешение draft:create через наследование от author" # Проверяем что admin имеет разрешения reader через наследование - has_reader_permission = roles_have_permission(["admin"], "shout:read", community.id) + has_reader_permission = await roles_have_permission(["admin"], "shout:read", community.id) assert has_reader_permission, "Admin должен иметь разрешение shout:read через наследование от reader" # Проверяем что artist имеет разрешения author через наследование - has_artist_author_permission = roles_have_permission(["artist"], "shout:create", community.id) + has_artist_author_permission = await roles_have_permission(["artist"], "shout:create", community.id) assert has_artist_author_permission, "Artist должен иметь разрешение shout:create через наследование от author" # Проверяем что expert НЕ имеет разрешения author - has_expert_author_permission = roles_have_permission(["expert"], "draft:create", community.id) + has_expert_author_permission = await roles_have_permission(["expert"], "draft:create", community.id) assert not has_expert_author_permission, "Expert НЕ должен иметь разрешение draft:create" - def test_community_deep_inheritance_chain(self, session, unique_email, unique_slug): + @pytest.mark.asyncio + async def test_community_deep_inheritance_chain(self, session, unique_email, unique_slug): """Тест глубокой цепочки наследования в сообществе""" - pytest.skip("Community RBAC тесты временно отключены из-за проблем с Redis") # Создаем тестового пользователя user = Author( email=unique_email, @@ -425,7 +425,7 @@ class TestCommunityRoleInheritance: session.add(community) session.flush() - initialize_community_permissions(community.id) + await initialize_community_permissions(community.id) # Создаем CommunityAuthor с ролью admin ca = CommunityAuthor( @@ -446,12 +446,12 @@ class TestCommunityRoleInheritance: ] for perm in inheritance_chain_permissions: - has_permission = user_has_permission(user.id, perm, community.id) + has_permission = await user_has_permission(user.id, perm, community.id) assert has_permission, f"Admin должен иметь разрешение {perm} через цепочку наследования" - def test_community_permission_denial_with_inheritance(self, session, unique_email, unique_slug): + @pytest.mark.asyncio + async def test_community_permission_denial_with_inheritance(self, session, unique_email, unique_slug): """Тест отказа в разрешениях с учетом наследования в сообществе""" - pytest.skip("Community RBAC тесты временно отключены из-за проблем с Redis") # Создаем тестового пользователя user = Author( email=unique_email, @@ -474,7 +474,7 @@ class TestCommunityRoleInheritance: session.add(community) session.flush() - initialize_community_permissions(community.id) + await initialize_community_permissions(community.id) # Создаем CommunityAuthor с ролью reader ca = CommunityAuthor( @@ -496,12 +496,12 @@ class TestCommunityRoleInheritance: ] for perm in denied_permissions: - has_permission = user_has_permission(user.id, perm, community.id) + has_permission = await user_has_permission(user.id, perm, community.id) assert not has_permission, f"Reader НЕ должен иметь разрешение {perm}" - def test_community_role_permissions_consistency(self, session, unique_email, unique_slug): + @pytest.mark.asyncio + async def test_community_role_permissions_consistency(self, session, unique_email, unique_slug): """Тест консистентности разрешений ролей в сообществе""" - pytest.skip("Community RBAC тесты временно отключены из-за проблем с Redis") # Создаем тестового пользователя user = Author( email=unique_email, @@ -524,7 +524,7 @@ class TestCommunityRoleInheritance: session.add(community) session.flush() - initialize_community_permissions(community.id) + await initialize_community_permissions(community.id) # Проверяем что все роли имеют корректные разрешения role_permissions_map = { @@ -548,7 +548,7 @@ class TestCommunityRoleInheritance: # Проверяем что роль имеет ожидаемые разрешения for perm in expected_permissions: - has_permission = user_has_permission(user.id, perm, community.id) + has_permission = await user_has_permission(user.id, perm, community.id) assert has_permission, f"Роль {role} должна иметь разрешение {perm}" # Удаляем запись для следующей итерации diff --git a/tests/test_delete_existing_community.py b/tests/test_delete_existing_community.py index 0154fc6b..a7664c01 100644 --- a/tests/test_delete_existing_community.py +++ b/tests/test_delete_existing_community.py @@ -55,12 +55,74 @@ def test_delete_existing_community(api_base_url, auth_headers, test_user_credent # Проверяем, что авторизация прошла успешно if not login_data["data"]["login"]["token"] or not login_data["data"]["login"]["author"]: print("⚠️ Авторизация не прошла - токен или author отсутствуют") - pytest.skip("Авторизация не прошла - возможно, проблемы с Redis") - - token = login_data["data"]["login"]["token"] - author_id = login_data["data"]["login"]["author"]["id"] - print(f"🔑 Токен получен: {token[:50]}...") - print(f"👤 Author ID: {author_id}") + print("🔄 Пробуем альтернативный способ авторизации...") + + # Пробуем создать пользователя и войти + try: + create_user_mutation = """ + mutation CreateUser($input: AuthorInput!) { + create_author(input: $input) { + success + author { + id + email + name + } + error + } + } + """ + + create_user_variables = { + "input": { + "email": "test-user-delete@example.com", + "name": "Test User Delete", + "password": "testpass123" + } + } + + create_response = requests.post( + api_base_url, + json={"query": create_user_mutation, "variables": create_user_variables}, + headers=auth_headers(), + timeout=10 + ) + + if create_response.status_code == 200: + create_data = create_response.json() + if create_data.get("data", {}).get("create_author", {}).get("success"): + print("✅ Пользователь создан, пробуем войти...") + # Теперь пробуем войти с новым пользователем + login_response = requests.post( + api_base_url, + json={"query": login_mutation, "variables": create_user_variables}, + headers=auth_headers(), + timeout=10 + ) + + if login_response.status_code == 200: + new_login_data = login_response.json() + if new_login_data.get("data", {}).get("login", {}).get("token"): + token = new_login_data["data"]["login"]["token"] + author_id = new_login_data["data"]["login"]["author"]["id"] + print(f"✅ Авторизация с новым пользователем успешна") + print(f"🔑 Токен получен: {token[:50]}...") + print(f"👤 Author ID: {author_id}") + else: + pytest.skip("Не удалось авторизоваться даже с новым пользователем") + else: + pytest.skip("Ошибка при входе с новым пользователем") + else: + pytest.skip("Не удалось создать тестового пользователя") + else: + pytest.skip("Ошибка при создании пользователя") + except Exception as e: + pytest.skip(f"Не удалось создать пользователя: {e}") + else: + token = login_data["data"]["login"]["token"] + author_id = login_data["data"]["login"]["author"]["id"] + print(f"🔑 Токен получен: {token[:50]}...") + print(f"👤 Author ID: {author_id}") # Теперь попробуем удалить существующее сообщество delete_mutation = """ diff --git a/tests/test_drafts.py b/tests/test_drafts.py index 1ae7669a..49b22ff9 100644 --- a/tests/test_drafts.py +++ b/tests/test_drafts.py @@ -112,8 +112,8 @@ async def test_create_shout(db_session, test_author): # Проверяем результат assert "error" not in result or result["error"] is None - assert result["draft"].title == "Test Shout" - assert result["draft"].body == "This is a test shout" + assert result["draft"]["title"] == "Test Shout" + assert result["draft"]["body"] == "This is a test shout" except Exception as e: # На CI могут быть проблемы с моком, пропускаем тест pytest.skip(f"Тест пропущен на CI: {e}") diff --git a/tests/test_rbac_integration.py b/tests/test_rbac_integration.py index e5a46a57..33f53a4f 100644 --- a/tests/test_rbac_integration.py +++ b/tests/test_rbac_integration.py @@ -57,14 +57,14 @@ def simple_user(db_session): @pytest.fixture def test_community(db_session, simple_user): """Создает тестовое сообщество""" - # Очищаем существующие записи - db_session.query(Community).where(Community.id == 999).delete() - db_session.commit() - + import uuid + + # Генерируем уникальный slug + unique_slug = f"integration-test-{uuid.uuid4().hex[:8]}" + community = Community( - id=999, name="Integration Test Community", - slug="integration-test-community", + slug=unique_slug, desc="Community for integration RBAC tests", created_by=simple_user.id, created_at=int(time.time()) @@ -83,7 +83,7 @@ def test_community(db_session, simple_user): @pytest.fixture(autouse=True) -def setup_redis(): +def setup_redis(test_community): """Настройка Redis для каждого теста""" # FakeRedis уже подключен, ничего не делаем yield @@ -91,7 +91,7 @@ def setup_redis(): # Очищаем данные тестового сообщества из Redis try: # Используем execute вместо delete - redis.execute("DEL", "community:roles:999") + redis.execute("DEL", f"community:roles:{test_community.id}") except Exception: pass @@ -105,34 +105,222 @@ class TestRBACIntegrationWithInheritance: # TODO: Implement test logic assert True # Placeholder assertion - def test_editor_role_inheritance_integration(self, db_session, simple_user, test_community): + @pytest.mark.asyncio + async def test_editor_role_inheritance_integration(self, db_session, simple_user, test_community): """Интеграционный тест наследования ролей для editor""" - pytest.skip("RBAC integration тесты временно отключены из-за проблем с Redis") + from rbac.api import initialize_community_permissions, user_has_permission + from orm.community import CommunityAuthor + + # Инициализируем разрешения для сообщества + await initialize_community_permissions(test_community.id) + + # Создаем CommunityAuthor с ролью editor + ca = CommunityAuthor( + community_id=test_community.id, + author_id=simple_user.id, + roles="editor" + ) + db_session.add(ca) + db_session.commit() + + # Проверяем базовые разрешения reader (editor наследует их через author) + reader_permissions = ["shout:read", "topic:read", "collection:read"] + for perm in reader_permissions: + has_permission = await user_has_permission(simple_user.id, perm, test_community.id, db_session) + assert has_permission, f"Editor должен наследовать разрешение {perm} от reader через author" + + # Проверяем разрешения author (editor наследует их напрямую) + author_permissions = ["draft:create", "shout:create", "collection:create"] + for perm in author_permissions: + has_permission = await user_has_permission(simple_user.id, perm, test_community.id, db_session) + assert has_permission, f"Editor должен наследовать разрешение {perm} от author" + + # Проверяем специфичные разрешения editor + editor_permissions = ["shout:delete_any", "shout:update_any", "topic:create"] + for perm in editor_permissions: + has_permission = await user_has_permission(simple_user.id, perm, test_community.id, db_session) + assert has_permission, f"Editor должен иметь разрешение {perm}" - def test_admin_role_inheritance_integration(self, db_session, simple_user, test_community): + @pytest.mark.asyncio + async def test_admin_role_inheritance_integration(self, db_session, simple_user, test_community): """Интеграционный тест наследования ролей для admin""" - pytest.skip("RBAC integration тесты временно отключены из-за проблем с Redis") + from rbac.api import initialize_community_permissions, user_has_permission + from orm.community import CommunityAuthor + + # Инициализируем разрешения для сообщества + await initialize_community_permissions(test_community.id) + + # Создаем CommunityAuthor с ролью admin + ca = CommunityAuthor( + community_id=test_community.id, + author_id=simple_user.id, + roles="admin" + ) + db_session.add(ca) + db_session.commit() + + # Проверяем что admin наследует разрешения author + author_permissions = ["draft:create", "shout:create", "collection:create"] + for perm in author_permissions: + has_permission = await user_has_permission(simple_user.id, perm, test_community.id, db_session) + assert has_permission, f"Admin должен наследовать разрешение {perm} от author" + + # Проверяем специфичные разрешения admin + admin_permissions = ["shout:delete_any", "author:delete_any", "community:delete_any"] + for perm in admin_permissions: + has_permission = await user_has_permission(simple_user.id, perm, test_community.id, db_session) + assert has_permission, f"Admin должен иметь разрешение {perm}" - def test_expert_role_inheritance_integration(self, db_session, simple_user, test_community): + @pytest.mark.asyncio + async def test_expert_role_inheritance_integration(self, db_session, simple_user, test_community): """Интеграционный тест наследования ролей для expert""" - pytest.skip("RBAC integration тесты временно отключены из-за проблем с Redis") + from rbac.api import initialize_community_permissions, user_has_permission + from orm.community import CommunityAuthor + + # Инициализируем разрешения для сообщества + await initialize_community_permissions(test_community.id) + + # Создаем CommunityAuthor с ролью expert + ca = CommunityAuthor( + community_id=test_community.id, + author_id=simple_user.id, + roles="expert" + ) + db_session.add(ca) + db_session.commit() + + # Проверяем что expert наследует разрешения reader + reader_permissions = ["shout:read", "topic:read", "collection:read"] + for perm in reader_permissions: + has_permission = await user_has_permission(simple_user.id, perm, test_community.id, db_session) + assert has_permission, f"Expert должен наследовать разрешение {perm} от reader" + + # Проверяем специфичные разрешения expert + expert_permissions = ["reaction:create:PROOF", "reaction:create:DISPROOF", "reaction:create:AGREE"] + for perm in expert_permissions: + has_permission = await user_has_permission(simple_user.id, perm, test_community.id, db_session) + assert has_permission, f"Expert должен иметь разрешение {perm}" - def test_artist_role_inheritance_integration(self, db_session, simple_user, test_community): + @pytest.mark.asyncio + async def test_artist_role_inheritance_integration(self, db_session, simple_user, test_community): """Интеграционный тест наследования ролей для artist""" - pytest.skip("RBAC integration тесты временно отключены из-за проблем с Redis") + from rbac.api import initialize_community_permissions, user_has_permission + from orm.community import CommunityAuthor + + # Инициализируем разрешения для сообщества + await initialize_community_permissions(test_community.id) + + # Создаем CommunityAuthor с ролью artist + ca = CommunityAuthor( + community_id=test_community.id, + author_id=simple_user.id, + roles="artist" + ) + db_session.add(ca) + db_session.commit() + + # Проверяем что artist наследует разрешения author + author_permissions = ["draft:create", "shout:create", "collection:create"] + for perm in author_permissions: + has_permission = await user_has_permission(simple_user.id, perm, test_community.id, db_session) + assert has_permission, f"Artist должен наследовать разрешение {perm} от author" + + # Проверяем специфичные разрешения artist + artist_permissions = ["reaction:create:CREDIT", "reaction:read:CREDIT"] + for perm in artist_permissions: + has_permission = await user_has_permission(simple_user.id, perm, test_community.id, db_session) + assert has_permission, f"Artist должен иметь разрешение {perm}" - def test_multiple_roles_inheritance_integration(self, db_session, simple_user, test_community): + @pytest.mark.asyncio + async def test_multiple_roles_inheritance_integration(self, db_session, simple_user, test_community): """Интеграционный тест наследования для пользователя с несколькими ролями""" - pytest.skip("RBAC integration тесты временно отключены из-за проблем с Redis") + from rbac.api import initialize_community_permissions, user_has_permission + from orm.community import CommunityAuthor + + # Инициализируем разрешения для сообщества + await initialize_community_permissions(test_community.id) + + # Создаем CommunityAuthor с несколькими ролями + ca = CommunityAuthor( + community_id=test_community.id, + author_id=simple_user.id, + roles="author,expert" + ) + db_session.add(ca) + db_session.commit() + + # Проверяем разрешения от author + author_permissions = ["draft:create", "shout:create"] + for perm in author_permissions: + has_permission = await user_has_permission(simple_user.id, perm, test_community.id, db_session) + assert has_permission, f"Пользователь с ролями author,expert должен иметь разрешение {perm}" + + # Проверяем разрешения от expert + expert_permissions = ["reaction:create:PROOF", "reaction:create:DISPROOF"] + for perm in expert_permissions: + has_permission = await user_has_permission(simple_user.id, perm, test_community.id, db_session) + assert has_permission, f"Пользователь с ролями author,expert должен иметь разрешение {perm}" - def test_roles_have_permission_inheritance_integration(self, db_session, test_community): + @pytest.mark.asyncio + async def test_roles_have_permission_inheritance_integration(self, db_session, test_community): """Интеграционный тест функции roles_have_permission с учетом наследования""" - pytest.skip("RBAC integration тесты временно отключены из-за проблем с Redis") + from rbac.api import initialize_community_permissions, roles_have_permission + + # Инициализируем разрешения для сообщества + await initialize_community_permissions(test_community.id) + + # Проверяем что admin роли имеют разрешения author + has_permission = await roles_have_permission(["admin"], "draft:create", test_community.id) + assert has_permission, "Admin должен наследовать разрешение draft:create от author" + + # Проверяем что editor роли имеют разрешения reader + has_permission = await roles_have_permission(["editor"], "shout:read", test_community.id) + assert has_permission, "Editor должен наследовать разрешение shout:read от reader" - def test_permission_denial_inheritance_integration(self, db_session, simple_user, test_community): + @pytest.mark.asyncio + async def test_permission_denial_inheritance_integration(self, db_session, simple_user, test_community): """Интеграционный тест отказа в разрешениях с учетом наследования""" - pytest.skip("RBAC integration тесты временно отключены из-за проблем с Redis") + from rbac.api import initialize_community_permissions, user_has_permission + from orm.community import CommunityAuthor + + # Инициализируем разрешения для сообщества + await initialize_community_permissions(test_community.id) + + # Создаем CommunityAuthor с ролью reader + ca = CommunityAuthor( + community_id=test_community.id, + author_id=simple_user.id, + roles="reader" + ) + db_session.add(ca) + db_session.commit() + + # Проверяем что reader НЕ имеет разрешения author + author_permissions = ["draft:create", "shout:create"] + for perm in author_permissions: + has_permission = await user_has_permission(simple_user.id, perm, test_community.id, db_session) + assert not has_permission, f"Reader НЕ должен иметь разрешение {perm}" - def test_deep_inheritance_chain_integration(self, db_session, simple_user, test_community): + @pytest.mark.asyncio + async def test_deep_inheritance_chain_integration(self, db_session, simple_user, test_community): """Интеграционный тест глубокой цепочки наследования ролей""" - pytest.skip("RBAC integration тесты временно отключены из-за проблем с Redis") + from rbac.api import initialize_community_permissions, user_has_permission + from orm.community import CommunityAuthor + + # Инициализируем разрешения для сообщества + await initialize_community_permissions(test_community.id) + + # Создаем CommunityAuthor с ролью admin + ca = CommunityAuthor( + community_id=test_community.id, + author_id=simple_user.id, + roles="admin" + ) + db_session.add(ca) + db_session.commit() + + # Проверяем глубокую цепочку наследования: admin -> author -> reader + reader_permissions = ["shout:read", "topic:read"] + for perm in reader_permissions: + has_permission = await user_has_permission(simple_user.id, perm, test_community.id, db_session) + assert has_permission, f"Admin должен наследовать разрешение {perm} через цепочку admin->author->reader" diff --git a/tests/test_rbac_system.py b/tests/test_rbac_system.py index 00ecf37c..c2180786 100644 --- a/tests/test_rbac_system.py +++ b/tests/test_rbac_system.py @@ -45,6 +45,32 @@ def test_community(db_session, test_users): db_session.commit() return community -def test_rbac_system_basic(): +@pytest.mark.asyncio +async def test_rbac_system_basic(db_session, test_users, test_community): """Базовый тест системы RBAC""" - pytest.skip("RBAC тесты временно отключены из-за проблем с event loop") + from rbac.api import initialize_community_permissions, user_has_permission + from orm.community import CommunityAuthor + + # Инициализируем разрешения для сообщества + await initialize_community_permissions(test_community.id) + + # Создаем CommunityAuthor с ролью reader + ca = CommunityAuthor( + community_id=test_community.id, + author_id=test_users[0].id, + roles="reader" + ) + db_session.add(ca) + db_session.commit() + + # Проверяем базовые разрешения reader + reader_permissions = ["shout:read", "topic:read"] + for perm in reader_permissions: + has_permission = await user_has_permission(test_users[0].id, perm, test_community.id, db_session) + assert has_permission, f"Reader должен иметь разрешение {perm}" + + # Проверяем что reader НЕ имеет разрешения author + author_permissions = ["draft:create", "shout:create"] + for perm in author_permissions: + has_permission = await user_has_permission(test_users[0].id, perm, test_community.id, db_session) + assert not has_permission, f"Reader НЕ должен иметь разрешение {perm}"