Test Postgres in Python Like SQLite
created: June 6, 2025, 12:56 a.m. | updated: June 6, 2025, 4:15 p.m.
name == "Alice"Manual Managementfrom py_pglite import PGliteManager , PGliteConfig # Custom configuration config = PGliteConfig ( timeout = 30 , cleanup_on_exit = True , log_level = "DEBUG" ) # Manual management with PGliteManager ( config ) as manager : engine = manager .
testclient import TestClient from sqlmodel import Session from py_pglite import pglite_engine app = FastAPI () def get_db (): # Production database dependency pass @ app .
Complex Testing Scenariodef test_complex_operations ( pglite_session : Session ): # Create related data user = User ( name = "Alice" , email = "[email protected]" ) pglite_session .
get_engine () # Multiple sessions work perfectly session1 = Session ( engine ) session2 = Session ( engine ) session3 = Session ( engine ) # ❌ Not recommended: Multiple engines from same manager with PGliteManager () as manager : engine1 = manager .
Creating multiple SQLAlchemy engines from the same PGlite manager can cause connection pool conflicts since they all connect to the same Unix socket.
2 days, 2 hours ago: Hacker News