Close Menu

    Subscribe to Updates

    Get the latest creative news from FooBar about art, design and business.

    What's Hot

    LG releases new 14-inch laptops before global launch

    Xiaomi releases smart washer dryer with self-cleaning feature in the UK

    Leak confirms that Pokémon Gen 10 Switch 2 game will debut at Pokémon Presents showcase

    Facebook X (Twitter) Instagram
    • Artificial Intelligence
    • Business Technology
    • Cryptocurrency
    • Gadgets
    • Gaming
    • Health
    • Software and Apps
    • Technology
    Facebook X (Twitter) Instagram Pinterest Vimeo
    Tech AI Verse
    • Home
    • Artificial Intelligence

      Tensions between the Pentagon and AI giant Anthropic reach a boiling point

      February 21, 2026

      Read the extended transcript: President Donald Trump interviewed by ‘NBC Nightly News’ anchor Tom Llamas

      February 6, 2026

      Stocks and bitcoin sink as investors dump software company shares

      February 4, 2026

      AI, crypto and Trump super PACs stash millions to spend on the midterms

      February 2, 2026

      To avoid accusations of AI cheating, college students are turning to AI

      January 29, 2026
    • Business

      Gartner: Why neoclouds are the future of GPU-as-a-Service

      February 21, 2026

      The HDD brand that brought you the 1.8-inch, 2.5-inch, and 3.5-inch hard drives is now back with a $19 pocket-sized personal cloud for your smartphones

      February 12, 2026

      New VoidLink malware framework targets Linux cloud servers

      January 14, 2026

      Nvidia Rubin’s rack-scale encryption signals a turning point for enterprise AI security

      January 13, 2026

      How KPMG is redefining the future of SAP consulting on a global scale

      January 10, 2026
    • Crypto

      Another European Country Bans Polymarket, Threatens Massive Fine

      February 20, 2026

      Why Is The US Stock Market Up Today?

      February 20, 2026

      Is XRP Price Preparing To Breach Its 2026 Downtrend? Here’s What History Says

      February 20, 2026

      “Disgrace” or “Win for American Wallets”? Supreme Court Tariff Bombshell Sparks Political Meltdown in Washington

      February 20, 2026

      Perle Labs CEO Ahmed Rashad on Why AI Needs Verifiable Data Infrastructure

      February 20, 2026
    • Technology

      LG releases new 14-inch laptops before global launch

      February 21, 2026

      Xiaomi releases smart washer dryer with self-cleaning feature in the UK

      February 21, 2026

      Leak confirms that Pokémon Gen 10 Switch 2 game will debut at Pokémon Presents showcase

      February 21, 2026

      Affordable 280Hz Tandem OLED monitor with glossy display: Gigabyte MO27Q28GR now available for $599.99

      February 21, 2026

      Strip out Windows 11’s bloatware, ads, and other grossness—for free

      February 21, 2026
    • Others
      • Gadgets
      • Gaming
      • Health
      • Software and Apps
    Check BMI
    Tech AI Verse
    You are at:Home»Technology»Test Postgres in Python Like SQLite
    Technology

    Test Postgres in Python Like SQLite

    TechAiVerseBy TechAiVerseJune 6, 2025No Comments5 Mins Read17 Views
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    Test Postgres in Python Like SQLite
    Share
    Facebook Twitter LinkedIn Pinterest WhatsApp Email

    Test Postgres in Python Like SQLite

    py-pglite







    A Python testing library that provides seamless integration between PGlite and Python test suites. Get the full power of PostgreSQL in your tests without the overhead of a full PostgreSQL installation.

    🎯 Why py-pglite?

    • ⚡ Blazing Fast: In-memory PostgreSQL for ultra-quick test runs
    • 🛠️ Effortless Setup: No PostgreSQL install needed—just Node.js(I know)!
    • 🐍 Pythonic: Native support for SQLAlchemy & SQLModel in your tests
    • 🧊 Fully Isolated: Every test module gets its own fresh database
    • 🦾 100% Compatible: True PostgreSQL features via PGlite
    • 🧩 Pytest Plug-and-Play: Ready-to-use fixtures for instant productivity

    📦 Installation

    Basic Installation

    With Optional Dependencies

    # For SQLModel support
    pip install "py-pglite[sqlmodel]"
    
    # For FastAPI integration
    pip install "py-pglite[fastapi]"
    
    # For development
    pip install "py-pglite[dev]"

    Requirements

    • Python: 3.10+
    • Node.js: 18+ (for PGlite)
    • SQLAlchemy: 2.0+

    The library automatically manages PGlite npm dependencies.

    🚀 Quick Start

    Basic Usage with Pytest

    import pytest
    from sqlmodel import Session, SQLModel, Field, select
    from py_pglite import pglite_session
    
    # Your models
    class User(SQLModel, table=True):
        id: int | None = Field(default=None, primary_key=True)
        name: str
        email: str
    
    # Test with automatic PGlite management
    def test_user_creation(pglite_session: Session):
        user = User(name="Alice", email="alice@example.com")
        pglite_session.add(user)
        pglite_session.commit()
        
        # Query back
        users = pglite_session.exec(select(User)).all()
        assert len(users) == 1
        assert users[0].name == "Alice"

    Manual Management

    from 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.get_engine()
        SQLModel.metadata.create_all(engine)
        
        with Session(engine) as session:
            # Your database operations here
            pass

    🔧 Features

    Pytest Fixtures

    • pglite_engine: SQLAlchemy engine connected to PGlite
    • pglite_session: Database session with automatic cleanup
    • pglite_manager: Direct access to PGlite process management

    Automatic Management

    • ✅ Process lifecycle management
    • ✅ Socket cleanup and health checks
    • ✅ Graceful shutdown and error handling
    • ✅ Per-test isolation with automatic cleanup
    • ✅ Node.js dependency management

    Configuration

    from py_pglite import PGliteConfig
    
    config = PGliteConfig(
        timeout=30,               # Startup timeout in seconds
        cleanup_on_exit=True,     # Auto cleanup on exit
        log_level="INFO",         # Logging level (DEBUG/INFO/WARNING/ERROR)
        socket_path="/tmp/.s.PGSQL.5432",  # Custom socket path
        work_dir=None,            # Working directory (None = temp dir)
        node_modules_check=True,  # Verify node_modules exists
        auto_install_deps=True,   # Auto-install npm dependencies
    )

    Utility Functions

    from py_pglite import utils
    
    # Database cleanup utilities
    utils.clean_database_data(engine)                    # Clean all data
    utils.clean_database_data(engine, exclude_tables=["users"])  # Exclude tables
    utils.reset_sequences(engine)                        # Reset auto-increment sequences
    utils.verify_database_empty(engine)                  # Check if database is empty
    
    # Schema operations
    utils.create_test_schema(engine, "test_schema")      # Create test schema
    utils.drop_test_schema(engine, "test_schema")        # Drop test schema
    
    # Get table statistics
    row_counts = utils.get_table_row_counts(engine)      # Dict of table row counts

    📚 Examples

    FastAPI Integration

    from fastapi import Depends, FastAPI
    from fastapi.testclient import TestClient
    from sqlmodel import Session
    from py_pglite import pglite_engine
    
    app = FastAPI()
    
    def get_db():
        # Production database dependency
        pass
    
    @app.post("/users/")
    def create_user(user_data: dict, db: Session = Depends(get_db)):
        # Your endpoint logic
        pass
    
    # Test with PGlite
    def test_create_user_endpoint(pglite_engine):
        # Override database dependency
        def override_get_db():
            with Session(pglite_engine) as session:
                yield session
        
        app.dependency_overrides[get_db] = override_get_db
        
        with TestClient(app) as client:
            response = client.post("/users/", json={"name": "Bob"})
            assert response.status_code == 200

    See also examples/test_fastapi_auth_example.py for an example of how to use py-pglite with FastAPI e2e test that includes authentication.

    Complex Testing Scenario

    def test_complex_operations(pglite_session: Session):
        # Create related data
        user = User(name="Alice", email="alice@example.com")
        pglite_session.add(user)
        pglite_session.commit()
        pglite_session.refresh(user)
        
        # Create dependent records
        orders = [
            Order(user_id=user.id, amount=100.0),
            Order(user_id=user.id, amount=250.0),
        ]
        pglite_session.add_all(orders)
        pglite_session.commit()
        
        # Complex query with joins
        result = pglite_session.exec(
            select(User.name, func.sum(Order.amount))
            .join(Order)
            .group_by(User.name)
        ).first()
        
        assert result[0] == "Alice"
        assert result[1] == 350.0

    🤝 Contributing

    Contributions welcome! Please read our Contributing Guide.

    1. Fork the repository
    2. Create a feature branch
    3. Make your changes
    4. Add tests for new functionality
    5. Run the development workflow: python hacking.py
    6. Submit a pull request

    📄 License

    Apache 2.0 License – see LICENSE file.

    🙏 Acknowledgments

    • PGlite – The amazing in-memory PostgreSQL
    • SQLAlchemy – Python SQL toolkit
    • SQLModel – Modern Python SQL toolkit
    • Pytest – Testing framework

    Best Practices

    Multiple Database Sessions

    For multiple database connections, use multiple sessions with the same engine rather than multiple engines:

    # ✅ Recommended: Multiple sessions with same engine
    with PGliteManager() as manager:
        engine = manager.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.get_engine()  # Can cause connection conflicts
        engine2 = manager.get_engine()  # when used simultaneously

    Why? Creating multiple SQLAlchemy engines from the same PGlite manager can cause connection pool conflicts since they all connect to the same Unix socket.

    Performance Tips

    • Use pglite_session fixture for automatic cleanup between tests
    • Use pglite_engine fixture when you need direct engine access
    • Use utility functions for efficient database operations
    • Consider custom configurations for specific test requirements

    Testing Patterns

    # Pattern 1: Simple CRUD testing
    def test_user_crud(pglite_session):
        # Create
        user = User(name="Test", email="test@example.com")
        pglite_session.add(user)
        pglite_session.commit()
        
        # Read
        found_user = pglite_session.get(User, user.id)
        assert found_user.name == "Test"
        
        # Update
        found_user.name = "Updated"
        pglite_session.commit()
        
        # Delete
        pglite_session.delete(found_user)
        pglite_session.commit()
    
    # Pattern 2: Custom cleanup
    def test_with_custom_cleanup(pglite_engine):
        SQLModel.metadata.create_all(pglite_engine)
        
        with Session(pglite_engine) as session:
            # Your test logic
            pass
        
        # Custom cleanup if needed
        utils.clean_database_data(pglite_engine)
    Share. Facebook Twitter Pinterest LinkedIn Reddit WhatsApp Telegram Email
    Previous ArticleHow we’re responding to The NYT’s data demands in order to protect user privacy
    Next Article Open Source Distilling
    TechAiVerse
    • Website

    Jonathan is a tech enthusiast and the mind behind Tech AI Verse. With a passion for artificial intelligence, consumer tech, and emerging innovations, he deliver clear, insightful content to keep readers informed. From cutting-edge gadgets to AI advancements and cryptocurrency trends, Jonathan breaks down complex topics to make technology accessible to all.

    Related Posts

    LG releases new 14-inch laptops before global launch

    February 21, 2026

    Xiaomi releases smart washer dryer with self-cleaning feature in the UK

    February 21, 2026

    Leak confirms that Pokémon Gen 10 Switch 2 game will debut at Pokémon Presents showcase

    February 21, 2026
    Leave A Reply Cancel Reply

    Top Posts

    Ping, You’ve Got Whale: AI detection system alerts ships of whales in their path

    April 22, 2025687 Views

    Lumo vs. Duck AI: Which AI is Better for Your Privacy?

    July 31, 2025277 Views

    6.7 Cummins Lifter Failure: What Years Are Affected (And Possible Fixes)

    April 14, 2025159 Views

    6 Best MagSafe Phone Grips (2025), Tested and Reviewed

    April 6, 2025119 Views
    Don't Miss
    Technology February 21, 2026

    LG releases new 14-inch laptops before global launch

    LG releases new 14-inch laptops before global launch – NotebookCheck.net News LG has kicked off…

    Xiaomi releases smart washer dryer with self-cleaning feature in the UK

    Leak confirms that Pokémon Gen 10 Switch 2 game will debut at Pokémon Presents showcase

    Affordable 280Hz Tandem OLED monitor with glossy display: Gigabyte MO27Q28GR now available for $599.99

    Stay In Touch
    • Facebook
    • Twitter
    • Pinterest
    • Instagram
    • YouTube
    • Vimeo

    Subscribe to Updates

    Get the latest creative news from SmartMag about art & design.

    About Us
    About Us

    Welcome to Tech AI Verse, your go-to destination for everything technology! We bring you the latest news, trends, and insights from the ever-evolving world of tech. Our coverage spans across global technology industry updates, artificial intelligence advancements, machine learning ethics, and automation innovations. Stay connected with us as we explore the limitless possibilities of technology!

    Facebook X (Twitter) Pinterest YouTube WhatsApp
    Our Picks

    LG releases new 14-inch laptops before global launch

    February 21, 20263 Views

    Xiaomi releases smart washer dryer with self-cleaning feature in the UK

    February 21, 20264 Views

    Leak confirms that Pokémon Gen 10 Switch 2 game will debut at Pokémon Presents showcase

    February 21, 20263 Views
    Most Popular

    7 Best Kids Bikes (2025): Mountain, Balance, Pedal, Coaster

    March 13, 20250 Views

    VTOMAN FlashSpeed 1500: Plenty Of Power For All Your Gear

    March 13, 20250 Views

    This new Roomba finally solves the big problem I have with robot vacuums

    March 13, 20250 Views
    © 2026 TechAiVerse. Designed by Divya Tech.
    • Home
    • About Us
    • Contact Us
    • Privacy Policy
    • Terms & Conditions

    Type above and press Enter to search. Press Esc to cancel.