-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_asyncio_core.py
More file actions
2209 lines (1687 loc) · 66.1 KB
/
test_asyncio_core.py
File metadata and controls
2209 lines (1687 loc) · 66.1 KB
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Core async database tests."""
from __future__ import annotations
import builtins
import importlib
import logging
import sqlite3
import sys
from typing import TYPE_CHECKING, Any, cast
import pytest
from sqliter import asyncio as sqliter_asyncio
from sqliter.asyncio import AsyncSqliterDB
from sqliter.exceptions import (
DatabaseConnectionError,
ForeignKeyConstraintError,
InvalidFilterError,
InvalidIndexError,
InvalidProjectionError,
InvalidUpdateError,
RecordDeletionError,
RecordFetchError,
RecordInsertionError,
RecordNotFoundError,
RecordUpdateError,
SqlExecutionError,
TableCreationError,
TableDeletionError,
)
from sqliter.orm import BaseDBModel, ForeignKey, ManyToMany
from sqliter.orm.m2m import _m2m_column_names
from sqliter.orm.registry import ModelRegistry
from sqliter.query import func
from tests.conftest import ComplexModel, ExampleModel
if TYPE_CHECKING:
from collections.abc import Mapping
from pathlib import Path
from pytest_mock import MockerFixture
class _FakeCursor:
"""Small async cursor test double."""
def __init__(
self,
*,
execute_error: BaseException | None = None,
fetchone_result: object = None,
fetchall_result: list[object] | None = None,
rowcount: int = 1,
lastrowid: int = 1,
) -> None:
self.execute_error = execute_error
self.fetchone_result = fetchone_result
self.fetchall_result = fetchall_result or []
self.rowcount = rowcount
self.lastrowid = lastrowid
async def execute(self, _sql: str, _values: object = ()) -> _FakeCursor:
if self.execute_error is not None:
raise self.execute_error
return self
async def fetchone(self) -> object:
return self.fetchone_result
async def fetchall(self) -> list[object]:
return self.fetchall_result
class _FakeConnection:
"""Small async connection test double."""
def __init__(self, cursor: _FakeCursor) -> None:
self._cursor = cursor
self.rollback_calls = 0
self.commit_calls = 0
self.closed = False
async def cursor(self) -> _FakeCursor:
return self._cursor
async def execute(self, _sql: str) -> None:
return None
async def commit(self) -> None:
self.commit_calls += 1
async def rollback(self) -> None:
self.rollback_calls += 1
async def close(self) -> None:
self.closed = True
def test_asyncio_import_error_without_aiosqlite(
monkeypatch: pytest.MonkeyPatch,
mocker: MockerFixture,
) -> None:
"""Importing sqliter.asyncio without aiosqlite raises a helpful error."""
real_import = builtins.__import__
def fake_import(
name: str,
globals_: Mapping[str, object] | None = None,
locals_: Mapping[str, object] | None = None,
fromlist: tuple[str, ...] = (),
level: int = 0,
) -> object:
if name == "aiosqlite":
msg = "No module named 'aiosqlite'"
raise ModuleNotFoundError(msg, name="aiosqlite")
return real_import(name, globals_, locals_, fromlist, level)
mocker.patch.dict(
"sys.modules",
{
"sqliter.asyncio": None,
"sqliter.asyncio.db": None,
"sqliter.asyncio.query": None,
"aiosqlite": None,
},
)
monkeypatch.setattr(builtins, "__import__", fake_import)
sys.modules.pop("sqliter.asyncio", None)
sys.modules.pop("sqliter.asyncio.db", None)
sys.modules.pop("sqliter.asyncio.query", None)
sys.modules.pop("aiosqlite", None)
module = importlib.import_module("sqliter.asyncio")
with pytest.raises(ImportError, match="aiosqlite is required"):
_ = module.AsyncSqliterDB
def test_asyncio_reraises_non_aiosqlite_import_errors(
monkeypatch: pytest.MonkeyPatch,
mocker: MockerFixture,
) -> None:
"""Importing sqliter.asyncio reraises unrelated module import failures."""
real_import = builtins.__import__
def fake_import(
name: str,
globals_: Mapping[str, object] | None = None,
locals_: Mapping[str, object] | None = None,
fromlist: tuple[str, ...] = (),
level: int = 0,
) -> object:
if name == "sqliter.asyncio.db":
msg = "No module named 'boommod'"
raise ModuleNotFoundError(msg, name="boommod")
return real_import(name, globals_, locals_, fromlist, level)
mocker.patch.dict(
"sys.modules",
{
"sqliter.asyncio": None,
"sqliter.asyncio.db": None,
"sqliter.asyncio.query": None,
},
)
monkeypatch.setattr(builtins, "__import__", fake_import)
sys.modules.pop("sqliter.asyncio", None)
sys.modules.pop("sqliter.asyncio.db", None)
sys.modules.pop("sqliter.asyncio.query", None)
with pytest.raises(ModuleNotFoundError, match="boommod"):
importlib.import_module("sqliter.asyncio")
def test_asyncio_module_getattr_paths() -> None:
"""Async package exposes expected attributes via __getattr__."""
module = importlib.reload(sqliter_asyncio)
assert module.__getattr__("AsyncSqliterDB") is AsyncSqliterDB
with pytest.raises(AttributeError, match="no attribute 'missing'"):
module.__getattr__("missing")
@pytest.mark.asyncio
async def test_async_create_and_get_table_names() -> None:
"""Async DB can create tables and list them."""
db = AsyncSqliterDB(memory=True)
await db.create_table(ExampleModel)
assert "test_table" in await db.get_table_names()
await db.close()
@pytest.mark.asyncio
async def test_async_build_insert_plan_binds_none_values() -> None:
"""Async insert plans keep placeholders stable when values are None."""
db = AsyncSqliterDB(memory=True)
model = ComplexModel(
name="Alice",
age=30.5,
is_active=True,
score=85,
nullable_field=None,
)
plan = db._build_insert_plan(model, timestamp_override=False)
assert '"nullable_field"' in plan.sql
assert "NULL" not in plan.sql
assert plan.sql.count("?") == len(plan.values)
assert plan.values[-1] is None
@pytest.mark.asyncio
async def test_async_crud_quotes_reserved_table_name() -> None:
"""Async core CRUD methods handle reserved table names."""
state = ModelRegistry.snapshot()
try:
class AsyncReservedCrudModel(BaseDBModel):
name: str
class Meta:
table_name = "order"
db = AsyncSqliterDB(memory=True)
await db.create_table(AsyncReservedCrudModel)
inserted = await db.insert(AsyncReservedCrudModel(name="Initial"))
fetched = await db.get(AsyncReservedCrudModel, inserted.pk)
assert fetched is not None
assert fetched.name == "Initial"
fetched.name = "Updated"
await db.update(fetched)
updated = await db.get(
AsyncReservedCrudModel, inserted.pk, bypass_cache=True
)
assert updated is not None
assert updated.name == "Updated"
await db.delete(AsyncReservedCrudModel, inserted.pk)
assert await db.get(AsyncReservedCrudModel, inserted.pk) is None
await db.close()
finally:
ModelRegistry.restore(state)
@pytest.mark.asyncio
async def test_async_insert_get_update_delete() -> None:
"""Async CRUD works for the core DB API."""
db = AsyncSqliterDB(memory=True)
await db.create_table(ExampleModel)
inserted = await db.insert(
ExampleModel(slug="mit", name="MIT", content="License text")
)
fetched = await db.get(ExampleModel, inserted.pk)
assert fetched is not None
assert fetched.slug == "mit"
inserted.content = "Updated"
await db.update(inserted)
updated = await db.get(ExampleModel, inserted.pk)
assert updated is not None
assert updated.content == "Updated"
await db.delete(ExampleModel, inserted.pk)
deleted = await db.get(ExampleModel, inserted.pk)
assert deleted is None
await db.close()
@pytest.mark.asyncio
async def test_async_insert_updates_supplied_instance() -> None:
"""Async insert should mark the supplied instance as saved."""
db = AsyncSqliterDB(memory=True)
await db.create_table(ExampleModel)
model = ExampleModel(slug="apache", name="Apache", content="License")
inserted = await db.insert(model)
assert inserted is model
assert model.pk == inserted.pk
assert model.pk > 0
await db.close()
@pytest.mark.asyncio
async def test_async_insert_updates_orm_instance_context() -> None:
"""Async insert should attach db_context to supplied ORM instances."""
state = ModelRegistry.snapshot()
try:
db = AsyncSqliterDB(memory=True)
class SavedAsyncORMModel(BaseDBModel):
"""ORM model for async insert context tests."""
name: str
await db.create_table(SavedAsyncORMModel)
model = SavedAsyncORMModel(name="saved")
inserted = await db.insert(model)
assert inserted is model
assert model.pk > 0
assert model.db_context is db
await db.close()
finally:
ModelRegistry.restore(state)
@pytest.mark.asyncio
async def test_async_get_table_names_keeps_memory_connection_open() -> None:
"""get_table_names keeps in-memory connections open after use."""
db = AsyncSqliterDB(memory=True)
assert await db.get_table_names() == []
assert db.conn is not None
assert db._model_field_to_db_column(ExampleModel, "slug") == "slug"
await db.close()
@pytest.mark.asyncio
async def test_async_get_table_names_closes_temporary_file_connection(
temp_db_path: str,
) -> None:
"""get_table_names closes a temporary file-backed connection after use."""
db = AsyncSqliterDB(temp_db_path)
assert await db.get_table_names() == []
assert db.conn is None
@pytest.mark.asyncio
async def test_async_query_builder_fetch_and_count() -> None:
"""Async QueryBuilder supports basic fetch and count operations."""
db = AsyncSqliterDB(memory=True)
await db.create_table(ExampleModel)
await db.insert(ExampleModel(slug="mit", name="MIT", content="One"))
await db.insert(ExampleModel(slug="gpl", name="GPL", content="Two"))
results = await db.select(ExampleModel).order("slug").fetch_all()
assert [item.slug for item in results] == ["gpl", "mit"]
filtered = await db.select(ExampleModel).filter(name="MIT").fetch_one()
assert filtered is not None
assert filtered.slug == "mit"
count = await db.select(ExampleModel).count()
assert count == 2
assert await db.select(ExampleModel).filter(name="GPL").exists() is True
await db.close()
@pytest.mark.asyncio
async def test_async_context_manager_commits_transaction(
temp_db_path: str,
) -> None:
"""Async context manager commits on success."""
db = AsyncSqliterDB(temp_db_path, auto_commit=False)
await db.create_table(ExampleModel)
async with db:
await db.insert(
ExampleModel(slug="apache", name="Apache", content="Three")
)
fetched = await db.get(ExampleModel, 1)
assert fetched is not None
assert fetched.slug == "apache"
assert db.conn is not None
await db.close()
@pytest.mark.asyncio
async def test_async_bulk_insert_and_update_where() -> None:
"""Async DB supports bulk insert and update_where."""
db = AsyncSqliterDB(memory=True)
await db.create_table(ExampleModel)
inserted = await db.bulk_insert(
[
ExampleModel(slug="a", name="A", content="one"),
ExampleModel(slug="b", name="B", content="two"),
]
)
assert len(inserted) == 2
updated_count = await db.update_where(
ExampleModel,
where={"slug": "a"},
values={"content": "updated"},
)
assert updated_count == 1
updated = await db.select(ExampleModel).filter(slug="a").fetch_one()
assert updated is not None
assert updated.content == "updated"
await db.close()
@pytest.mark.asyncio
async def test_async_bulk_insert_updates_supplied_instances() -> None:
"""Async bulk_insert should mark supplied instances as saved."""
db = AsyncSqliterDB(memory=True)
await db.create_table(ExampleModel)
instances = [
ExampleModel(slug="a", name="A", content="one"),
ExampleModel(slug="b", name="B", content="two"),
]
inserted = await db.bulk_insert(instances)
assert inserted == instances
assert all(
result is instance
for result, instance in zip(inserted, instances, strict=True)
)
assert [instance.pk for instance in instances] == [1, 2]
await db.close()
@pytest.mark.asyncio
async def test_async_bulk_insert_updates_orm_instance_context() -> None:
"""Async bulk_insert should attach db_context to supplied ORM instances."""
state = ModelRegistry.snapshot()
try:
db = AsyncSqliterDB(memory=True)
class SavedAsyncBulkORMModel(BaseDBModel):
"""ORM model for async bulk insert context tests."""
name: str
await db.create_table(SavedAsyncBulkORMModel)
instances = [
SavedAsyncBulkORMModel(name="first"),
SavedAsyncBulkORMModel(name="second"),
]
inserted = await db.bulk_insert(instances)
assert inserted == instances
assert all(
result is instance
for result, instance in zip(inserted, instances, strict=True)
)
assert [instance.pk for instance in instances] == [1, 2]
assert all(instance.db_context is db for instance in instances)
await db.close()
finally:
ModelRegistry.restore(state)
def test_async_init_rejects_reset() -> None:
"""Async init rejects reset=True."""
with pytest.raises(ValueError, match="reset=True is not supported"):
AsyncSqliterDB(memory=True, reset=True)
@pytest.mark.asyncio
async def test_async_create_with_reset_clears_existing_tables(
temp_db_path: str,
) -> None:
"""Async create(reset=True) drops existing user tables."""
initial = AsyncSqliterDB(temp_db_path)
await initial.create_table(ExampleModel)
assert "test_table" in await initial.get_table_names()
await initial.close()
reset_db = await AsyncSqliterDB.create(temp_db_path, reset=True)
assert "test_table" not in await reset_db.get_table_names()
await reset_db.close()
@pytest.mark.asyncio
async def test_async_reset_database_quotes_reserved_table_name(
temp_db_path: str,
) -> None:
"""Async reset handles reserved table names."""
state = ModelRegistry.snapshot()
try:
class AsyncReservedResetModel(BaseDBModel):
name: str
class Meta:
table_name = "order"
initial = AsyncSqliterDB(temp_db_path)
await initial.create_table(AsyncReservedResetModel)
await initial.close()
reset_db = await AsyncSqliterDB.create(temp_db_path, reset=True)
assert "order" not in await reset_db.get_table_names()
await reset_db.close()
finally:
ModelRegistry.restore(state)
@pytest.mark.asyncio
async def test_async_db_properties_expose_sync_configuration(
mocker: MockerFixture,
) -> None:
"""Async DB exposes sync-backed properties and reset logging."""
logger = logging.getLogger("sqliter.asyncio.test")
db = AsyncSqliterDB(
memory=True,
auto_commit=False,
debug=True,
logger=logger,
)
assert db.debug is True
assert db.logger is logger
assert db.is_memory is True
assert db.filename is None
assert db.auto_commit is False
assert db.is_autocommit is False
assert db.in_transaction is False
await db.create_table(ExampleModel)
logger_debug = mocker.spy(db.logger, "debug")
await db.reset_database()
assert logger_debug.call_count >= 1
assert any(
"Database reset" in call.args[0] for call in logger_debug.call_args_list
)
await db.close()
@pytest.mark.asyncio
async def test_async_reset_database_rolls_back_inside_context(
temp_db_path: str,
) -> None:
"""reset_database should not flush an enclosing async transaction."""
db = AsyncSqliterDB(temp_db_path)
await db.create_table(ExampleModel)
await db.insert(ExampleModel(slug="kept", name="Kept", content="row"))
await db.close()
db = AsyncSqliterDB(temp_db_path)
msg = "boom"
async def fail_transaction() -> None:
async with db:
await db.reset_database()
raise RuntimeError(msg)
with pytest.raises(RuntimeError, match=msg):
await fail_transaction()
await db.close()
db = AsyncSqliterDB(temp_db_path)
assert "test_table" in await db.get_table_names()
fetched = await db.get(ExampleModel, 1)
assert fetched is not None
assert fetched.slug == "kept"
await db.close()
@pytest.mark.asyncio
async def test_async_drop_table_removes_table() -> None:
"""drop_table removes an existing table."""
db = AsyncSqliterDB(memory=True)
await db.create_table(ExampleModel)
await db.drop_table(ExampleModel)
assert "test_table" not in await db.get_table_names()
await db.close()
@pytest.mark.asyncio
async def test_async_drop_table_quotes_reserved_table_name() -> None:
"""Async drop_table handles reserved table names."""
state = ModelRegistry.snapshot()
try:
class AsyncReservedDropModel(BaseDBModel):
name: str
class Meta:
table_name = "order"
db = AsyncSqliterDB(memory=True)
await db.create_table(AsyncReservedDropModel)
await db.drop_table(AsyncReservedDropModel)
assert "order" not in await db.get_table_names()
await db.close()
finally:
ModelRegistry.restore(state)
@pytest.mark.asyncio
async def test_async_connect_and_get_table_names_wrap_connection_errors(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Connection setup failures are wrapped consistently."""
async def fail_connect(_filename: str) -> None:
msg = "boom"
raise sqlite3.Error(msg)
asyncio_db_module = cast(
"Any", importlib.import_module("sqliter.asyncio.db")
)
aiosqlite_module = cast("Any", asyncio_db_module.aiosqlite)
monkeypatch.setattr(aiosqlite_module, "connect", fail_connect)
db = AsyncSqliterDB(memory=True)
with pytest.raises(DatabaseConnectionError):
await db.connect()
async def connect_without_state() -> _FakeConnection:
return _FakeConnection(_FakeCursor())
monkeypatch.setattr(db, "connect", connect_without_state)
with pytest.raises(
DatabaseConnectionError,
match="Failed to establish a database connection",
):
await db.get_table_names()
@pytest.mark.asyncio
async def test_async_create_table_force_and_indexes() -> None:
"""create_table(force=True) rebuilds indexed tables."""
state = ModelRegistry.snapshot()
try:
class IndexedModel(BaseDBModel):
"""Model with regular and unique indexes."""
slug: str
name: str
class Meta:
"""Index metadata."""
indexes = ("name", ("slug", "name"))
unique_indexes = ("slug",)
db = AsyncSqliterDB(memory=True)
await db.create_table(IndexedModel)
await db.create_table(IndexedModel, force=True)
table_name = IndexedModel.get_table_name()
conn = await db.connect()
cursor = await conn.cursor()
await db.execute_cursor(cursor, f'PRAGMA index_list("{table_name}")')
indexes = [row[1] for row in await cursor.fetchall()]
assert f"idx_{table_name}_name" in indexes
assert f"idx_{table_name}_slug_name" in indexes
assert f"idx_{table_name}_slug_unique" in indexes
await db.close()
finally:
ModelRegistry.restore(state)
@pytest.mark.asyncio
async def test_async_create_indexes_creates_index() -> None:
"""Async _create_indexes creates indexes outside create_table."""
state = ModelRegistry.snapshot()
try:
class ManualAsyncIndexModel(BaseDBModel):
"""Model for manual async index creation."""
slug: str
name: str
class Meta:
"""Manual index metadata."""
table_name = "manual_async_index_model"
db = AsyncSqliterDB(memory=True)
await db.create_table(ManualAsyncIndexModel)
await db._create_indexes(ManualAsyncIndexModel, ["name"], unique=True)
table_name = ManualAsyncIndexModel.get_table_name()
conn = await db.connect()
cursor = await conn.cursor()
await db.execute_cursor(cursor, f'PRAGMA index_list("{table_name}")')
indexes = [row[1] for row in await cursor.fetchall()]
assert f"idx_{table_name}_name_unique" in indexes
await db.close()
finally:
ModelRegistry.restore(state)
@pytest.mark.asyncio
async def test_async_create_table_invalid_index_raises() -> None:
"""Async create_table surfaces invalid index configuration."""
state = ModelRegistry.snapshot()
try:
class BadIndexModel(BaseDBModel):
"""Model with invalid async index metadata."""
slug: str
class Meta:
"""Broken index metadata."""
indexes = ("missing",)
db = AsyncSqliterDB(memory=True)
with pytest.raises(InvalidIndexError, match="BadIndexModel"):
await db.create_table(BadIndexModel)
assert BadIndexModel.get_table_name() not in await db.get_table_names()
await db.close()
finally:
ModelRegistry.restore(state)
@pytest.mark.asyncio
async def test_async_create_table_force_invalid_index_preserves_table() -> None:
"""Async force=True validates indexes before dropping the old table."""
state = ModelRegistry.snapshot()
try:
class ExistingAsyncIndexModel(BaseDBModel):
"""Existing async table for force validation tests."""
slug: str
class Meta:
"""Existing table metadata."""
table_name = "async_force_index_model"
class BadAsyncReplacementModel(BaseDBModel):
"""Replacement model with invalid index metadata."""
slug: str
class Meta:
"""Invalid replacement metadata."""
table_name = "async_force_index_model"
indexes = ("missing",)
db = AsyncSqliterDB(memory=True)
await db.create_table(ExistingAsyncIndexModel)
with pytest.raises(InvalidIndexError, match="BadAsyncReplacementModel"):
await db.create_table(BadAsyncReplacementModel, force=True)
assert "async_force_index_model" in await db.get_table_names()
await db.close()
finally:
ModelRegistry.restore(state)
@pytest.mark.asyncio
async def test_async_create_table_force_quotes_reserved_table_name() -> None:
"""Async create_table(force=True) handles reserved table names."""
state = ModelRegistry.snapshot()
try:
class AsyncReservedInitialModel(BaseDBModel):
name: str
class Meta:
table_name = "order"
class AsyncReservedReplacementModel(BaseDBModel):
name: str
email: str
class Meta:
table_name = "order"
db = AsyncSqliterDB(memory=True)
await db.create_table(AsyncReservedInitialModel)
await db.create_table(AsyncReservedReplacementModel, force=True)
conn = await db.connect()
cursor = await conn.cursor()
await db.execute_cursor(cursor, 'PRAGMA table_info("order")')
columns = [row[1] for row in await cursor.fetchall()]
assert "email" in columns
await db.close()
finally:
ModelRegistry.restore(state)
@pytest.mark.asyncio
async def test_async_table_and_sql_wrappers_handle_sqlite_errors(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Raw SQL, create_table, and drop_table wrap sqlite failures."""
db = AsyncSqliterDB(memory=True)
fake_conn = _FakeConnection(_FakeCursor())
db.conn = cast("Any", fake_conn)
async def fail_execute(
_cursor: _FakeCursor,
_sql: str,
_values: object = (),
) -> _FakeCursor:
msg = "bad sql"
raise sqlite3.Error(msg)
monkeypatch.setattr(db, "_execute_async", fail_execute)
with pytest.raises(TableCreationError):
await db.create_table(ExampleModel)
with pytest.raises(SqlExecutionError):
await db._execute_sql("SELECT 1")
with pytest.raises(TableDeletionError):
await db.drop_table(ExampleModel)
await db.close()
@pytest.mark.asyncio
async def test_async_bulk_insert_rejects_mixed_models() -> None:
"""bulk_insert rejects mixed model types."""
state = ModelRegistry.snapshot()
try:
class OtherModel(BaseDBModel):
"""Second model for mixed bulk insert validation."""
name: str
db = AsyncSqliterDB(memory=True)
await db.create_table(ExampleModel)
await db.create_table(OtherModel)
with pytest.raises(TypeError, match="All instances must be the same"):
await db.bulk_insert(
[
ExampleModel(slug="a", name="A", content="one"),
OtherModel(name="B"),
]
)
await db.close()
finally:
ModelRegistry.restore(state)
@pytest.mark.asyncio
async def test_async_bulk_insert_empty_returns_empty_list() -> None:
"""bulk_insert returns an empty list for no input."""
db = AsyncSqliterDB(memory=True)
assert await db.bulk_insert([]) == []
await db.close()
@pytest.mark.asyncio
async def test_async_bulk_insert_fk_violation_raises(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""bulk_insert wraps FK failures in ForeignKeyConstraintError."""
db = AsyncSqliterDB(memory=True)
fake_conn = _FakeConnection(
_FakeCursor(
execute_error=sqlite3.IntegrityError(
"FOREIGN KEY constraint failed"
)
)
)
db.conn = cast("Any", fake_conn)
async def return_conn() -> _FakeConnection:
return fake_conn
monkeypatch.setattr(db, "connect", return_conn)
with pytest.raises(ForeignKeyConstraintError):
await db.bulk_insert([ExampleModel(slug="a", name="A", content="one")])
assert fake_conn.rollback_calls == 1
await db.close()
@pytest.mark.asyncio
async def test_async_bulk_insert_non_fk_integrity_error_raises(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""bulk_insert wraps non-FK IntegrityError as RecordInsertionError."""
db = AsyncSqliterDB(memory=True)
fake_conn = _FakeConnection(
_FakeCursor(
execute_error=sqlite3.IntegrityError("UNIQUE constraint failed")
)
)
db.conn = cast("Any", fake_conn)
async def return_conn() -> _FakeConnection:
return fake_conn
monkeypatch.setattr(db, "connect", return_conn)
with pytest.raises(RecordInsertionError):
await db.bulk_insert([ExampleModel(slug="a", name="A", content="one")])
assert fake_conn.rollback_calls == 1
await db.close()
@pytest.mark.asyncio
async def test_async_bulk_insert_sqlite_error_rolls_back(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""bulk_insert wraps generic sqlite errors and rolls back."""
db = AsyncSqliterDB(memory=True)
fake_conn = _FakeConnection(
_FakeCursor(execute_error=sqlite3.Error("bulk failure"))
)
db.conn = cast("Any", fake_conn)
async def return_conn() -> _FakeConnection:
return fake_conn
monkeypatch.setattr(db, "connect", return_conn)
with pytest.raises(RecordInsertionError):
await db.bulk_insert([ExampleModel(slug="a", name="A", content="one")])
assert fake_conn.rollback_calls == 1
await db.close()
@pytest.mark.asyncio
async def test_async_get_validates_negative_cache_ttl() -> None:
"""Get rejects negative cache TTL."""
db = AsyncSqliterDB(memory=True)
with pytest.raises(ValueError, match="cache_ttl must be non-negative"):
await db.get(ExampleModel, 1, cache_ttl=-1)
await db.close()
@pytest.mark.asyncio
async def test_async_get_uses_cache_after_first_lookup() -> None:
"""Get serves repeated lookups from cache."""
db = AsyncSqliterDB(memory=True, cache_enabled=True)
await db.create_table(ExampleModel)
inserted = await db.insert(
ExampleModel(slug="cached", name="Cached", content="once")
)
first = await db.get(ExampleModel, inserted.pk)
second = await db.get(ExampleModel, inserted.pk)
assert first is second
await db.close()
@pytest.mark.asyncio
async def test_async_get_does_not_cache_default_negative_result(
tmp_path: Path,
) -> None:
"""Default negative cache entries do not mask inserts from other DBs."""
db_path = tmp_path / "async-negative-cache.db"
db_reader = AsyncSqliterDB(str(db_path), cache_enabled=True)
db_writer = AsyncSqliterDB(str(db_path), cache_enabled=True)
await db_reader.create_table(ExampleModel)
assert await db_reader.get(ExampleModel, 1) is None
await db_writer.insert(
ExampleModel(pk=1, slug="later", name="Later", content="Inserted")
)
fetched = await db_reader.get(ExampleModel, 1)
assert fetched is not None
assert fetched.slug == "later"
await db_reader.close()
await db_writer.close()
@pytest.mark.asyncio