app.request

简介

Application提供request和若干test_*方法,可以模拟前端请求,方便测试。

完整的方法列表如下:

def request(self, localpart='/', method='GET', data=None, host="0.0.0.0:8080", headers=None, https=False, env=None): ...
def test_get(self, localpart='/', query=None, headers=None, status_code=200, parsejson=True, https=False, env=None): ...
def test_delete(self, localpart='/', query=None, headers=None, status_code=200, parsejson=True, https=False, env=None): ...
def test_head(self, localpart='/', query=None, headers=None, status_code=200, parsejson=True, https=False, env=None): ...
def test_post(self, localpart='/', data=None, headers=None, status_code=200, parsejson=True, https=False, env=None): ...
def test_put(self, localpart='/', data=None, headers=None, status_code=200, parsejson=True, https=False, env=None): ... 

示例

下面的示例使用nose进行doctest测试。

example.py

from lessweb import Application

def add(x:int, y:int):
    """
    >>> with app.test_get('/add/1/2') as ret:
    ...   assert ret['sum'] == 3
    >>> ret = app.request('/add/2/3')
    >>> ret
    <Storage {'status': '200 OK', 'status_code': 200, 'headers': {'Content-Type': 'text/html; charset=utf-8'}, 'header_items': [('Content-Type', 'text/html; charset=utf-8')], 'data': b'{"sum": 5}'}>
    """
    return {'sum': x+y}

app = Application()
app.add_get_mapping('/add/{x}/{y}', add)

if __name__ == '__main__':
    app.run()

测试命令: nosetests --with-doctest example.py
测试结果:

.
----------------------------------------------------------------------
Ran 1 test in 0.005s

OK