============================= 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 79 items                                                             

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_celery_telegram_tasks.py::test_telegram_update_task_execution PASSED [  5%]
tests/integration/test_emojis_api.py::test_search_emojis_by_term PASSED  [  6%]
tests/integration/test_emojis_api.py::test_search_emojis_by_category PASSED [  7%]
tests/integration/test_emojis_api.py::test_get_categories_list PASSED    [  8%]
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   [ 15%]
tests/integration/test_i18n_api.py::test_update_user_locale PASSED       [ 16%]
tests/integration/test_i18n_api.py::test_save_custom_translation_override PASSED [ 17%]
tests/integration/test_i18n_api.py::test_audit_translations_and_missing_keys PASSED [ 18%]
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 PASSED [ 21%]
tests/integration/test_message_studio_e2e_publishing.py::test_message_studio_publishing_changes_real_bot_response PASSED [ 22%]
tests/integration/test_multi_bot_engine.py::test_multi_tenant_multi_bot_engine_lifecycle PASSED [ 24%]
tests/integration/test_multilingual_bot_responses.py::test_language_selection_in_actual_bot_responses PASSED [ 25%]
tests/integration/test_text_designer_api.py::test_text_designer_api_endpoints PASSED [ 26%]
tests/tenant_isolation/test_tenant_isolation.py::test_strict_tenant_isolation PASSED [ 27%]
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 [ 39%]
tests/unit/test_bot_engine.py::test_webhook_secret_generation_and_verification PASSED [ 40%]
tests/unit/test_bot_engine.py::test_rate_limit_retry_handling PASSED     [ 41%]
tests/unit/test_broadcast_engine.py::test_broadcast_audience_selection_and_opt_out FAILED [ 43%]
tests/unit/test_coupons_and_entitlements.py::test_coupon_validation_and_discounts PASSED [ 44%]
tests/unit/test_coupons_and_entitlements.py::test_entitlement_enforcement_and_feature_gates PASSED [ 45%]
tests/unit/test_emojis.py::test_telegram_html_emoji_formatting PASSED    [ 46%]
tests/unit/test_emojis.py::test_telegram_markdown_emoji_formatting PASSED [ 48%]
tests/unit/test_emojis.py::test_id_precision_is_preserved_as_string PASSED [ 49%]
tests/unit/test_emojis.py::test_custom_emoji_validation PASSED           [ 50%]
tests/unit/test_formatter_and_engine.py::test_box_header_formatting PASSED [ 51%]
tests/unit/test_formatter_and_engine.py::test_separator_presets PASSED   [ 53%]
tests/unit/test_formatter_and_engine.py::test_info_block_formatting PASSED [ 54%]
tests/unit/test_formatter_and_engine.py::test_progress_bar_generation PASSED [ 55%]
tests/unit/test_formatter_and_engine.py::test_progress_step_header PASSED [ 56%]
tests/unit/test_formatter_and_engine.py::test_telegram_message_builder PASSED [ 58%]
tests/unit/test_i18n.py::test_supported_locales_catalog PASSED           [ 59%]
tests/unit/test_i18n.py::test_rtl_detection PASSED                       [ 60%]
tests/unit/test_i18n.py::test_plural_rules PASSED                        [ 62%]
tests/unit/test_i18n.py::test_formatting PASSED                          [ 63%]
tests/unit/test_i18n.py::test_fallback_resolution PASSED                 [ 64%]
tests/unit/test_i18n.py::test_translation_engine PASSED                  [ 65%]
tests/unit/test_i18n.py::test_bcp47_locale_normalization PASSED          [ 67%]
tests/unit/test_i18n.py::test_interpolation PASSED                       [ 68%]
tests/unit/test_i18n.py::test_missing_translation_fallback PASSED        [ 69%]
tests/unit/test_i18n.py::test_telegram_keyboard_builder PASSED           [ 70%]
tests/unit/test_message_studio.py::test_variable_interpolation PASSED    [ 72%]
tests/unit/test_message_studio.py::test_missing_variables_fallback PASSED [ 73%]
tests/unit/test_message_studio.py::test_keyboard_matrix_ordering PASSED  [ 74%]
tests/unit/test_message_studio.py::test_aiogram_keyboard_generation PASSED [ 75%]
tests/unit/test_message_studio.py::test_default_system_templates PASSED  [ 77%]
tests/unit/test_plugins_engine.py::test_plugin_permission_check PASSED   [ 78%]
tests/unit/test_plugins_engine.py::test_plugin_hook_execution_in_sandbox PASSED [ 79%]
tests/unit/test_plugins_engine.py::test_plugin_crypto_price_tracker PASSED [ 81%]
tests/unit/test_security.py::test_password_hashing PASSED                [ 82%]
tests/unit/test_security.py::test_aes_256_gcm_encryption PASSED          [ 83%]
tests/unit/test_security.py::test_jwt_tokens PASSED                      [ 84%]
tests/unit/test_security.py::test_token_hashing PASSED                   [ 86%]
tests/unit/test_unicode_styler.py::test_small_caps_transformation PASSED [ 87%]
tests/unit/test_unicode_styler.py::test_tag_and_variable_preservation PASSED [ 88%]
tests/unit/test_unicode_styler.py::test_other_unicode_styles PASSED      [ 89%]
tests/unit/test_unicode_styler.py::test_symbol_catalog_contents PASSED   [ 91%]
tests/unit/test_validators_and_presets.py::test_html_validator_valid PASSED [ 92%]
tests/unit/test_validators_and_presets.py::test_html_validator_invalid_tags PASSED [ 93%]
tests/unit/test_validators_and_presets.py::test_html_validator_unclosed_tags PASSED [ 94%]
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_broadcast_audience_selection_and_opt_out _________________

self = <sqlalchemy.dialects.postgresql.asyncpg.AsyncAdapt_asyncpg_cursor object at 0x7500422b9150>
operation = 'INSERT INTO bots (id, name, username, status, default_locale, created_at, updated_at, tenant_id) VALUES ($1::UUID, $2::VARCHAR, $3::VARCHAR, $4::VARCHAR, $5::VARCHAR, $6::TIMESTAMP WITH TIME ZONE, $7::TIMESTAMP WITH TIME ZONE, $8::UUID)'
parameters = (UUID('606285c5-02c7-4308-9bf9-3a2441f07611'), 'Broadcast Test Bot', 'bcast_bot_0e1828', 'active', 'en', datetime.datetime(2026, 11, 18, 8, 54, 51, 177834, tzinfo=datetime.timezone.utc), ...)

    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 "bots" violates foreign key constraint "bots_tenant_id_fkey"
E   DETAIL:  Key (tenant_id)=(b154fd6b-59c3-4499-acec-1e33ac785317) is not present in table "tenants".

asyncpg/protocol/protocol.pyx:197: ForeignKeyViolationError

The above exception was the direct cause of the following exception:

self = <sqlalchemy.engine.base.Connection object at 0x750042218f80>
dialect = <sqlalchemy.dialects.postgresql.asyncpg.PGDialect_asyncpg object at 0x7500421cd9d0>
context = <sqlalchemy.dialects.postgresql.asyncpg.PGExecutionContext_asyncpg object at 0x75004221ad80>
statement = <sqlalchemy.dialects.postgresql.asyncpg.PGCompiler_asyncpg object at 0x750042218230>
parameters = [(UUID('606285c5-02c7-4308-9bf9-3a2441f07611'), 'Broadcast Test Bot', 'bcast_bot_0e1828', 'active', 'en', datetime.datetime(2026, 11, 18, 8, 54, 51, 177834, tzinfo=datetime.timezone.utc), ...)]

    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 = <class 'sqlalchemy.dialects.postgresql.asyncpg.AsyncAdapt_asyncpg_connection'>
dbapi = <sqlalchemy.dialects.postgresql.asyncpg.AsyncAdapt_asyncpg_dbapi object at 0x750042255e50>
error = ForeignKeyViolationError('insert or update on table "bots" violates foreign key constraint "bots_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 "bots" violates foreign key constraint "bots_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 = <sqlalchemy.ext.asyncio.session.AsyncSession object at 0x75004231be00>

    @pytest.mark.asyncio
    async def test_broadcast_audience_selection_and_opt_out(db_session: AsyncSession):
        tenant_id = uuid.uuid4()
        bot_id = uuid.uuid4()
    
        # 1. Setup Tenant and Bot
        tenant = Tenant(
            id=tenant_id,
            name=f"Broadcast Org {tenant_id.hex[:6]}",
            slug=f"bcast-{tenant_id.hex[:6]}",
            plan_id="pro",
        )
        bot = Bot(
            id=bot_id,
            tenant_id=tenant_id,
            name="Broadcast Test Bot",
            username=f"bcast_bot_{uuid.uuid4().hex[:6]}",
            status="active",
            default_locale="en",
        )
        db_session.add_all([tenant, bot])
>       await db_session.commit()

tests/unit/test_broadcast_engine.py:30: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
.venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py:1309: in commit
    await greenlet_spawn(self.sync_session.commit)
.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:2177: in commit
    trans.commit(_to_root=True)
<sqlalchemy generated _go() wrapper for sqlalchemy.orm.session.SessionTransaction.commit>:2: in commit
    return target(fn, self, _to_root=_to_root)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.12/site-packages/sqlalchemy/orm/state_changes.py:137: in _go
    ret_value = fn(self, *arg, **kw)
                ^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py:1412: in commit
    self._prepare_impl()
<sqlalchemy generated _go() wrapper for sqlalchemy.orm.session.SessionTransaction._prepare_impl>:2: in _prepare_impl
    return target(fn, self)
           ^^^^^^^^^^^^^^^^
.venv/lib/python3.12/site-packages/sqlalchemy/orm/state_changes.py:137: in _go
    ret_value = fn(self, *arg, **kw)
                ^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py:1386: in _prepare_impl
    self.session.flush()
.venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py:4626: in flush
    self._flush(objects)
<sqlalchemy generated warned() wrapper for sqlalchemy.orm.session.Session._flush>: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:1065: 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 = <class 'sqlalchemy.dialects.postgresql.asyncpg.AsyncAdapt_asyncpg_connection'>
dbapi = <sqlalchemy.dialects.postgresql.asyncpg.AsyncAdapt_asyncpg_dbapi object at 0x750042255e50>
error = ForeignKeyViolationError('insert or update on table "bots" violates foreign key constraint "bots_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 "bots" violates foreign key constraint "bots_tenant_id_fkey"
E                   [SQL: INSERT INTO bots (id, name, username, status, default_locale, created_at, updated_at, tenant_id) VALUES ($1::UUID, $2::VARCHAR, $3::VARCHAR, $4::VARCHAR, $5::VARCHAR, $6::TIMESTAMP WITH TIME ZONE, $7::TIMESTAMP WITH TIME ZONE, $8::UUID)]
E                   [parameters: (UUID('606285c5-02c7-4308-9bf9-3a2441f07611'), 'Broadcast Test Bot', 'bcast_bot_0e1828', 'active', 'en', datetime.datetime(2026, 11, 18, 8, 54, 51, 177834, tzinfo=datetime.timezone.utc), datetime.datetime(2026, 11, 18, 8, 54, 51, 177840, tzinfo=datetime.timezone.utc), UUID('b154fd6b-59c3-4499-acec-1e33ac785317'))]
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
=========================== short test summary info ============================
FAILED tests/unit/test_broadcast_engine.py::test_broadcast_audience_selection_and_opt_out
========================= 1 failed, 78 passed in 8.48s =========================
