From a0b5a55daf06c30ef5baa59be95f8eb1adb9b769 Mon Sep 17 00:00:00 2001 From: Olivier Date: Mon, 18 May 2026 18:22:32 +0200 Subject: [PATCH] fix: isolate tests on in-memory SQLite to protect production database Tests were importing the production engine and dropping all tables on teardown, corrupting topology.db in the Docker volume. Set DATABASE_URL to sqlite:///:memory: before any import in the test file, and use StaticPool in database.py when running against :memory: so all connections share the same in-memory database. Co-Authored-By: Claude Sonnet 4.6 --- backend/database.py | 10 ++++++---- backend/tests/test_validation.py | 3 +++ 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/backend/database.py b/backend/database.py index c0b5580..b08e495 100644 --- a/backend/database.py +++ b/backend/database.py @@ -9,10 +9,12 @@ os.makedirs("data", exist_ok=True) _DATABASE_URL = os.environ.get("DATABASE_URL", "sqlite:///./data/topology.db") -engine = create_engine( - _DATABASE_URL, - connect_args={"check_same_thread": False} -) +_engine_kwargs: dict = {"connect_args": {"check_same_thread": False}} +if ":memory:" in _DATABASE_URL: + from sqlalchemy.pool import StaticPool + _engine_kwargs["poolclass"] = StaticPool + +engine = create_engine(_DATABASE_URL, **_engine_kwargs) @event.listens_for(Engine, "connect") diff --git a/backend/tests/test_validation.py b/backend/tests/test_validation.py index 1a88209..f76d003 100644 --- a/backend/tests/test_validation.py +++ b/backend/tests/test_validation.py @@ -15,6 +15,9 @@ from sqlalchemy import text import sys, os sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +# Redirect to an in-memory database so tests never touch the production volume. +os.environ["DATABASE_URL"] = "sqlite:///:memory:" + from database import engine, Base from main import app, _migrate_users_must_change_password, _migrate_users_token_version, _migrate_users