I am using mongomock to mock MongoDB collections in unit tests, which are built around pytest. I usually have to create a mock database and collection and then perform the assertions for every single test like this:
import mongomock
import pymongo
@mongomock.patch(servers=(("server.com", 27017),))
def test_func1():
# create mock collection
docs = [{"Name": John}, {"Name": "Jack"}]
mock_client = pymongo.MongoClient("server.com")
mock_client.db.collection.insert_many(docs)
# perform assertions as required for func1
@mongomock.patch(servers=(("server.com", 27017),))
def test_func2():
# create mock collection
docs = [{"Name": John}, {"Name": "Jack"}]
mock_client = pymongo.MongoClient("server.com")
mock_client.db.collection.insert_many(docs)
# perform assertions as required for func2
The above works fine, but I would like to have to avoid creating a mock database for every unit test. I have tried to create an helper function that creates the mock database and returns the mock client, but when I call that function within an unit test, the mock databases do not persist. How can I make the mock database to persist across tests?