如何在Motor Client中测试使用Mongodb的python龙卷风应用程序

问题描述

我想用pytest测试龙卷风python应用程序。

为此,我想为mongo创建一个 mock 数据库,并使用Motor“ fake”客户端模拟对mongodb的调用

我找到了很多pymongo的解决方案,但没有找到 motor 解决方案。

有什么主意吗?

解决方法

我不太明白您的问题——为什么不直接使用硬编码的 JSON 数据? 如果您只想拥有一个可以模拟以下内容的类:

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)

所以我建议创建一个类:

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)

如果你能澄清你的问题,我会完善我的答案。