Pytest Mock Resources

2.12.4 · active · verified Wed Apr 15

A pytest plugin for easily instantiating reproducible mock resources such as PostgreSQL, MongoDB, Redis, and more. It leverages Docker to manage container lifecycles, providing real service instances for robust integration testing without relying on complex mocks. The library is actively maintained with frequent releases, currently at version 2.12.4.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `pytest-mock-resources` to create a mock PostgreSQL database. It defines a simple SQLAlchemy model, sets up a `create_postgres_fixture` that yields a SQLAlchemy session, and then shows two isolated tests creating users.

import pytest
from sqlalchemy import create_engine, text
from sqlalchemy.orm import declarative_base, sessionmaker

# Define a simple SQLAlchemy model (if using ORM)
Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String)

    def __repr__(self):
        return f"<User(id={self.id}, name='{self.name}')>"

from sqlalchemy import Column, Integer, String
from pytest_mock_resources import create_postgres_fixture

# Create a PostgreSQL fixture, providing the SQLAlchemy Base and enabling session
# This fixture will provide a SQLAlchemy session object to tests that request 'pg'
pg = create_postgres_fixture(Base, session=True)

def test_user_creation(pg):
    """Test creating a user in the mock PostgreSQL database."""
    # 'pg' is a SQLAlchemy session provided by the fixture
    new_user = User(name='Alice')
    pg.add(new_user)
    pg.commit()
    pg.refresh(new_user)

    result = pg.execute(text("SELECT name FROM users WHERE id = :id"), {'id': new_user.id}).scalar_one()
    assert result == 'Alice'

def test_another_user_creation(pg):
    """Another test, ensuring isolation between tests (new empty database)."""
    # This test gets a fresh, empty database instance
    assert pg.query(User).count() == 0
    new_user = User(name='Bob')
    pg.add(new_user)
    pg.commit()
    assert pg.query(User).count() == 1

view raw JSON →