This repository has been archived by the owner on Oct 3, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
test_apistar_request_id.py
83 lines (54 loc) · 2.28 KB
/
test_apistar_request_id.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import pytest
from apistar import App, Route, TestClient, exceptions
from apistar_request_id import RequestId, RequestIdHooks
def index() -> dict:
return {}
def fail() -> dict:
raise exceptions.BadRequest("fail")
def fail_2() -> dict:
raise RuntimeError("fail")
routes = [
Route("/", method="GET", handler=index),
Route("/fail", method="GET", handler=fail),
Route("/fail-2", method="GET", handler=fail_2),
]
event_hooks = [
RequestIdHooks()
]
@pytest.fixture(scope="session")
def app():
return App(routes=routes, event_hooks=event_hooks)
@pytest.fixture
def client(app):
return TestClient(app)
def test_request_id_can_be_autogenerated(client):
# Given that I don't have an existing request id
# When I make a request to the app
response = client.get("/")
# Then my response should contain an autogenerated request id
assert response.headers["x-request-id"]
# And the request id for the current thread should be cleared
assert RequestId.get_request_id() is None
def test_request_id_can_be_set_from_request_headers(client):
# Given that I have an existing request id
# When I make a request to the app
response = client.get("/", headers={"x-request-id": "a-request-id"})
# Then that same request id should appear in the response headers
assert response.headers["x-request-id"] == "a-request-id"
# And the request id for the current thread should be cleared
assert RequestId.get_request_id() is None
def test_request_id_can_be_set_on_error(client):
# Given that I have an existing request id
# When I make a request to the app
response = client.get("/fail", headers={"x-request-id": "a-request-id"})
# Then that same request id should appear in the response headers
assert response.headers["x-request-id"] == "a-request-id"
# And the request id for the current thread should be cleared
assert RequestId.get_request_id() is None
def test_request_id_can_be_set_on_internal_error(client):
# Given that I have an existing request id
# When I make a request to the app
with pytest.raises(RuntimeError):
client.get("/fail-2", headers={"x-request-id": "a-request-id"})
# Then the request id should be set and subsequently cleared
assert RequestId.get_request_id() is None