============================= 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
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 1 item                                                               

tests/integration/test_bot_modular_api_and_execution.py::test_bot_modular_api_and_execution_lifecycle FAILED [100%]

=================================== FAILURES ===================================
_________________ test_bot_modular_api_and_execution_lifecycle _________________

async_client = <httpx.AsyncClient object at 0x7d0915a4b740>
db_session = <sqlalchemy.ext.asyncio.session.AsyncSession object at 0x7d0915aa7d40>

    @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) == 11
        assert "redeem_codes" in [m["id"] for m in mods]
    
        mod_map = {m["id"]: m for m in mods}
        # Auto-provisioned foundational modules should be active
        assert mod_map["welcome_message"]["is_enabled"] is True
        assert mod_map["broadcasts"]["is_enabled"] is True
        # Others installed on-demand
        assert mod_map["referrals"]["is_enabled"] is False
    
        # --------------------------------------------------------------------------
        # 3. Install & Toggle Modules via API
        # --------------------------------------------------------------------------
        # Activate Referrals
        toggle_ref = await async_client.post(
            f"/api/v1/bots/{bot_id}/modules/referrals/toggle",
            headers=headers,
            json={"is_enabled": True},
        )
        assert toggle_ref.status_code == 200
        assert toggle_ref.json()["data"]["is_enabled"] is True
    
        # Activate Subscriptions
        toggle_sub = await async_client.post(
            f"/api/v1/bots/{bot_id}/modules/subscriptions/toggle",
            headers=headers,
            json={"is_enabled": True},
        )
        assert toggle_sub.status_code == 200
        assert toggle_sub.json()["data"]["is_enabled"] is True
    
        # Update Auto Filter Config & Toggle
        cfg_resp = await async_client.patch(
            f"/api/v1/bots/{bot_id}/modules/auto_filter/config",
            headers=headers,
            json={
                "config": {
                    "rules": [{"trigger": "catalog", "match_type": "contains", "response": "📦 120 Products Available in Store."}],
                    "blocked_words": ["malware"],
                    "action_on_blocked": "warn",
                }
            },
        )
        assert cfg_resp.status_code == 200
        await async_client.post(
            f"/api/v1/bots/{bot_id}/modules/auto_filter/toggle",
            headers=headers,
            json={"is_enabled": True},
        )
    
        # --------------------------------------------------------------------------
        # 4. Verify Real Webhook Execution Against Modules
        # --------------------------------------------------------------------------
        TelegramApiService.clear_sent_messages()
    
        # Query bot secret token to sign webhook requests
        bot_obj = await db_session.get(Bot, bot_id)
        webhook_obj = bot_obj.webhook
        # Use mock matching token
        secret_token = "valid_secret_for_webhook"
        webhook_obj.secret_hash = hash_webhook_secret(secret_token)
        await db_session.commit()
    
        webhook_headers = {"X-Telegram-Bot-Api-Secret-Token": secret_token}
    
        # 4.1 Test /referral command with Referrals active
        resp_ref = await async_client.post(
            f"/webhooks/telegram/{bot_id}",
            headers=webhook_headers,
            json={
                "update_id": 10001,
                "message": {
                    "from": {"id": 555111, "username": "testuser1"},
                    "chat": {"id": 555111},
                    "text": "/referral",
                },
            },
        )
        assert resp_ref.status_code == 200
        sent = TelegramApiService.get_sent_messages()
        assert len(sent) >= 1
        assert "Your Referral Portal" in sent[-1]["text"]
    
        # 4.2 Toggle Referrals OFF and verify execution is blocked!
        await async_client.post(
            f"/api/v1/bots/{bot_id}/modules/referrals/toggle",
            headers=headers,
            json={"is_enabled": False},
        )
        resp_ref_off = await async_client.post(
            f"/webhooks/telegram/{bot_id}",
            headers=webhook_headers,
            json={
                "update_id": 10002,
                "message": {
                    "from": {"id": 555111, "username": "testuser1"},
                    "chat": {"id": 555111},
                    "text": "/referral",
                },
            },
        )
        assert resp_ref_off.status_code == 200
        sent_off = TelegramApiService.get_sent_messages()
        assert "The Referral Program is currently deactivated" in sent_off[-1]["text"]
    
        # 4.3 Test Auto-Filter keyword rule execution
        resp_filter = await async_client.post(
            f"/webhooks/telegram/{bot_id}",
            headers=webhook_headers,
            json={
                "update_id": 10003,
                "message": {
                    "from": {"id": 555111, "username": "testuser1"},
                    "chat": {"id": 555111},
                    "text": "Please show me the catalog items",
                },
            },
        )
        assert resp_filter.status_code == 200
        assert resp_filter.json().get("auto_filtered") is True
        sent_filter = TelegramApiService.get_sent_messages()
        assert "120 Products Available in Store" in sent_filter[-1]["text"]
    
        # 4.4 Test Subscriptions /plans command
        resp_sub = await async_client.post(
            f"/webhooks/telegram/{bot_id}",
            headers=webhook_headers,
            json={
                "update_id": 10004,
                "message": {
                    "from": {"id": 555111, "username": "testuser1"},
                    "chat": {"id": 555111},
                    "text": "/plans",
                },
            },
        )
        assert resp_sub.status_code == 200
        sent_sub = TelegramApiService.get_sent_messages()
        assert "VIP Subscription Tiers" in sent_sub[-1]["text"]
    
        # 4.5 Test Admin Verification Endpoint
        verify_resp = await async_client.post(
            f"/api/v1/bots/{bot_id}/modules/verify-admin",
            headers=headers,
            json={"chat_id": "-1002345678901", "module_id": "force_join"},
        )
        assert verify_resp.status_code == 200
        verify_data = verify_resp.json()["data"]
        assert verify_data["is_admin"] is True
        assert verify_data["can_post_messages"] is True
    
        # --------------------------------------------------------------------------
        # 5. Redeem Codes & 3-Way Trigger Control Endpoints & Execution
        # --------------------------------------------------------------------------
        # 5.1 Enable redeem_codes module
        await async_client.post(
            f"/api/v1/bots/{bot_id}/modules/redeem_codes/toggle",
            headers=headers,
            json={"is_enabled": True},
        )
    
        # 5.2 Create a redeem code via API
        create_rc = await async_client.post(
            f"/api/v1/bots/{bot_id}/redeem-codes",
            headers=headers,
            json={
                "code": "PROMO2026",
                "title": "Welcome Gift Voucher",
                "reward_type": "subscription_days",
                "reward_value": 7,
                "max_uses": 5,
            },
        )
        assert create_rc.status_code == 201
        rc_data = create_rc.json()["data"]
        assert rc_data["code"] == "PROMO2026"
        assert rc_data["reward_type"] == "subscription_days"
        assert rc_data["reward_value"] == 7
        code_id = rc_data["id"]
    
        # 5.3 List redeem codes
        list_rc = await async_client.get(
            f"/api/v1/bots/{bot_id}/redeem-codes",
            headers=headers,
        )
        assert list_rc.status_code == 200
        assert any(c["code"] == "PROMO2026" for c in list_rc.json()["data"])
    
        # 5.4 Test Webhook execution for /redeem PROMO2026
        TelegramApiService.clear_sent_messages()
        resp_redeem = await async_client.post(
            f"/webhooks/telegram/{bot_id}",
            headers=webhook_headers,
            json={
                "update_id": 10005,
                "message": {
                    "from": {"id": 555222, "username": "promouser"},
                    "chat": {"id": 555222},
                    "text": "/redeem PROMO2026",
                },
            },
        )
        assert resp_redeem.status_code == 200
        sent_redeem = TelegramApiService.get_sent_messages()
        assert len(sent_redeem) >= 1
        assert "Redemption Successful" in sent_redeem[-1]["text"]
    
        # 5.5 Test 3-Way Trigger Toggle API
        # Turn OFF commands for redeem_codes
        trigger_patch = await async_client.patch(
            f"/api/v1/bots/{bot_id}/modules/redeem_codes/triggers",
            headers=headers,
            json={
                "enable_command": False,
                "enable_inline_button": True,
                "enable_menu_button": False,
            },
        )
        assert trigger_patch.status_code == 200
        trigger_data = trigger_patch.json()["data"]
        assert trigger_data["enable_command"] is False
        assert trigger_data["enable_inline_button"] is True
        assert trigger_data["enable_menu_button"] is False
    
        # 5.6 Now sending /redeem should be blocked because enable_command is False
        TelegramApiService.clear_sent_messages()
        resp_redeem_blocked = await async_client.post(
            f"/webhooks/telegram/{bot_id}",
            headers=webhook_headers,
            json={
                "update_id": 10006,
                "message": {
                    "from": {"id": 555333, "username": "blockeduser"},
                    "chat": {"id": 555333},
                    "text": "/redeem PROMO2026",
                },
            },
        )
        assert resp_redeem_blocked.status_code == 200
        sent_blocked = TelegramApiService.get_sent_messages()
        assert len(sent_blocked) >= 1
>       assert "command trigger is disabled" in sent_blocked[-1]["text"]
E       AssertionError: assert 'command trigger is disabled' in '⚠️ <i>The command /redeem has been turned off by the bot administrator.</i>'

tests/integration/test_bot_modular_api_and_execution.py:300: AssertionError
----------------------------- Captured stdout call -----------------------------
2026-11-19 05:09:22 [info     ] dispatching_domain_event       event_id=4d3ddec4-681a-4418-9d82-7ff74d9239d9 event_type=TenantCreatedEvent handlers_count=1
2026-11-19 05:09:22 [info     ] domain_event_recorded          event_id=4d3ddec4-681a-4418-9d82-7ff74d9239d9 event_type=TenantCreatedEvent tenant_id=e15e5290-57c3-407d-9311-e1833682daad user_id=None
2026-11-19 05:09:22 [info     ] dispatching_domain_event       event_id=107d6f21-e2f0-4ab6-b972-b438cc51c346 event_type=UserRegisteredEvent handlers_count=1
2026-11-19 05:09:22 [info     ] domain_event_recorded          event_id=107d6f21-e2f0-4ab6-b972-b438cc51c346 event_type=UserRegisteredEvent tenant_id=None user_id=ae171292-c86b-45ce-a4dc-a0a6be37b216
2026-11-19 05:09:22 [info     ] dispatching_domain_event       event_id=cf050130-0a8a-4817-895c-45da4e298ef5 event_type=TenantCreatedEvent handlers_count=1
2026-11-19 05:09:22 [info     ] domain_event_recorded          event_id=cf050130-0a8a-4817-895c-45da4e298ef5 event_type=TenantCreatedEvent tenant_id=8943e9e9-0bd1-4cae-ac68-21d1a3be0d6c user_id=None
2026-11-19 05:09:22 [info     ] bot_registered_successfully    bot_id=6dbf7417-10ac-49d8-8fe6-dfe6800d5960 tenant_id=8943e9e9-0bd1-4cae-ac68-21d1a3be0d6c username=modular_bot_acd225
2026-11-19 05:09:23 [warning  ] celery_enqueue_fallback_to_sync bot_id=6dbf7417-10ac-49d8-8fe6-dfe6800d5960 error='[Errno 111] Connection refused'
2026-11-19 05:09:24 [warning  ] celery_enqueue_fallback_to_sync bot_id=6dbf7417-10ac-49d8-8fe6-dfe6800d5960 error='[Errno 111] Connection refused'
2026-11-19 05:09:25 [warning  ] celery_enqueue_fallback_to_sync bot_id=6dbf7417-10ac-49d8-8fe6-dfe6800d5960 error='[Errno 111] Connection refused'
2026-11-19 05:09:26 [warning  ] celery_enqueue_fallback_to_sync bot_id=6dbf7417-10ac-49d8-8fe6-dfe6800d5960 error='[Errno 111] Connection refused'
2026-11-19 05:09:27 [warning  ] celery_enqueue_fallback_to_sync bot_id=6dbf7417-10ac-49d8-8fe6-dfe6800d5960 error='[Errno 111] Connection refused'
2026-11-19 05:09:28 [warning  ] celery_enqueue_fallback_to_sync bot_id=6dbf7417-10ac-49d8-8fe6-dfe6800d5960 error='[Errno 111] Connection refused'
------------------------------ Captured log call -------------------------------
WARNING  kombu.connection:connection.py:760 No hostname was supplied. Reverting to default 'localhost'
=========================== short test summary info ============================
FAILED tests/integration/test_bot_modular_api_and_execution.py::test_bot_modular_api_and_execution_lifecycle
============================== 1 failed in 7.12s ===============================
