How to test python tornado application that use Mongodb with Motor Client

321 Views Asked by At

I want to test my tornado python application with pytest.

for that purpose, I want to have a mock db for the mongo and to use motor "fake" client to simulate the calls to the mongodb.

I found alot of solution for pymongo but not for motor.

any idea?

1

There are 1 best solutions below

0
Constantine Kurbatov On

I do not clearly understand your problem — why not just have hard-coded JSON data? If you just want to have a class that would mock the following:

from motor.motor_tornado import MotorClient

client = MotorClient(MONGODB_URL) 
my_db = client.my_db
result = await my_db['my_collection'].insert_one(my_json_load)

So I recommend creating a Class:

Class Collection():
   database = []

   async def insert_one(self,data):
       database.append(data)
       data['_id'] = "5063114bd386d8fadbd6b004" ## You may make it random or consequent
       ...
       ## Also, you may save the 'database' list to the pickle on disk to preserve data between runs 
       return data
   async def find_one(self, data):
       ## Search in the list
       return data

   async def delete_one(self, data_id):
       delete_one.deleted_count = 1
       return

## Then create a collection:
my_db = {}
my_db['my_collecton'] = Collection()

### The following is the part of 'views.py' 
from tornado.web import RequestHandler, authenticated
from tornado.escape import xhtml_escape

class UserHandler(RequestHandler):
   async def post(self, name):
        getusername = xhtml_escape(self.get_argument("user_variable"))
        my_json_load = {'username':getusername}
        result = await my_db['my_collection'].insert_one(my_json_load)
        ...
        return self.write(result)

If you would clarify your question, I will develop my answer.