diff --git a/backend/app/core/deps.py b/backend/app/core/deps.py index b7140a2..eece509 100644 --- a/backend/app/core/deps.py +++ b/backend/app/core/deps.py @@ -6,7 +6,7 @@ from app.config import settings # 处理 sqlite 协议兼容 db_url = settings.DATABASE_URL -if db_url.startswith("sqlite"): +if db_url.startswith("sqlite://"): db_url = db_url.replace("sqlite://", "sqlite+aiosqlite://") engine = create_async_engine(db_url, echo=False, pool_pre_ping=True) diff --git a/backend/tests/test_deps_import.py b/backend/tests/test_deps_import.py index 7d4741b..6be367e 100644 --- a/backend/tests/test_deps_import.py +++ b/backend/tests/test_deps_import.py @@ -1,10 +1,48 @@ """Regression coverage for application dependency module imports.""" +import importlib +import sys from pathlib import Path +import pytest + def test_dependency_module_compiles(): """Database initialization dependencies remain valid Python syntax.""" module_path = Path(__file__).parents[1] / "app" / "core" / "deps.py" compile(module_path.read_text(encoding="utf-8"), str(module_path), "exec") + + +@pytest.mark.parametrize( + ("database_url", "expected_url"), + [ + ("sqlite:///./pingwatch.db", "sqlite+aiosqlite:///./pingwatch.db"), + ( + "sqlite+aiosqlite:///./pingwatch.db", + "sqlite+aiosqlite:///./pingwatch.db", + ), + ], +) +def test_dependency_module_normalizes_sqlite_url_once( + monkeypatch, database_url, expected_url +): + """Plain SQLite URLs gain the async driver without duplicating an existing one.""" + monkeypatch.setenv("DATABASE_URL", database_url) + sys.modules.pop("app.core.deps", None) + sys.modules.pop("app.config", None) + + deps = importlib.import_module("app.core.deps") + + assert str(deps.engine.url) == expected_url + + +def test_dependency_module_initializes_with_default_sqlite_url(monkeypatch): + """The default database setting can initialize the asynchronous dependency.""" + monkeypatch.delenv("DATABASE_URL", raising=False) + sys.modules.pop("app.core.deps", None) + sys.modules.pop("app.config", None) + + deps = importlib.import_module("app.core.deps") + + assert str(deps.engine.url) == "sqlite+aiosqlite:///./pingwatch.db"