-
-
Notifications
You must be signed in to change notification settings - Fork 864
/
test_base.py
304 lines (230 loc) Β· 8.83 KB
/
test_base.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
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
import asyncio
import aiofiles
import pytest
from starlette.applications import Starlette
from starlette.background import BackgroundTask
from starlette.middleware import Middleware
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import PlainTextResponse, StreamingResponse
from starlette.routing import Route
from starlette.testclient import TestClient
class CustomMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
response = await call_next(request)
response.headers["Custom-Header"] = "Example"
return response
app = Starlette()
app.add_middleware(CustomMiddleware)
@app.route("/")
def homepage(request):
return PlainTextResponse("Homepage")
@app.route("/exc")
def exc(request):
raise Exception()
@app.route("/no-response")
class NoResponse:
def __init__(self, scope, receive, send):
pass
def __await__(self):
return self.dispatch().__await__()
async def dispatch(self):
pass
@app.websocket_route("/ws")
async def websocket_endpoint(session):
await session.accept()
await session.send_text("Hello, world!")
await session.close()
def test_custom_middleware():
client = TestClient(app)
response = client.get("/")
assert response.headers["Custom-Header"] == "Example"
with pytest.raises(Exception):
response = client.get("/exc")
with pytest.raises(RuntimeError):
response = client.get("/no-response")
with client.websocket_connect("/ws") as session:
text = session.receive_text()
assert text == "Hello, world!"
def test_middleware_decorator():
app = Starlette()
@app.route("/homepage")
def homepage(request):
return PlainTextResponse("Homepage")
@app.middleware("http")
async def plaintext(request, call_next):
if request.url.path == "/":
return PlainTextResponse("OK")
response = await call_next(request)
response.headers["Custom"] = "Example"
return response
client = TestClient(app)
response = client.get("/")
assert response.text == "OK"
response = client.get("/homepage")
assert response.text == "Homepage"
assert response.headers["Custom"] == "Example"
def test_state_data_across_multiple_middlewares():
expected_value1 = "foo"
expected_value2 = "bar"
class aMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
request.state.foo = expected_value1
response = await call_next(request)
return response
class bMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
request.state.bar = expected_value2
response = await call_next(request)
response.headers["X-State-Foo"] = request.state.foo
return response
class cMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
response = await call_next(request)
response.headers["X-State-Bar"] = request.state.bar
return response
app = Starlette()
app.add_middleware(aMiddleware)
app.add_middleware(bMiddleware)
app.add_middleware(cMiddleware)
@app.route("/")
def homepage(request):
return PlainTextResponse("OK")
client = TestClient(app)
response = client.get("/")
assert response.text == "OK"
assert response.headers["X-State-Foo"] == expected_value1
assert response.headers["X-State-Bar"] == expected_value2
def test_app_middleware_argument():
def homepage(request):
return PlainTextResponse("Homepage")
app = Starlette(
routes=[Route("/", homepage)], middleware=[Middleware(CustomMiddleware)]
)
client = TestClient(app)
response = client.get("/")
assert response.headers["Custom-Header"] == "Example"
def test_middleware_repr():
middleware = Middleware(CustomMiddleware)
assert repr(middleware) == "Middleware(CustomMiddleware)"
def test_custom_middleware_streaming(tmp_path):
"""
Ensure that a StreamingResponse completes successfully with BaseHTTPMiddleware
"""
@app.route("/streaming")
async def some_streaming(_):
async def numbers_stream():
"""
Should produce something like:
<html><body><ul><li>1...</li></ul></body></html>
"""
yield ("<html><body><ul>")
for number in range(1, 4):
yield "<li>%d</li>" % number
yield ("</ul></body></html>")
return StreamingResponse(numbers_stream())
client = TestClient(app)
response = client.get("/streaming")
assert response.headers["Custom-Header"] == "Example"
assert (
response.text
== "<html><body><ul><li>1</li><li>2</li><li>3</li></ul></body></html>"
)
def test_custom_middleware_streaming_exception_on_start():
"""
Ensure that BaseHTTPMiddleware handles exceptions on response start
"""
@app.route("/broken-streaming-on-start")
async def broken_stream_start(request):
async def broken():
raise ValueError("Oh no!")
yield 0 # pragma: no cover
return StreamingResponse(broken())
client = TestClient(app)
with pytest.raises(ValueError):
# right before body stream starts (only start message emitted)
# this should trigger _first_ message being None
response = client.get("/broken-streaming-on-start")
def test_custom_middleware_streaming_exception_midstream():
"""
Ensure that BaseHTTPMiddleware handles exceptions after streaming has started
"""
@app.route("/broken-streaming-midstream")
async def broken_stream_midstream(request):
async def broken():
yield ("<html><body><ul>")
for number in range(1, 3):
yield "<li>%d</li>" % number
if number >= 2:
raise RuntimeError("This is a broken stream")
return StreamingResponse(broken())
client = TestClient(app)
with pytest.raises(RuntimeError):
# after body streaming has started
response = client.get("/broken-streaming-midstream")
def test_custom_middleware_streaming_background(tmp_path):
"""
Ensure that BaseHTTPMiddleware with a StreamingResponse runs BackgroundTasks after response.
This test writes to a temporary file
"""
@app.route("/background-after-streaming")
async def background_after_streaming(request):
filepath = request.query_params["filepath"]
async def background():
await asyncio.sleep(1)
async with aiofiles.open(filepath, mode="w") as fl: # pragma: no cover
await fl.write("background last")
async def numbers_stream():
async with aiofiles.open(filepath, mode="w") as fl:
await fl.write("handler first")
for number in range(1, 4):
yield "%d\n" % number
return StreamingResponse(
numbers_stream(), background=BackgroundTask(background)
)
client = TestClient(app)
# Set up a file to track whether background has run
filepath = tmp_path / "background_test.txt"
filepath.write_text("Test Start")
response = client.get("/background-after-streaming?filepath={}".format(filepath))
assert response.headers["Custom-Header"] == "Example"
assert response.text == "1\n2\n3\n"
with filepath.open() as fl:
# background should not have run yet
assert fl.read() == "handler first"
class Custom404Middleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
resp = await call_next(request)
if resp.status_code == 404:
return PlainTextResponse("Oh no!")
return resp
def test_custom_middleware_pending_tasks(tmp_path):
"""
Ensure that tasks are not pending left due to call_next method
"""
app.add_middleware(Custom404Middleware)
@app.route("/trivial")
async def trivial(_):
return PlainTextResponse("Working")
@app.route("/streaming_task_count")
async def some_streaming(_):
async def numbers_stream():
for number in range(1, 4):
yield "%d\n" % number
return StreamingResponse(numbers_stream())
client = TestClient(app)
task_count = lambda: len(asyncio.Task.all_tasks())
# Task_count after issuing requests must not grow
assert task_count() == 1
response = client.get("/missing")
assert task_count() <= 2
response = client.get("/missing")
assert task_count() <= 2
response = client.get("/trivial")
assert task_count() <= 2
response = client.get("/streaming_task_count")
assert response.text == "1\n2\n3\n"
assert task_count() <= 2
response = client.get("/missing")
assert task_count() <= 2
response = client.get("/trivial")
assert response.text == "Working"