Skip to main content
https://img.shields.io/pypi/v/mongomock.svg?style=flat-square https://img.shields.io/github/actions/workflow/status/mongomock/mongomock/lint-and-test.yml?branch=develop&style=flat-square https://img.shields.io/pypi/l/mongomock.svg?style=flat-square https://img.shields.io/codecov/c/github/mongomock/mongomock.svg?style=flat-square

What is this?

Mongomock is a small library to help testing Python code that interacts with MongoDB via Pymongo.

To understand what it’s useful for, we can take the following code:

def increase_votes(collection):
    for document in collection.find():
        collection.update_one(document, {'$set': {'votes': document['votes'] + 1}})

The above code can be tested in several ways:

  1. It can be tested against a real mongodb instance with pymongo.

  2. It can receive a record-replay style mock as an argument. In this manner we record the expected calls (find, and then a series of updates), and replay them later.

  3. It can receive a carefully hand-crafted mock responding to find() and update() appropriately.

Option number 1 is obviously the best approach here, since we are testing against a real mongodb instance. However, a mongodb instance needs to be set up for this, and cleaned before/after the test. You might want to run your tests in continuous integration servers, on your laptop, or other bizarre platforms - which makes the mongodb requirement a liability.

We are left with #2 and #3. Unfortunately they are very high maintenance in real scenarios, since they replicate the series of calls made in the code, violating the DRY rule. Let’s see #2 in action - we might write our test like so:

def test_increase_votes():
    objects = [dict(...), dict(...), ...]
    collection_mock = my_favorite_mock_library.create_mock(Collection)
    record()
    collection_mock.find().AndReturn(objects)
    for obj in objects:
        collection_mock.update_one(obj, {'$set': {'votes': obj['votes']}})
    replay()
    increase_votes(collection_mock)
    verify()

Let’s assume the code changes one day, because the author just learned about the ‘$inc’ instruction:

def increase_votes(collection):
    collection.update_many({}, {'$inc': {'votes': 1}})

This breaks the test, although the end result being tested is just the same. The test also repeats large portions of the code we already wrote.

We are left, therefore, with option #3 – you want something to behave like a mongodb database collection, without being one. This is exactly what this library aims to provide. With mongomock, the test simply becomes:

def test_increase_votes():
    collection = mongomock.MongoClient().db.collection
    objects = [dict(votes=1), dict(votes=2), ...]
    for obj in objects:
        obj['_id'] = collection.insert_one(obj).inserted_id
    increase_votes(collection)
    for obj in objects:
        stored_obj = collection.find_one({'_id': obj['_id']})
        stored_obj['votes'] -= 1
        assert stored_obj == obj # by comparing all fields we make sure only votes changed

This code checks increase_votes with respect to its functionality, not syntax or algorithm, and therefore is much more robust as a test.

If the code to be tested is creating the connection itself with pymongo, you can use mongomock.patch (NOTE: you should use pymongo.MongoClient(...) rather than from pymongo import MongoClient, as shown below):

@mongomock.patch(servers=(('server.example.com', 27017),))
def test_increate_votes_endpoint():
  objects = [dict(votes=1), dict(votes=2), ...]
  client = pymongo.MongoClient('server.example.com')
  client.db.collection.insert_many(objects)
  call_endpoint('/votes')
  ... verify client.db.collection

Important Note About Project Status & Development

MongoDB is complex. This library aims at a reasonably complete mock of MongoDB for testing purposes, not a perfect replica. This means some features are not likely to make it in any time soon.

Also, since many corner cases are encountered along the way, our goal is to try and TDD our way into completeness. This means that every time we encounter a missing or broken (incompatible) feature, we write a test for it and fix it. There are probably lots of such issues hiding around lurking, so feel free to open issues and/or pull requests and help the project out!

NOTE: We don’t include pymongo functionality as “stubs” or “placeholders”. Since this library is used to validate production code, it is unacceptable to behave differently than the real pymongo implementation. In such cases it is better to throw NotImplementedError than implement a modified version of the original behavior.

Upgrading to Pymongo v4

The major version 4 of Pymongo changed the API quite a bit. The Mongomock library has evolved to help you ease the migration:

  1. Upgrade to Mongomock v4 or above: if your tests are running with Pymongo installed, Mongomock will adapt its own API to the version of Pymongo installed.

  2. Upgrade to Pymongo v4 or above: your tests using Mongomock will fail exactly where your code would fail in production, so that you can fix it before releasing.

Contributing

When submitting a PR, please make sure that:

  1. You include tests for the feature you are adding or bug you are fixing. Preferably, the test should compare against the real MongoDB engine (see examples in tests for reference).

  2. No existing test got deleted or unintentionally castrated

  3. The build passes on your PR.

To download, setup and perfom tests, run the following commands on Mac / Linux:

$ git clone git@github.com:mongomock/mongomock.git
$ pipx install hatch
$ cd mongomock
$ hatch test

Alternatively, docker-compose can be used to simplify dependency management for local development:

$ git clone git@github.com:mongomock/mongomock.git
$ cd mongomock
$ docker compose build
$ docker compose run --rm mongomock

If you want to run hatch against a specific environment in the container:

$ docker compose run --rm mongomock hatch test -py=3.11 -i pymongo=4

If you’d like to run only one test, you can also add the test name at the end of your command:

$ docker compose run --rm mongomock hatch test -py=3.12 -i pymongo=4 tests/test__mongomock.py::MongoClientCollectionTest::test__insert

NOTE: If the MongoDB image was updated, or you want to try a different MongoDB version in docker-compose, you’ll have to issue a docker compose down before you do anything else to ensure you’re running against the intended version.

utcnow

When developing features that need to make use of “now,” please use the libraries utcnow helper method in the following way:

import mongomock
# Awesome code!
now_reference = mongomock.utcnow()

This provides users a consistent way to mock the notion of “now” in mongomock if they so choose. Please see utcnow docstring for more details.

Branching model

The branching model used for this project follows the gitflow workflow. This means that pull requests should be issued against the develop branch and not the master branch. If you want to contribute to the legacy 2.x branch then your pull request should go into the support/2.x branch.

Releasing

When ready for a release, tag the develop branch with a new tag (please keep semver names) and push your tags to GitHub. The CI should do the rest.

To add release notes, create a release in GitHub’s Releases Page then generate the release notes locally with:

python -c "from pbr import git; git.write_git_changelog()"

Then you can get the relevant section in the generated Changelog file.

Acknowledgements

Mongomock has originally been developed by Rotem Yaari, then by Martin Domke. It is currently being developed and maintained by Pascal Corpet .

Also, many thanks go to the following people for helping out, contributing pull requests and fixing bugs:

  • Alec Perkins

  • Alexandre Viau

  • Austin W Ellis

  • Andrey Ovchinnikov

  • Arthur Hirata

  • Baruch Oxman

  • Corey Downing

  • Craig Hobbs

  • Daniel Murray

  • David Fischer

  • Diego Garcia

  • Dmitriy Kostochko

  • Drew Winstel

  • Eddie Linder

  • Edward D’Souza

  • Emily Rosengren

  • Eugene Chernyshov

  • Grigoriy Osadchenko

  • Israel Teixeira

  • Jacob Perkins

  • Jason Burchfield

  • Jason Sommer

  • Jeff Browning

  • Jeff McGee

  • Joël Franusic

  • Jonathan Hedén

  • Julian Hille

  • Krzysztof Płocharz

  • Lyon Zhang

  • Lucas Rangel Cezimbra

  • Marc Prewitt

  • Marcin Barczynski

  • Marian Galik

  • Michał Albrycht

  • Mike Ho

  • Nigel Choi

  • Omer Gertel

  • Omer Katz

  • Papp Győző

  • Paul Glass

  • Scott Sexton

  • Srinivas Reddy Thatiparthy

  • Taras Boiko

  • Todd Tomkinson

  • Xinyan Lu

  • Zachary Carter

  • catty (ca77y _at_ live.com)

  • emosenkis

  • hthieu1110

  • יppetlinskiy

  • pacud

  • tipok

  • waskew (waskew _at_ narrativescience.com)

  • jmsantorum (jmsantorum [at] gmail [dot] com)

  • lidongyong

  • Juan Gutierrez

Release files for mongomock 4.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for mongomock 4.3.0
File Size Uploaded
mongomock-4.3.0.tar.gz 135.9 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for mongomock 4.3.0
File Interpreter ABI Platform
mongomock-4.3.0-py2.py3-none-any.whl Python 3, Python 2 none any Details

Total release size: 200.8 kB

Release files / mongomock-4.3.0.tar.gz

Download URL mongomock-4.3.0.tar.gz
Size 135.9 kB
Tags Source
SHA-256 checksum
How to use checksums
32667b79066fabc12d4f17f16a8fd7361b5f4435208b3ba32c226e52212a8c30
BLAKE2b-256 checksum
How to use checksums
4da44a560a9f2a0bec43d5f63104f55bc48666d619ca74825c8ae156b08547cf
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via python-httpx/0.27.2

Release files / mongomock-4.3.0-py2.py3-none-any.whl

Download URL mongomock-4.3.0-py2.py3-none-any.whl
Size 64.9 kB
Tags Python 2 Python 3
SHA-256 checksum
How to use checksums
5ef86bd12fc8806c6e7af32f21266c61b6c4ba96096f85129852d1c4fec1327e
BLAKE2b-256 checksum
How to use checksums
944d8bea712978e3aff017a2ab50f262c620e9239cc36f348aae45e48d6a4786
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via python-httpx/0.27.2

Release history Release notifications | RSS feed

This release

4.3.0 This release

2 release files

4.1.2

2 release files

4.1.1

1 release file

4.0.0

2 release files

3.22.1

2 release files

3.22.0

2 release files

3.21.0

2 release files

3.18.0

2 release files

3.17.0

2 release files

3.16.0

1 release file

3.15.0

1 release file

3.14.0

1 release file

3.13.0

1 release file

3.12.0

1 release file

3.11.1

1 release file

3.11.0

1 release file

3.10.0

1 release file

3.9.0

1 release file

3.8.0

1 release file

3.7.0

1 release file

3.6.0

1 release file

3.5.0

1 release file

3.4.0

1 release file

3.3.0

1 release file

3.2.1

1 release file

3.2.0

1 release file

3.1.1

1 release file

3.1.0

1 release file

3.0.0

1 release file

2.3.1

1 release file

2.3.0

1 release file

2.2.0

1 release file

2.1.0

1 release file

2.0.0

1 release file

1.2.0

1 release file

1.1.0

1 release file

1.0.1

1 release file

1.0.0

1 release file

0.0.2

1 release file

0.0.1

1 release file

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page