在python中模拟bottle.request对象

问题描述 投票:1回答:3

我正在使用框架。我的代码就像

from bottle import request

def abc():
    x = request.get_header('x')
    ...
    ...
    data = request.json()
    ...
    ...

我正在为这个函数编写UT,我想模拟get_headerjsonbottle.request,并从中返回我的模拟数据。

我试过了。

from mock import patch

@patch('bottle.request.headers', return_value={'x': 'x'})
@patch('bottle.request.json', return_value=...)
def test_abc(self, _, __):
    ...
    ...

但它给request.headers的错误是只读的。我还要嘲笑request.json

在此先感谢您的帮助:)。

python unit-testing mocking bottle python-unittest
3个回答
1
投票

一个简单的替代方法,模拟一个瓶子请求,可以将它注入你的函数:

from bottle import request

def abc(_request=None):
    if _request is not None:
      request = _request

    x = request.get_header('x')
    ...
    ...
    data = request.json()
    ...
    ...

这应该是安全的,因为您的测试代码可以直接使用虚假请求对象调用您的视图,并且您的生产代码将跳过条件。

我不知道这对于带有命名参数的url路由是如何工作的,因为我从未使用过瓶子。


1
投票

检查瓶子,标题和json的源代码如下:

    @DictProperty('environ', 'bottle.request.headers', read_only=True)
    def headers(self):
        ''' A :class:`WSGIHeaderDict` that provides case-insensitive access to
            HTTP request headers. '''
        return WSGIHeaderDict(self.environ)

所以在我的pytest案例中,我修改了request.environ,如下所示:

def test_xxx(monkeypatch):
    monkeypatch.setitem(request.environ, 'bottle.request.json', {'name': 'xxx', 'version': '0.1'})
    add_xxx()
    assert 

0
投票

使用Boddle https://github.com/keredson/boddle

def test_abc(self, _, __):
    with boddle(headers={'x':'x'}):
        # tests
© www.soinside.com 2019 - 2024. All rights reserved.