2018-07-31 08:55:24 -07:00
|
|
|
from sqlite_utils import Database
|
2022-01-05 17:57:03 -08:00
|
|
|
from sqlite_utils.utils import sqlite3
|
2018-07-31 08:55:24 -07:00
|
|
|
import pytest
|
|
|
|
|
|
2022-01-05 17:57:03 -08:00
|
|
|
CREATE_TABLES = """
|
|
|
|
|
create table Gosh (c1 text, c2 text, c3 text);
|
|
|
|
|
create table Gosh2 (c1 text, c2 text, c3 text);
|
|
|
|
|
"""
|
|
|
|
|
|
2018-07-31 08:55:24 -07:00
|
|
|
|
2023-07-22 12:04:31 -07:00
|
|
|
def pytest_configure(config):
|
|
|
|
|
import sys
|
|
|
|
|
|
2025-12-16 19:34:45 -08:00
|
|
|
sys._called_from_test = True # type: ignore[attr-defined]
|
2023-07-22 12:04:31 -07:00
|
|
|
|
|
|
|
|
|
2025-12-11 16:56:12 -08:00
|
|
|
@pytest.fixture(autouse=True)
|
|
|
|
|
def close_all_databases():
|
|
|
|
|
"""Automatically close all Database objects created during a test."""
|
|
|
|
|
databases = []
|
|
|
|
|
original_init = Database.__init__
|
|
|
|
|
|
|
|
|
|
def tracking_init(self, *args, **kwargs):
|
|
|
|
|
original_init(self, *args, **kwargs)
|
|
|
|
|
databases.append(self)
|
|
|
|
|
|
2025-12-16 19:34:45 -08:00
|
|
|
Database.__init__ = tracking_init # type: ignore[method-assign]
|
2025-12-11 16:56:12 -08:00
|
|
|
yield
|
2025-12-16 19:34:45 -08:00
|
|
|
Database.__init__ = original_init # type: ignore[method-assign]
|
2025-12-11 16:56:12 -08:00
|
|
|
for db in databases:
|
|
|
|
|
try:
|
|
|
|
|
db.close()
|
|
|
|
|
except Exception:
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
2018-07-31 08:55:24 -07:00
|
|
|
@pytest.fixture
|
|
|
|
|
def fresh_db():
|
2019-07-22 17:12:54 -07:00
|
|
|
return Database(memory=True)
|
2018-07-31 08:55:24 -07:00
|
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.fixture
|
|
|
|
|
def existing_db():
|
2019-07-22 17:12:54 -07:00
|
|
|
database = Database(memory=True)
|
2020-09-07 14:56:59 -07:00
|
|
|
database.executescript(
|
2018-07-31 08:55:24 -07:00
|
|
|
"""
|
|
|
|
|
CREATE TABLE foo (text TEXT);
|
|
|
|
|
INSERT INTO foo (text) values ("one");
|
|
|
|
|
INSERT INTO foo (text) values ("two");
|
|
|
|
|
INSERT INTO foo (text) values ("three");
|
|
|
|
|
"""
|
|
|
|
|
)
|
|
|
|
|
return database
|
2022-01-05 17:57:03 -08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.fixture
|
|
|
|
|
def db_path(tmpdir):
|
|
|
|
|
path = str(tmpdir / "test.db")
|
|
|
|
|
db = sqlite3.connect(path)
|
|
|
|
|
db.executescript(CREATE_TABLES)
|
2025-12-11 16:56:12 -08:00
|
|
|
db.close()
|
2022-01-05 17:57:03 -08:00
|
|
|
return path
|