-
Notifications
You must be signed in to change notification settings - Fork 4
/
test_hooks.py
69 lines (47 loc) · 1.88 KB
/
test_hooks.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
from http import HTTPStatus
import json
import pytest
from roll import HttpError
pytestmark = pytest.mark.asyncio
async def test_request_hook_can_alter_response(client, app):
@app.listen('request')
async def listener(request, response):
response.status = 400
response.body = b'another response'
return True # Shortcut the response process.
@app.route('/test')
async def get(req, resp):
resp.body = 'test response'
resp = await client.get('/test')
assert resp.status == HTTPStatus.BAD_REQUEST
assert resp.body == b'another response'
async def test_response_hook_can_alter_response(client, app):
@app.listen('response')
async def listener(request, response):
assert response.body == 'test response'
response.body = 'another response'
response.status = 400
@app.route('/test')
async def get(req, resp):
resp.body = 'test response'
resp = await client.get('/test')
assert resp.status == HTTPStatus.BAD_REQUEST
assert resp.body == b'another response'
async def test_error_with_json_format(client, app):
@app.listen('error')
async def listener(request, response, error):
assert error.message == 'JSON error'
response.json = {'status': error.status, 'message': error.message}
@app.route('/test')
async def get(req, resp):
raise HttpError(HTTPStatus.INTERNAL_SERVER_ERROR, message='JSON error')
resp = await client.get('/test')
assert resp.status == HTTPStatus.INTERNAL_SERVER_ERROR
error = json.loads(resp.body)
assert error == {"status": 500, "message": "JSON error"}
async def test_third_parties_can_call_hook_their_way(client, app):
@app.listen('custom')
async def listener(myarg):
return myarg
assert await app.hook('custom', myarg='kwarg') == 'kwarg'
assert await app.hook('custom', 'arg') == 'arg'