I am using mock
module for Python 2.7 to mock my other functions and using
unittest
for writing unit tests.
I am wondering if mocking the MongoDB is different than using mock functionality (mock.patch
a function that is being called?) Or I need to use another different package for that purpose?
I do not think I want to have a test mongodb instance running. All I want is some tempo data and being able to call pymongo
functionality. I am just a bit lost in thinking of is there a way to write a mock for a module (like pymongo
), or anything is achievable by mock
module.
So appreciate if you could provide an example or tutorial on this.
from pymongo import MongoClient monog_url = 'mongodb://localhost:27017' client = MongoClient(monog_url) db = client.db class Dao(object): def __init__(self): pass def save(self, user): db_doc = { 'name': user.name, 'email': user.email } db.users.save(db_doc) def getbyname(self, user): db_doc = { 'name': user.name, } return db.users.find(db_doc)
To test this, I do not really want a test mongodb up and running! But also, I think I do not want to mock db.userssave and db.users.find because I want to actually be able to retrieve the data that I saved and make sure it is in the db. I think I need to create some fixtures per models that are in my memory and work with them. Just do I need an external tool to do so?
I am thinking of keeping some fake data like this, just do not know how to properly deal with it.
users = { {'name' : 'Kelly', 'email' : '[email protected]'}, {'name': 'Sam', 'email': '[email protected]'} }
If you have a Python object, you can convert it into a JSON string by using the json.dumps() method.
To handle extensive Unstructured data, you can use the MongoDB Database. MongoDB Database can connect to web applications through any programming language like PHP, Python, Ruby, Scala, C, C++, etc.
mongomock is a package to do just what the name implies, mocking a mongo database. To use with mongoengine, simply specify mongomock when connecting with mongoengine: connect('mongoenginetest', host='mongomock://localhost') conn = get_connection()
I recommend using mongomock for mocking mongodb. It's basically an in-memory mongodb with pymongo interface and made specifically for this purpose.
https://github.com/mongomock/mongomock
You can also do this if you're just doing something simple, and you don't really need to retrieve by field.
@mock.patch("pymongo.collection.Collection.find") def test_name(self, mock_find): mock_find.return_value = {'name' : 'Kelly', 'email' : '[email protected]'} # rest of test
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With