============================= 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 115 items                                                            

tests/integration/test_ai_api.py::test_ai_module_full_lifecycle PASSED   [  0%]
tests/integration/test_auth.py::test_auth_workflow PASSED                [  1%]
tests/integration/test_billing_checkout_and_lifecycle.py::test_full_billing_lifecycle_and_security PASSED [  2%]
tests/integration/test_billing_webhooks.py::test_razorpay_and_stripe_webhooks_and_deduplication PASSED [  3%]
tests/integration/test_bot_modular_api_and_execution.py::test_bot_modular_api_and_execution_lifecycle FAILED [  4%]
tests/integration/test_bot_synthesizer_api.py::test_bot_synthesizer_api_full_flow PASSED [  5%]
tests/integration/test_broadcasts_api.py::test_broadcast_and_notifications_full_lifecycle PASSED [  6%]
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 [  8%]
tests/integration/test_emojis_api.py::test_get_categories_list PASSED    [  9%]
tests/integration/test_emojis_api.py::test_bulk_emoji_import_and_packs_management PASSED [ 10%]
tests/integration/test_health.py::test_health_liveness PASSED            [ 11%]
tests/integration/test_health.py::test_health_readiness PASSED           [ 12%]
tests/integration/test_i18n_api.py::test_get_locales_list PASSED         [ 13%]
tests/integration/test_i18n_api.py::test_get_translation_bundle PASSED   [ 13%]
tests/integration/test_i18n_api.py::test_update_user_locale PASSED       [ 14%]
tests/integration/test_i18n_api.py::test_save_custom_translation_override PASSED [ 15%]
tests/integration/test_i18n_api.py::test_audit_translations_and_missing_keys PASSED [ 16%]
tests/integration/test_i18n_api.py::test_ai_translation_and_human_approval_workflow PASSED [ 17%]
tests/integration/test_marketplace_api.py::test_marketplace_api_full_lifecycle_and_tenant_isolation PASSED [ 18%]
tests/integration/test_mcp_api.py::test_mcp_pro_full_lifecycle_and_tenant_isolation PASSED [ 19%]
tests/integration/test_message_studio_api.py::test_bot_message_studio_lifecycle PASSED [ 20%]
tests/integration/test_message_studio_e2e_publishing.py::test_message_studio_publishing_changes_real_bot_response PASSED [ 20%]
tests/integration/test_multi_bot_engine.py::test_multi_tenant_multi_bot_engine_lifecycle PASSED [ 21%]
tests/integration/test_multilingual_bot_responses.py::test_language_selection_in_actual_bot_responses PASSED [ 22%]
tests/integration/test_plugins_api.py::test_plugins_module_full_lifecycle PASSED [ 23%]
tests/integration/test_telegram_auth.py::test_telegram_auth_success_and_login PASSED [ 24%]
tests/integration/test_telegram_auth.py::test_telegram_auth_tampered_payload_rejected PASSED [ 25%]
tests/integration/test_telegram_auth.py::test_telegram_auth_replay_expired_rejected PASSED [ 26%]
tests/integration/test_telegram_auth.py::test_telegram_auth_future_timestamp_rejected PASSED [ 26%]
tests/integration/test_telegram_auth.py::test_telegram_account_linking PASSED [ 27%]
tests/integration/test_telegram_auth.py::test_telegram_config_endpoint PASSED [ 28%]
tests/integration/test_text_designer_api.py::test_text_designer_api_endpoints PASSED [ 29%]
tests/tenant_isolation/test_tenant_isolation.py::test_strict_tenant_isolation PASSED [ 30%]
tests/unit/test_ai_engine.py::test_openai_provider_models_and_completion PASSED [ 31%]
tests/unit/test_ai_engine.py::test_openrouter_provider_models_and_completion PASSED [ 32%]
tests/unit/test_ai_engine.py::test_ai_provider_factory PASSED            [ 33%]
tests/unit/test_billing_gateways.py::test_razorpay_payment_signature_verification PASSED [ 33%]
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_bot_modular_engine.py::test_module_catalog_definitions FAILED [ 40%]
tests/unit/test_bot_modular_engine.py::test_bot_module_lifecycle FAILED  [ 41%]
tests/unit/test_bot_modular_engine.py::test_force_join_gating_behavior PASSED [ 42%]
tests/unit/test_bot_modular_engine.py::test_referrals_and_growth_attribution PASSED [ 43%]
tests/unit/test_bot_modular_engine.py::test_auto_filter_keyword_and_blocked_words PASSED [ 44%]
tests/unit/test_bot_synthesizer.py::test_ai_synthesizer_support_desk_intent PASSED [ 45%]
tests/unit/test_bot_synthesizer.py::test_ai_synthesizer_ecommerce_store_intent PASSED [ 46%]
tests/unit/test_broadcast_engine.py::test_broadcast_audience_selection_and_opt_out PASSED [ 46%]
tests/unit/test_channel_adapters.py::test_channel_registry_resolution PASSED [ 47%]
tests/unit/test_channel_adapters.py::test_telegram_channel_adapter_lifecycle PASSED [ 48%]
tests/unit/test_channel_adapters.py::test_discord_channel_adapter_normalization PASSED [ 49%]
tests/unit/test_channel_adapters.py::test_generic_webhook_hmac_and_normalization PASSED [ 50%]
tests/unit/test_coupons_and_entitlements.py::test_coupon_validation_and_discounts PASSED [ 51%]
tests/unit/test_coupons_and_entitlements.py::test_entitlement_enforcement_and_feature_gates PASSED [ 52%]
tests/unit/test_emojis.py::test_telegram_html_emoji_formatting PASSED    [ 53%]
tests/unit/test_emojis.py::test_telegram_markdown_emoji_formatting PASSED [ 53%]
tests/unit/test_emojis.py::test_id_precision_is_preserved_as_string PASSED [ 54%]
tests/unit/test_emojis.py::test_custom_emoji_validation PASSED           [ 55%]
tests/unit/test_formatter_and_engine.py::test_box_header_formatting PASSED [ 56%]
tests/unit/test_formatter_and_engine.py::test_separator_presets PASSED   [ 57%]
tests/unit/test_formatter_and_engine.py::test_info_block_formatting PASSED [ 58%]
tests/unit/test_formatter_and_engine.py::test_progress_bar_generation PASSED [ 59%]
tests/unit/test_formatter_and_engine.py::test_progress_step_header PASSED [ 60%]
tests/unit/test_formatter_and_engine.py::test_telegram_message_builder PASSED [ 60%]
tests/unit/test_i18n.py::test_supported_locales_catalog PASSED           [ 61%]
tests/unit/test_i18n.py::test_rtl_detection PASSED                       [ 62%]
tests/unit/test_i18n.py::test_plural_rules PASSED                        [ 63%]
tests/unit/test_i18n.py::test_formatting PASSED                          [ 64%]
tests/unit/test_i18n.py::test_fallback_resolution PASSED                 [ 65%]
tests/unit/test_i18n.py::test_translation_engine PASSED                  [ 66%]
tests/unit/test_i18n.py::test_bcp47_locale_normalization PASSED          [ 66%]
tests/unit/test_i18n.py::test_interpolation PASSED                       [ 67%]
tests/unit/test_i18n.py::test_missing_translation_fallback PASSED        [ 68%]
tests/unit/test_i18n.py::test_telegram_keyboard_builder PASSED           [ 69%]
tests/unit/test_marketplace.py::test_marketplace_bot_manifests_catalog_integrity PASSED [ 70%]
tests/unit/test_marketplace.py::test_reusable_marketplace_modules_catalog PASSED [ 71%]
tests/unit/test_mcp_protocol.py::test_platform_mcp_tools_registry_integrity PASSED [ 72%]
tests/unit/test_mcp_protocol.py::test_mcp_server_initialize_handshake PASSED [ 73%]
tests/unit/test_mcp_protocol.py::test_mcp_server_ping_and_invalid_methods PASSED [ 73%]
tests/unit/test_message_studio.py::test_variable_interpolation PASSED    [ 74%]
tests/unit/test_message_studio.py::test_missing_variables_fallback PASSED [ 75%]
tests/unit/test_message_studio.py::test_keyboard_matrix_ordering PASSED  [ 76%]
tests/unit/test_message_studio.py::test_aiogram_keyboard_generation PASSED [ 77%]
tests/unit/test_message_studio.py::test_default_system_templates PASSED  [ 78%]
tests/unit/test_plugins_engine.py::test_plugin_permission_check PASSED   [ 79%]
tests/unit/test_plugins_engine.py::test_plugin_hook_execution_in_sandbox PASSED [ 80%]
tests/unit/test_plugins_engine.py::test_plugin_crypto_price_tracker PASSED [ 80%]
tests/unit/test_security.py::test_password_hashing PASSED                [ 81%]
tests/unit/test_security.py::test_aes_256_gcm_encryption PASSED          [ 82%]
tests/unit/test_security.py::test_jwt_tokens PASSED                      [ 83%]
tests/unit/test_security.py::test_token_hashing PASSED                   [ 84%]
tests/unit/test_security_audit.py::test_secure_filename_and_path_traversal_neutralization PASSED [ 85%]
tests/unit/test_security_audit.py::test_validate_file_content_magic_bytes_and_extensions PASSED [ 86%]
tests/unit/test_security_audit.py::test_safe_template_rendering_zero_ssti_and_eval PASSED [ 86%]
tests/unit/test_security_audit.py::test_in_app_rate_limiter_sliding_window PASSED [ 87%]
tests/unit/test_security_audit.py::test_sql_injection_defense_via_parameterized_queries PASSED [ 88%]
tests/unit/test_security_audit.py::test_audit_service_action_logging PASSED [ 89%]
tests/unit/test_unicode_styler.py::test_small_caps_transformation PASSED [ 90%]
tests/unit/test_unicode_styler.py::test_tag_and_variable_preservation PASSED [ 91%]
tests/unit/test_unicode_styler.py::test_other_unicode_styles PASSED      [ 92%]
tests/unit/test_unicode_styler.py::test_symbol_catalog_contents PASSED   [ 93%]
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 [ 99%]
tests/unit/test_workflow_engine.py::test_workflow_engine_end_to_end_graph_execution PASSED [100%]

=================================== FAILURES ===================================
_________________ test_bot_modular_api_and_execution_lifecycle _________________

async_client = <httpx.AsyncClient object at 0x7ce71a8d4c50>
db_session = <sqlalchemy.ext.asyncio.session.AsyncSession object at 0x7ce71ab9b530>

    @pytest.mark.asyncio
    async def test_bot_modular_api_and_execution_lifecycle(
        async_client: AsyncClient,
        db_session: AsyncSession,
    ):
        # --------------------------------------------------------------------------
        # 1. Setup Tenant, User, and Bot
        # --------------------------------------------------------------------------
        user_email = f"mod_dev_{uuid.uuid4().hex[:6]}@example.com"
        reg_resp = await async_client.post(
            "/api/v1/auth/register",
            json={"email": user_email, "password": "PasswordM123!", "full_name": "Modular Dev"},
        )
        user_token = reg_resp.json()["data"]["access_token"]
    
        tenant_resp = await async_client.post(
            "/api/v1/tenants",
            headers={"Authorization": f"Bearer {user_token}"},
            json={"name": "Modular Fleet Org", "slug": f"mod-{uuid.uuid4().hex[:6]}"},
        )
        tenant_id = uuid.UUID(tenant_resp.json()["data"]["id"])
        headers = {
            "Authorization": f"Bearer {user_token}",
            "X-Tenant-ID": str(tenant_id),
        }
    
        # Register Bot
        bot_token = f"token_modular_{uuid.uuid4().hex[:8]}_test"
        bot_username = f"modular_bot_{uuid.uuid4().hex[:6]}"
        TelegramApiService.register_mock_bot(bot_token, bot_username, "Modular Bot")
    
        bot_reg_resp = await async_client.post(
            "/api/v1/bots",
            headers=headers,
            json={"token": bot_token, "name": "Nexus Modular Bot", "default_locale": "en"},
        )
        assert bot_reg_resp.status_code == 201
        bot_data = bot_reg_resp.json()["data"]
        bot_id = uuid.UUID(bot_data["id"])
    
        # --------------------------------------------------------------------------
        # 2. Query Bot Modules API: GET /api/v1/bots/{bot_id}/modules
        # --------------------------------------------------------------------------
        modules_resp = await async_client.get(f"/api/v1/bots/{bot_id}/modules", headers=headers)
        assert modules_resp.status_code == 200
        mods = modules_resp.json()["data"]
>       assert len(mods) == 10
E       AssertionError: assert 11 == 10
E        +  where 11 = len([{'id': 'welcome_message', 'name': 'Welcome Message & Onboarding', 'category': 'engagement', 'icon': 'sparkles', ...}, {'id': 'force_join', 'name': 'Force Join Channel Guard', 'category': 'security', 'icon': 'shield-check', ...}, {'id': 'referrals', 'name': 'Referral & Viral Growth Engine', 'category': 'growth', 'icon': 'share-2', ...}, {'id': 'redeem_codes', 'name': 'Redeem Codes & Gift Vouchers', 'category': 'monetization', 'icon': 'gift', ...}, {'id': 'broadcasts', 'name': 'Broadcast & Announcement Pipeline', 'category': 'messaging', 'icon': 'radio', ...}, {'id': 'user_management', 'name': 'Audience & Subscriber Directory', 'category': 'management', 'icon': 'users', ...}, ...])

tests/integration/test_bot_modular_api_and_execution.py:59: AssertionError
----------------------------- Captured stdout call -----------------------------
2026-11-19 05:03:35 [info     ] dispatching_domain_event       event_id=538e95c7-a813-4070-a650-e621b2e66e0b event_type=TenantCreatedEvent handlers_count=1
2026-11-19 05:03:35 [info     ] domain_event_recorded          event_id=538e95c7-a813-4070-a650-e621b2e66e0b event_type=TenantCreatedEvent tenant_id=77f8af23-3f6c-47e3-bc26-d2d46559bb7e user_id=None
2026-11-19 05:03:35 [info     ] dispatching_domain_event       event_id=66c23c38-ac87-4dd2-8ee7-80fb6ec612f4 event_type=UserRegisteredEvent handlers_count=1
2026-11-19 05:03:35 [info     ] domain_event_recorded          event_id=66c23c38-ac87-4dd2-8ee7-80fb6ec612f4 event_type=UserRegisteredEvent tenant_id=None user_id=4df21e66-e865-4e10-9662-10f734c006a9
2026-11-19 05:03:35 [info     ] dispatching_domain_event       event_id=c478d0ef-8cb8-420e-bbd3-0ef9816bc79a event_type=TenantCreatedEvent handlers_count=1
2026-11-19 05:03:35 [info     ] domain_event_recorded          event_id=c478d0ef-8cb8-420e-bbd3-0ef9816bc79a event_type=TenantCreatedEvent tenant_id=b68c2d33-ec47-45c7-a985-f4ac15c485a8 user_id=None
2026-11-19 05:03:35 [info     ] bot_registered_successfully    bot_id=c7d5e190-dd3d-419f-9c78-5b0c5b95f3aa tenant_id=b68c2d33-ec47-45c7-a985-f4ac15c485a8 username=modular_bot_689e92
_______________________ test_module_catalog_definitions ________________________

    @pytest.mark.asyncio
    async def test_module_catalog_definitions():
        """Verifies all 9 core modules are fully defined with schema and defaults."""
        expected_modules = {
            "welcome_message",
            "force_join",
            "referrals",
            "broadcasts",
            "user_management",
            "auto_filter",
            "payments",
            "subscriptions",
            "ai_assistant",
            "logs_tracker",
        }
>       assert set(CORE_MODULE_DEFINITIONS.keys()) == expected_modules
E       AssertionError: assert {'ai_assistan...ayments', ...} == {'ai_assistan...ayments', ...}
E         
E         Extra items in the left set:
E         'redeem_codes'
E         
E         Full diff: (-: missing in left side, +: extra in left side)
E           {
E               'ai_assistant',...
E         
E         ...Full output truncated, use '-vv' to show

tests/unit/test_bot_modular_engine.py:50: AssertionError
__________________________ test_bot_module_lifecycle ___________________________

db_session = <sqlalchemy.ext.asyncio.session.AsyncSession object at 0x7ce719e68a70>

    @pytest.mark.asyncio
    async def test_bot_module_lifecycle(db_session: AsyncSession):
        """Tests install, list, toggle on/off, update config, and uninstall of bot modules."""
        bot = await create_dummy_bot(db_session, "Modular Test Bot")
        bot_id = bot.id
    
        service = BotModuleService(db_session)
    
        # 1. List modules initially - none installed
        modules = await service.list_bot_modules(bot_id)
>       assert len(modules) == 10
E       AssertionError: assert 11 == 10
E        +  where 11 = len([{'id': 'welcome_message', 'name': 'Welcome Message & Onboarding', 'category': 'engagement', 'icon': 'sparkles', ...}, {'id': 'force_join', 'name': 'Force Join Channel Guard', 'category': 'security', 'icon': 'shield-check', ...}, {'id': 'referrals', 'name': 'Referral & Viral Growth Engine', 'category': 'growth', 'icon': 'share-2', ...}, {'id': 'redeem_codes', 'name': 'Redeem Codes & Gift Vouchers', 'category': 'monetization', 'icon': 'gift', ...}, {'id': 'broadcasts', 'name': 'Broadcast & Announcement Pipeline', 'category': 'messaging', 'icon': 'radio', ...}, {'id': 'user_management', 'name': 'Audience & Subscriber Directory', 'category': 'management', 'icon': 'users', ...}, ...])

tests/unit/test_bot_modular_engine.py:70: AssertionError
=========================== short test summary info ============================
FAILED tests/integration/test_bot_modular_api_and_execution.py::test_bot_modular_api_and_execution_lifecycle
FAILED tests/unit/test_bot_modular_engine.py::test_module_catalog_definitions
FAILED tests/unit/test_bot_modular_engine.py::test_bot_module_lifecycle - Ass...
======================== 3 failed, 112 passed in 26.06s ========================
