【问题标题】:How can I use mock for testing inside greenlet?如何使用 mock 在 greenlet 中进行测试?
【发布时间】:2016-07-15 04:35:14
【问题描述】:

我在 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" 语句,但没有成功...

【问题讨论】:

  • 我认为greenlet内部有模拟对象重复。
  • 您的样品帮我解决问题,谢谢!

标签: python mocking gevent greenlets mongomock


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2022-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-19
    • 1970-01-01
    • 1970-01-01
    • 2021-05-21
    • 1970-01-01
    相关资源
    最近更新 更多