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 aMongoDBServiceexposinguri,host,port,username,password,database,replica_set,exec_js(), andset_profiling_level().mongodb_image: Docker image name used for the MongoDB service (default:"mongo:latest", envMONGODB_IMAGE).mongodb_username: Root username, orNonewhenMONGODB_USER=""disables authentication (default:"mongo_user", envMONGODB_USER).mongodb_password: Root password (default:"mongo_password", envMONGODB_PASSWORD).mongodb_database_name: Base database name (default:"pytest_db", envMONGODB_DATABASE;<mongodb_database_name>_<worker>underpytest-xdist"database"isolation).mongodb_port: Optional pinned host TCP port (default:None, envMONGODB_PORT).mongodb_replica_set: Optional single-node replica set name (default:None, envMONGODB_REPLICA_SET).xdist_mongodb_isolation_level: Worker isolation mode:"database"(default) or"server".mongodb_connectionandmongodb_database: Deprecatedpymongoclient 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:
ServiceContainerService handle for a running MongoDB container.
- 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) ondatabase.- Parameters:
level – Profiling level (
0off,1slow operations,2all operations).slow_ms – Optional slow-operation threshold in milliseconds.
database – Target database (defaults to
self.database).
- Raises:
ValueError – If
levelis not0,1, or2, orslow_msis negative.RuntimeError – If
db.setProfilingLevelfails inside the container.
- 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_scriptinside a MongoDB container viamongosh --quiet.Supports both authenticated sessions (
userandpasswordprovided) and unauthenticated sessions (bothuserandpasswordset toNone).- Returns:
Tuple of
(exit_code, output_bytes).- Raises:
ValueError – If only one of
userorpasswordis 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_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
NonewhenMONGODB_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--keyFilewhen authentication is enabled and electing a writablePRIMARY), custommongodflags,init_jsbootstrap scripts, andsystem.profileactivation.- Yields:
Active MongoDBService instance.