Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: close connection thread properly if BaseException raised in connect step #317

Merged
merged 1 commit into from
Feb 3, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion aiosqlite/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ async def _connect(self) -> "Connection":
future = asyncio.get_event_loop().create_future()
self._tx.put_nowait((future, self._connector))
self._connection = await future
except Exception:
except BaseException:
self._stop_running()
self._connection = None
raise
Expand Down
18 changes: 18 additions & 0 deletions aiosqlite/tests/smoke.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from tempfile import TemporaryDirectory
from threading import Thread
from unittest import IsolatedAsyncioTestCase, SkipTest
from unittest.mock import patch

import aiosqlite
from .helpers import setup_logger
Expand Down Expand Up @@ -351,6 +352,23 @@ async def test_connect_error(self):
with self.assertRaisesRegex(OperationalError, "unable to open database"):
await aiosqlite.connect(bad_db)

async def test_connect_base_exception(self):
# Check if connect task is cancelled, thread is properly closed.
def _raise_cancelled_error(*_, **__):
raise asyncio.CancelledError("I changed my mind")

connection = aiosqlite.Connection(lambda: sqlite3.connect(":memory:"), 64)
with (
patch.object(sqlite3, "connect", side_effect=_raise_cancelled_error),
self.assertRaisesRegex(asyncio.CancelledError, "I changed my mind"),
):
async with connection:
...
# Terminate the thread here if the test fails to have a clear error.
if connection._running:
connection._stop_running()
raise AssertionError("connection thread was not stopped")

async def test_iterdump(self):
async with aiosqlite.connect(":memory:") as db:
await db.execute("create table foo (i integer, k charvar(250))")
Expand Down