From b9fcf17ae4ff318bb79101965ef3f326e7271319 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B5=85=E5=BF=B5?= Date: Sat, 1 Aug 2026 11:04:44 +0800 Subject: [PATCH] feat: db base + config tests Co-Authored-By: Claude --- yunke-server/app/db/__init__.py | 0 yunke-server/app/db/base.py | 48 +++++++++++++++++++++ yunke-server/pyproject.toml | 1 + yunke-server/tests/__init__.py | 0 yunke-server/tests/conftest.py | 17 ++++++++ yunke-server/tests/test_config.py | 69 ++++++++++++++++++++++++++++++ yunke-server/tests/test_db_base.py | 58 +++++++++++++++++++++++++ 7 files changed, 193 insertions(+) create mode 100644 yunke-server/app/db/__init__.py create mode 100644 yunke-server/app/db/base.py create mode 100644 yunke-server/tests/__init__.py create mode 100644 yunke-server/tests/conftest.py create mode 100644 yunke-server/tests/test_config.py create mode 100644 yunke-server/tests/test_db_base.py diff --git a/yunke-server/app/db/__init__.py b/yunke-server/app/db/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/yunke-server/app/db/base.py b/yunke-server/app/db/base.py new file mode 100644 index 0000000..34e6318 --- /dev/null +++ b/yunke-server/app/db/base.py @@ -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 diff --git a/yunke-server/pyproject.toml b/yunke-server/pyproject.toml index 9d93e5e..13b20f2 100644 --- a/yunke-server/pyproject.toml +++ b/yunke-server/pyproject.toml @@ -22,6 +22,7 @@ dependencies = [ dev = [ "pytest", "pytest-asyncio", + "aiosqlite", "respx", "ruff", ] diff --git a/yunke-server/tests/__init__.py b/yunke-server/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/yunke-server/tests/conftest.py b/yunke-server/tests/conftest.py new file mode 100644 index 0000000..2d44b35 --- /dev/null +++ b/yunke-server/tests/conftest.py @@ -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() diff --git a/yunke-server/tests/test_config.py b/yunke-server/tests/test_config.py new file mode 100644 index 0000000..699ca6f --- /dev/null +++ b/yunke-server/tests/test_config.py @@ -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 == "" diff --git a/yunke-server/tests/test_db_base.py b/yunke-server/tests/test_db_base.py new file mode 100644 index 0000000..69ee6b6 --- /dev/null +++ b/yunke-server/tests/test_db_base.py @@ -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()