Created At: 2026-11-18T08:42:23Z Completed At: 2026-11-18T08:42:29Z Command exited with code 1. Command output: ============================= 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 9 items tests/unit/test_billing_gateways.py::test_razorpay_payment_signature_verification PASSED [ 11%] tests/unit/test_billing_gateways.py::test_razorpay_webhook_signature_verification PASSED [ 22%] tests/unit/test_billing_gateways.py::test_stripe_webhook_signature_verification PASSED [ 33%] tests/unit/test_billing_gateways.py::test_gateway_factory_resolution PASSED [ 44%] tests/unit/test_wallet_and_ledger.py::test_wallet_credit_debit_and_immutable_checksum FAILED [ 55%] tests/unit/test_coupons_and_entitlements.py::test_coupon_validation_and_discounts FAILED [ 66%] tests/unit/test_coupons_and_entitlements.py::test_entitlement_enforcement_and_feature_gates PASSED [ 77%] tests/integration/test_billing_checkout_and_lifecycle.py::test_full_billing_lifecycle_and_security FAILED [ 88%] tests/integration/test_billing_webhooks.py::test_razorpay_and_stripe_webhooks_and_deduplication PASSED [100%] =================================== FAILURES =================================== _______________ test_wallet_credit_debit_and_immutable_checksum ________________ self = operation = 'INSERT INTO wallets (id, balance, currency, is_frozen, tenant_id, created_at, updated_at) VALUES ($1::UUID, $2::INTEGER, $3::VARCHAR, $4::BOOLEAN, $5::UUID, $6::TIMESTAMP WITH TIME ZONE, $7::TIMESTAMP WITH TIME ZONE)' parameters = (UUID('606c9539-9ab6-4486-a64f-da3c75f5a842'), 0, 'INR', False, UUID('907cb77b-5910-4330-baf7-d0f78ff9a7e6'), datetime.datetime(2026, 11, 18, 8, 42, 27, 404886, 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 "wallets" violates foreign key constraint "wallets_tenant_id_fkey" E DETAIL: Key (tenant_id)=(907cb77b-5910-4330-baf7-d0f78ff9a7e6) 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('606c9539-9ab6-4486-a64f-da3c75f5a842'), 0, 'INR', False, UUID('907cb77b-5910-4330-baf7-d0f78ff9a7e6'), datetime.datetime(2026, 11, 18, 8, 42, 27, 404886, 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 = dbapi = error = ForeignKeyViolationError('insert or update on table "wallets" violates foreign key constraint "wallets_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 "wallets" violates foreign key constraint "wallets_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: @pytest.mark.asyncio async def test_wallet_credit_debit_and_immutable_checksum(): tenant_id = uuid.uuid4() async with get_db_session() as session: wallet_service = WalletService(session) # 1. Initial wallet creation > wallet = await wallet_service.get_or_create_wallet(tenant_id) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ tests/unit/test_wallet_and_ledger.py:16: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ modules/billing/wallet_service.py:16: in get_or_create_wallet return await self.repo.get_or_create_wallet(tenant_id) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ modules/billing/repository.py:283: in get_or_create_wallet await self.db.commit() .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) :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() :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) :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 = dbapi = error = ForeignKeyViolationError('insert or update on table "wallets" violates foreign key constraint "wallets_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 "wallets" violates foreign key constraint "wallets_tenant_id_fkey" E [SQL: INSERT INTO wallets (id, balance, currency, is_frozen, tenant_id, created_at, updated_at) VALUES ($1::UUID, $2::INTEGER, $3::VARCHAR, $4::BOOLEAN, $5::UUID, $6::TIMESTAMP WITH TIME ZONE, $7::TIMESTAMP WITH TIME ZONE)] E [parameters: (UUID('606c9539-9ab6-4486-a64f-da3c75f5a842'), 0, 'INR', False, UUID('907cb77b-5910-4330-baf7-d0f78ff9a7e6'), datetime.datetime(2026, 11, 18, 8, 42, 27, 404886, tzinfo=datetime.timezone.utc), datetime.datetime(2026, 11, 18, 8, 42, 27, 404891, 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 ----------------------------- Captured stdout call ----------------------------- 2026-11-18 08:42:27 [info ] initializing_db_engine max_overflow=5 pool_size=10 _____________________ test_coupon_validation_and_discounts _____________________ @pytest.mark.asyncio async def test_coupon_validation_and_discounts(): async with get_db_session() as session: billing_service = BillingService(session) > await billing_service.seed_default_plans() tests/unit/test_coupons_and_entitlements.py:17: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ modules/billing/service.py:136: in seed_default_plans await self.repo.upsert_plan(plan) modules/billing/repository.py:39: in upsert_plan existing = await self.get_plan_by_id(plan.id) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ modules/billing/repository.py:35: in get_plan_by_id res = await self.db.execute(select(Plan).where(Plan.id == plan_id)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py:652: in execute result = await greenlet_spawn( .venv/lib/python3.12/site-packages/sqlalchemy/util/concurrency.py:214: in greenlet_spawn result = context.throw(*sys.exc_info()) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py:2555: in execute return self._execute_internal( .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py:2432: in _execute_internal conn = self._connection_for_bind(bind) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py:2255: in _connection_for_bind return trans._connection_for_bind(engine, execution_options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ :2: in _connection_for_bind return target(fn, self, bind, execution_options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .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:1282: in _connection_for_bind conn = bind.connect() ^^^^^^^^^^^^^^ .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py:3279: in connect return self._connection_cls(self) ^^^^^^^^^^^^^^^^^^^^^^^^^^ .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py:154: in __init__ self._dbapi_connection = engine.raw_connection() ^^^^^^^^^^^^^^^^^^^^^^^ .venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py:3303: in raw_connection return self.pool.connect() ^^^^^^^^^^^^^^^^^^^ .venv/lib/python3.12/site-packages/sqlalchemy/pool/base.py:460: in connect return _ConnectionFairy._checkout(self) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .venv/lib/python3.12/site-packages/sqlalchemy/pool/base.py:1454: in _checkout 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/pool/base.py:1392: in _checkout result = pool._dialect._do_ping_w_event( .venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py:968: in _do_ping_w_event return self.do_ping(dbapi_connection) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py:1223: in do_ping dbapi_connection.ping() .venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py:879: in ping self._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) .venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py:856: in _handle_exception_no_connection super()._handle_exception_no_connection(dbapi, error) .venv/lib/python3.12/site-packages/sqlalchemy/connectors/asyncio.py:409: in _handle_exception_no_connection raise error.with_traceback(exc_info[2]) .venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py:877: in ping _ = await_(self._async_ping()) ^^^^^^^^^^^^^^^^^^^^^^^^^^ .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:886: in _async_ping await tr.start() .venv/lib/python3.12/site-packages/asyncpg/transaction.py:146: in start await self._connection.execute(query) .venv/lib/python3.12/site-packages/asyncpg/connection.py:377: in execute result = await self._protocol.query(query, timeout) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ > ??? E RuntimeError: Task cb=[_run_until_complete_cb() at /usr/lib/python3.12/asyncio/base_events.py:182]> got Future attached to a different loop asyncpg/protocol/protocol.pyx:341: RuntimeError ------------------------------ Captured log call ------------------------------- ERROR sqlalchemy.pool.impl.AsyncAdaptedQueuePool:base.py:389 Exception terminating connection > Traceback (most recent call last): File "asyncpg/protocol/protocol.pyx", line 585, in asyncpg.protocol.protocol.BaseProtocol.close File "asyncpg/protocol/protocol.pyx", line 677, in _drain_cancels File "asyncpg/protocol/protocol.pyx", line 624, in asyncpg.protocol.protocol.BaseProtocol._request_cancel File "/root/telegram-saas/.venv/lib/python3.12/site-packages/asyncpg/connection.py", line 1712, in _cancel_current_command self._cancellations.add(self._loop.create_task( ^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.12/asyncio/base_events.py", line 456, in create_task self._check_closed() File "/usr/lib/python3.12/asyncio/base_events.py", line 541, in _check_closed raise RuntimeError('Event loop is closed') RuntimeError: Event loop is closed During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/root/telegram-saas/.venv/lib/python3.12/site-packages/asyncpg/connection.py", line 1536, in close await self._protocol.close(timeout) File "asyncpg/protocol/protocol.pyx", line 610, in close File "asyncpg/protocol/protocol.pyx", line 697, in asyncpg.protocol.protocol.BaseProtocol._handle_waiter_on_connection_lost File "/usr/lib/python3.12/asyncio/base_events.py", line 795, in call_soon self._check_closed() File "/usr/lib/python3.12/asyncio/base_events.py", line 541, in _check_closed raise RuntimeError('Event loop is closed') RuntimeError: Event loop is closed During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/root/telegram-saas/.venv/lib/python3.12/site-packages/sqlalchemy/pool/base.py", line 370, in _close_connection self._dialect.do_terminate(connection) File "/root/telegram-saas/.venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py", line 1190, in do_terminate dbapi_connection.terminate() File "/root/telegram-saas/.venv/lib/python3.12/site-packages/sqlalchemy/connectors/asyncio.py", line 440, in terminate await_(asyncio.shield(self._terminate_graceful_close())) File "/root/telegram-saas/.venv/lib/python3.12/site-packages/sqlalchemy/util/concurrency.py", line 171, in await_ return current.parent.switch(awaitable) # type: ignore[no-any-return] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/root/telegram-saas/.venv/lib/python3.12/site-packages/sqlalchemy/util/concurrency.py", line 209, in greenlet_spawn value = await result ^^^^^^^^^^^^ File "/root/telegram-saas/.venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/asyncpg.py", line 955, in _terminate_graceful_close await self._connection.close(timeout=2) File "/root/telegram-saas/.venv/lib/python3.12/site-packages/asyncpg/connection.py", line 1539, in close self._abort() File "/root/telegram-saas/.venv/lib/python3.12/site-packages/asyncpg/connection.py", line 1600, in _abort self._protocol.abort() File "asyncpg/protocol/protocol.pyx", line 567, in asyncpg.protocol.protocol.BaseProtocol.abort File "/usr/lib/python3.12/asyncio/sslproto.py", line 250, in abort self._force_close(None) File "/usr/lib/python3.12/asyncio/sslproto.py", line 255, in _force_close self._ssl_protocol._abort(exc) File "/usr/lib/python3.12/asyncio/sslproto.py", line 671, in _abort self._transport._force_close(exc) File "/usr/lib/python3.12/asyncio/selector_events.py", line 906, in _force_close self._loop.call_soon(self._call_connection_lost, exc) File "/usr/lib/python3.12/asyncio/base_events.py", line 795, in call_soon self._check_closed() File "/usr/lib/python3.12/asyncio/base_events.py", line 541, in _check_closed raise RuntimeError('Event loop is closed') RuntimeError: Event loop is closed ___________________ test_full_billing_lifecycle_and_security ___________________ async_client = @pytest.mark.asyncio async def test_full_billing_lifecycle_and_security(async_client: AsyncClient): settings = get_settings() # 1. Register new user and tenant email = f"billing_user_{uuid.uuid4().hex[:6]}@example.com" reg_resp = await async_client.post( "/api/v1/auth/register", json={"email": email, "password": "Password123!", "full_name": "Billing Admin"}, ) assert reg_resp.status_code == 201 token = reg_resp.json()["data"]["access_token"] headers = {"Authorization": f"Bearer {token}"} # Get Tenant ID me_resp = await async_client.get("/api/v1/auth/me", headers=headers) > tenant_id = me_resp.json()["data"]["default_tenant_id"] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ E KeyError: 'default_tenant_id' tests/integration/test_billing_checkout_and_lifecycle.py:30: KeyError ----------------------------- Captured stdout call ----------------------------- 2026-11-18 08:42:28 [info ] dispatching_domain_event event_id=890577d0-8221-4025-b205-1cd2ad80c892 event_type=UserRegisteredEvent handlers_count=0 =============================== warnings summary =============================== tests/integration/test_billing_webhooks.py::test_razorpay_and_stripe_webhooks_and_deduplication /root/telegram-saas/.venv/lib/python3.12/site-packages/pydantic/_internal/_generate_schema.py:1124: RuntimeWarning: coroutine 'Connection._cancel' was never awaited args = tuple(self._resolve_forward_ref(a) if isinstance(a, ForwardRef) else a for a in args) Enable tracemalloc to get traceback where the object was allocated. See https://docs.pytest.org/en/stable/how-to/capture-warnings.html#resource-warnings for more info. -- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html =========================== short test summary info ============================ FAILED tests/unit/test_wallet_and_ledger.py::test_wallet_credit_debit_and_immutable_checksum FAILED tests/unit/test_coupons_and_entitlements.py::test_coupon_validation_and_discounts FAILED tests/integration/test_billing_checkout_and_lifecycle.py::test_full_billing_lifecycle_and_security ==================== 3 failed, 6 passed, 1 warning in 1.45s ====================