Skip to main content

Python testing library for PGlite - in-memory PostgreSQL for tests

Project description

Py-PGlite

py-pglite Logo

Instant PostgreSQL for Python testing

pip install py-pglite


def test_users(pglite_session):
    user = User(name="Alice")
    pglite_session.add(user)
    pglite_session.commit()
    assert user.id == 1  # It's real PostgreSQL!

That's it. No Docker, no setup, no config files. Real PostgreSQL, instant testing.

CI PyPI Python

License MyPy Ruff codecov


Zero-Config Quick Start

SQLAlchemy (Zero imports needed)

def test_sqlalchemy_just_works(pglite_session):
    # Tables created automatically
    user = User(name="Alice", email="alice@test.com")  
    pglite_session.add(user)
    pglite_session.commit()
    
    assert user.id is not None
    assert User.query.count() == 1  # Real PostgreSQL!

Django (Auto-configured)

def test_django_just_works(db):
    # Models ready automatically
    Post.objects.create(title="Hello", content="World")
    assert Post.objects.count() == 1  # Real PostgreSQL!

Raw SQL (Pure speed)

def test_raw_sql_power(pglite_engine):
    with pglite_engine.connect() as conn:
        # Full PostgreSQL features
        result = conn.execute(text("""
            SELECT '{"users": [{"name": "Alice"}]}'::json ->> 'users'
        """)).scalar()
        assert '"name": "Alice"' in result  # JSON queries work!

🚀 Why py-pglite?

# ❌ Traditional testing
def test_old_way():
    # 1. Install PostgreSQL
    # 2. Configure connection  
    # 3. Manage test databases
    # 4. Handle cleanup
    # 5. Docker containers...
    pass

# ✅ py-pglite way  
def test_new_way(pglite_session):
    User.objects.create(name="Alice")  # Just works!

The magic:

  • 🎯 Zero config - No setup, no Docker, no servers
  • ⚡ Sweet spot - PostgreSQL power + near-SQLite convenience
  • 🔄 Isolated - Fresh database per test
  • 🎪 Full featured - JSON, arrays, window functions, etc.
  • 🧪 Framework ready - SQLAlchemy, Django, FastAPI
  • 🚀 Fast setup - 2-3s vs 30-60s Docker PostgreSQL startup

📦 Installation

# Core (framework-agnostic)
pip install py-pglite

# With your favorite framework
pip install py-pglite[sqlalchemy]  # SQLAlchemy + SQLModel
pip install py-pglite[django]      # Django + pytest-django  
pip install py-pglite[all]         # Everything

🎯 Real Examples

SQLAlchemy + FastAPI (Production ready)

from fastapi.testclient import TestClient

def test_api_endpoint(client: TestClient):
    # Auto-configured FastAPI + SQLAlchemy + PostgreSQL
    response = client.post("/users/", json={"name": "Alice"})
    assert response.status_code == 201
    
    response = client.get("/users/")
    assert len(response.json()) == 1

Django Models (Zero setup)

def test_django_models(db):
    # Django auto-configured with real PostgreSQL
    user = User.objects.create_user("alice", "alice@test.com") 
    blog = Blog.objects.create(title="Hello", author=user)
    
    assert Blog.objects.filter(author__username="alice").count() == 1

PostgreSQL Features (Full power)

def test_postgresql_features(pglite_session):
    pglite_session.execute(text("""
        CREATE TABLE analytics (
            id SERIAL PRIMARY KEY,
            data JSONB,
            tags TEXT[],
            created TIMESTAMP DEFAULT NOW()
        )
    """))
    
    # JSON operations
    pglite_session.execute(text("""
        INSERT INTO analytics (data, tags) VALUES 
        ('{"clicks": 100, "views": 1000}', ARRAY['web', 'mobile'])
    """))
    
    # Complex PostgreSQL query
    result = pglite_session.execute(text("""
        SELECT data->>'clicks' as clicks,
               array_length(tags, 1) as tag_count,
               extract(hour from created) as hour
        FROM analytics 
        WHERE data->>'clicks' > '50'
    """)).fetchone()
    
    assert result.clicks == '100'
    assert result.tag_count == 2

🏗️ Architecture

py_pglite/
├── 📦 Core (no dependencies)
├── 🔧 SQLAlchemy integration  
├── 🌟 Django integration
└── ⚡ Auto-discovery pytest plugin

Design principles:

  • Framework agnostic core - Use with anything
  • Optional integrations - Only load what you need
  • Zero configuration - Intelligent defaults
  • Perfect isolation - No framework interference

🎪 Advanced Features

🔧 Custom Configuration
@pytest.fixture(scope="session")
def custom_pglite():
    config = PGliteConfig(
        port_range=(5500, 5600),
        timeout=30,
        cleanup_on_exit=True
    )
    with PGliteManager(config) as manager:
        yield manager
🚀 Performance Testing
def test_bulk_insert_performance(pglite_session):
    users = [User(name=f"user_{i}") for i in range(1000)]
    pglite_session.add_all(users)
    pglite_session.commit()
    
    assert pglite_session.query(User).count() == 1000
    # Blazing fast with real PostgreSQL!
🎯 Framework Isolation
# Pure SQLAlchemy tests
pytest -m sqlalchemy -p no:django

# Pure Django tests
pytest -m django

# Directory isolation
pytest tests/sqlalchemy/  # Auto-isolated
pytest tests/django/       # Auto-isolated

💝 Community

"Finally, PostgreSQL testing that just works!" - Happy Developer

"From 30 minutes of setup to 30 seconds. Game changer." - Django User

"Vite for databases. This is the future." - FastAPI Enthusiast


Built for developers who want PostgreSQL testing without the complexity.

🎯 View Examples • 📚 Contributing • 🐛 Issues


py-pglite: Because testing should be simple.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

py_pglite-0.2.1.tar.gz (209.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

py_pglite-0.2.1-py3-none-any.whl (36.0 kB view details)

Uploaded Python 3

File details

Details for the file py_pglite-0.2.1.tar.gz.

File metadata

  • Download URL: py_pglite-0.2.1.tar.gz
  • Upload date:
  • Size: 209.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for py_pglite-0.2.1.tar.gz
Algorithm Hash digest
SHA256 a63fec7cd6b92d3efdb29f1a4d46eb26cb9055218b20e7d56465a049df0fc860
MD5 456e4eade3570da8596839ba6469e3da
BLAKE2b-256 ada6922b29260a8aee44d473167719236460125086399ff07c519f1860530c47

See more details on using hashes here.

Provenance

The following attestation bundles were made for py_pglite-0.2.1.tar.gz:

Publisher: release.yml on wey-gu/py-pglite

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file py_pglite-0.2.1-py3-none-any.whl.

File metadata

  • Download URL: py_pglite-0.2.1-py3-none-any.whl
  • Upload date:
  • Size: 36.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for py_pglite-0.2.1-py3-none-any.whl
Algorithm Hash digest
SHA256 6f2e70fd944ff10c193e97813cd34d7006ede391b415c6dec5f96e3730e831c1
MD5 93d8ef4e9335be1e3a32c89f67b1a250
BLAKE2b-256 ac31f3205f1ec0016ebe649ece291049e958f2784c4287d1657d90aab7e33a35

See more details on using hashes here.

Provenance

The following attestation bundles were made for py_pglite-0.2.1-py3-none-any.whl:

Publisher: release.yml on wey-gu/py-pglite

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page