MongoDB#

Integration with MongoDB, a NoSQL document-oriented database.

Installation#

pip install pytest-databases

The fixture provides a running MongoDB service and validates availability with MongoDB’s bundled mongosh client. Install the MongoDB client library that your application already uses (for example, PyMongo).

Usage Example#

import pymongo
from pytest_databases.docker.mongodb import MongoDBService

pytest_plugins = ["pytest_databases.docker.mongodb"]

def test_mongodb_service(mongodb_service: MongoDBService) -> None:
    client = pymongo.MongoClient(mongodb_service.uri)
    try:
        client.admin.command("ping")
        db = client[mongodb_service.database]
        collection = db["mycollection"]
        collection.insert_one({"name": "test_document", "value": 1})
        result = collection.find_one({"name": "test_document"})
        assert result is not None
        assert result["value"] == 1
    finally:
        client.close()

Replica Sets and Query Profiling#

Set MONGODB_REPLICA_SET (or override mongodb_replica_set to return a replica set name such as "rs0") to start MongoDB as an initialized single-node replica set with an elected PRIMARY — generating an internal 0400 --keyFile automatically when authentication is enabled and adding replicaSet and directConnection=true to mongodb_service.uri for multi-document transactions, change streams, replSetGetStatus, and local.oplog.rs tests. Set MONGODB_USER="" (or override mongodb_username to return None) for unauthenticated containers.

exec_js() (exec_mongosh()) executes JavaScript inside the container via mongosh, and set_profiling_level() configures system.profile. Custom fixtures calling provide_mongodb_service() can also pass command, env, init_js, profiling_level, and slow_ms.

Available Fixtures#

  • mongodb_service: Provides a MongoDBService exposing uri, host, port, username, password, database, replica_set, exec_js(), and set_profiling_level().

  • mongodb_image: Docker image name used for the MongoDB service (default: "mongo:latest", env MONGODB_IMAGE).

  • mongodb_username: Root username, or None when MONGODB_USER="" disables authentication (default: "mongo_user", env MONGODB_USER).

  • mongodb_password: Root password (default: "mongo_password", env MONGODB_PASSWORD).

  • mongodb_database_name: Base database name (default: "pytest_db", env MONGODB_DATABASE; <mongodb_database_name>_<worker> under pytest-xdist "database" isolation).

  • mongodb_port: Optional pinned host TCP port (default: None, env MONGODB_PORT).

  • mongodb_replica_set: Optional single-node replica set name (default: None, env MONGODB_REPLICA_SET).

  • xdist_mongodb_isolation_level: Worker isolation mode: "database" (default) or "server".

  • mongodb_connection and mongodb_database: Deprecated pymongo client and database fixtures.

Service API#

MongoDB container service fixtures.

class pytest_databases.docker.mongodb.MongoDBService(container: docker.models.containers.Container, host: str, port: int, username: str | None = 'mongo_user', password: str | None = 'mongo_password', database: str = 'pytest_db', replica_set: str | None = None)[source]#

Bases: ServiceContainer

Service handle for a running MongoDB container.

username: str | None = 'mongo_user'#
password: str | None = 'mongo_password'#
database: str = 'pytest_db'#
replica_set: str | None = None#
property uri: str#

Standard mongodb:// connection URI reflecting credentials and replica-set mode.

Returns:

Percent-encoded MongoDB connection URI targeting self.database.

exec_js(eval_script: str, *, database: str | None = None, auth_source: str = 'admin') → tuple[int, bytes][source]#

Execute a JavaScript snippet via in-container mongosh.

Returns:

Tuple of (exit_code, output_bytes).

set_profiling_level(level: Literal[0, 1, 2], *, slow_ms: int | None = None, database: str | None = None) → None[source]#

Configure the MongoDB query profiler (system.profile) on database.

Parameters:
  • level – Profiling level (0 off, 1 slow operations, 2 all operations).

  • slow_ms – Optional slow-operation threshold in milliseconds.

  • database – Target database (defaults to self.database).

Raises:
  • ValueError – If level is not 0, 1, or 2, or slow_ms is negative.

  • RuntimeError – If db.setProfilingLevel fails inside the container.

__init__(container: docker.models.containers.Container, host: str, port: int, username: str | None = 'mongo_user', password: str | None = 'mongo_password', database: str = 'pytest_db', replica_set: str | None = None) → None#
pytest_databases.docker.mongodb.exec_mongosh(container: docker.models.containers.Container, eval_script: str, *, user: str | None = None, password: str | None = None, database: str | None = None, auth_source: str = 'admin') → tuple[int, bytes][source]#

Execute eval_script inside a MongoDB container via mongosh --quiet.

Supports both authenticated sessions (user and password provided) and unauthenticated sessions (both user and password set to None).

Returns:

Tuple of (exit_code, output_bytes).

Raises:

ValueError – If only one of user or password is provided.

pytest_databases.docker.mongodb.mongodb_connection(mongodb_service: MongoDBService) → Generator[Any, None, None][source]#

Provide a deprecated pymongo MongoClient connected to MongoDB.

Yields:

Active pymongo MongoClient instance.

pytest_databases.docker.mongodb.mongodb_database(mongodb_service: MongoDBService) → Generator[Any, None, None][source]#

Provide a deprecated pymongo Database instance for testing.

Yields:

Active pymongo Database instance.

pytest_databases.docker.mongodb.mongodb_database_name() → str[source]#

Return the default session database name for MongoDB (MONGODB_DATABASE).

pytest_databases.docker.mongodb.mongodb_image() → str[source]#

Return the MongoDB container image.

pytest_databases.docker.mongodb.mongodb_password() → str | None[source]#

Return the root password for MongoDB.

pytest_databases.docker.mongodb.mongodb_port() → int | None[source]#

Return an optional pinned host TCP port for MongoDB (MONGODB_PORT).

pytest_databases.docker.mongodb.mongodb_replica_set() → str | None[source]#

Return an optional replica-set name for MongoDB (MONGODB_REPLICA_SET).

pytest_databases.docker.mongodb.mongodb_service(docker_service: DockerService, xdist_mongodb_isolation_level: XdistIsolationLevel, mongodb_image: str, mongodb_username: str | None, mongodb_password: str | None, mongodb_database_name: str, mongodb_port: int | None, mongodb_replica_set: str | None) → Generator[MongoDBService, None, None][source]#

Provide a running MongoDB container service.

Yields:

Active MongoDBService instance.

pytest_databases.docker.mongodb.mongodb_username() → str | None[source]#

Return the root username for MongoDB, or None when MONGODB_USER="" disables auth.

pytest_databases.docker.mongodb.provide_mongodb_service(docker_service: DockerService, image: str, name: str, isolation_level: XdistIsolationLevel, *, username: str | None = 'mongo_user', password: str | None = 'mongo_password', database: str = 'pytest_db', host_port: int | None = None, replica_set: str | None = None, command: str | Sequence[str] | None = None, env: Mapping[str, str] | None = None, init_js: str | Path | Sequence[str | Path] | None = None, profiling_level: Literal[0, 1, 2] | None = None, slow_ms: int | None = None, timeout: int = 120, pause: float = 0.5) → Generator[MongoDBService, None, None][source]#

Start and manage a MongoDB container service.

Supports authenticated and unauthenticated deployments (username=None), single-node replica sets (replica_set="rs0", automatically generating an internal --keyFile when authentication is enabled and electing a writable PRIMARY), custom mongod flags, init_js bootstrap scripts, and system.profile activation.

Yields:

Active MongoDBService instance.

pytest_databases.docker.mongodb.xdist_mongodb_isolation_level() → Literal['database', 'server'][source]#

Return the pytest-xdist isolation level for MongoDB.