惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

A
About on SuperTechFans
D
DataBreaches.Net
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
V
Visual Studio Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
B
Blog RSS Feed
Recent Announcements
Recent Announcements
The Register - Security
The Register - Security
S
Secure Thoughts
Y
Y Combinator Blog
The Last Watchdog
The Last Watchdog
L
LINUX DO - 最新话题
V2EX - 技术
V2EX - 技术
腾讯CDC
GbyAI
GbyAI
G
Google Developers Blog
博客园 - 司徒正美
博客园 - 三生石上(FineUI控件)
T
The Exploit Database - CXSecurity.com
T
Threat Research - Cisco Blogs
P
Proofpoint News Feed
Schneier on Security
Schneier on Security
Microsoft Security Blog
Microsoft Security Blog
Jina AI
Jina AI
WordPress大学
WordPress大学
aimingoo的专栏
aimingoo的专栏
MyScale Blog
MyScale Blog
Help Net Security
Help Net Security
K
Kaspersky official blog
P
Privacy & Cybersecurity Law Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
AI
AI
MongoDB | Blog
MongoDB | Blog
Scott Helme
Scott Helme
J
Java Code Geeks
Engineering at Meta
Engineering at Meta
H
Heimdal Security Blog
H
Help Net Security
D
Darknet – Hacking Tools, Hacker News & Cyber Security
云风的 BLOG
云风的 BLOG
Microsoft Azure Blog
Microsoft Azure Blog
S
Security Affairs
TaoSecurity Blog
TaoSecurity Blog
The GitHub Blog
The GitHub Blog
Hacker News: Ask HN
Hacker News: Ask HN
Martin Fowler
Martin Fowler
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Project Zero
Project Zero
T
The Blog of Author Tim Ferriss
Last Week in AI
Last Week in AI

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Testing FastAPI + SQLAlchemy with Real PostgreSQL Fixtures: No More Mocking Misery
Ugur Aslim · 2026-05-23 · via DEV Community

Ugur Aslim

Testing FastAPI + SQLAlchemy with Real PostgreSQL Fixtures: No More Mocking Misery

I spent three months debugging why a query worked in tests but failed in production. The culprit? I'd mocked the entire database layer.

Mocks are seductive. They're fast, isolated, and you control everything. But they're also liars. They hide migration bugs, concurrency issues, transaction edge cases, and the thousand small ways your ORM behaves differently under real database constraints. I'd rather catch those bugs in CI than at 2 AM in production.

This post shows you how to test FastAPI + SQLAlchemy against real PostgreSQL instances—cheaply, quickly, and with perfect isolation. No mocking the data layer. No false confidence.

Why Real Databases Beat Mocks

Before diving into code, let me be direct about why I changed my mind.

Mocks hide real problems. When you mock session.query(), you're not testing how SQLAlchemy constructs queries, handles N+1 problems, or manages transactions. You're testing your test setup.

Migrations are invisible to mocks. I once added a NOT NULL constraint in a migration. Tests passed (mocked). Production broke (real database). Now I run real migrations in every test database.

Concurrency and locks don't exist in mocks. Row-level locking, deadlock conditions, and transaction isolation levels are real problems in multi-tenant systems. Mocks can't catch them.

Your ORM behaves differently than you expect. SQLAlchemy's relationship loading, cascade deletes, and lazy vs. eager loading have edge cases. Real tests find them.

The trade-off isn't as bad as it sounds. Docker + pytest fixtures make spinning up isolated PostgreSQL databases fast—we're talking milliseconds for setup, and modern CI can parallelize tests across multiple database instances.

The Setup: Docker Compose + Pytest Fixtures

I use a minimal Docker Compose setup that spins up PostgreSQL and tears it down cleanly between test runs.

docker-compose.test.yml:

version: '3.8'
services:
  postgres-test:
    image: postgres:16-alpine
    environment:
      POSTGRES_USER: test_user
      POSTGRES_PASSWORD: test_password
      POSTGRES_DB: test_db
    ports:
      - "5433:5432"
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U test_user"]
      interval: 1s
      timeout: 5s
      retries: 10
    tmpfs:
      - /var/lib/postgresql/data

Enter fullscreen mode Exit fullscreen mode

The tmpfs line is crucial—it stores the database in RAM, making writes blazingly fast. Perfect for tests.

conftest.py — this is where the magic happens:

import pytest
import subprocess
import time
from sqlalchemy import create_engine, text
from sqlalchemy.pool import NullPool
from sqlalchemy.orm import sessionmaker, Session

# Import your models
from app.models import Base
from app.database import get_db


@pytest.fixture(scope="session")
def docker_compose():
    """Spin up Docker Compose once per test session."""
    subprocess.run(
        ["docker-compose", "-f", "docker-compose.test.yml", "up", "-d"],
        check=True,
        cwd=".",
    )

    # Wait for postgres to be ready
    max_retries = 30
    for i in range(max_retries):
        try:
            engine = create_engine(
                "postgresql://test_user:test_password@localhost:5433/test_db"
            )
            with engine.connect() as conn:
                conn.execute(text("SELECT 1"))
            break
        except Exception as e:
            if i == max_retries - 1:
                raise
            time.sleep(0.5)

    yield

    # Tear down
    subprocess.run(
        ["docker-compose", "-f", "docker-compose.test.yml", "down"],
        check=True,
        cwd=".",
    )


@pytest.fixture
def db_session(docker_compose):
    """Create a fresh database session for each test."""
    # Create engine with NullPool—don't reuse connections between tests
    engine = create_engine(
        "postgresql://test_user:test_password@localhost:5433/test_db",
        poolclass=NullPool,
    )

    # Run migrations (I use Alembic; you could also use Base.metadata.create_all)
    subprocess.run(
        ["alembic", "upgrade", "head"],
        check=True,
        cwd=".",
    )

    SessionLocal = sessionmaker(bind=engine, expire_on_commit=False)
    session = SessionLocal()

    yield session

    # Cleanup: rollback any uncommitted transactions
    session.rollback()
    session.close()

    # Drop all tables between tests for true isolation
    Base.metadata.drop_all(engine)


@pytest.fixture
def client(db_session):
    """Provide a FastAPI test client with dependency injection."""
    from fastapi.testclient import TestClient
    from app.main import app

    def override_get_db():
        yield db_session

    app.dependency_overrides[get_db] = override_get_db

    return TestClient(app)

Enter fullscreen mode Exit fullscreen mode

Notice the key decisions:

  • NullPool: Each test gets a fresh connection. No connection reuse surprises.
  • drop_all() after each test: Complete isolation. No shared state.
  • Alembic migrations run in every test: You catch migration bugs immediately.

Real Test Example: Catching What Mocks Miss

Let's test a user creation endpoint with a unique email constraint:

from app.models import User
from datetime import datetime


def test_create_user_success(client, db_session):
    """Test successful user creation."""
    response = client.post(
        "/users",
        json={"email": "alice@example.com", "name": "Alice"},
    )

    assert response.status_code == 201
    assert response.json()["email"] == "alice@example.com"

    # Verify it's actually in the database
    user = db_session.query(User).filter_by(email="alice@example.com").first()
    assert user is not None
    assert user.name == "Alice"


def test_create_duplicate_email_fails(client, db_session):
    """Test that duplicate emails are rejected.

    This catches:
    - Whether your database constraint actually exists
    - Whether your error handling returns the right status code
    - Whether the transaction rolled back properly
    """
    # Insert first user
    client.post(
        "/users",
        json={"email": "bob@example.com", "name": "Bob"},
    )

    # Try to insert duplicate
    response = client.post(
        "/users",
        json={"email": "bob@example.com", "name": "Bob 2"},
    )

    assert response.status_code == 409  # Conflict
    assert "already exists" in response.json()["detail"].lower()

    # Verify only one user exists
    count = db_session.query(User).filter_by(email="bob@example.com").count()
    assert count == 1


def test_n_plus_one_query_detection(client, db_session):
    """Catch N+1 queries against real PostgreSQL."""
    from sqlalchemy import event

    # Track queries
    queries = []

    @event.listens_for(engine, "before_cursor_execute")
    def receive_before_cursor_execute(conn, cursor, statement, params, context, executemany):
        queries.append(statement)

    # Create users with posts
    for i in range(5):
        user = User(email=f"user{i}@example.com", name=f"User {i}")
        db_session.add(user)
    db_session.commit()

    # Fetch users and their posts efficiently
    users = db_session.query(User).options(joinedload(User.posts)).all()

    # Against a real database, you can verify query patterns
    # Mocks can't catch these subtle performance bugs
    assert len(queries) < 10  # Rough check; adjust for your schema

Enter fullscreen mode Exit fullscreen mode

That last test is impossible to write meaningfully against mocks. With real PostgreSQL, you actually catch N+1 queries, missing indexes, and transaction issues.

Gotcha: Test Database Concurrency

Here's what burned me: I created a test for concurrent writes, but because each test got its own db_session, I wasn't actually testing multiple concurrent connections.

Solution: When you need true concurrency tests, use separate database sessions:

def test_concurrent_writes(db_session):
    """Test actual concurrent database writes."""
    from concurrent.futures import ThreadPoolExecutor
    from app.database import SessionLocal

    def create_user(email: str):
        session = SessionLocal()
        try:
            user = User(email=email, name=email.split("@")[0])
            session.add(user)
            session.commit()
            return user.id
        finally:
            session.close()

    # Run 10 writes concurrently
    with ThreadPoolExecutor(max_workers=10) as executor:
        futures = [
            executor.submit(create_user, f"user{i}@example.com")
            for i in range(10)
        ]
        results = [f.result() for f in futures]

    # Verify all succeeded
    assert len(set(results)) == 10  # All IDs unique

Enter fullscreen mode Exit fullscreen mode

This actually stress-tests your database and connection pool. Mocks wouldn't catch connection pool exhaustion or deadlocks.

Speed: It's Faster Than You Think

People worry real database tests are slow. They're not—especially with tmpfs and good fixture design:

  • Database spin-up: ~2s (once per session)
  • Per-test setup: ~50ms
  • Typical test execution: ~100ms

A 100-test suite runs in under 15 seconds locally. In CI with parallelization