From b789bad6c0d2705791a110c6701d18bc85bf9749 Mon Sep 17 00:00:00 2001 From: Tim Van Baak Date: Wed, 16 Jun 2021 20:17:24 -0700 Subject: [PATCH] Switch tests to run on a tempfile db --- amanuensis/db/database.py | 4 ++-- tests/conftest.py | 29 ++++++++++++++++++++--------- 2 files changed, 22 insertions(+), 11 deletions(-) diff --git a/amanuensis/db/database.py b/amanuensis/db/database.py index 90eaa49..a2ec806 100644 --- a/amanuensis/db/database.py +++ b/amanuensis/db/database.py @@ -39,10 +39,10 @@ class DbContext: if path and uri: 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 - self.engine = create_engine(db_uri, echo=echo) + self.engine = create_engine(self.db_uri, echo=echo) @event.listens_for(self.engine, "connect") def set_sqlite_pragma(dbapi_connection, connection_record): diff --git a/tests/conftest.py b/tests/conftest.py index b5bc8d3..f8b2a29 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,22 +1,35 @@ """ pytest test fixtures """ +import os 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.lexicon as lexiq import amanuensis.backend.membership as memq import amanuensis.backend.user as userq from amanuensis.config import AmanuensisConfig +from amanuensis.db import DbContext from amanuensis.server import get_app @pytest.fixture -def db() -> DbContext: - """Provides an initialized database in memory.""" - db = DbContext(uri="sqlite:///:memory:", echo=False) +def db(request) -> DbContext: + """Provides a fully-initialized ephemeral database.""" + db_fd, db_path = tempfile.mkstemp() + db = DbContext(path=db_path, echo=False) db.create_all() + + def db_teardown(): + close_all_sessions() + os.close(db_fd) + os.unlink(db_path) + + request.addfinalizer(db_teardown) + return db @@ -128,12 +141,10 @@ def lexicon_with_editor(make): class TestConfig(AmanuensisConfig): TESTING = True - SECRET_KEY = "secret key" - DATABASE_URI = "sqlite:///:memory:" + SECRET_KEY = os.urandom(32).hex() @pytest.fixture -def app(db): +def app(db: DbContext): """Provides an application running on top of the test database.""" - server_app = get_app(TestConfig, db) - return server_app + return get_app(TestConfig(), db)