-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathtest_http_asgi.py
More file actions
320 lines (265 loc) · 11 KB
/
Copy pathtest_http_asgi.py
File metadata and controls
320 lines (265 loc) · 11 KB
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import asyncio
import threading
import unittest
import azure.functions as func
from azure.functions._abc import TraceContext, RetryContext
from azure.functions._http_asgi import (
AsgiMiddleware
)
import pytest
class MockAsgiApplication:
response_code = 200
response_body = b''
response_headers = [
[b"content-type", b"text/plain"],
]
startup_called = False
shutdown_called = False
def __init__(self, fail_startup=False, fail_shutdown=False):
self.fail_startup = fail_startup
self.fail_shutdown = fail_shutdown
async def __call__(self, scope, receive, send):
self.received_scope = scope
# Verify against ASGI specification
assert scope['asgi.spec_version'] in ['2.0', '2.1']
assert isinstance(scope['asgi.spec_version'], str)
assert scope['asgi.version'] in ['2.0', '2.1', '2.2']
assert isinstance(scope['asgi.version'], str)
assert isinstance(scope['type'], str)
if scope['type'] == 'lifespan':
self.startup_called = True
startup_message = await receive()
assert startup_message['type'] == 'lifespan.startup'
if self.fail_startup:
if isinstance(self.fail_startup, str):
await send({
"type": "lifespan.startup.failed",
"message": self.fail_startup})
else:
await send({"type": "lifespan.startup.failed"})
else:
await send({"type": "lifespan.startup.complete"})
shutdown_message = await receive()
assert shutdown_message['type'] == 'lifespan.shutdown'
if self.fail_shutdown:
if isinstance(self.fail_shutdown, str):
await send({
"type": "lifespan.shutdown.failed",
"message": self.fail_shutdown})
else:
await send({"type": "lifespan.shutdown.failed"})
else:
await send({"type": "lifespan.shutdown.complete"})
self.shutdown_called = True
elif scope['type'] == 'http':
assert scope['http_version'] in ['1.0', '1.1', '2']
assert isinstance(scope['http_version'], str)
assert scope['method'] in ['POST', 'GET', 'PUT', 'DELETE', 'PATCH']
assert isinstance(scope['method'], str)
assert scope['scheme'] in ['http', 'https']
assert isinstance(scope['scheme'], str)
assert isinstance(scope['path'], str)
assert isinstance(scope['raw_path'], bytes)
assert isinstance(scope['query_string'], bytes)
assert isinstance(scope['root_path'], str)
assert hasattr(scope['headers'], '__iter__')
for k, v in scope['headers']:
assert isinstance(k, bytes)
assert isinstance(v, bytes)
assert scope['client'] is None or hasattr(scope['client'],
'__iter__')
if scope['client']:
assert len(scope['client']) == 2
assert isinstance(scope['client'][0], str)
assert isinstance(scope['client'][1], int)
assert scope['server'] is None or hasattr(scope['server'],
'__iter__')
if scope['server']:
assert len(scope['server']) == 2
assert isinstance(scope['server'][0], str)
assert isinstance(scope['server'][1], int)
self.received_request = await receive()
assert self.received_request['type'] == 'http.request'
assert isinstance(self.received_request['body'], bytes)
assert isinstance(self.received_request['more_body'], bool)
await send(
{
"type": "http.response.start",
"status": self.response_code,
"headers": self.response_headers,
}
)
await send(
{
"type": "http.response.body",
"body": self.response_body,
}
)
self.next_request = await receive()
assert self.next_request['type'] == 'http.disconnect'
else:
raise AssertionError(f"unexpected type {scope['type']}")
class TestHttpAsgiMiddleware(unittest.TestCase):
def _generate_func_request(
self,
method="POST",
url="https://function.azurewebsites.net/api/http?firstname=rt",
headers={
"Content-Type": "application/json",
"x-ms-site-restricted-token": "xmsrt"
},
params={
"firstname": "roger"
},
route_params={},
body=b'{ "lastname": "tsang" }'
) -> func.HttpRequest:
return func.HttpRequest(
method=method,
url=url,
headers=headers,
params=params,
route_params=route_params,
body=body
)
def _generate_func_context(
self,
invocation_id='123e4567-e89b-12d3-a456-426655440000',
thread_local_storage=threading.local(),
function_name='httptrigger',
function_directory='/home/roger/wwwroot/httptrigger',
trace_context=TraceContext,
retry_context=RetryContext
) -> func.Context:
class MockContext(func.Context):
def __init__(self, ii, tls, fn, fd, tc, rc):
self._invocation_id = ii
self._thread_local_storage = tls
self._function_name = fn
self._function_directory = fd
self._trace_context = tc
self._retry_context = rc
@property
def invocation_id(self):
return self._invocation_id
@property
def thread_local_storage(self):
return self._thread_local_storage
@property
def function_name(self):
return self._function_name
@property
def function_directory(self):
return self._function_directory
@property
def trace_context(self):
return self._trace_context
@property
def retry_context(self):
return self._retry_context
return MockContext(invocation_id, thread_local_storage, function_name,
function_directory, trace_context, retry_context)
def test_middleware_calls_app(self):
app = MockAsgiApplication()
test_body = b'Hello world!'
app.response_body = test_body
app.response_code = 200
req = self._generate_func_request()
response = AsgiMiddleware(app).handle(req)
# Verify asserted
self.assertEqual(response.status_code, 200)
self.assertEqual(response.get_body(), test_body)
def test_middleware_calls_app_http(self):
app = MockAsgiApplication()
test_body = b'Hello world!'
app.response_body = test_body
app.response_code = 200
req = self._generate_func_request(url="http://a.b.com")
response = AsgiMiddleware(app).handle(req)
# Verify asserted
self.assertEqual(response.status_code, 200)
self.assertEqual(response.get_body(), test_body)
def test_middleware_calls_app_with_context(self):
"""Test if the middleware can be used by exposing the .handle method,
specifically when the middleware is used as
def main(req, context):
return AsgiMiddleware(app).handle(req, context)
"""
app = MockAsgiApplication()
test_body = b'Hello world!'
app.response_body = test_body
app.response_code = 200
req = self._generate_func_request()
ctx = self._generate_func_context()
response = AsgiMiddleware(app).handle(req, ctx)
# Verify asserted
self.assertEqual(response.status_code, 200)
self.assertEqual(response.get_body(), test_body)
def test_middleware_wrapper(self):
"""Test if the middleware can be used by exposing the .main property,
specifically when the middleware is used as
main = AsgiMiddleware(app).main
"""
app = MockAsgiApplication()
test_body = b'Hello world!'
app.response_body = test_body
app.response_code = 200
req = self._generate_func_request()
ctx = self._generate_func_context()
main = AsgiMiddleware(app).main
response = main(req, ctx)
# Verify asserted
self.assertEqual(response.status_code, 200)
self.assertEqual(response.get_body(), test_body)
def test_middleware_async_calls_app_with_context(self):
"""Test the middleware with the awaitable handle_async() method
async def main(req, context):
return await AsgiMiddleware(app).handle_async(req, context)
"""
app = MockAsgiApplication()
test_body = b'Hello world!'
app.response_body = test_body
app.response_code = 200
req = self._generate_func_request()
ctx = self._generate_func_context()
async def run_test():
return await AsgiMiddleware(app).handle_async(req, ctx)
response = asyncio.run(run_test())
# Verify asserted
self.assertEqual(response.status_code, 200)
self.assertEqual(response.get_body(), test_body)
def test_function_app_lifecycle_events(self):
mock_app = MockAsgiApplication()
middleware = AsgiMiddleware(mock_app)
async def run_test():
await middleware.notify_startup()
assert mock_app.startup_called
await middleware.notify_shutdown()
assert mock_app.shutdown_called
asyncio.run(run_test())
def test_function_app_lifecycle_events_with_failures(self):
apps = [
MockAsgiApplication(False, True),
MockAsgiApplication(True, False),
MockAsgiApplication(True, True),
MockAsgiApplication("bork", False),
MockAsgiApplication(False, "bork"),
MockAsgiApplication("bork", "bork"),
]
async def run_test(mock_app):
middleware = AsgiMiddleware(mock_app)
await middleware.notify_startup()
assert mock_app.startup_called
await middleware.notify_shutdown()
assert mock_app.shutdown_called
for mock_app in apps:
asyncio.run(run_test(mock_app))
def test_calling_shutdown_without_startup_errors(self):
mock_app = MockAsgiApplication()
middleware = AsgiMiddleware(mock_app)
async def run_test():
await middleware.notify_shutdown()
with pytest.raises(RuntimeError):
asyncio.run(run_test())