I'm using nosetests for Python code to test code with MongoDB connection, I have used the python mock standard library with mongoMock: https://github.com/vmalloc/mongomock ,I have patched the pymongo.MongoClient module to mock it, but the problem is the mongoMock object does not replace the actual object, that means the test function is still using the actual mongoDB connection.
This is the actual code:
def post_data():
connection = MongoClient('mongodb://localhost:27017/').customers.review
post = {"author": "Mike",
"text": "My first blog post!",
"tags": ["mongodb", "python", "pymongo"],
"votes":1}
print connection
connection.insert_one(post)
the testing function:
@mock.patch('pymongo.MongoClient')
def test_post_data(mock_MongoClient):
mock_MongoClient.return_value= mongomock.MongoClient().db.collection
post_data()
when I run the test the code is still inserting on the real database and the code prints the actual connection!! Please, what's the wrong with it and how to do it properly?
Thanks in advance!
I resolved the problem, it was tricky for me because the actual code and the test code were working without any problem and just the mock object was not called by the actual because when I did @mock.patch I was mention to this module @mock.patch'pymongo.MongoClient'
that's why I should create my connection by writing
connection = pymongo.MongoClient('mongodb://localhost:27017/').customers.review
instead of writing
connection = MongoClient('mongodb://localhost:27017/').customers.review
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.