mongomock如何与电机一起使用?

How can mongomock can be use with motor?

我有一个用 Tornado 和 Motor 实现的服务器, 我遇到了这个 pymongo 的模拟: https://github.com/vmalloc/mongomock

我真的很喜欢在不真正调用数据库的情况下对我的代码进行单元测试的想法,因为 运行 它们非常快。

我试过修补电机以将调用传递给 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)