1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
|
# Copyright Amethyst Reese
# Licensed under the MIT license
import asyncio
import sqlite3
from pathlib import Path
from sqlite3 import OperationalError
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
class SmokeTest(IsolatedAsyncioTestCase):
@classmethod
def setUpClass(cls):
setup_logger()
def setUp(self):
td = TemporaryDirectory()
self.addCleanup(td.cleanup)
self.db = Path(td.name).resolve() / "test.db"
async def test_connection_await(self):
db = await aiosqlite.connect(self.db)
self.assertIsInstance(db, aiosqlite.Connection)
async with db.execute("select 1, 2") as cursor:
rows = await cursor.fetchall()
self.assertEqual(rows, [(1, 2)])
await db.close()
async def test_connection_context(self):
async with aiosqlite.connect(self.db) as db:
self.assertIsInstance(db, aiosqlite.Connection)
async with db.execute("select 1, 2") as cursor:
rows = await cursor.fetchall()
self.assertEqual(rows, [(1, 2)])
async def test_connection_locations(self):
TEST_DB = self.db.as_posix()
class Fake: # pylint: disable=too-few-public-methods
def __str__(self):
return TEST_DB
locs = (Path(TEST_DB), TEST_DB, TEST_DB.encode(), Fake())
async with aiosqlite.connect(locs[0]) as db:
await db.execute("create table foo (i integer, k integer)")
await db.execute("insert into foo (i, k) values (1, 5)")
await db.commit()
cursor = await db.execute("select * from foo")
rows = await cursor.fetchall()
for loc in locs:
async with aiosqlite.connect(loc) as db:
cursor = await db.execute("select * from foo")
self.assertEqual(await cursor.fetchall(), rows)
async def test_multiple_connections(self):
async with aiosqlite.connect(self.db) as db:
await db.execute(
"create table multiple_connections "
"(i integer primary key asc, k integer)"
)
async def do_one_conn(i):
async with aiosqlite.connect(self.db) as db:
await db.execute("insert into multiple_connections (k) values (?)", [i])
await db.commit()
await asyncio.gather(*[do_one_conn(i) for i in range(10)])
async with aiosqlite.connect(self.db) as db:
cursor = await db.execute("select * from multiple_connections")
rows = await cursor.fetchall()
assert len(rows) == 10
async def test_multiple_queries(self):
async with aiosqlite.connect(self.db) as db:
await db.execute(
"create table multiple_queries "
"(i integer primary key asc, k integer)"
)
await asyncio.gather(
*[
db.execute("insert into multiple_queries (k) values (?)", [i])
for i in range(10)
]
)
await db.commit()
async with aiosqlite.connect(self.db) as db:
cursor = await db.execute("select * from multiple_queries")
rows = await cursor.fetchall()
assert len(rows) == 10
async def test_iterable_cursor(self):
async with aiosqlite.connect(self.db) as db:
cursor = await db.cursor()
await cursor.execute(
"create table iterable_cursor " "(i integer primary key asc, k integer)"
)
await cursor.executemany(
"insert into iterable_cursor (k) values (?)", [[i] for i in range(10)]
)
await db.commit()
async with aiosqlite.connect(self.db) as db:
cursor = await db.execute("select * from iterable_cursor")
rows = []
async for row in cursor:
rows.append(row)
assert len(rows) == 10
async def test_multi_loop_usage(self):
results = {}
def runner(k, conn):
async def query():
async with conn.execute("select * from foo") as cursor:
rows = await cursor.fetchall()
self.assertEqual(len(rows), 2)
return rows
with self.subTest(k):
loop = asyncio.new_event_loop()
rows = loop.run_until_complete(query())
loop.close()
results[k] = rows
async with aiosqlite.connect(":memory:") as db:
await db.execute("create table foo (id int, name varchar)")
await db.execute(
"insert into foo values (?, ?), (?, ?)", (1, "Sally", 2, "Janet")
)
await db.commit()
threads = [Thread(target=runner, args=(k, db)) for k in range(4)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
self.assertEqual(len(results), 4)
for rows in results.values():
self.assertEqual(len(rows), 2)
async def test_context_cursor(self):
async with aiosqlite.connect(self.db) as db:
async with db.cursor() as cursor:
await cursor.execute(
"create table context_cursor "
"(i integer primary key asc, k integer)"
)
await cursor.executemany(
"insert into context_cursor (k) values (?)",
[[i] for i in range(10)],
)
await db.commit()
async with aiosqlite.connect(self.db) as db:
async with db.execute("select * from context_cursor") as cursor:
rows = []
async for row in cursor:
rows.append(row)
assert len(rows) == 10
async def test_cursor_return_self(self):
async with aiosqlite.connect(self.db) as db:
cursor = await db.cursor()
result = await cursor.execute(
"create table test_cursor_return_self (i integer, k integer)"
)
self.assertEqual(result, cursor, "cursor execute returns itself")
result = await cursor.executemany(
"insert into test_cursor_return_self values (?, ?)", [(1, 1), (2, 2)]
)
self.assertEqual(result, cursor)
result = await cursor.executescript(
"insert into test_cursor_return_self values (3, 3);"
"insert into test_cursor_return_self values (4, 4);"
"insert into test_cursor_return_self values (5, 5);"
)
self.assertEqual(result, cursor)
async def test_connection_properties(self):
async with aiosqlite.connect(self.db) as db:
self.assertEqual(db.total_changes, 0)
async with db.cursor() as cursor:
self.assertFalse(db.in_transaction)
await cursor.execute(
"create table test_properties "
"(i integer primary key asc, k integer, d text)"
)
await cursor.execute(
"insert into test_properties (k, d) values (1, 'hi')"
)
self.assertTrue(db.in_transaction)
await db.commit()
self.assertFalse(db.in_transaction)
self.assertEqual(db.total_changes, 1)
self.assertIsNone(db.row_factory)
self.assertEqual(db.text_factory, str)
async with db.cursor() as cursor:
await cursor.execute("select * from test_properties")
row = await cursor.fetchone()
self.assertIsInstance(row, tuple)
self.assertEqual(row, (1, 1, "hi"))
with self.assertRaises(TypeError):
_ = row["k"]
async with db.cursor() as cursor:
cursor.row_factory = aiosqlite.Row
self.assertEqual(cursor.row_factory, aiosqlite.Row)
await cursor.execute("select * from test_properties")
row = await cursor.fetchone()
self.assertIsInstance(row, aiosqlite.Row)
self.assertEqual(row[1], 1)
self.assertEqual(row[2], "hi")
self.assertEqual(row["k"], 1)
self.assertEqual(row["d"], "hi")
db.row_factory = aiosqlite.Row
db.text_factory = bytes
self.assertEqual(db.row_factory, aiosqlite.Row)
self.assertEqual(db.text_factory, bytes)
async with db.cursor() as cursor:
await cursor.execute("select * from test_properties")
row = await cursor.fetchone()
self.assertIsInstance(row, aiosqlite.Row)
self.assertEqual(row[1], 1)
self.assertEqual(row[2], b"hi")
self.assertEqual(row["k"], 1)
self.assertEqual(row["d"], b"hi")
async def test_fetch_all(self):
async with aiosqlite.connect(self.db) as db:
await db.execute(
"create table test_fetch_all (i integer primary key asc, k integer)"
)
await db.execute(
"insert into test_fetch_all (k) values (10), (24), (16), (32)"
)
await db.commit()
async with aiosqlite.connect(self.db) as db:
cursor = await db.execute("select k from test_fetch_all where k < 30")
rows = await cursor.fetchall()
self.assertEqual(rows, [(10,), (24,), (16,)])
async def test_enable_load_extension(self):
"""Assert that after enabling extension loading, they can be loaded"""
async with aiosqlite.connect(self.db) as db:
try:
await db.enable_load_extension(True)
await db.load_extension("test")
except OperationalError as e:
assert "not authorized" not in e.args
except AttributeError as e:
raise SkipTest(
"python was not compiled with sqlite3 "
"extension support, so we can't test it"
) from e
async def test_set_progress_handler(self):
"""
Assert that after setting a progress handler returning 1, DB operations are aborted
"""
async with aiosqlite.connect(self.db) as db:
await db.set_progress_handler(lambda: 1, 1)
with self.assertRaises(OperationalError):
await db.execute(
"create table test_progress_handler (i integer primary key asc, k integer)"
)
async def test_create_function(self):
"""Assert that after creating a custom function, it can be used"""
def no_arg():
return "no arg"
def one_arg(num):
return num * 2
async with aiosqlite.connect(self.db) as db:
await db.create_function("no_arg", 0, no_arg)
await db.create_function("one_arg", 1, one_arg)
async with db.execute("SELECT no_arg();") as res:
row = await res.fetchone()
self.assertEqual(row[0], "no arg")
async with db.execute("SELECT one_arg(10);") as res:
row = await res.fetchone()
self.assertEqual(row[0], 20)
async def test_create_function_deterministic(self):
"""Assert that after creating a deterministic custom function, it can be used.
https://sqlite.org/deterministic.html
"""
def one_arg(num):
return num * 2
async with aiosqlite.connect(self.db) as db:
await db.create_function("one_arg", 1, one_arg, deterministic=True)
await db.execute("create table foo (id int, bar int)")
# Non-deterministic functions cannot be used in indexes
await db.execute("create index t on foo(one_arg(bar))")
async def test_set_trace_callback(self):
statements = []
def callback(statement: str):
statements.append(statement)
async with aiosqlite.connect(self.db) as db:
await db.set_trace_callback(callback)
await db.execute("select 10")
self.assertIn("select 10", statements)
async def test_connect_error(self):
bad_db = Path("/something/that/shouldnt/exist.db")
with self.assertRaisesRegex(OperationalError, "unable to open database"):
async with aiosqlite.connect(bad_db) as db:
self.assertIsNone(db) # should never be reached
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))")
await db.executemany(
"insert into foo values (?, ?)", [(1, "hello"), (2, "world")]
)
lines = [line async for line in db.iterdump()]
self.assertEqual(
lines,
[
"BEGIN TRANSACTION;",
"CREATE TABLE foo (i integer, k charvar(250));",
"INSERT INTO \"foo\" VALUES(1,'hello');",
"INSERT INTO \"foo\" VALUES(2,'world');",
"COMMIT;",
],
)
async def test_cursor_on_closed_connection(self):
db = await aiosqlite.connect(self.db)
cursor = await db.execute("select 1, 2")
await db.close()
with self.assertRaisesRegex(ValueError, "Connection closed"):
await cursor.fetchall()
with self.assertRaisesRegex(ValueError, "Connection closed"):
await cursor.fetchall()
async def test_cursor_on_closed_connection_loop(self):
db = await aiosqlite.connect(self.db)
cursor = await db.execute("select 1, 2")
tasks = []
for i in range(100):
if i == 50:
tasks.append(asyncio.ensure_future(db.close()))
tasks.append(asyncio.ensure_future(cursor.fetchall()))
for task in tasks:
try:
await task
except sqlite3.ProgrammingError:
pass
async def test_close_twice(self):
db = await aiosqlite.connect(self.db)
await db.close()
# no error
await db.close()
async def test_backup_aiosqlite(self):
def progress(a, b, c):
print(a, b, c)
async with (
aiosqlite.connect(":memory:") as db1,
aiosqlite.connect(":memory:") as db2,
):
await db1.execute("create table foo (i integer, k charvar(250))")
await db1.executemany(
"insert into foo values (?, ?)", [(1, "hello"), (2, "world")]
)
await db1.commit()
with self.assertRaisesRegex(OperationalError, "no such table: foo"):
await db2.execute("select * from foo")
await db1.backup(db2, progress=progress)
async with db2.execute("select * from foo") as cursor:
rows = await cursor.fetchall()
self.assertEqual(rows, [(1, "hello"), (2, "world")])
async def test_backup_sqlite(self):
async with aiosqlite.connect(":memory:") as db1:
with sqlite3.connect(":memory:") as db2:
await db1.execute("create table foo (i integer, k charvar(250))")
await db1.executemany(
"insert into foo values (?, ?)", [(1, "hello"), (2, "world")]
)
await db1.commit()
with self.assertRaisesRegex(OperationalError, "no such table: foo"):
db2.execute("select * from foo")
await db1.backup(db2)
cursor = db2.execute("select * from foo")
rows = cursor.fetchall()
self.assertEqual(rows, [(1, "hello"), (2, "world")])
|