============================= test session starts ============================== platform linux -- Python 3.12.3, pytest-9.2.0, pluggy-1.7.0 -- /root/telegram-saas/.venv/bin/python3 cachedir: .pytest_cache rootdir: /root/telegram-saas configfile: pyproject.toml testpaths: tests plugins: anyio-4.16.0, asyncio-1.5.0 asyncio: mode=Mode.AUTO, debug=False, asyncio_default_fixture_loop_scope=function, asyncio_default_test_loop_scope=function collecting ... collected 88 items tests/integration/test_ai_api.py::test_ai_module_full_lifecycle PASSED [ 1%] tests/integration/test_auth.py::test_auth_workflow PASSED [ 2%] tests/integration/test_billing_checkout_and_lifecycle.py::test_full_billing_lifecycle_and_security PASSED [ 3%] tests/integration/test_billing_webhooks.py::test_razorpay_and_stripe_webhooks_and_deduplication PASSED [ 4%] tests/integration/test_broadcasts_api.py::test_broadcast_and_notifications_full_lifecycle PASSED [ 5%] tests/integration/test_celery_telegram_tasks.py::test_telegram_update_task_execution PASSED [ 6%] tests/integration/test_emojis_api.py::test_search_emojis_by_term PASSED [ 7%] tests/integration/test_emojis_api.py::test_search_emojis_by_category PASSED [ 9%] tests/integration/test_emojis_api.py::test_get_categories_list PASSED [ 10%] tests/integration/test_emojis_api.py::test_bulk_emoji_import_and_packs_management PASSED [ 11%] tests/integration/test_health.py::test_health_liveness PASSED [ 12%] tests/integration/test_health.py::test_health_readiness PASSED [ 13%] tests/integration/test_i18n_api.py::test_get_locales_list PASSED [ 14%] tests/integration/test_i18n_api.py::test_get_translation_bundle PASSED [ 15%] tests/integration/test_i18n_api.py::test_update_user_locale PASSED [ 17%] tests/integration/test_i18n_api.py::test_save_custom_translation_override PASSED [ 18%] tests/integration/test_i18n_api.py::test_audit_translations_and_missing_keys PASSED [ 19%] tests/integration/test_i18n_api.py::test_ai_translation_and_human_approval_workflow PASSED [ 20%] tests/integration/test_message_studio_api.py::test_bot_message_studio_lifecycle FAILED [ 21%] tests/integration/test_message_studio_e2e_publishing.py::test_message_studio_publishing_changes_real_bot_response FAILED [ 22%] tests/integration/test_multi_bot_engine.py::test_multi_tenant_multi_bot_engine_lifecycle FAILED [ 23%] tests/integration/test_multilingual_bot_responses.py::test_language_selection_in_actual_bot_responses FAILED [ 25%] tests/integration/test_plugins_api.py::test_plugins_module_full_lifecycle FAILED [ 26%] tests/integration/test_text_designer_api.py::test_text_designer_api_endpoints FAILED [ 27%] tests/tenant_isolation/test_tenant_isolation.py::test_strict_tenant_isolation FAILED [ 28%] tests/unit/test_ai_engine.py::test_openai_provider_models_and_completion PASSED [ 29%] tests/unit/test_ai_engine.py::test_openrouter_provider_models_and_completion PASSED [ 30%] tests/unit/test_ai_engine.py::test_ai_provider_factory PASSED [ 31%] tests/unit/test_billing_gateways.py::test_razorpay_payment_signature_verification PASSED [ 32%] tests/unit/test_billing_gateways.py::test_razorpay_webhook_signature_verification PASSED [ 34%] tests/unit/test_billing_gateways.py::test_stripe_webhook_signature_verification PASSED [ 35%] tests/unit/test_billing_gateways.py::test_gateway_factory_resolution PASSED [ 36%] tests/unit/test_bot_engine.py::test_bot_token_validation_with_getme PASSED [ 37%] tests/unit/test_bot_engine.py::test_bot_token_encryption_and_decryption PASSED [ 38%] tests/unit/test_bot_engine.py::test_webhook_secret_generation_and_verification PASSED [ 39%] tests/unit/test_bot_engine.py::test_rate_limit_retry_handling PASSED [ 40%] tests/unit/test_broadcast_engine.py::test_broadcast_audience_selection_and_opt_out PASSED [ 42%] tests/unit/test_coupons_and_entitlements.py::test_coupon_validation_and_discounts PASSED [ 43%] tests/unit/test_coupons_and_entitlements.py::test_entitlement_enforcement_and_feature_gates PASSED [ 44%] tests/unit/test_emojis.py::test_telegram_html_emoji_formatting PASSED [ 45%] tests/unit/test_emojis.py::test_telegram_markdown_emoji_formatting PASSED [ 46%] tests/unit/test_emojis.py::test_id_precision_is_preserved_as_string PASSED [ 47%] tests/unit/test_emojis.py::test_custom_emoji_validation PASSED [ 48%] tests/unit/test_formatter_and_engine.py::test_box_header_formatting PASSED [ 50%] tests/unit/test_formatter_and_engine.py::test_separator_presets PASSED [ 51%] tests/unit/test_formatter_and_engine.py::test_info_block_formatting PASSED [ 52%] tests/unit/test_formatter_and_engine.py::test_progress_bar_generation PASSED [ 53%] tests/unit/test_formatter_and_engine.py::test_progress_step_header PASSED [ 54%] tests/unit/test_formatter_and_engine.py::test_telegram_message_builder PASSED [ 55%] tests/unit/test_i18n.py::test_supported_locales_catalog PASSED [ 56%] tests/unit/test_i18n.py::test_rtl_detection PASSED [ 57%] tests/unit/test_i18n.py::test_plural_rules PASSED [ 59%] tests/unit/test_i18n.py::test_formatting PASSED [ 60%] tests/unit/test_i18n.py::test_fallback_resolution PASSED [ 61%] tests/unit/test_i18n.py::test_translation_engine PASSED [ 62%] tests/unit/test_i18n.py::test_bcp47_locale_normalization PASSED [ 63%] tests/unit/test_i18n.py::test_interpolation PASSED [ 64%] tests/unit/test_i18n.py::test_missing_translation_fallback PASSED [ 65%] tests/unit/test_i18n.py::test_telegram_keyboard_builder PASSED [ 67%] tests/unit/test_message_studio.py::test_variable_interpolation PASSED [ 68%] tests/unit/test_message_studio.py::test_missing_variables_fallback PASSED [ 69%] tests/unit/test_message_studio.py::test_keyboard_matrix_ordering PASSED [ 70%] tests/unit/test_message_studio.py::test_aiogram_keyboard_generation PASSED [ 71%] tests/unit/test_message_studio.py::test_default_system_templates PASSED [ 72%] tests/unit/test_plugins_engine.py::test_plugin_permission_check PASSED [ 73%] tests/unit/test_plugins_engine.py::test_plugin_hook_execution_in_sandbox PASSED [ 75%] tests/unit/test_plugins_engine.py::test_plugin_crypto_price_tracker PASSED [ 76%] tests/unit/test_security.py::test_password_hashing PASSED [ 77%] tests/unit/test_security.py::test_aes_256_gcm_encryption PASSED [ 78%] tests/unit/test_security.py::test_jwt_tokens PASSED [ 79%] tests/unit/test_security.py::test_token_hashing PASSED [ 80%] tests/unit/test_security_audit.py::test_secure_filename_and_path_traversal_neutralization FAILED [ 81%] tests/unit/test_security_audit.py::test_validate_file_content_magic_bytes_and_extensions PASSED [ 82%] tests/unit/test_security_audit.py::test_safe_template_rendering_zero_ssti_and_eval PASSED [ 84%] tests/unit/test_security_audit.py::test_in_app_rate_limiter_sliding_window PASSED [ 85%] tests/unit/test_security_audit.py::test_sql_injection_defense_via_parameterized_queries PASSED [ 86%] tests/unit/test_security_audit.py::test_audit_service_action_logging FAILED [ 87%] tests/unit/test_unicode_styler.py::test_small_caps_transformation PASSED [ 88%] tests/unit/test_unicode_styler.py::test_tag_and_variable_preservation PASSED [ 89%] tests/unit/test_unicode_styler.py::test_other_unicode_styles PASSED [ 90%] tests/unit/test_unicode_styler.py::test_symbol_catalog_contents PASSED [ 92%] tests/unit/test_validators_and_presets.py::test_html_validator_valid PASSED [ 93%] tests/unit/test_validators_and_presets.py::test_html_validator_invalid_tags PASSED [ 94%] tests/unit/test_validators_and_presets.py::test_html_validator_unclosed_tags PASSED [ 95%] tests/unit/test_validators_and_presets.py::test_message_length_validator PASSED [ 96%] tests/unit/test_validators_and_presets.py::test_callback_data_validator PASSED [ 97%] tests/unit/test_validators_and_presets.py::test_preset_manager_loads_all_presets PASSED [ 98%] tests/unit/test_wallet_and_ledger.py::test_wallet_credit_debit_and_immutable_checksum PASSED [100%] =================================== FAILURES =================================== ______________________ test_bot_message_studio_lifecycle _______________________ async_client = db_session = @pytest.mark.asyncio async def test_bot_message_studio_lifecycle(async_client: AsyncClient, db_session: AsyncSession): # 1. Setup User A & Tenant A user_a_email = f"user_studio_{uuid.uuid4().hex[:6]}@example.com" resp_a = await async_client.post( "/api/v1/auth/register", json={"email": user_a_email, "password": "PasswordA123!", "full_name": "Studio Master"}, ) token_a = resp_a.json()["data"]["access_token"] tenant_resp = await async_client.post( "/api/v1/tenants", headers={"Authorization": f"Bearer {token_a}"}, json={"name": "Studio Tenant", "slug": f"studio-{uuid.uuid4().hex[:6]}"}, ) tenant_id = tenant_resp.json()["data"]["id"] headers_a = { "Authorization": f"Bearer {token_a}", "X-Tenant-ID": str(tenant_id), } # 2. Insert Bot A & Bot B into database for Tenant A bot_a = Bot( tenant_id=uuid.UUID(tenant_id), name="Business Bot A", username=f"biz_bot_a_{uuid.uuid4().hex[:6]}", status="active", default_locale="en", ) bot_b = Bot( tenant_id=uuid.UUID(tenant_id), name="Business Bot B", username=f"biz_bot_b_{uuid.uuid4().hex[:6]}", status="active", default_locale="en", ) db_session.add(bot_a) db_session.add(bot_b) await db_session.commit() await db_session.refresh(bot_a) await db_session.refresh(bot_b) bot_a_id = str(bot_a.id) bot_b_id = str(bot_b.id) # 3. Create a Message Template with Buttons create_payload = { "message_key": "welcome", "title": "Main Welcome Screen", "message_text": "🙏 Welcome, {first_name}!\n\nWelcome to our VIP club. Choose below:", "parse_mode": "HTML", "media_type": "none", "locale": "en", "is_active": True, "is_draft": False, "buttons": [ { "text": "💎 Buy Premium", "button_type": "callback_data", "action_value": "act:buy_premium", "row_position": 0, "column_position": 0, "sort_order": 0, }, { "text": "👤 My Account", "button_type": "callback_data", "action_value": "act:account", "row_position": 1, "column_position": 0, "sort_order": 0, }, { "text": "📞 Support", "button_type": "callback_data", "action_value": "act:support", "row_position": 1, "column_position": 1, "sort_order": 1, }, ], } post_resp = await async_client.post( f"/api/v1/bots/{bot_a_id}/messages", headers=headers_a, json=create_payload, ) assert post_resp.status_code == 201, post_resp.text data = post_resp.json()["data"] template_id = data["id"] assert data["message_key"] == "welcome" assert len(data["buttons"]) == 3 assert data["current_version"] == 1 # 4. Preview Template with Variables preview_resp = await async_client.post( f"/api/v1/bots/{bot_a_id}/messages/{template_id}/preview", headers=headers_a, json={"variables": {"first_name": "Karan"}}, ) assert preview_resp.status_code == 200 p_data = preview_resp.json()["data"] assert "Welcome, Karan!" in p_data["rendered_text"] assert len(p_data["keyboard"]) == 2 # 2 rows # 5. Update Template (creates Version 2) update_payload = { "title": "Updated Welcome Screen", "message_text": "🔥 Hello {first_name}! Welcome to the Updated Experience.", "buttons": [ { "text": "🚀 Get Started", "button_type": "callback_data", "action_value": "act:start", "row_position": 0, "column_position": 0, "sort_order": 0, } ], } patch_resp = await async_client.patch( f"/api/v1/bots/{bot_a_id}/messages/{template_id}", headers=headers_a, json=update_payload, ) assert patch_resp.status_code == 200 patched_data = patch_resp.json()["data"] assert patched_data["current_version"] == 2 assert len(patched_data["buttons"]) == 1 # 6. Check Versions List vers_resp = await async_client.get( f"/api/v1/bots/{bot_a_id}/messages/{template_id}/versions", headers=headers_a, ) assert vers_resp.status_code == 200 v_list = vers_resp.json()["data"] assert len(v_list) == 2 assert v_list[0]["version"] == 2 assert v_list[1]["version"] == 1 # 7. Rollback to Version 1 roll_resp = await async_client.post( f"/api/v1/bots/{bot_a_id}/messages/{template_id}/rollback", headers=headers_a, json={"version": 1}, ) assert roll_resp.status_code == 200 rolled_data = roll_resp.json()["data"] assert "VIP club" in rolled_data["message_text"] assert len(rolled_data["buttons"]) == 3 assert rolled_data["current_version"] == 3 # 8. Duplicate Template to Bot B dup_resp = await async_client.post( f"/api/v1/bots/{bot_a_id}/messages/{template_id}/duplicate", headers=headers_a, json={"target_bot_id": bot_b_id}, ) assert dup_resp.status_code == 201 dup_data = dup_resp.json()["data"] assert dup_data["bot_id"] == bot_b_id assert dup_data["message_key"] == "welcome" assert len(dup_data["buttons"]) == 3 # 9. Tenant Isolation Check: User B from Tenant B cannot access Bot A's messages user_b_email = f"user_b_{uuid.uuid4().hex[:6]}@example.com" resp_b = await async_client.post( "/api/v1/auth/register", json={"email": user_b_email, "password": "PasswordB123!", "full_name": "Hacker Beta"}, ) > token_b = resp_b.json()["data"]["access_token"] ^^^^^^^^^^^^^^^^^^^^^ E KeyError: 'data' tests/integration/test_message_studio_api.py:180: KeyError ----------------------------- Captured stdout call ----------------------------- 2026-11-18 09:26:35 [info ] dispatching_domain_event event_id=0be241d0-375a-4e85-9911-665039af0d7c event_type=UserRegisteredEvent handlers_count=0 2026-11-18 09:26:35 [info ] dispatching_domain_event event_id=c144647b-a735-49a9-a09d-0ab57961e57f event_type=TenantCreatedEvent handlers_count=0 2026-11-18 09:26:35 [warning ] cache_invalidation_failed error='Event loop is closed' 2026-11-18 09:26:35 [warning ] rate_limit_exceeded ip=127.0.0.1 path=/api/v1/auth/register retry_after=56 ___________ test_message_studio_publishing_changes_real_bot_response ___________ async_client = db_session = @pytest.mark.asyncio async def test_message_studio_publishing_changes_real_bot_response( async_client: AsyncClient, db_session: AsyncSession, ): TelegramApiService.clear_mocks() # 1. Setup mock bot token and register bot with getMe mock_token = f"token_studio_{uuid.uuid4().hex[:8]}_test" bot_username = f"studio_test_bot_{uuid.uuid4().hex[:6]}" TelegramApiService.register_mock_bot(mock_token, bot_username, "Studio Test Bot") # 2. Register Tenant & User user_email = f"publisher_{uuid.uuid4().hex[:6]}@example.com" reg_resp = await async_client.post( "/api/v1/auth/register", json={"email": user_email, "password": "PasswordA123!", "full_name": "Publisher Boss"}, ) > assert reg_resp.status_code == 201 E assert 429 == 201 E + where 429 = .status_code tests/integration/test_message_studio_e2e_publishing.py:29: AssertionError ----------------------------- Captured stdout call ----------------------------- 2026-11-18 09:26:35 [warning ] rate_limit_exceeded ip=127.0.0.1 path=/api/v1/auth/register retry_after=56 _________________ test_multi_tenant_multi_bot_engine_lifecycle _________________ async_client = db_session = @pytest.mark.asyncio async def test_multi_tenant_multi_bot_engine_lifecycle( async_client: AsyncClient, db_session: AsyncSession, ): # ------------------------------------------------------------- # 1. Setup Mock Bot Tokens # ------------------------------------------------------------- token_a1 = f"token_a1_{uuid.uuid4().hex[:8]}_test" token_a2 = f"token_a2_{uuid.uuid4().hex[:8]}_test" token_b1 = f"token_b1_{uuid.uuid4().hex[:8]}_test" bot_uname_a1 = f"alpha_bot_1_{uuid.uuid4().hex[:6]}" bot_uname_a2 = f"alpha_bot_2_{uuid.uuid4().hex[:6]}" bot_uname_b1 = f"beta_bot_1_{uuid.uuid4().hex[:6]}" TelegramApiService.register_mock_bot(token_a1, bot_uname_a1, "Alpha One") TelegramApiService.register_mock_bot(token_a2, bot_uname_a2, "Alpha Two") TelegramApiService.register_mock_bot(token_b1, bot_uname_b1, "Beta One") # ------------------------------------------------------------- # 2. Register User A & Tenant Alpha # ------------------------------------------------------------- user_a_email = f"user_a_{uuid.uuid4().hex[:6]}@example.com" resp_a = await async_client.post( "/api/v1/auth/register", json={"email": user_a_email, "password": "PasswordA123!", "full_name": "Alice Alpha"}, ) > token_user_a = resp_a.json()["data"]["access_token"] ^^^^^^^^^^^^^^^^^^^^^ E KeyError: 'data' tests/integration/test_multi_bot_engine.py:40: KeyError ----------------------------- Captured stdout call ----------------------------- 2026-11-18 09:26:35 [warning ] rate_limit_exceeded ip=127.0.0.1 path=/api/v1/auth/register retry_after=56 _______________ test_language_selection_in_actual_bot_responses ________________ async_client = db_session = @pytest.mark.asyncio async def test_language_selection_in_actual_bot_responses( async_client: AsyncClient, db_session: AsyncSession, ): TelegramApiService.clear_mocks() # 1. Setup mock bot mock_token = f"token_i18n_{uuid.uuid4().hex[:8]}_test" bot_username = f"i18n_bot_{uuid.uuid4().hex[:6]}" TelegramApiService.register_mock_bot(mock_token, bot_username, "Multilingual Bot") # 2. Register Tenant & Bot user_email = f"i18n_owner_{uuid.uuid4().hex[:6]}@example.com" reg_resp = await async_client.post( "/api/v1/auth/register", json={"email": user_email, "password": "Password123!", "full_name": "I18n Org Lead"}, ) > token = reg_resp.json()["data"]["access_token"] ^^^^^^^^^^^^^^^^^^^^^^^ E KeyError: 'data' tests/integration/test_multilingual_bot_responses.py:29: KeyError ----------------------------- Captured stdout call ----------------------------- 2026-11-18 09:26:35 [warning ] rate_limit_exceeded ip=127.0.0.1 path=/api/v1/auth/register retry_after=56 ______________________ test_plugins_module_full_lifecycle ______________________ async_client = db_session = @pytest.mark.asyncio async def test_plugins_module_full_lifecycle( async_client: AsyncClient, db_session: AsyncSession, ): # 1. Register User and Create Tenant email = f"plugin_user_{uuid.uuid4().hex[:6]}@example.com" reg_resp = await async_client.post( "/api/v1/auth/register", json={"email": email, "password": "Password123!", "full_name": "Plugin Architect"}, ) > assert reg_resp.status_code == 201 E assert 429 == 201 E + where 429 = .status_code tests/integration/test_plugins_api.py:18: AssertionError ----------------------------- Captured stdout call ----------------------------- 2026-11-18 09:26:35 [warning ] rate_limit_exceeded ip=127.0.0.1 path=/api/v1/auth/register retry_after=56 _______________________ test_text_designer_api_endpoints _______________________ async_client = db_session = @pytest.mark.asyncio async def test_text_designer_api_endpoints(async_client: AsyncClient, db_session: AsyncSession): # 1. Setup User & Tenant user_email = f"designer_{uuid.uuid4().hex[:6]}@example.com" reg_resp = await async_client.post( "/api/v1/auth/register", json={"email": user_email, "password": "PasswordA123!", "full_name": "Designer Master"}, ) > token = reg_resp.json()["data"]["access_token"] ^^^^^^^^^^^^^^^^^^^^^^^ E KeyError: 'data' tests/integration/test_text_designer_api.py:16: KeyError ----------------------------- Captured stdout call ----------------------------- 2026-11-18 09:26:35 [warning ] rate_limit_exceeded ip=127.0.0.1 path=/api/v1/auth/register retry_after=56 _________________________ test_strict_tenant_isolation _________________________ async_client = @pytest.mark.asyncio async def test_strict_tenant_isolation(async_client: AsyncClient): # Setup User A user_a_email = f"user_a_{uuid.uuid4().hex[:6]}@example.com" resp_a = await async_client.post( "/api/v1/auth/register", json={"email": user_a_email, "password": "PasswordA123!", "full_name": "User Alpha"}, ) > token_a = resp_a.json()["data"]["access_token"] ^^^^^^^^^^^^^^^^^^^^^ E KeyError: 'data' tests/tenant_isolation/test_tenant_isolation.py:14: KeyError ----------------------------- Captured stdout call ----------------------------- 2026-11-18 09:26:35 [warning ] rate_limit_exceeded ip=127.0.0.1 path=/api/v1/auth/register retry_after=56 ____________ test_secure_filename_and_path_traversal_neutralization ____________ @pytest.mark.unit def test_secure_filename_and_path_traversal_neutralization(): # 1. Directory traversal attacks > assert secure_filename("../../etc/passwd") == "etc_passwd" E AssertionError: assert 'passwd' == 'etc_passwd' E E - etc_passwd E ? ---- E + passwd tests/unit/test_security_audit.py:18: AssertionError ______________________ test_audit_service_action_logging _______________________ self = operation = 'INSERT INTO audit_logs (id, tenant_id, user_id, action, resource, ip_address, details, created_at, updated_at) VALUES...3::UUID, $4::VARCHAR, $5::VARCHAR, $6::VARCHAR, $7::JSONB, $8::TIMESTAMP WITH TIME ZONE, $9::TIMESTAMP WITH TIME ZONE)' parameters = (UUID('057cd393-a806-43aa-82a9-157a22ec094a'), UUID('47c2a061-edf7-4657-8637-3ad72e2ae12c'), None, 'SECURITY_KEY_ROTATION', 'vault:token_v1', '192.0.2.1', ...) async def _prepare_and_execute(self, operation, parameters): adapt_connection = self._adapt_connection async with adapt_connection._execute_mutex: if adapt_connection._transaction is None: await adapt_connection._start_transaction() if parameters is None: parameters = () try: prepared_stmt, attributes = await adapt_connection._prepare( operation, self._invalidate_schema_cache_asof ) if attributes: self._description = [ ( attr.name, attr.type.oid, None, None, None, None, None, ) for attr in attributes ] else: self._description = None if self.server_side: self._cursor = await prepared_stmt.cursor(*parameters) self._rowcount = -1 else: > self._rows = deque(await prepared_stmt.fetch(*parameters)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py:620: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ .venv/lib/python3.12/site-packages/asyncpg/prepared_stmt.py:177: in fetch data = await self.__bind_execute(args, 0, timeout) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .venv/lib/python3.12/site-packages/asyncpg/prepared_stmt.py:268: in __bind_execute data, status, _ = await self.__do_execute( .venv/lib/python3.12/site-packages/asyncpg/prepared_stmt.py:257: in __do_execute return await executor(protocol) ^^^^^^^^^^^^^^^^^^^^^^^^ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ > ??? E asyncpg.exceptions.ForeignKeyViolationError: insert or update on table "audit_logs" violates foreign key constraint "audit_logs_tenant_id_fkey" E DETAIL: Key (tenant_id)=(47c2a061-edf7-4657-8637-3ad72e2ae12c) is not present in table "tenants". asyncpg/protocol/protocol.pyx:197: ForeignKeyViolationError The above exception was the direct cause of the following exception: self = dialect = context = statement = parameters = [(UUID('057cd393-a806-43aa-82a9-157a22ec094a'), UUID('47c2a061-edf7-4657-8637-3ad72e2ae12c'), None, 'SECURITY_KEY_ROTATION', 'vault:token_v1', '192.0.2.1', ...)] def _exec_single_context( self, dialect: Dialect, context: ExecutionContext, statement: Union[str, Compiled], parameters: Optional[_AnyMultiExecuteParams], ) -> CursorResult[Unpack[TupleAny]]: """continue the _execute_context() method for a single DBAPI cursor.execute() or cursor.executemany() call. """ if dialect.bind_typing is BindTyping.SETINPUTSIZES: generic_setinputsizes = context._prepare_set_input_sizes() if generic_setinputsizes: try: dialect.do_set_input_sizes( context.cursor, generic_setinputsizes, context ) except BaseException as e: self._handle_dbapi_exception( e, str(statement), parameters, None, context ) cursor, str_statement, parameters = ( context.cursor, context.statement, context.parameters, ) effective_parameters: Optional[_AnyExecuteParams] if not context.executemany: effective_parameters = parameters[0] else: effective_parameters = parameters evt_handled: bool = False try: if self._has_events or self.engine._has_events: for fn in self.dispatch.before_cursor_execute: str_statement, effective_parameters = fn( self, cursor, str_statement, effective_parameters, context, context.executemany, ) if self._echo: self._log_info(str_statement) stats = context._get_cache_stats() self._log_parameters( effective_parameters, stats, ismulti=context.executemany ) if context.execute_style is ExecuteStyle.EXECUTEMANY: effective_parameters = cast( "_CoreMultiExecuteParams", effective_parameters ) if self.dialect._has_events: for fn in self.dialect.dispatch.do_executemany: if fn( cursor, str_statement, effective_parameters, context, ): evt_handled = True break if not evt_handled: self.dialect.do_executemany( cursor, str_statement, effective_parameters, context, ) elif not effective_parameters and context.no_parameters: if self.dialect._has_events: for fn in self.dialect.dispatch.do_execute_no_params: if fn(cursor, str_statement, context): evt_handled = True break if not evt_handled: self.dialect.do_execute_no_params( cursor, str_statement, context ) else: effective_parameters = cast( "_CoreSingleExecuteParams", effective_parameters ) if self.dialect._has_events: for fn in self.dialect.dispatch.do_execute: if fn( cursor, str_statement, effective_parameters, context, ): evt_handled = True break if not evt_handled: > self.dialect.do_execute( cursor, str_statement, effective_parameters, context ) .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py:1977: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ .venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py:1192: in do_execute cursor.execute(statement, parameters) .venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py:671: in execute await_(self._prepare_and_execute(operation, parameters)) .venv/lib/python3.12/site-packages/sqlalchemy/util/concurrency.py:171: in await_ return current.parent.switch(awaitable) # type: ignore[no-any-return] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .venv/lib/python3.12/site-packages/sqlalchemy/util/concurrency.py:209: in greenlet_spawn value = await result ^^^^^^^^^^^^ .venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py:633: in _prepare_and_execute self._handle_exception(error) .venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py:583: in _handle_exception self._adapt_connection._handle_exception(error) .venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py:862: in _handle_exception super()._handle_exception(error) .venv/lib/python3.12/site-packages/sqlalchemy/connectors/asyncio.py:412: in _handle_exception self._handle_exception_no_connection(self.dbapi, error) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ cls = dbapi = error = ForeignKeyViolationError('insert or update on table "audit_logs" violates foreign key constraint "audit_logs_tenant_id_fkey"') @classmethod def _handle_exception_no_connection( cls, dbapi: Any, error: Exception ) -> NoReturn: if not isinstance(error, AsyncAdapt_asyncpg_dbapi.Error): exception_mapping = dbapi._asyncpg_error_translate for super_ in type(error).__mro__: if super_ in exception_mapping: message = error.args[0] translated_error = exception_mapping[super_]( message, error ) > raise translated_error from error E sqlalchemy.dialects.postgresql.asyncpg.AsyncAdapt_asyncpg_dbapi.ForeignKeyViolationError: insert or update on table "audit_logs" violates foreign key constraint "audit_logs_tenant_id_fkey" .venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py:855: ForeignKeyViolationError The above exception was the direct cause of the following exception: db_session = @pytest.mark.asyncio async def test_audit_service_action_logging(db_session: AsyncSession): tenant_id = uuid.uuid4() audit_service = AuditService(db_session) > log_entry = await audit_service.log_action( tenant_id=tenant_id, action="SECURITY_KEY_ROTATION", resource="vault:token_v1", ip_address="192.0.2.1", details={"key_version": 2, "actor": "admin"}, ) tests/unit/test_security_audit.py:112: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ modules/audit/service.py:29: in log_action await self.db.flush() .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py:1031: in flush await greenlet_spawn(self.sync_session.flush, objects=objects) .venv/lib/python3.12/site-packages/sqlalchemy/util/concurrency.py:216: in greenlet_spawn result = context.switch(value) ^^^^^^^^^^^^^^^^^^^^^ .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py:4626: in flush self._flush(objects) :2: in _flush return target(fn, self, objects=objects) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .venv/lib/python3.12/site-packages/sqlalchemy/util/deprecations.py:281: in warned return fn(*args, **kwargs) # type: ignore[no-any-return] ^^^^^^^^^^^^^^^^^^^ .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py:4769: in _flush with util.safe_reraise(): .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py:166: in __exit__ raise exc_value.with_traceback(exc_tb) .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py:4730: in _flush flush_context.execute() .venv/lib/python3.12/site-packages/sqlalchemy/orm/unitofwork.py:467: in execute rec.execute(self) .venv/lib/python3.12/site-packages/sqlalchemy/orm/unitofwork.py:643: in execute util.preloaded.orm_persistence._save_obj( .venv/lib/python3.12/site-packages/sqlalchemy/orm/persistence.py:92: in _save_obj _emit_insert_statements( .venv/lib/python3.12/site-packages/sqlalchemy/orm/persistence.py:1250: in _emit_insert_statements result = connection.execute( .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py:1494: in execute return meth( .venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py:534: in _execute_on_connection return connection._execute_clauseelement( .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py:1714: in _execute_clauseelement ret = self._execute_context( .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py:1868: in _execute_context return self._exec_single_context( .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py:1996: in _exec_single_context self._handle_dbapi_exception( .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py:2351: in _handle_dbapi_exception raise sqlalchemy_exception.with_traceback(exc_info[2]) from e .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py:1977: in _exec_single_context self.dialect.do_execute( .venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py:1192: in do_execute cursor.execute(statement, parameters) .venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py:671: in execute await_(self._prepare_and_execute(operation, parameters)) .venv/lib/python3.12/site-packages/sqlalchemy/util/concurrency.py:171: in await_ return current.parent.switch(awaitable) # type: ignore[no-any-return] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .venv/lib/python3.12/site-packages/sqlalchemy/util/concurrency.py:209: in greenlet_spawn value = await result ^^^^^^^^^^^^ .venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py:633: in _prepare_and_execute self._handle_exception(error) .venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py:583: in _handle_exception self._adapt_connection._handle_exception(error) .venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py:862: in _handle_exception super()._handle_exception(error) .venv/lib/python3.12/site-packages/sqlalchemy/connectors/asyncio.py:412: in _handle_exception self._handle_exception_no_connection(self.dbapi, error) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ cls = dbapi = error = ForeignKeyViolationError('insert or update on table "audit_logs" violates foreign key constraint "audit_logs_tenant_id_fkey"') @classmethod def _handle_exception_no_connection( cls, dbapi: Any, error: Exception ) -> NoReturn: if not isinstance(error, AsyncAdapt_asyncpg_dbapi.Error): exception_mapping = dbapi._asyncpg_error_translate for super_ in type(error).__mro__: if super_ in exception_mapping: message = error.args[0] translated_error = exception_mapping[super_]( message, error ) > raise translated_error from error E sqlalchemy.exc.IntegrityError: (sqlalchemy.dialects.postgresql.asyncpg.ForeignKeyViolationError) insert or update on table "audit_logs" violates foreign key constraint "audit_logs_tenant_id_fkey" E [SQL: INSERT INTO audit_logs (id, tenant_id, user_id, action, resource, ip_address, details, created_at, updated_at) VALUES ($1::UUID, $2::UUID, $3::UUID, $4::VARCHAR, $5::VARCHAR, $6::VARCHAR, $7::JSONB, $8::TIMESTAMP WITH TIME ZONE, $9::TIMESTAMP WITH TIME ZONE)] E [parameters: (UUID('057cd393-a806-43aa-82a9-157a22ec094a'), UUID('47c2a061-edf7-4657-8637-3ad72e2ae12c'), None, 'SECURITY_KEY_ROTATION', 'vault:token_v1', '192.0.2.1', '{"key_version": 2, "actor": "admin"}', datetime.datetime(2026, 11, 18, 9, 26, 36, 81012, tzinfo=datetime.timezone.utc), datetime.datetime(2026, 11, 18, 9, 26, 36, 81015, tzinfo=datetime.timezone.utc))] E (Background on this error at: https://sqlalche.me/e/21/gkpj) .venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py:855: IntegrityError =============================== warnings summary =============================== tests/unit/test_security_audit.py:15 /root/telegram-saas/tests/unit/test_security_audit.py:15: PytestUnknownMarkWarning: Unknown pytest.mark.unit - is this a typo? You can register custom marks to avoid this warning - for details, see https://docs.pytest.org/en/stable/how-to/mark.html @pytest.mark.unit tests/unit/test_security_audit.py:25 /root/telegram-saas/tests/unit/test_security_audit.py:25: PytestUnknownMarkWarning: Unknown pytest.mark.unit - is this a typo? You can register custom marks to avoid this warning - for details, see https://docs.pytest.org/en/stable/how-to/mark.html @pytest.mark.unit tests/unit/test_security_audit.py:50 /root/telegram-saas/tests/unit/test_security_audit.py:50: PytestUnknownMarkWarning: Unknown pytest.mark.unit - is this a typo? You can register custom marks to avoid this warning - for details, see https://docs.pytest.org/en/stable/how-to/mark.html @pytest.mark.unit tests/unit/test_security_audit.py:72 /root/telegram-saas/tests/unit/test_security_audit.py:72: PytestUnknownMarkWarning: Unknown pytest.mark.unit - is this a typo? You can register custom marks to avoid this warning - for details, see https://docs.pytest.org/en/stable/how-to/mark.html @pytest.mark.unit -- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html =========================== short test summary info ============================ FAILED tests/integration/test_message_studio_api.py::test_bot_message_studio_lifecycle FAILED tests/integration/test_message_studio_e2e_publishing.py::test_message_studio_publishing_changes_real_bot_response FAILED tests/integration/test_multi_bot_engine.py::test_multi_tenant_multi_bot_engine_lifecycle FAILED tests/integration/test_multilingual_bot_responses.py::test_language_selection_in_actual_bot_responses FAILED tests/integration/test_plugins_api.py::test_plugins_module_full_lifecycle FAILED tests/integration/test_text_designer_api.py::test_text_designer_api_endpoints FAILED tests/tenant_isolation/test_tenant_isolation.py::test_strict_tenant_isolation FAILED tests/unit/test_security_audit.py::test_secure_filename_and_path_traversal_neutralization FAILED tests/unit/test_security_audit.py::test_audit_service_action_logging =================== 9 failed, 79 passed, 4 warnings in 4.68s ===================