python – mongomock如何与马达一起使用?

我有一个用Tornado和Motor实现的服务器,

而且我遇到过这个pymongo的模拟:

https://github.com/vmalloc/mongomock

为了快速运行它,我真的很喜欢对我的代码进行单元测试而没有真正调用DB的想法.

我已经尝试修补马达来将调用传递给mongomock,就像那样:

from mock import MagicMock
import mongomock
p = mock.patch('motor.MotorClient.__delegate_class__', new=mongomock.MongoClient)
p1 = mock.patch('motor.MotorDatabase.__delegate_class__', new=MagicMock())

p.start()
p1.start()

def fin():
    p.stop()
    p1.stop()

request.addfinalizer(fin)

它失败了:

Traceback (most recent call last):
  File "C:\Users\ifruchte\venv\lib\site-packages\pytest_tornado\plugin.py", line 136, in http_server
    http_app = request.getfuncargvalue(request.config.option.app_fixture)
  File "C:\Users\ifruchte\venv\lib\site-packages\_pytest\python.py", line 1337, in getfuncargvalue
    return self._get_active_fixturedef(argname).cached_result[0]
  File "C:\Users\ifruchte\venv\lib\site-packages\_pytest\python.py", line 1351, in _get_active_fixturedef
    result = self._getfuncargvalue(fixturedef)
  File "C:\Users\ifruchte\venv\lib\site-packages\_pytest\python.py", line 1403, in _getfuncargvalue
    val = fixturedef.execute(request=subrequest)
  File "C:\Users\ifruchte\venv\lib\site-packages\_pytest\python.py", line 1858, in execute
    self.yieldctx)
  File "C:\Users\ifruchte\venv\lib\site-packages\_pytest\python.py", line 1784, in call_fixture_func
    res = fixturefunc(**kwargs)
  File "C:\Users\ifruchte\PycharmProjects\pyrecman\tests\__init__.py", line 65, in app
    return get_app(db=motor_db(io_loop))
  File "C:\Users\ifruchte\PycharmProjects\pyrecman\tests\__init__.py", line 27, in motor_db
    return motor.MotorClient(options.mongo_url, io_loop=io_loop)[options.db_name]
  File "C:\Users\ifruchte\venv\lib\site-packages\motor\__init__.py", line 1003, in __getattr__
    return MotorDatabase(self, name)
  File "C:\Users\ifruchte\venv\lib\site-packages\motor\__init__.py", line 1254, in __init__
    delegate = Database(connection.delegate, name)
  File "C:\Users\ifruchte\venv\lib\site-packages\pymongo\database.py", line 61, in __init__
    **connection.write_concern)
TypeError: attribute of type 'Collection' is not callable

谁知道怎么做?或者我在这里浪费时间?

最佳答案 无需实例化magicmock.

p1 = mock.patch(‘motor.MotorDatabase .__ delegate_class__’,new = MagicMock)

点赞