{"id":6829,"library":"pytest-mock-resources","title":"Pytest Mock Resources","description":"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.","status":"active","version":"2.12.4","language":"en","source_language":"en","source_url":"https://github.com/schireson/pytest-mock-resources","tags":["pytest","testing","mocking","database","docker","integration testing","postgresql","mongodb","redis","mysql","redshift","sqlite"],"install":[{"cmd":"pip install pytest-mock-resources pytest","lang":"bash","label":"Install core library and pytest"},{"cmd":"pip install pytest-mock-resources[postgres] psycopg2-binary","lang":"bash","label":"Install with PostgreSQL support (example)"}],"dependencies":[{"reason":"Core testing framework, as this is a pytest plugin.","package":"pytest"},{"reason":"Required for most container-based mock resources (PostgreSQL, MongoDB, Redis, MySQL, Redshift). SQLite is an exception.","package":"Docker","optional":false},{"reason":"PostgreSQL driver. The library recommends users explicitly install database drivers for their chosen resources.","package":"psycopg2-binary","optional":true},{"reason":"Asynchronous PostgreSQL driver, typically used with async fixtures and sqlalchemy.ext.asyncio.","package":"asyncpg","optional":true},{"reason":"MongoDB driver for the MongoDB mock resource.","package":"pymongo","optional":true},{"reason":"Redis client for the Redis mock resource.","package":"redis","optional":true},{"reason":"Generally recommended for testing with asynchronous fixtures.","package":"pytest-asyncio","optional":true}],"imports":[{"note":"Used to create a pytest fixture for a PostgreSQL database.","symbol":"create_postgres_fixture","correct":"from pytest_mock_resources import create_postgres_fixture"},{"note":"Used to customize the configuration for PostgreSQL fixtures.","symbol":"PostgresConfig","correct":"from pytest_mock_resources import PostgresConfig"},{"note":"Used to create a pytest fixture for a MongoDB database.","symbol":"create_mongo_fixture","correct":"from pytest_mock_resources import create_mongo_fixture"},{"note":"Used to create a pytest fixture for a Redis instance.","symbol":"create_redis_fixture","correct":"from pytest_mock_resources import create_redis_fixture"}],"quickstart":{"code":"import pytest\nfrom sqlalchemy import create_engine, text\nfrom sqlalchemy.orm import declarative_base, sessionmaker\n\n# Define a simple SQLAlchemy model (if using ORM)\nBase = declarative_base()\n\nclass User(Base):\n    __tablename__ = 'users'\n    id = Column(Integer, primary_key=True)\n    name = Column(String)\n\n    def __repr__(self):\n        return f\"<User(id={self.id}, name='{self.name}')>\"\n\nfrom sqlalchemy import Column, Integer, String\nfrom pytest_mock_resources import create_postgres_fixture\n\n# Create a PostgreSQL fixture, providing the SQLAlchemy Base and enabling session\n# This fixture will provide a SQLAlchemy session object to tests that request 'pg'\npg = create_postgres_fixture(Base, session=True)\n\ndef test_user_creation(pg):\n    \"\"\"Test creating a user in the mock PostgreSQL database.\"\"\"\n    # 'pg' is a SQLAlchemy session provided by the fixture\n    new_user = User(name='Alice')\n    pg.add(new_user)\n    pg.commit()\n    pg.refresh(new_user)\n\n    result = pg.execute(text(\"SELECT name FROM users WHERE id = :id\"), {'id': new_user.id}).scalar_one()\n    assert result == 'Alice'\n\ndef test_another_user_creation(pg):\n    \"\"\"Another test, ensuring isolation between tests (new empty database).\"\"\"\n    # This test gets a fresh, empty database instance\n    assert pg.query(User).count() == 0\n    new_user = User(name='Bob')\n    pg.add(new_user)\n    pg.commit()\n    assert pg.query(User).count() == 1","lang":"python","description":"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."},"warnings":[{"fix":"Ensure Docker Desktop or a Docker daemon is active before running tests that rely on these fixtures. Refer to the official Docker documentation for installation and setup.","message":"Most `pytest-mock-resources` fixtures (PostgreSQL, MongoDB, Redis, MySQL, Redshift) require Docker to be installed and running on the test environment. SQLite is a notable exception.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Always add specific database client libraries (e.g., `pip install psycopg2-binary`) directly to your project's `requirements.txt` or `pyproject.toml` instead of relying on `pytest-mock-resources` extras.","message":"While `pytest-mock-resources` provides 'extras' for installing database drivers (e.g., `[postgres]` for `psycopg2-binary`), the maintainers recommend explicitly installing these client libraries (e.g., `psycopg2-binary`, `pymongo`, `redis`) as first-party dependencies in your project. This avoids potential version conflicts or unexpected behavior.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Install `pytest-asyncio` (`pip install pytest-asyncio`) and mark your async test functions with `@pytest.mark.asyncio`.","message":"When using asynchronous database fixtures, you will generally need to install `pytest-asyncio` for proper fixture handling and test execution.","severity":"gotcha","affected_versions":"All versions supporting async fixtures (>=2.0)"},{"fix":"Avoid `flushall` or other global state-modifying commands in parallel Redis tests. Consider `scope='session'` for Redis if global setup is acceptable, or use distinct keyspacing for each test to prevent clashes. Be aware of the 16-test parallel limit for Redis.","message":"Running `Redis` tests in parallel (e.g., with `pytest-xdist`) can lead to cross-test state issues if operations like `flushall` are used, as internal Redis database selection mechanisms might not fully isolate tests. The default Redis container limit also restricts simultaneous tests to 16.","severity":"gotcha","affected_versions":"All versions"},{"fix":"If experiencing issues, ensure your specific PostgreSQL driver is explicitly configured using `PostgresConfig(drivername='...')` within a `pmr_postgres_config` fixture to match your setup. For `psycopg` (v3), be aware of the new installation `psycopg[binary]` vs. `psycopg2-binary`.","message":"For PostgreSQL drivers, `pytest-mock-resources` versions 2.10.3 and 2.12.3 included fixes for improved default driver selection heuristics and compatibility with `psycopg` (specifically `psycopg2-binary` and async use with the dynamic `psycopg` drivername). If you were relying on older driver auto-detection or using `psycopg` for async, these versions might alter behavior.","severity":"breaking","affected_versions":">=2.10.3, >=2.12.3"},{"fix":"Refer to the `pytest-mock-resources` documentation on 'CI Support' for detailed configuration examples, including `setup_remote_docker` for CircleCI or `services: - docker:dind` and `DOCKER_HOST`, `PYTEST_MOCK_RESOURCES_HOST` environment variables for GitLab.","message":"Running tests with `pytest-mock-resources` in CI/CD environments (e.g., CircleCI, GitLab) often requires specific Docker service configurations and environment variables to ensure the test containers are accessible.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-15T00:00:00.000Z","next_check":"2026-07-14T00:00:00.000Z","problems":[]}