| 1 |
from django.core.exceptions import ImproperlyConfigured |
| 2 |
from django.core.handlers.wsgi import WSGIHandler, WSGIRequest, get_script_name |
| 3 |
from django.core.signals import request_finished, request_started |
| 4 |
from django.db import close_old_connections, connection |
| 5 |
from django.test import ( |
| 6 |
AsyncRequestFactory, |
| 7 |
RequestFactory, |
| 8 |
SimpleTestCase, |
| 9 |
TransactionTestCase, |
| 10 |
override_settings, |
| 11 |
) |
| 12 |
|
| 13 |
|
| 14 |
class HandlerTests(SimpleTestCase): |
| 15 |
request_factory = RequestFactory() |
| 16 |
|
| 17 |
def setUp(self): |
| 18 |
request_started.disconnect(close_old_connections) |
| 19 |
self.addCleanup(request_started.connect, close_old_connections) |
| 20 |
|
| 21 |
def test_middleware_initialized(self): |
| 22 |
handler = WSGIHandler() |
| 23 |
self.assertIsNotNone(handler._middleware_chain) |
| 24 |
|
| 25 |
def test_bad_path_info(self): |
| 26 |
""" |
| 27 |
A non-UTF-8 path populates PATH_INFO with an URL-encoded path and |
| 28 |
produces a 404. |
| 29 |
""" |
| 30 |
environ = self.request_factory.get("/").environ |
| 31 |
environ["PATH_INFO"] = "\xed" |
| 32 |
handler = WSGIHandler() |
| 33 |
response = handler(environ, lambda *a, **k: None) |
| 34 |
# The path of the request will be encoded to '/%ED'. |
| 35 |
self.assertEqual(response.status_code, 404) |
| 36 |
|
| 37 |
def test_non_ascii_query_string(self): |
| 38 |
""" |
| 39 |
Non-ASCII query strings are properly decoded (#20530, #22996). |
| 40 |
""" |
| 41 |
environ = self.request_factory.get("/").environ |
| 42 |
raw_query_strings = [ |
| 43 |
b"want=caf%C3%A9", # This is the proper way to encode 'café' |
| 44 |
b"want=caf\xc3\xa9", # UA forgot to quote bytes |
| 45 |
b"want=caf%E9", # UA quoted, but not in UTF-8 |
| 46 |
# UA forgot to convert Latin-1 to UTF-8 and to quote (typical of |
| 47 |
# MSIE). |
| 48 |
b"want=caf\xe9", |
| 49 |
] |
| 50 |
got = [] |
| 51 |
for raw_query_string in raw_query_strings: |
| 52 |
# Simulate http.server.BaseHTTPRequestHandler.parse_request |
| 53 |
# handling of raw request. |
| 54 |
environ["QUERY_STRING"] = str(raw_query_string, "iso-8859-1") |
| 55 |
request = WSGIRequest(environ) |
| 56 |
got.append(request.GET["want"]) |
| 57 |
# %E9 is converted to the Unicode replacement character by parse_qsl |
| 58 |
self.assertEqual(got, ["café", "café", "caf\ufffd", "café"]) |
| 59 |
|
| 60 |
def test_non_ascii_cookie(self): |
| 61 |
"""Non-ASCII cookies set in JavaScript are properly decoded (#20557).""" |
| 62 |
environ = self.request_factory.get("/").environ |
| 63 |
raw_cookie = 'want="café"'.encode("utf-8").decode("iso-8859-1") |
| 64 |
environ["HTTP_COOKIE"] = raw_cookie |
| 65 |
request = WSGIRequest(environ) |
| 66 |
self.assertEqual(request.COOKIES["want"], "café") |
| 67 |
|
| 68 |
def test_invalid_unicode_cookie(self): |
| 69 |
""" |
| 70 |
Invalid cookie content should result in an absent cookie, but not in a |
| 71 |
crash while trying to decode it (#23638). |
| 72 |
""" |
| 73 |
environ = self.request_factory.get("/").environ |
| 74 |
environ["HTTP_COOKIE"] = "x=W\x03c(h]\x8e" |
| 75 |
request = WSGIRequest(environ) |
| 76 |
# We don't test COOKIES content, as the result might differ between |
| 77 |
# Python version because parsing invalid content became stricter in |
| 78 |
# latest versions. |
| 79 |
self.assertIsInstance(request.COOKIES, dict) |
| 80 |
|
| 81 |
@override_settings(ROOT_URLCONF="handlers.urls") |
| 82 |
def test_invalid_multipart_boundary(self): |
| 83 |
""" |
| 84 |
Invalid boundary string should produce a "Bad Request" response, not a |
| 85 |
server error (#23887). |
| 86 |
""" |
| 87 |
environ = self.request_factory.post("/malformed_post/").environ |
| 88 |
environ["CONTENT_TYPE"] = "multipart/form-data; boundary=WRONG\x07" |
| 89 |
handler = WSGIHandler() |
| 90 |
response = handler(environ, lambda *a, **k: None) |
| 91 |
# Expect "bad request" response |
| 92 |
self.assertEqual(response.status_code, 400) |
| 93 |
|
| 94 |
|
| 95 |
@override_settings(ROOT_URLCONF="handlers.urls", MIDDLEWARE=[]) |
| 96 |
class TransactionsPerRequestTests(TransactionTestCase): |
| 97 |
available_apps = [] |
| 98 |
|
| 99 |
def test_no_transaction(self): |
| 100 |
response = self.client.get("/in_transaction/") |
| 101 |
self.assertContains(response, "False") |
| 102 |
|
| 103 |
def test_auto_transaction(self): |
| 104 |
old_atomic_requests = connection.settings_dict["ATOMIC_REQUESTS"] |
| 105 |
try: |
| 106 |
connection.settings_dict["ATOMIC_REQUESTS"] = True |
| 107 |
response = self.client.get("/in_transaction/") |
| 108 |
finally: |
| 109 |
connection.settings_dict["ATOMIC_REQUESTS"] = old_atomic_requests |
| 110 |
self.assertContains(response, "True") |
| 111 |
|
| 112 |
async def test_auto_transaction_async_view(self): |
| 113 |
old_atomic_requests = connection.settings_dict["ATOMIC_REQUESTS"] |
| 114 |
try: |
| 115 |
connection.settings_dict["ATOMIC_REQUESTS"] = True |
| 116 |
msg = "You cannot use ATOMIC_REQUESTS with async views." |
| 117 |
with self.assertRaisesMessage(RuntimeError, msg): |
| 118 |
await self.async_client.get("/async_regular/") |
| 119 |
finally: |
| 120 |
connection.settings_dict["ATOMIC_REQUESTS"] = old_atomic_requests |
| 121 |
|
| 122 |
def test_no_auto_transaction(self): |
| 123 |
old_atomic_requests = connection.settings_dict["ATOMIC_REQUESTS"] |
| 124 |
try: |
| 125 |
connection.settings_dict["ATOMIC_REQUESTS"] = True |
| 126 |
response = self.client.get("/not_in_transaction/") |
| 127 |
finally: |
| 128 |
connection.settings_dict["ATOMIC_REQUESTS"] = old_atomic_requests |
| 129 |
self.assertContains(response, "False") |
| 130 |
try: |
| 131 |
connection.settings_dict["ATOMIC_REQUESTS"] = True |
| 132 |
response = self.client.get("/not_in_transaction_using_none/") |
| 133 |
finally: |
| 134 |
connection.settings_dict["ATOMIC_REQUESTS"] = old_atomic_requests |
| 135 |
self.assertContains(response, "False") |
| 136 |
try: |
| 137 |
connection.settings_dict["ATOMIC_REQUESTS"] = True |
| 138 |
response = self.client.get("/not_in_transaction_using_text/") |
| 139 |
finally: |
| 140 |
connection.settings_dict["ATOMIC_REQUESTS"] = old_atomic_requests |
| 141 |
# The non_atomic_requests decorator is used for an incorrect table. |
| 142 |
self.assertContains(response, "True") |
| 143 |
|
| 144 |
|
| 145 |
@override_settings(ROOT_URLCONF="handlers.urls") |
| 146 |
class SignalsTests(SimpleTestCase): |
| 147 |
def setUp(self): |
| 148 |
self.signals = [] |
| 149 |
self.signaled_environ = None |
| 150 |
request_started.connect(self.register_started) |
| 151 |
self.addCleanup(request_started.disconnect, self.register_started) |
| 152 |
request_finished.connect(self.register_finished) |
| 153 |
self.addCleanup(request_finished.disconnect, self.register_finished) |
| 154 |
|
| 155 |
def register_started(self, **kwargs): |
| 156 |
self.signals.append("started") |
| 157 |
self.signaled_environ = kwargs.get("environ") |
| 158 |
|
| 159 |
def register_finished(self, **kwargs): |
| 160 |
self.signals.append("finished") |
| 161 |
|
| 162 |
def test_request_signals(self): |
| 163 |
response = self.client.get("/regular/") |
| 164 |
self.assertEqual(self.signals, ["started", "finished"]) |
| 165 |
self.assertEqual(response.content, b"regular content") |
| 166 |
self.assertEqual(self.signaled_environ, response.wsgi_request.environ) |
| 167 |
|
| 168 |
def test_request_signals_streaming_response(self): |
| 169 |
response = self.client.get("/streaming/") |
| 170 |
self.assertEqual(self.signals, ["started"]) |
| 171 |
self.assertEqual(b"".join(list(response)), b"streaming content") |
| 172 |
self.assertEqual(self.signals, ["started", "finished"]) |
| 173 |
|
| 174 |
|
| 175 |
def empty_middleware(get_response): |
| 176 |
pass |
| 177 |
|
| 178 |
|
| 179 |
@override_settings(ROOT_URLCONF="handlers.urls") |
| 180 |
class HandlerRequestTests(SimpleTestCase): |
| 181 |
request_factory = RequestFactory() |
| 182 |
|
| 183 |
def test_async_view(self): |
| 184 |
"""Calling an async view down the normal synchronous path.""" |
| 185 |
response = self.client.get("/async_regular/") |
| 186 |
self.assertEqual(response.status_code, 200) |
| 187 |
|
| 188 |
def test_suspiciousop_in_view_returns_400(self): |
| 189 |
response = self.client.get("/suspicious/") |
| 190 |
self.assertEqual(response.status_code, 400) |
| 191 |
|
| 192 |
def test_bad_request_in_view_returns_400(self): |
| 193 |
response = self.client.get("/bad_request/") |
| 194 |
self.assertEqual(response.status_code, 400) |
| 195 |
|
| 196 |
def test_invalid_urls(self): |
| 197 |
response = self.client.get("~%A9helloworld") |
| 198 |
self.assertEqual(response.status_code, 404) |
| 199 |
self.assertEqual(response.context["request_path"], "/~%25A9helloworld") |
| 200 |
|
| 201 |
response = self.client.get("d%aao%aaw%aan%aal%aao%aaa%aad%aa/") |
| 202 |
self.assertEqual( |
| 203 |
response.context["request_path"], |
| 204 |
"/d%25AAo%25AAw%25AAn%25AAl%25AAo%25AAa%25AAd%25AA", |
| 205 |
) |
| 206 |
|
| 207 |
response = self.client.get("/%E2%99%E2%99%A5/") |
| 208 |
self.assertEqual(response.context["request_path"], "/%25E2%2599%E2%99%A5/") |
| 209 |
|
| 210 |
response = self.client.get("/%E2%98%8E%E2%A9%E2%99%A5/") |
| 211 |
self.assertEqual( |
| 212 |
response.context["request_path"], "/%E2%98%8E%25E2%25A9%E2%99%A5/" |
| 213 |
) |
| 214 |
|
| 215 |
def test_environ_path_info_type(self): |
| 216 |
environ = self.request_factory.get("/%E2%A8%87%87%A5%E2%A8%A0").environ |
| 217 |
self.assertIsInstance(environ["PATH_INFO"], str) |
| 218 |
|
| 219 |
def test_handle_accepts_httpstatus_enum_value(self): |
| 220 |
def start_response(status, headers): |
| 221 |
start_response.status = status |
| 222 |
|
| 223 |
environ = self.request_factory.get("/httpstatus_enum/").environ |
| 224 |
WSGIHandler()(environ, start_response) |
| 225 |
self.assertEqual(start_response.status, "200 OK") |
| 226 |
|
| 227 |
@override_settings(MIDDLEWARE=["handlers.tests.empty_middleware"]) |
| 228 |
def test_middleware_returns_none(self): |
| 229 |
msg = "Middleware factory handlers.tests.empty_middleware returned None." |
| 230 |
with self.assertRaisesMessage(ImproperlyConfigured, msg): |
| 231 |
self.client.get("/") |
| 232 |
|
| 233 |
def test_no_response(self): |
| 234 |
msg = ( |
| 235 |
"The view %s didn't return an HttpResponse object. It returned None " |
| 236 |
"instead." |
| 237 |
) |
| 238 |
tests = ( |
| 239 |
("/no_response_fbv/", "handlers.views.no_response"), |
| 240 |
("/no_response_cbv/", "handlers.views.NoResponse.__call__"), |
| 241 |
) |
| 242 |
for url, view in tests: |
| 243 |
with ( |
| 244 |
self.subTest(url=url), |
| 245 |
self.assertRaisesMessage(ValueError, msg % view), |
| 246 |
): |
| 247 |
self.client.get(url) |
| 248 |
|
| 249 |
def test_streaming(self): |
| 250 |
response = self.client.get("/streaming/") |
| 251 |
self.assertEqual(response.status_code, 200) |
| 252 |
self.assertEqual(b"".join(list(response)), b"streaming content") |
| 253 |
|
| 254 |
def test_async_streaming(self): |
| 255 |
response = self.client.get("/async_streaming/") |
| 256 |
self.assertEqual(response.status_code, 200) |
| 257 |
msg = ( |
| 258 |
"StreamingHttpResponse must consume asynchronous iterators in order to " |
| 259 |
"serve them synchronously. Use a synchronous iterator instead." |
| 260 |
) |
| 261 |
with self.assertWarnsMessage(Warning, msg) as ctx: |
| 262 |
self.assertEqual(b"".join(list(response)), b"streaming content") |
| 263 |
self.assertEqual(ctx.filename, __file__) |
| 264 |
|
| 265 |
|
| 266 |
class ScriptNameTests(SimpleTestCase): |
| 267 |
def test_get_script_name(self): |
| 268 |
# Regression test for #23173 |
| 269 |
# Test first without PATH_INFO |
| 270 |
script_name = get_script_name({"SCRIPT_URL": "/foobar/"}) |
| 271 |
self.assertEqual(script_name, "/foobar/") |
| 272 |
|
| 273 |
script_name = get_script_name({"SCRIPT_URL": "/foobar/", "PATH_INFO": "/"}) |
| 274 |
self.assertEqual(script_name, "/foobar") |
| 275 |
|
| 276 |
def test_get_script_name_double_slashes(self): |
| 277 |
""" |
| 278 |
WSGI squashes multiple successive slashes in PATH_INFO, get_script_name |
| 279 |
should take that into account when forming SCRIPT_NAME (#17133). |
| 280 |
""" |
| 281 |
script_name = get_script_name( |
| 282 |
{ |
| 283 |
"SCRIPT_URL": "/mst/milestones//accounts/login//help", |
| 284 |
"PATH_INFO": "/milestones/accounts/login/help", |
| 285 |
} |
| 286 |
) |
| 287 |
self.assertEqual(script_name, "/mst") |
| 288 |
|
| 289 |
|
| 290 |
@override_settings(ROOT_URLCONF="handlers.urls") |
| 291 |
class AsyncHandlerRequestTests(SimpleTestCase): |
| 292 |
"""Async variants of the normal handler request tests.""" |
| 293 |
|
| 294 |
async def test_sync_view(self): |
| 295 |
"""Calling a sync view down the asynchronous path.""" |
| 296 |
response = await self.async_client.get("/regular/") |
| 297 |
self.assertEqual(response.status_code, 200) |
| 298 |
|
| 299 |
async def test_async_view(self): |
| 300 |
"""Calling an async view down the asynchronous path.""" |
| 301 |
response = await self.async_client.get("/async_regular/") |
| 302 |
self.assertEqual(response.status_code, 200) |
| 303 |
|
| 304 |
async def test_suspiciousop_in_view_returns_400(self): |
| 305 |
response = await self.async_client.get("/suspicious/") |
| 306 |
self.assertEqual(response.status_code, 400) |
| 307 |
|
| 308 |
async def test_bad_request_in_view_returns_400(self): |
| 309 |
response = await self.async_client.get("/bad_request/") |
| 310 |
self.assertEqual(response.status_code, 400) |
| 311 |
|
| 312 |
async def test_no_response(self): |
| 313 |
msg = ( |
| 314 |
"The view handlers.views.no_response didn't return an " |
| 315 |
"HttpResponse object. It returned None instead." |
| 316 |
) |
| 317 |
with self.assertRaisesMessage(ValueError, msg): |
| 318 |
await self.async_client.get("/no_response_fbv/") |
| 319 |
|
| 320 |
async def test_unawaited_response(self): |
| 321 |
msg = ( |
| 322 |
"The view handlers.views.CoroutineClearingView.__call__ didn't" |
| 323 |
" return an HttpResponse object. It returned an unawaited" |
| 324 |
" coroutine instead. You may need to add an 'await'" |
| 325 |
" into your view." |
| 326 |
) |
| 327 |
with self.assertRaisesMessage(ValueError, msg): |
| 328 |
await self.async_client.get("/unawaited/") |
| 329 |
|
| 330 |
def test_root_path(self): |
| 331 |
async_request_factory = AsyncRequestFactory() |
| 332 |
request = async_request_factory.request( |
| 333 |
**{"path": "/root/somepath/", "root_path": "/root"} |
| 334 |
) |
| 335 |
self.assertEqual(request.path, "/root/somepath/") |
| 336 |
self.assertEqual(request.script_name, "/root") |
| 337 |
self.assertEqual(request.path_info, "/somepath/") |
| 338 |
|
| 339 |
@override_settings(FORCE_SCRIPT_NAME="/FORCED_PREFIX") |
| 340 |
def test_force_script_name(self): |
| 341 |
async_request_factory = AsyncRequestFactory() |
| 342 |
request = async_request_factory.request(**{"path": "/FORCED_PREFIX/somepath/"}) |
| 343 |
self.assertEqual(request.path, "/FORCED_PREFIX/somepath/") |
| 344 |
self.assertEqual(request.script_name, "/FORCED_PREFIX") |
| 345 |
self.assertEqual(request.path_info, "/somepath/") |
| 346 |
|
| 347 |
async def test_sync_streaming(self): |
| 348 |
response = await self.async_client.get("/streaming/") |
| 349 |
self.assertEqual(response.status_code, 200) |
| 350 |
msg = ( |
| 351 |
"StreamingHttpResponse must consume synchronous iterators in order to " |
| 352 |
"serve them asynchronously. Use an asynchronous iterator instead." |
| 353 |
) |
| 354 |
with self.assertWarnsMessage(Warning, msg) as ctx: |
| 355 |
self.assertEqual( |
| 356 |
b"".join([chunk async for chunk in response]), b"streaming content" |
| 357 |
) |
| 358 |
self.assertEqual(ctx.filename, __file__) |
| 359 |
|
| 360 |
async def test_async_streaming(self): |
| 361 |
response = await self.async_client.get("/async_streaming/") |
| 362 |
self.assertEqual(response.status_code, 200) |
| 363 |
self.assertEqual( |
| 364 |
b"".join([chunk async for chunk in response]), b"streaming content" |
| 365 |
) |