gpt4 book ai didi

python - 我如何使用模拟在 greenlet 中进行测试?

转载 作者:行者123 更新时间:2023-11-28 17:28:50 25 4
gpt4 key购买 nike

我将 bottle & gevent 用于我的 python (2.7.6) 应用程序。

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

最佳答案

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

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

关于python - 我如何使用模拟在 greenlet 中进行测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36253511/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com