forked from aws/aws-xray-sdk-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_aiohttp.py
201 lines (153 loc) · 5.67 KB
/
test_aiohttp.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
"""
Tests the middleware for aiohttp server
Expects pytest-aiohttp
"""
import asyncio
from unittest.mock import patch
from aiohttp import web
import pytest
from aws_xray_sdk.core.emitters.udp_emitter import UDPEmitter
from aws_xray_sdk.core.async_context import AsyncContext
from tests.util import get_new_stubbed_recorder
from aws_xray_sdk.ext.aiohttp.middleware import middleware
class CustomStubbedEmitter(UDPEmitter):
"""
Custom stubbed emitter which stores all segments instead of the last one
"""
def __init__(self, daemon_address='127.0.0.1:2000'):
super(CustomStubbedEmitter, self).__init__(daemon_address)
self.local = []
def send_entity(self, entity):
self.local.append(entity)
def pop(self):
try:
return self.local.pop(0)
except IndexError:
return None
class TestServer(object):
"""
Simple class to hold a copy of the event loop
"""
__test__ = False
def __init__(self, loop):
self._loop = loop
async def handle_ok(self, request: web.Request) -> web.Response:
"""
Handle / request
"""
return web.Response(text="ok")
async def handle_error(self, request: web.Request) -> web.Response:
"""
Handle /error which returns a 404
"""
return web.Response(text="not found", status=404)
async def handle_exception(self, request: web.Request) -> web.Response:
"""
Handle /exception which raises a KeyError
"""
return {}['key']
async def handle_delay(self, request: web.Request) -> web.Response:
"""
Handle /delay request
"""
await asyncio.sleep(0.3, loop=self._loop)
return web.Response(text="ok")
def get_app(self) -> web.Application:
app = web.Application(middlewares=[middleware])
app.router.add_get('/', self.handle_ok)
app.router.add_get('/error', self.handle_error)
app.router.add_get('/exception', self.handle_exception)
app.router.add_get('/delay', self.handle_delay)
return app
@classmethod
def app(cls, loop=None) -> web.Application:
return cls(loop=loop).get_app()
@pytest.fixture(scope='function')
def recorder(loop):
"""
Clean up context storage before and after each test run
"""
xray_recorder = get_new_stubbed_recorder()
xray_recorder.configure(service='test', sampling=False, context=AsyncContext(loop=loop))
patcher = patch('aws_xray_sdk.ext.aiohttp.middleware.xray_recorder', xray_recorder)
patcher.start()
xray_recorder.clear_trace_entities()
yield xray_recorder
xray_recorder.clear_trace_entities()
patcher.stop()
async def test_ok(test_client, loop, recorder):
"""
Test a normal response
:param test_client: AioHttp test client fixture
:param loop: Eventloop fixture
:param recorder: X-Ray recorder fixture
"""
client = await test_client(TestServer.app(loop=loop))
resp = await client.get('/')
assert resp.status == 200
segment = recorder.emitter.pop()
assert not segment.in_progress
request = segment.http['request']
response = segment.http['response']
assert request['method'] == 'GET'
assert request['url'] == 'http://127.0.0.1:{port}/'.format(port=client.port)
assert response['status'] == 200
async def test_error(test_client, loop, recorder):
"""
Test a 4XX response
:param test_client: AioHttp test client fixture
:param loop: Eventloop fixture
:param recorder: X-Ray recorder fixture
"""
client = await test_client(TestServer.app(loop=loop))
resp = await client.get('/error')
assert resp.status == 404
segment = recorder.emitter.pop()
assert not segment.in_progress
assert segment.error
request = segment.http['request']
response = segment.http['response']
assert request['method'] == 'GET'
assert request['url'] == 'http://127.0.0.1:{port}/error'.format(port=client.port)
assert request['client_ip'] == '127.0.0.1'
assert response['status'] == 404
async def test_exception(test_client, loop, recorder):
"""
Test handling an exception
:param test_client: AioHttp test client fixture
:param loop: Eventloop fixture
:param recorder: X-Ray recorder fixture
"""
client = await test_client(TestServer.app(loop=loop))
resp = await client.get('/exception')
await resp.text() # Need this to trigger Exception
segment = recorder.emitter.pop()
assert not segment.in_progress
assert segment.fault
request = segment.http['request']
response = segment.http['response']
exception = segment.cause['exceptions'][0]
assert request['method'] == 'GET'
assert request['url'] == 'http://127.0.0.1:{port}/exception'.format(port=client.port)
assert request['client_ip'] == '127.0.0.1'
assert response['status'] == 500
assert exception.type == 'KeyError'
async def test_concurrent(test_client, loop, recorder):
"""
Test multiple concurrent requests
:param test_client: AioHttp test client fixture
:param loop: Eventloop fixture
:param recorder: X-Ray recorder fixture
"""
client = await test_client(TestServer.app(loop=loop))
recorder.emitter = CustomStubbedEmitter()
async def get_delay():
resp = await client.get('/delay')
assert resp.status == 200
await asyncio.wait([get_delay(), get_delay(), get_delay(),
get_delay(), get_delay(), get_delay(),
get_delay(), get_delay(), get_delay()],
loop=loop)
# Ensure all ID's are different
ids = [item.id for item in recorder.emitter.local]
assert len(ids) == len(set(ids))