feat: db base + config tests

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
浅念
2026-08-01 11:04:44 +08:00
parent 2031607beb
commit b9fcf17ae4
7 changed files with 193 additions and 0 deletions
View File
+48
View File
@@ -0,0 +1,48 @@
"""Database core: declarative base, async engine, session factory.
Production targets MySQL via `asyncmy` (configured by `Settings.db_url`).
Unit tests build their own in-memory SQLite engines (see `tests/test_db_base.py`)
and only import `Base` / `async_session_maker` from here.
"""
from collections.abc import AsyncIterator
from sqlalchemy.ext.asyncio import (
AsyncSession,
async_sessionmaker,
create_async_engine,
)
from sqlalchemy.orm import DeclarativeBase
from app.config import get_settings
class Base(DeclarativeBase):
"""Common declarative base for all ORM models in the project."""
settings = get_settings()
async_engine = create_async_engine(
settings.db_url,
pool_pre_ping=True,
future=True,
)
async_session_maker: async_sessionmaker[AsyncSession] = async_sessionmaker(
async_engine,
expire_on_commit=False,
)
async def get_session() -> AsyncIterator[AsyncSession]:
"""FastAPI dependency that yields an `AsyncSession`.
Usage::
@app.get("/")
async def index(session: AsyncSession = Depends(get_session)):
...
"""
async with async_session_maker() as session:
yield session
+1
View File
@@ -22,6 +22,7 @@ dependencies = [
dev = [
"pytest",
"pytest-asyncio",
"aiosqlite",
"respx",
"ruff",
]
View File
+17
View File
@@ -0,0 +1,17 @@
"""Shared pytest fixtures for the yunke-server test suite."""
import pytest
from app.config import get_settings
@pytest.fixture(autouse=True)
def reset_settings_cache():
"""Ensure each test starts with a fresh Settings cache.
Tests that mutate env vars and call `get_settings()` must also clear the
`lru_cache` themselves; this fixture is a safety net that runs after every
test so a cached `Settings` from one test never leaks into the next.
"""
yield
get_settings.cache_clear()
+69
View File
@@ -0,0 +1,69 @@
"""Tests for app.config.get_settings — env-var binding and cache isolation."""
from pathlib import Path
from app.config import Settings, get_settings
def test_get_settings_reads_env_vars(monkeypatch):
"""get_settings() must reflect env vars set before it is called."""
# Clear any cached singleton from earlier tests / module imports.
get_settings.cache_clear()
monkeypatch.setenv("YUNKE_BASE_URL", "https://example.test/")
monkeypatch.setenv("YUNKE_USERNAME", "tester")
monkeypatch.setenv("YUNKE_PASSWORD", "shh")
monkeypatch.setenv(
"DB_URL",
"mysql+asyncmy://u:p@db.example:3306/yunke_test",
)
monkeypatch.setenv("REDIS_URL", "redis://redis.example:6379/2")
monkeypatch.setenv("MEDIA_DIR", "/tmp/yunke_media")
monkeypatch.setenv("ENCRYPTION_KEY", "abc123")
settings = get_settings()
assert settings.yunke_base_url == "https://example.test/"
assert settings.yunke_username == "tester"
assert settings.yunke_password == "shh"
assert settings.db_url == "mysql+asyncmy://u:p@db.example:3306/yunke_test"
assert settings.redis_url == "redis://redis.example:6379/2"
assert settings.media_dir == Path("/tmp/yunke_media")
assert settings.encryption_key == "abc123"
def test_get_settings_is_cached(monkeypatch):
"""get_settings() returns the same instance until the cache is cleared."""
get_settings.cache_clear()
first = get_settings()
second = get_settings()
assert first is second
# After clearing the cache, a new instance is built.
get_settings.cache_clear()
third = get_settings()
assert third is not first
def test_get_settings_picks_up_changes_after_cache_clear(monkeypatch):
"""After cache_clear(), the next call re-reads the environment."""
get_settings.cache_clear()
monkeypatch.setenv("DB_URL", "sqlite+aiosqlite:///:memory:")
initial = get_settings()
assert initial.db_url == "sqlite+aiosqlite:///:memory:"
monkeypatch.setenv("DB_URL", "mysql+asyncmy://other:3306/yunke")
# Cached value must NOT change just because env changed.
assert get_settings().db_url == "sqlite+aiosqlite:///:memory:"
# After clearing, the new env var is picked up.
get_settings.cache_clear()
assert get_settings().db_url == "mysql+asyncmy://other:3306/yunke"
def test_settings_constructable_without_env():
"""Settings() can be built with defaults (no env required)."""
s = Settings()
assert isinstance(s.db_url, str)
assert s.encryption_key == ""
+58
View File
@@ -0,0 +1,58 @@
"""Tests for app.db.base — Base class, async engine + sessionmaker plumbing.
These tests build an isolated in-memory SQLite async engine; they never touch
the production MySQL engine defined in app.db.base.
"""
import sqlalchemy as sa
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
from sqlalchemy.orm import Mapped, mapped_column
from app.db.base import Base, async_session_maker
def test_base_is_declarative_subclass():
"""Base must be a DeclarativeBase subclass (SQLAlchemy 2.0 style)."""
from sqlalchemy.orm import DeclarativeBase
assert issubclass(Base, DeclarativeBase)
def test_async_session_maker_is_async_sessionmaker():
"""async_session_maker must be an async_sessionmaker instance."""
assert isinstance(async_session_maker, async_sessionmaker)
async def test_round_trip_through_in_memory_sqlite():
"""Build a throwaway model, create tables, insert + query a row.
Uses an in-memory async SQLite engine built locally inside the test so the
production MySQL engine is never exercised here.
"""
class _Row(Base):
__tablename__ = "test_row"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(sa.String(50))
engine = create_async_engine("sqlite+aiosqlite:///:memory:")
try:
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
SessionLocal = async_sessionmaker(engine, expire_on_commit=False)
async with SessionLocal() as session:
session.add(_Row(id=1, name="hello"))
await session.commit()
fetched = (
await session.execute(sa.select(_Row).where(_Row.id == 1))
).scalar_one()
assert fetched.id == 1
assert fetched.name == "hello"
finally:
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await engine.dispose()