【问题标题】:How to test python tornado application that use Mongodb with Motor Client如何测试使用 Mongodb 和 Motor Client 的 python tornado 应用程序
【发布时间】:2020-08-24 10:00:27
【问题描述】:

我想用 pytest 测试我的 tornado python 应用程序。

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

我为 pymongo 找到了很多解决方案,但对于 motor 却没有。

有什么想法吗?

【问题讨论】:

    标签: python mongodb pymongo tornado tornado-motor


    【解决方案1】:

    我没有清楚地理解您的问题 — 为什么不只使用硬编码的 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)
    

    如果你能澄清你的问题,我会制定我的答案。

    【讨论】:

      猜你喜欢
      • 2016-10-22
      • 1970-01-01
      • 1970-01-01
      • 2020-03-31
      • 1970-01-01
      • 2019-06-04
      • 1970-01-01
      • 2023-04-02
      • 2022-07-15
      相关资源
      最近更新 更多