Python 如何在greenlet内部使用mock进行测试?

Python 如何在greenlet内部使用mock进行测试?,python,mocking,gevent,greenlets,mongomock,Python,Mocking,Gevent,Greenlets,Mongomock,我在python(2.7.6)应用程序中使用了瓶子和gevent # -*- coding: utf-8 -*- from __future__ import unicode_literals from gevent import spawn, monkey from bottle import Bottle from .settings import MONGODB_HOST, MONGODB_PORT, MONGODB_NAME monkey.patch_all() mongo_clie

我在python(2.7.6)应用程序中使用了瓶子和gevent

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from gevent import spawn, monkey
from bottle import Bottle
from .settings import MONGODB_HOST, MONGODB_PORT, MONGODB_NAME

monkey.patch_all()

mongo_client = MongoClient(MONGODB_HOST, MONGODB_PORT)
db = mongo_client[MONGODB_NAME]

class MyApp(object):

    def insert_event(self):
        data = {'a': self.a, 'b': self.b}  # some data
        db.events.insert(data)

    def request(self):
        # request data processing...
        spawn(self.insert_event)
        return {}

app = Bottle()
app.route('/', method='POST')(MyApp().request)
我想用mongomock()来测试它

我的考试失败了

FAIL: test_request (my_app.tests.TestViews)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/mock/mock.py", line 1305, in patched
    return func(*args, **keywargs)
  File "/srv/mysite/my_app/tests/views.py", line 71, in test_request
    self.assertTrue(last_event)
AssertionError: None is not true

如果我使用self.insert\u事件而不使用spawn,这是可行的。我尝试使用patch.object、“with”语句,但没有成功…

我找到了解决方案。我需要模拟gevent.spawn方法。因为我在协同路由结束之前得到HTTP响应。这是我的解决方案:

@patch('my_app.app.db', db)
@patch('my_app.app.spawn',
       lambda method, *args, **kwargs: method(*args, **kwargs))
class TestViews(TestCase):

我认为greenlet里面有模拟对象复制。您的示例帮助我解决了一个问题,谢谢!
@patch('my_app.app.db', db)
@patch('my_app.app.spawn',
       lambda method, *args, **kwargs: method(*args, **kwargs))
class TestViews(TestCase):