test: fix hang in group binding regression tests by isolating sessions and mocking lifespan

This commit is contained in:
liumangmang
2026-06-01 09:32:44 +08:00
parent 518e3e8efc
commit 830b6df587
+25 -5
View File
@@ -22,7 +22,8 @@ from app.utils.auth import get_current_user
@pytest.fixture() @pytest.fixture()
def db_session(): def engine():
"""Create a fresh in-memory database for each test."""
engine = create_engine( engine = create_engine(
"sqlite://", "sqlite://",
connect_args={"check_same_thread": False}, connect_args={"check_same_thread": False},
@@ -30,24 +31,43 @@ def db_session():
) )
from app.models import admin_user, upstream, snapshot, webhook_config, notification_log, custom_page, website, revoked_token, upstream_key from app.models import admin_user, upstream, snapshot, webhook_config, notification_log, custom_page, website, revoked_token, upstream_key
Base.metadata.create_all(bind=engine) Base.metadata.create_all(bind=engine)
return engine
@pytest.fixture()
def db_session(engine):
"""Provide a fresh session for the test logic."""
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
db = TestingSessionLocal() db = TestingSessionLocal()
try: try:
yield db yield db
finally: finally:
db.close() db.close()
Base.metadata.drop_all(bind=engine)
@pytest.fixture() @pytest.fixture()
def client(db_session): def client(engine, monkeypatch):
"""Provide a TestClient with a fresh session factory for each request."""
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
def override_get_db(): def override_get_db():
yield db_session db = TestingSessionLocal()
try:
yield db
finally:
db.close()
# Mock lifespan-related database initialization to avoid using the real DB file
monkeypatch.setattr("app.main.init_db", lambda: None)
monkeypatch.setattr("app.main._init_admin", lambda: None)
monkeypatch.setattr("app.main.start_scheduler", lambda: None)
monkeypatch.setattr("app.main.stop_scheduler", lambda: None)
app.dependency_overrides[get_db] = override_get_db app.dependency_overrides[get_db] = override_get_db
app.dependency_overrides[get_current_user] = lambda: object() app.dependency_overrides[get_current_user] = lambda: object()
try: try:
yield TestClient(app) with TestClient(app) as c:
yield c
finally: finally:
app.dependency_overrides.clear() app.dependency_overrides.clear()