-
-
Notifications
You must be signed in to change notification settings - Fork 864
/
test_base.py
191 lines (140 loc) Β· 5.36 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
import pytest
from starlette.applications import Starlette
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)"
async def numbers_stream(minimum, maximum):
yield ("<html><body><ul>")
for number in range(minimum, maximum + 1):
yield "<li>%d</li>" % number
yield ("</ul></body></html>")
async def somthing_broken(minimum, maximum, error_at=2):
if error_at <= 0:
raise RuntimeError("This is a stream that breaks when it starts")
yield ("<html><body><ul>")
for number in range(minimum, maximum + 1):
yield "<li>%d</li>" % number
if number >= error_at:
raise RuntimeError("This is a broken stream")
@app.route("/streaming")
async def some_streaming(_):
return StreamingResponse(numbers_stream(1, 3))
@app.route("/broken-streaming/{error_at:int}")
async def some_broken_streaming(request):
error_at = request.path_params["error_at"]
return StreamingResponse(somthing_broken(1, 5, error_at=error_at))
def test_custom_middleware_streaming():
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>"
)
with pytest.raises(RuntimeError):
# after body streaming has started
response = client.get("/broken-streaming/2")
with pytest.raises(RuntimeError):
# right before body stream starts (only start message emitted)
# this should trigger _first_ message being None
response = client.get("/broken-streaming/0")