4

我在 python (2.7.6) 应用程序中使用了 bottle & 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 ( https://github.com/vmalloc/mongomock ) 测试它。

from __future__ import unicode_literals
from unittest import TestCase
from webtest import TestApp
from mock import patch
from mongomock import MongoClient
from ..app import app as my_app

db = MongoClient().db

@patch('my_app.app.db', db)
class TestViews(TestCase):

    def setUp(self):
        self.app = TestApp(ssp_app)
        self.db = db

    def test_request(self):
        response = self.app.post('/', {})
        last_event = self.db.events.find_one({})
        self.assertTrue(last_event)

我的测试失败了。

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

如果我在没有 spawn 的情况下使用 self.insert_event 就可以了。我尝试使用patch.object,“with”语句,但没有成功......

4

1 回答 1

3

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

@patch('my_app.app.db', db)
@patch('my_app.app.spawn',
       lambda method, *args, **kwargs: method(*args, **kwargs))
class TestViews(TestCase):
于 2016-04-08T17:22:10.700 回答