Switch tests to run on a tempfile db

This commit is contained in:
Tim Van Baak 2021-06-16 20:17:24 -07:00
parent 3cfc01a9c8
commit b789bad6c0
2 changed files with 22 additions and 11 deletions

View File

@ -39,10 +39,10 @@ class DbContext:
if path and uri: if path and uri:
raise ValueError("Only one of path and uri may be specified") raise ValueError("Only one of path and uri may be specified")
db_uri = uri if uri else f"sqlite:///{os.path.abspath(path)}" self.db_uri = uri if uri else f"sqlite:///{os.path.abspath(path)}"
# Create an engine and enable foreign key constraints in sqlite # Create an engine and enable foreign key constraints in sqlite
self.engine = create_engine(db_uri, echo=echo) self.engine = create_engine(self.db_uri, echo=echo)
@event.listens_for(self.engine, "connect") @event.listens_for(self.engine, "connect")
def set_sqlite_pragma(dbapi_connection, connection_record): def set_sqlite_pragma(dbapi_connection, connection_record):

View File

@ -1,22 +1,35 @@
""" """
pytest test fixtures pytest test fixtures
""" """
import os
import pytest import pytest
import tempfile
from sqlalchemy.orm.session import close_all_sessions
from amanuensis.db import DbContext
import amanuensis.backend.character as charq import amanuensis.backend.character as charq
import amanuensis.backend.lexicon as lexiq import amanuensis.backend.lexicon as lexiq
import amanuensis.backend.membership as memq import amanuensis.backend.membership as memq
import amanuensis.backend.user as userq import amanuensis.backend.user as userq
from amanuensis.config import AmanuensisConfig from amanuensis.config import AmanuensisConfig
from amanuensis.db import DbContext
from amanuensis.server import get_app from amanuensis.server import get_app
@pytest.fixture @pytest.fixture
def db() -> DbContext: def db(request) -> DbContext:
"""Provides an initialized database in memory.""" """Provides a fully-initialized ephemeral database."""
db = DbContext(uri="sqlite:///:memory:", echo=False) db_fd, db_path = tempfile.mkstemp()
db = DbContext(path=db_path, echo=False)
db.create_all() db.create_all()
def db_teardown():
close_all_sessions()
os.close(db_fd)
os.unlink(db_path)
request.addfinalizer(db_teardown)
return db return db
@ -128,12 +141,10 @@ def lexicon_with_editor(make):
class TestConfig(AmanuensisConfig): class TestConfig(AmanuensisConfig):
TESTING = True TESTING = True
SECRET_KEY = "secret key" SECRET_KEY = os.urandom(32).hex()
DATABASE_URI = "sqlite:///:memory:"
@pytest.fixture @pytest.fixture
def app(db): def app(db: DbContext):
"""Provides an application running on top of the test database.""" """Provides an application running on top of the test database."""
server_app = get_app(TestConfig, db) return get_app(TestConfig(), db)
return server_app