Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock bottle.request object in python

I am using bottle framework. I have code like

from bottle import request

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

I am writing UTs for this function, I want to mock get_header and json of bottle.request, and return my mock data from that.

I tried.

from mock import patch

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

But it gives error for request.headers is read-only. I also have to mock request.json.

Thanks for help in advance :).

like image 295
Nilesh Avatar asked Sep 05 '26 02:09

Nilesh


1 Answers

Check the source code of bottle, headers and json are like:

    @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)

So in my pytest cases, I patched request.environ like below:

def test_xxx(monkeypatch):
    monkeypatch.setitem(request.environ, 'bottle.request.json', {'name': 'xxx', 'version': '0.1'})
    add_xxx()
    assert 
like image 167
feiyuw Avatar answered Sep 07 '26 14:09

feiyuw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!