Skip to content

Commit 883695f

Browse files
authored
fix: close connection thread properly if BaseException raised in connect step (#317)
1 parent 5391d28 commit 883695f

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

aiosqlite/core.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@ async def _connect(self) -> "Connection":
138138
future = asyncio.get_event_loop().create_future()
139139
self._tx.put_nowait((future, self._connector))
140140
self._connection = await future
141-
except Exception:
141+
except BaseException:
142142
self._stop_running()
143143
self._connection = None
144144
raise

aiosqlite/tests/smoke.py

+18
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from tempfile import TemporaryDirectory
88
from threading import Thread
99
from unittest import IsolatedAsyncioTestCase, SkipTest
10+
from unittest.mock import patch
1011

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

355+
async def test_connect_base_exception(self):
356+
# Check if connect task is cancelled, thread is properly closed.
357+
def _raise_cancelled_error(*_, **__):
358+
raise asyncio.CancelledError("I changed my mind")
359+
360+
connection = aiosqlite.Connection(lambda: sqlite3.connect(":memory:"), 64)
361+
with (
362+
patch.object(sqlite3, "connect", side_effect=_raise_cancelled_error),
363+
self.assertRaisesRegex(asyncio.CancelledError, "I changed my mind"),
364+
):
365+
async with connection:
366+
...
367+
# Terminate the thread here if the test fails to have a clear error.
368+
if connection._running:
369+
connection._stop_running()
370+
raise AssertionError("connection thread was not stopped")
371+
354372
async def test_iterdump(self):
355373
async with aiosqlite.connect(":memory:") as db:
356374
await db.execute("create table foo (i integer, k charvar(250))")

0 commit comments

Comments
 (0)