๐Ÿ“ฆ encode / apistar

๐Ÿ“„ test_event_hooks.py ยท 53 lines
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
53import pytest

from apistar import App, Route, http, test

ON_ERROR = None


class CustomResponseHeader():
    def on_request(self):
        self.message = 'Ran hooks'

    def on_response(self, response: http.Response):
        response.headers['Custom'] = self.message

    def on_error(self):
        global ON_ERROR
        ON_ERROR = 'Ran on_error'


def hello_world():
    return {'hello': 'world'}


def error():
    assert 1 == 2


routes = [
    Route('/hello', method='GET', handler=hello_world),
    Route('/error', method='GET', handler=error),
]

event_hooks = [CustomResponseHeader]

app = App(routes=routes, event_hooks=event_hooks)

client = test.TestClient(app)


def test_on_response():
    response = client.get('/hello')
    assert response.status_code == 200
    assert response.headers['Custom'] == 'Ran hooks'


def test_on_error():
    global ON_ERROR

    ON_ERROR = None
    with pytest.raises(AssertionError):
        client.get('/error')
    assert ON_ERROR == 'Ran on_error'