Skip to content

Commit

Permalink
fix: close connection thread properly if BaseException raised in conn…
Browse files Browse the repository at this point in the history
…ect step (#317)
  • Loading branch information
gpajot authored Feb 3, 2025
1 parent 5391d28 commit 883695f
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
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

0 comments on commit 883695f

Please sign in to comment.