Debian Codegraph @

django/test/client.py

raw
1 import json
2 import mimetypes
3 import os
4 import sys
5 from collections.abc import Iterable
6 from copy import copy
7 from functools import partial
8 from http import HTTPStatus
9 from importlib import import_module
10 from io import BytesIO, IOBase
11 from urllib.parse import unquote_to_bytes, urljoin, urlsplit
12
13 from asgiref.sync import sync_to_async
14
15 from django.conf import settings
16 from django.core.handlers.asgi import ASGIRequest
17 from django.core.handlers.base import BaseHandler
18 from django.core.handlers.wsgi import LimitedStream, WSGIRequest
19 from django.core.serializers.json import DjangoJSONEncoder
20 from django.core.signals import got_request_exception, request_finished, request_started
21 from django.db import close_old_connections
22 from django.http import HttpHeaders, HttpRequest, QueryDict, SimpleCookie
23 from django.test import signals
24 from django.test.utils import ContextList
25 from django.urls import resolve
26 from django.utils.encoding import force_bytes
27 from django.utils.functional import SimpleLazyObject
28 from django.utils.http import urlencode
29 from django.utils.regex_helper import _lazy_re_compile
30
31 __all__ = (
32 "AsyncClient",
33 "AsyncRequestFactory",
34 "Client",
35 "RedirectCycleError",
36 "RequestFactory",
37 "encode_file",
38 "encode_multipart",
39 )
40
41
42 BOUNDARY = "BoUnDaRyStRiNg"
43 MULTIPART_CONTENT = "multipart/form-data; boundary=%s" % BOUNDARY
44 CONTENT_TYPE_RE = _lazy_re_compile(r".*; charset=([\w-]+);?")
45 # Structured suffix spec: https://tools.ietf.org/html/rfc6838#section-4.2.8
46 JSON_CONTENT_TYPE_RE = _lazy_re_compile(r"^application\/(.+\+)?json")
47
48 REDIRECT_STATUS_CODES = frozenset(
49 [
50 HTTPStatus.MOVED_PERMANENTLY,
51 HTTPStatus.FOUND,
52 HTTPStatus.SEE_OTHER,
53 HTTPStatus.TEMPORARY_REDIRECT,
54 HTTPStatus.PERMANENT_REDIRECT,
55 ]
56 )
57
58
59 class RedirectCycleError(Exception):
60 """The test client has been asked to follow a redirect loop."""
61
62 def __init__(self, message, last_response):
63 super().__init__(message)
64 self.last_response = last_response
65 self.redirect_chain = last_response.redirect_chain
66
67
68 class FakePayload(IOBase):
69 """
70 A wrapper around BytesIO that restricts what can be read since data from
71 the network can't be sought and cannot be read outside of its content
72 length. This makes sure that views can't do anything under the test client
73 that wouldn't work in real life.
74 """
75
76 def __init__(self, initial_bytes=None):
77 self.__content = BytesIO()
78 self.__len = 0
79 self.read_started = False
80 if initial_bytes is not None:
81 self.write(initial_bytes)
82
83 def __len__(self):
84 return self.__len
85
86 def read(self, size=-1, /):
87 if not self.read_started:
88 self.__content.seek(0)
89 self.read_started = True
90 if size == -1 or size is None:
91 size = self.__len
92 assert (
93 self.__len >= size
94 ), "Cannot read more than the available bytes from the HTTP incoming data."
95 content = self.__content.read(size)
96 self.__len -= len(content)
97 return content
98
99 def readline(self, size=-1, /):
100 if not self.read_started:
101 self.__content.seek(0)
102 self.read_started = True
103 if size == -1 or size is None:
104 size = self.__len
105 assert (
106 self.__len >= size
107 ), "Cannot read more than the available bytes from the HTTP incoming data."
108 content = self.__content.readline(size)
109 self.__len -= len(content)
110 return content
111
112 def write(self, b, /):
113 if self.read_started:
114 raise ValueError("Unable to write a payload after it's been read")
115 content = force_bytes(b)
116 self.__content.write(content)
117 self.__len += len(content)
118
119
120 def closing_iterator_wrapper(iterable, close):
121 try:
122 yield from iterable
123 finally:
124 request_finished.disconnect(close_old_connections)
125 close() # will fire request_finished
126 request_finished.connect(close_old_connections)
127
128
129 async def aclosing_iterator_wrapper(iterable, close):
130 try:
131 async for chunk in iterable:
132 yield chunk
133 finally:
134 request_finished.disconnect(close_old_connections)
135 close() # will fire request_finished
136 request_finished.connect(close_old_connections)
137
138
139 def conditional_content_removal(request, response):
140 """
141 Simulate the behavior of most web servers by removing the content of
142 responses for HEAD requests, 1xx, 204, and 304 responses. Ensure
143 compliance with RFC 9112 Section 6.3.
144 """
145 if 100 <= response.status_code < 200 or response.status_code in (204, 304):
146 if response.streaming:
147 response.streaming_content = []
148 else:
149 response.content = b""
150 if request.method == "HEAD":
151 if response.streaming:
152 response.streaming_content = []
153 else:
154 response.content = b""
155 return response
156
157
158 class ClientHandler(BaseHandler):
159 """
160 An HTTP Handler that can be used for testing purposes. Use the WSGI
161 interface to compose requests, but return the raw HttpResponse object with
162 the originating WSGIRequest attached to its ``wsgi_request`` attribute.
163 """
164
165 def __init__(self, enforce_csrf_checks=True, *args, **kwargs):
166 self.enforce_csrf_checks = enforce_csrf_checks
167 super().__init__(*args, **kwargs)
168
169 def __call__(self, environ):
170 # Set up middleware if needed. We couldn't do this earlier, because
171 # settings weren't available.
172 if self._middleware_chain is None:
173 self.load_middleware()
174
175 request_started.disconnect(close_old_connections)
176 request_started.send(sender=self.__class__, environ=environ)
177 request_started.connect(close_old_connections)
178 request = WSGIRequest(environ)
179 # sneaky little hack so that we can easily get round
180 # CsrfViewMiddleware. This makes life easier, and is probably
181 # required for backwards compatibility with external tests against
182 # admin views.
183 request._dont_enforce_csrf_checks = not self.enforce_csrf_checks
184
185 # Request goes through middleware.
186 response = self.get_response(request)
187
188 # Simulate behaviors of most web servers.
189 conditional_content_removal(request, response)
190
191 # Attach the originating request to the response so that it could be
192 # later retrieved.
193 response.wsgi_request = request
194
195 # Emulate a WSGI server by calling the close method on completion.
196 if response.streaming:
197 if response.is_async:
198 response.streaming_content = aclosing_iterator_wrapper(
199 response.streaming_content, response.close
200 )
201 else:
202 response.streaming_content = closing_iterator_wrapper(
203 response.streaming_content, response.close
204 )
205 else:
206 request_finished.disconnect(close_old_connections)
207 response.close() # will fire request_finished
208 request_finished.connect(close_old_connections)
209
210 return response
211
212
213 class AsyncClientHandler(BaseHandler):
214 """An async version of ClientHandler."""
215
216 def __init__(self, enforce_csrf_checks=True, *args, **kwargs):
217 self.enforce_csrf_checks = enforce_csrf_checks
218 super().__init__(*args, **kwargs)
219
220 async def __call__(self, scope):
221 # Set up middleware if needed. We couldn't do this earlier, because
222 # settings weren't available.
223 if self._middleware_chain is None:
224 self.load_middleware(is_async=True)
225 # Extract body file from the scope, if provided.
226 if "_body_file" in scope:
227 body_file = scope.pop("_body_file")
228 else:
229 body_file = FakePayload("")
230
231 request_started.disconnect(close_old_connections)
232 await request_started.asend(sender=self.__class__, scope=scope)
233 request_started.connect(close_old_connections)
234 # Wrap FakePayload body_file to allow large read() in test environment.
235 request = ASGIRequest(scope, LimitedStream(body_file, len(body_file)))
236 # Sneaky little hack so that we can easily get round
237 # CsrfViewMiddleware. This makes life easier, and is probably required
238 # for backwards compatibility with external tests against admin views.
239 request._dont_enforce_csrf_checks = not self.enforce_csrf_checks
240 # Request goes through middleware.
241 response = await self.get_response_async(request)
242 # Simulate behaviors of most web servers.
243 conditional_content_removal(request, response)
244 # Attach the originating ASGI request to the response so that it could
245 # be later retrieved.
246 response.asgi_request = request
247 # Emulate a server by calling the close method on completion.
248 if response.streaming:
249 if response.is_async:
250 response.streaming_content = aclosing_iterator_wrapper(
251 response.streaming_content, response.close
252 )
253 else:
254 response.streaming_content = closing_iterator_wrapper(
255 response.streaming_content, response.close
256 )
257 else:
258 request_finished.disconnect(close_old_connections)
259 # Will fire request_finished.
260 await sync_to_async(response.close, thread_sensitive=False)()
261 request_finished.connect(close_old_connections)
262 return response
263
264
265 def store_rendered_templates(store, signal, sender, template, context, **kwargs):
266 """
267 Store templates and contexts that are rendered.
268
269 The context is copied so that it is an accurate representation at the time
270 of rendering.
271 """
272 store.setdefault("templates", []).append(template)
273 if "context" not in store:
274 store["context"] = ContextList()
275 store["context"].append(copy(context))
276
277
278 def encode_multipart(boundary, data):
279 """
280 Encode multipart POST data from a dictionary of form values.
281
282 The key will be used as the form data name; the value will be transmitted
283 as content. If the value is a file, the contents of the file will be sent
284 as an application/octet-stream; otherwise, str(value) will be sent.
285 """
286 lines = []
287
288 def to_bytes(s):
289 return force_bytes(s, settings.DEFAULT_CHARSET)
290
291 # Not by any means perfect, but good enough for our purposes.
292 def is_file(thing):
293 return hasattr(thing, "read") and callable(thing.read)
294
295 # Each bit of the multipart form data could be either a form value or a
296 # file, or a *list* of form values and/or files. Remember that HTTP field
297 # names can be duplicated!
298 for key, value in data.items():
299 if value is None:
300 raise TypeError(
301 "Cannot encode None for key '%s' as POST data. Did you mean "
302 "to pass an empty string or omit the value?" % key
303 )
304 elif is_file(value):
305 lines.extend(encode_file(boundary, key, value))
306 elif not isinstance(value, str) and isinstance(value, Iterable):
307 for item in value:
308 if is_file(item):
309 lines.extend(encode_file(boundary, key, item))
310 else:
311 lines.extend(
312 to_bytes(val)
313 for val in [
314 "--%s" % boundary,
315 'Content-Disposition: form-data; name="%s"' % key,
316 "",
317 item,
318 ]
319 )
320 else:
321 lines.extend(
322 to_bytes(val)
323 for val in [
324 "--%s" % boundary,
325 'Content-Disposition: form-data; name="%s"' % key,
326 "",
327 value,
328 ]
329 )
330
331 lines.extend(
332 [
333 to_bytes("--%s--" % boundary),
334 b"",
335 ]
336 )
337 return b"\r\n".join(lines)
338
339
340 def encode_file(boundary, key, file):
341 def to_bytes(s):
342 return force_bytes(s, settings.DEFAULT_CHARSET)
343
344 # file.name might not be a string. For example, it's an int for
345 # tempfile.TemporaryFile().
346 file_has_string_name = hasattr(file, "name") and isinstance(file.name, str)
347 filename = os.path.basename(file.name) if file_has_string_name else ""
348
349 if hasattr(file, "content_type"):
350 content_type = file.content_type
351 elif filename:
352 content_type = mimetypes.guess_type(filename)[0]
353 else:
354 content_type = None
355
356 if content_type is None:
357 content_type = "application/octet-stream"
358 filename = filename or key
359 return [
360 to_bytes("--%s" % boundary),
361 to_bytes(
362 'Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename)
363 ),
364 to_bytes("Content-Type: %s" % content_type),
365 b"",
366 to_bytes(file.read()),
367 ]
368
369
370 class RequestFactory:
371 """
372 Class that lets you create mock Request objects for use in testing.
373
374 Usage:
375
376 rf = RequestFactory()
377 get_request = rf.get('/hello/')
378 post_request = rf.post('/submit/', {'foo': 'bar'})
379
380 Once you have a request object you can pass it to any view function,
381 just as if that view had been hooked up using a URLconf.
382 """
383
384 def __init__(
385 self,
386 *,
387 json_encoder=DjangoJSONEncoder,
388 headers=None,
389 query_params=None,
390 **defaults,
391 ):
392 self.json_encoder = json_encoder
393 self.defaults = defaults
394 self.cookies = SimpleCookie()
395 self.errors = BytesIO()
396 if headers:
397 self.defaults.update(HttpHeaders.to_wsgi_names(headers))
398 if query_params:
399 self.defaults["QUERY_STRING"] = urlencode(query_params, doseq=True)
400
401 def _base_environ(self, **request):
402 """
403 The base environment for a request.
404 """
405 # This is a minimal valid WSGI environ dictionary, plus:
406 # - HTTP_COOKIE: for cookie support,
407 # - REMOTE_ADDR: often useful, see #8551.
408 # See https://www.python.org/dev/peps/pep-3333/#environ-variables
409 return {
410 "HTTP_COOKIE": "; ".join(
411 sorted(
412 "%s=%s" % (morsel.key, morsel.coded_value)
413 for morsel in self.cookies.values()
414 )
415 ),
416 "PATH_INFO": "/",
417 "REMOTE_ADDR": "127.0.0.1",
418 "REQUEST_METHOD": "GET",
419 "SCRIPT_NAME": "",
420 "SERVER_NAME": "testserver",
421 "SERVER_PORT": "80",
422 "SERVER_PROTOCOL": "HTTP/1.1",
423 "wsgi.version": (1, 0),
424 "wsgi.url_scheme": "http",
425 "wsgi.input": FakePayload(b""),
426 "wsgi.errors": self.errors,
427 "wsgi.multiprocess": True,
428 "wsgi.multithread": False,
429 "wsgi.run_once": False,
430 **self.defaults,
431 **request,
432 }
433
434 def request(self, **request):
435 "Construct a generic request object."
436 return WSGIRequest(self._base_environ(**request))
437
438 def _encode_data(self, data, content_type):
439 if content_type is MULTIPART_CONTENT:
440 return encode_multipart(BOUNDARY, data)
441 else:
442 # Encode the content so that the byte representation is correct.
443 match = CONTENT_TYPE_RE.match(content_type)
444 if match:
445 charset = match[1]
446 else:
447 charset = settings.DEFAULT_CHARSET
448 return force_bytes(data, encoding=charset)
449
450 def _encode_json(self, data, content_type):
451 """
452 Return encoded JSON if data is a dict, list, or tuple and content_type
453 is application/json.
454 """
455 should_encode = JSON_CONTENT_TYPE_RE.match(content_type) and isinstance(
456 data, (dict, list, tuple)
457 )
458 return json.dumps(data, cls=self.json_encoder) if should_encode else data
459
460 def _get_path(self, parsed):
461 path = unquote_to_bytes(parsed.path)
462 # Replace the behavior where non-ASCII values in the WSGI environ are
463 # arbitrarily decoded with ISO-8859-1.
464 # Refs comment in `get_bytes_from_wsgi()`.
465 return path.decode("iso-8859-1")
466
467 def get(
468 self, path, data=None, secure=False, *, headers=None, query_params=None, **extra
469 ):
470 """Construct a GET request."""
471 if query_params and data:
472 raise ValueError("query_params and data arguments are mutually exclusive.")
473 query_params = data or query_params
474 query_params = {} if query_params is None else query_params
475 return self.generic(
476 "GET",
477 path,
478 secure=secure,
479 headers=headers,
480 query_params=query_params,
481 **extra,
482 )
483
484 def post(
485 self,
486 path,
487 data=None,
488 content_type=MULTIPART_CONTENT,
489 secure=False,
490 *,
491 headers=None,
492 query_params=None,
493 **extra,
494 ):
495 """Construct a POST request."""
496 data = self._encode_json({} if data is None else data, content_type)
497 post_data = self._encode_data(data, content_type)
498
499 return self.generic(
500 "POST",
501 path,
502 post_data,
503 content_type,
504 secure=secure,
505 headers=headers,
506 query_params=query_params,
507 **extra,
508 )
509
510 def head(
511 self, path, data=None, secure=False, *, headers=None, query_params=None, **extra
512 ):
513 """Construct a HEAD request."""
514 if query_params and data:
515 raise ValueError("query_params and data arguments are mutually exclusive.")
516 query_params = data or query_params
517 query_params = {} if query_params is None else query_params
518 return self.generic(
519 "HEAD",
520 path,
521 secure=secure,
522 headers=headers,
523 query_params=query_params,
524 **extra,
525 )
526
527 def trace(self, path, secure=False, *, headers=None, query_params=None, **extra):
528 """Construct a TRACE request."""
529 return self.generic(
530 "TRACE",
531 path,
532 secure=secure,
533 headers=headers,
534 query_params=query_params,
535 **extra,
536 )
537
538 def options(
539 self,
540 path,
541 data="",
542 content_type="application/octet-stream",
543 secure=False,
544 *,
545 headers=None,
546 query_params=None,
547 **extra,
548 ):
549 "Construct an OPTIONS request."
550 return self.generic(
551 "OPTIONS",
552 path,
553 data,
554 content_type,
555 secure=secure,
556 headers=headers,
557 query_params=query_params,
558 **extra,
559 )
560
561 def put(
562 self,
563 path,
564 data="",
565 content_type="application/octet-stream",
566 secure=False,
567 *,
568 headers=None,
569 query_params=None,
570 **extra,
571 ):
572 """Construct a PUT request."""
573 data = self._encode_json(data, content_type)
574 return self.generic(
575 "PUT",
576 path,
577 data,
578 content_type,
579 secure=secure,
580 headers=headers,
581 query_params=query_params,
582 **extra,
583 )
584
585 def patch(
586 self,
587 path,
588 data="",
589 content_type="application/octet-stream",
590 secure=False,
591 *,
592 headers=None,
593 query_params=None,
594 **extra,
595 ):
596 """Construct a PATCH request."""
597 data = self._encode_json(data, content_type)
598 return self.generic(
599 "PATCH",
600 path,
601 data,
602 content_type,
603 secure=secure,
604 headers=headers,
605 query_params=query_params,
606 **extra,
607 )
608
609 def delete(
610 self,
611 path,
612 data="",
613 content_type="application/octet-stream",
614 secure=False,
615 *,
616 headers=None,
617 query_params=None,
618 **extra,
619 ):
620 """Construct a DELETE request."""
621 data = self._encode_json(data, content_type)
622 return self.generic(
623 "DELETE",
624 path,
625 data,
626 content_type,
627 secure=secure,
628 headers=headers,
629 query_params=query_params,
630 **extra,
631 )
632
633 def generic(
634 self,
635 method,
636 path,
637 data="",
638 content_type="application/octet-stream",
639 secure=False,
640 *,
641 headers=None,
642 query_params=None,
643 **extra,
644 ):
645 """Construct an arbitrary HTTP request."""
646 parsed = urlsplit(str(path)) # path can be lazy
647 data = force_bytes(data, settings.DEFAULT_CHARSET)
648 r = {
649 "PATH_INFO": self._get_path(parsed),
650 "REQUEST_METHOD": method,
651 "SERVER_PORT": "443" if secure else "80",
652 "wsgi.url_scheme": "https" if secure else "http",
653 }
654 if data:
655 r.update(
656 {
657 "CONTENT_LENGTH": str(len(data)),
658 "CONTENT_TYPE": content_type,
659 "wsgi.input": FakePayload(data),
660 }
661 )
662 if headers:
663 extra.update(HttpHeaders.to_wsgi_names(headers))
664 if query_params:
665 extra["QUERY_STRING"] = urlencode(query_params, doseq=True)
666 r.update(extra)
667 # If QUERY_STRING is absent or empty, we want to extract it from the URL.
668 if not r.get("QUERY_STRING"):
669 # WSGI requires latin-1 encoded strings. See get_path_info().
670 r["QUERY_STRING"] = parsed.query.encode().decode("iso-8859-1")
671 return self.request(**r)
672
673
674 class AsyncRequestFactory(RequestFactory):
675 """
676 Class that lets you create mock ASGI-like Request objects for use in
677 testing. Usage:
678
679 rf = AsyncRequestFactory()
680 get_request = rf.get("/hello/")
681 post_request = rf.post("/submit/", {"foo": "bar"})
682
683 Once you have a request object you can pass it to any view function,
684 including synchronous ones. The reason we have a separate class here is:
685 a) this makes ASGIRequest subclasses, and
686 b) AsyncClient can subclass it.
687 """
688
689 def _base_scope(self, **request):
690 """The base scope for a request."""
691 # This is a minimal valid ASGI scope, plus:
692 # - headers['cookie'] for cookie support,
693 # - 'client' often useful, see #8551.
694 scope = {
695 "asgi": {"version": "3.0"},
696 "type": "http",
697 "http_version": "1.1",
698 "client": ["127.0.0.1", 0],
699 "server": ("testserver", "80"),
700 "scheme": "http",
701 "method": "GET",
702 "headers": [],
703 **self.defaults,
704 **request,
705 }
706 scope["headers"].append(
707 (
708 b"cookie",
709 b"; ".join(
710 sorted(
711 ("%s=%s" % (morsel.key, morsel.coded_value)).encode("ascii")
712 for morsel in self.cookies.values()
713 )
714 ),
715 )
716 )
717 return scope
718
719 def request(self, **request):
720 """Construct a generic request object."""
721 # This is synchronous, which means all methods on this class are.
722 # AsyncClient, however, has an async request function, which makes all
723 # its methods async.
724 if "_body_file" in request:
725 body_file = request.pop("_body_file")
726 else:
727 body_file = FakePayload("")
728 # Wrap FakePayload body_file to allow large read() in test environment.
729 return ASGIRequest(
730 self._base_scope(**request), LimitedStream(body_file, len(body_file))
731 )
732
733 def generic(
734 self,
735 method,
736 path,
737 data="",
738 content_type="application/octet-stream",
739 secure=False,
740 *,
741 headers=None,
742 query_params=None,
743 **extra,
744 ):
745 """Construct an arbitrary HTTP request."""
746 parsed = urlsplit(str(path)) # path can be lazy.
747 data = force_bytes(data, settings.DEFAULT_CHARSET)
748 s = {
749 "method": method,
750 "path": self._get_path(parsed),
751 "server": ("127.0.0.1", "443" if secure else "80"),
752 "scheme": "https" if secure else "http",
753 "headers": [(b"host", b"testserver")],
754 }
755 if self.defaults:
756 extra = {**self.defaults, **extra}
757 if data:
758 s["headers"].extend(
759 [
760 (b"content-length", str(len(data)).encode("ascii")),
761 (b"content-type", content_type.encode("ascii")),
762 ]
763 )
764 s["_body_file"] = FakePayload(data)
765 if query_params:
766 s["query_string"] = urlencode(query_params, doseq=True)
767 elif query_string := extra.pop("QUERY_STRING", None):
768 s["query_string"] = query_string
769 else:
770 # If QUERY_STRING is absent or empty, we want to extract it from
771 # the URL.
772 s["query_string"] = parsed.query
773 if headers:
774 extra.update(HttpHeaders.to_asgi_names(headers))
775 s["headers"] += [
776 # Avoid breaking test clients that just want to supply normalized
777 # ASGI names, regardless of the fact that ASGIRequest drops headers
778 # with underscores (CVE-2026-3902).
779 (key.lower().replace("_", "-").encode("ascii"), value.encode("latin1"))
780 for key, value in extra.items()
781 ]
782 return self.request(**s)
783
784
785 class ClientMixin:
786 """
787 Mixin with common methods between Client and AsyncClient.
788 """
789
790 def store_exc_info(self, **kwargs):
791 """Store exceptions when they are generated by a view."""
792 self.exc_info = sys.exc_info()
793
794 def check_exception(self, response):
795 """
796 Look for a signaled exception, clear the current context exception
797 data, re-raise the signaled exception, and clear the signaled exception
798 from the local cache.
799 """
800 response.exc_info = self.exc_info
801 if self.exc_info:
802 _, exc_value, _ = self.exc_info
803 self.exc_info = None
804 if self.raise_request_exception:
805 raise exc_value
806
807 @property
808 def session(self):
809 """Return the current session variables."""
810 engine = import_module(settings.SESSION_ENGINE)
811 cookie = self.cookies.get(settings.SESSION_COOKIE_NAME)
812 if cookie:
813 return engine.SessionStore(cookie.value)
814 session = engine.SessionStore()
815 session.save()
816 self.cookies[settings.SESSION_COOKIE_NAME] = session.session_key
817 return session
818
819 async def asession(self):
820 engine = import_module(settings.SESSION_ENGINE)
821 cookie = self.cookies.get(settings.SESSION_COOKIE_NAME)
822 if cookie:
823 return engine.SessionStore(cookie.value)
824 session = engine.SessionStore()
825 await session.asave()
826 self.cookies[settings.SESSION_COOKIE_NAME] = session.session_key
827 return session
828
829 def login(self, **credentials):
830 """
831 Set the Factory to appear as if it has successfully logged into a site.
832
833 Return True if login is possible or False if the provided credentials
834 are incorrect.
835 """
836 from django.contrib.auth import authenticate
837
838 user = authenticate(**credentials)
839 if user:
840 self._login(user)
841 return True
842 return False
843
844 async def alogin(self, **credentials):
845 """See login()."""
846 from django.contrib.auth import aauthenticate
847
848 user = await aauthenticate(**credentials)
849 if user:
850 await self._alogin(user)
851 return True
852 return False
853
854 def force_login(self, user, backend=None):
855 if backend is None:
856 backend = self._get_backend()
857 user.backend = backend
858 self._login(user, backend)
859
860 async def aforce_login(self, user, backend=None):
861 if backend is None:
862 backend = self._get_backend()
863 user.backend = backend
864 await self._alogin(user, backend)
865
866 def _get_backend(self):
867 from django.contrib.auth import load_backend
868
869 for backend_path in settings.AUTHENTICATION_BACKENDS:
870 backend = load_backend(backend_path)
871 if hasattr(backend, "get_user"):
872 return backend_path
873
874 def _login(self, user, backend=None):
875 from django.contrib.auth import login
876
877 # Create a fake request to store login details.
878 request = HttpRequest()
879 if self.session:
880 request.session = self.session
881 else:
882 engine = import_module(settings.SESSION_ENGINE)
883 request.session = engine.SessionStore()
884 login(request, user, backend)
885 # Save the session values.
886 request.session.save()
887 self._set_login_cookies(request)
888
889 async def _alogin(self, user, backend=None):
890 from django.contrib.auth import alogin
891
892 # Create a fake request to store login details.
893 request = HttpRequest()
894 session = await self.asession()
895 if session:
896 request.session = session
897 else:
898 engine = import_module(settings.SESSION_ENGINE)
899 request.session = engine.SessionStore()
900
901 await alogin(request, user, backend)
902 # Save the session values.
903 await request.session.asave()
904 self._set_login_cookies(request)
905
906 def _set_login_cookies(self, request):
907 # Set the cookie to represent the session.
908 session_cookie = settings.SESSION_COOKIE_NAME
909 self.cookies[session_cookie] = request.session.session_key
910 cookie_data = {
911 "max-age": None,
912 "path": "/",
913 "domain": settings.SESSION_COOKIE_DOMAIN,
914 "secure": settings.SESSION_COOKIE_SECURE or None,
915 "expires": None,
916 }
917 self.cookies[session_cookie].update(cookie_data)
918
919 def logout(self):
920 """Log out the user by removing the cookies and session object."""
921 from django.contrib.auth import get_user, logout
922
923 request = HttpRequest()
924 if self.session:
925 request.session = self.session
926 request.user = get_user(request)
927 else:
928 engine = import_module(settings.SESSION_ENGINE)
929 request.session = engine.SessionStore()
930 logout(request)
931 self.cookies = SimpleCookie()
932
933 async def alogout(self):
934 """See logout()."""
935 from django.contrib.auth import aget_user, alogout
936
937 request = HttpRequest()
938 session = await self.asession()
939 if session:
940 request.session = session
941 request.user = await aget_user(request)
942 else:
943 engine = import_module(settings.SESSION_ENGINE)
944 request.session = engine.SessionStore()
945 await alogout(request)
946 self.cookies = SimpleCookie()
947
948 def _parse_json(self, response, **extra):
949 if not hasattr(response, "_json"):
950 if not JSON_CONTENT_TYPE_RE.match(response.get("Content-Type")):
951 raise ValueError(
952 'Content-Type header is "%s", not "application/json"'
953 % response.get("Content-Type")
954 )
955 response._json = json.loads(response.text, **extra)
956 return response._json
957
958 def _follow_redirect(
959 self,
960 response,
961 *,
962 data="",
963 content_type="",
964 headers=None,
965 query_params=None,
966 **extra,
967 ):
968 """Follow a single redirect contained in response using GET."""
969 response_url = response.url
970 redirect_chain = response.redirect_chain
971 redirect_chain.append((response_url, response.status_code))
972
973 url = urlsplit(response_url)
974 if url.scheme:
975 extra["wsgi.url_scheme"] = url.scheme
976 if url.hostname:
977 extra["SERVER_NAME"] = url.hostname
978 extra["HTTP_HOST"] = url.hostname
979 if url.port:
980 extra["SERVER_PORT"] = str(url.port)
981
982 path = url.path
983 # RFC 3986 Section 6.2.3: Empty path should be normalized to "/".
984 if not path and url.netloc:
985 path = "/"
986 # Prepend the request path to handle relative path redirects
987 if not path.startswith("/"):
988 path = urljoin(response.request["PATH_INFO"], path)
989
990 if response.status_code in (
991 HTTPStatus.TEMPORARY_REDIRECT,
992 HTTPStatus.PERMANENT_REDIRECT,
993 ):
994 # Preserve request method and query string (if needed)
995 # post-redirect for 307/308 responses.
996 request_method = response.request["REQUEST_METHOD"].lower()
997 if request_method not in ("get", "head"):
998 extra["QUERY_STRING"] = url.query
999 request_method = getattr(self, request_method)
1000 else:
1001 request_method = self.get
1002 data = QueryDict(url.query)
1003 content_type = None
1004
1005 return request_method(
1006 path,
1007 data=data,
1008 content_type=content_type,
1009 follow=False,
1010 headers=headers,
1011 query_params=query_params,
1012 **extra,
1013 )
1014
1015 def _ensure_redirects_not_cyclic(self, response):
1016 """
1017 Raise a RedirectCycleError if response contains too many redirects.
1018 """
1019 redirect_chain = response.redirect_chain
1020 if redirect_chain[-1] in redirect_chain[:-1]:
1021 # Check that we're not redirecting to somewhere we've already been
1022 # to, to prevent loops.
1023 raise RedirectCycleError("Redirect loop detected.", last_response=response)
1024 if len(redirect_chain) > 20:
1025 # Such a lengthy chain likely also means a loop, but one with a
1026 # growing path, changing view, or changing query argument. 20 is
1027 # the value of "network.http.redirection-limit" from Firefox.
1028 raise RedirectCycleError("Too many redirects.", last_response=response)
1029
1030
1031 class Client(ClientMixin, RequestFactory):
1032 """
1033 A class that can act as a client for testing purposes.
1034
1035 It allows the user to compose GET and POST requests, and
1036 obtain the response that the server gave to those requests.
1037 The server Response objects are annotated with the details
1038 of the contexts and templates that were rendered during the
1039 process of serving the request.
1040
1041 Client objects are stateful - they will retain cookie (and
1042 thus session) details for the lifetime of the Client instance.
1043
1044 This is not intended as a replacement for Twill/Selenium or
1045 the like - it is here to allow testing against the
1046 contexts and templates produced by a view, rather than the
1047 HTML rendered to the end-user.
1048 """
1049
1050 def __init__(
1051 self,
1052 enforce_csrf_checks=False,
1053 raise_request_exception=True,
1054 *,
1055 headers=None,
1056 query_params=None,
1057 **defaults,
1058 ):
1059 super().__init__(headers=headers, query_params=query_params, **defaults)
1060 self.handler = ClientHandler(enforce_csrf_checks)
1061 self.raise_request_exception = raise_request_exception
1062 self.exc_info = None
1063 self.extra = None
1064 self.headers = None
1065
1066 def request(self, **request):
1067 """
1068 Make a generic request. Compose the environment dictionary and pass
1069 to the handler, return the result of the handler. Assume defaults for
1070 the query environment, which can be overridden using the arguments to
1071 the request.
1072 """
1073 environ = self._base_environ(**request)
1074
1075 # Curry a data dictionary into an instance of the template renderer
1076 # callback function.
1077 data = {}
1078 on_template_render = partial(store_rendered_templates, data)
1079 signal_uid = "template-render-%s" % id(request)
1080 signals.template_rendered.connect(on_template_render, dispatch_uid=signal_uid)
1081 # Capture exceptions created by the handler.
1082 exception_uid = "request-exception-%s" % id(request)
1083 got_request_exception.connect(self.store_exc_info, dispatch_uid=exception_uid)
1084 try:
1085 response = self.handler(environ)
1086 finally:
1087 signals.template_rendered.disconnect(dispatch_uid=signal_uid)
1088 got_request_exception.disconnect(dispatch_uid=exception_uid)
1089 # Check for signaled exceptions.
1090 self.check_exception(response)
1091 # Save the client and request that stimulated the response.
1092 response.client = self
1093 response.request = request
1094 # Add any rendered template detail to the response.
1095 response.templates = data.get("templates", [])
1096 response.context = data.get("context")
1097 response.json = partial(self._parse_json, response)
1098 # Attach the ResolverMatch instance to the response.
1099 urlconf = getattr(response.wsgi_request, "urlconf", None)
1100 response.resolver_match = SimpleLazyObject(
1101 lambda: resolve(request["PATH_INFO"], urlconf=urlconf),
1102 )
1103 # Flatten a single context. Not really necessary anymore thanks to the
1104 # __getattr__ flattening in ContextList, but has some edge case
1105 # backwards compatibility implications.
1106 if response.context and len(response.context) == 1:
1107 response.context = response.context[0]
1108 # Update persistent cookie data.
1109 if response.cookies:
1110 self.cookies.update(response.cookies)
1111 return response
1112
1113 def get(
1114 self,
1115 path,
1116 data=None,
1117 follow=False,
1118 secure=False,
1119 *,
1120 headers=None,
1121 query_params=None,
1122 **extra,
1123 ):
1124 """Request a response from the server using GET."""
1125 self.extra = extra
1126 self.headers = headers
1127 response = super().get(
1128 path,
1129 data=data,
1130 secure=secure,
1131 headers=headers,
1132 query_params=query_params,
1133 **extra,
1134 )
1135 if follow:
1136 response = self._handle_redirects(
1137 response, data=data, headers=headers, query_params=query_params, **extra
1138 )
1139 return response
1140
1141 def post(
1142 self,
1143 path,
1144 data=None,
1145 content_type=MULTIPART_CONTENT,
1146 follow=False,
1147 secure=False,
1148 *,
1149 headers=None,
1150 query_params=None,
1151 **extra,
1152 ):
1153 """Request a response from the server using POST."""
1154 self.extra = extra
1155 self.headers = headers
1156 response = super().post(
1157 path,
1158 data=data,
1159 content_type=content_type,
1160 secure=secure,
1161 headers=headers,
1162 query_params=query_params,
1163 **extra,
1164 )
1165 if follow:
1166 response = self._handle_redirects(
1167 response,
1168 data=data,
1169 content_type=content_type,
1170 headers=headers,
1171 query_params=query_params,
1172 **extra,
1173 )
1174 return response
1175
1176 def head(
1177 self,
1178 path,
1179 data=None,
1180 follow=False,
1181 secure=False,
1182 *,
1183 headers=None,
1184 query_params=None,
1185 **extra,
1186 ):
1187 """Request a response from the server using HEAD."""
1188 self.extra = extra
1189 self.headers = headers
1190 response = super().head(
1191 path,
1192 data=data,
1193 secure=secure,
1194 headers=headers,
1195 query_params=query_params,
1196 **extra,
1197 )
1198 if follow:
1199 response = self._handle_redirects(
1200 response, data=data, headers=headers, query_params=query_params, **extra
1201 )
1202 return response
1203
1204 def options(
1205 self,
1206 path,
1207 data="",
1208 content_type="application/octet-stream",
1209 follow=False,
1210 secure=False,
1211 *,
1212 headers=None,
1213 query_params=None,
1214 **extra,
1215 ):
1216 """Request a response from the server using OPTIONS."""
1217 self.extra = extra
1218 self.headers = headers
1219 response = super().options(
1220 path,
1221 data=data,
1222 content_type=content_type,
1223 secure=secure,
1224 headers=headers,
1225 query_params=query_params,
1226 **extra,
1227 )
1228 if follow:
1229 response = self._handle_redirects(
1230 response,
1231 data=data,
1232 content_type=content_type,
1233 headers=headers,
1234 query_params=query_params,
1235 **extra,
1236 )
1237 return response
1238
1239 def put(
1240 self,
1241 path,
1242 data="",
1243 content_type="application/octet-stream",
1244 follow=False,
1245 secure=False,
1246 *,
1247 headers=None,
1248 query_params=None,
1249 **extra,
1250 ):
1251 """Send a resource to the server using PUT."""
1252 self.extra = extra
1253 self.headers = headers
1254 response = super().put(
1255 path,
1256 data=data,
1257 content_type=content_type,
1258 secure=secure,
1259 headers=headers,
1260 query_params=query_params,
1261 **extra,
1262 )
1263 if follow:
1264 response = self._handle_redirects(
1265 response,
1266 data=data,
1267 content_type=content_type,
1268 headers=headers,
1269 query_params=query_params,
1270 **extra,
1271 )
1272 return response
1273
1274 def patch(
1275 self,
1276 path,
1277 data="",
1278 content_type="application/octet-stream",
1279 follow=False,
1280 secure=False,
1281 *,
1282 headers=None,
1283 query_params=None,
1284 **extra,
1285 ):
1286 """Send a resource to the server using PATCH."""
1287 self.extra = extra
1288 self.headers = headers
1289 response = super().patch(
1290 path,
1291 data=data,
1292 content_type=content_type,
1293 secure=secure,
1294 headers=headers,
1295 query_params=query_params,
1296 **extra,
1297 )
1298 if follow:
1299 response = self._handle_redirects(
1300 response,
1301 data=data,
1302 content_type=content_type,
1303 headers=headers,
1304 query_params=query_params,
1305 **extra,
1306 )
1307 return response
1308
1309 def delete(
1310 self,
1311 path,
1312 data="",
1313 content_type="application/octet-stream",
1314 follow=False,
1315 secure=False,
1316 *,
1317 headers=None,
1318 query_params=None,
1319 **extra,
1320 ):
1321 """Send a DELETE request to the server."""
1322 self.extra = extra
1323 self.headers = headers
1324 response = super().delete(
1325 path,
1326 data=data,
1327 content_type=content_type,
1328 secure=secure,
1329 headers=headers,
1330 query_params=query_params,
1331 **extra,
1332 )
1333 if follow:
1334 response = self._handle_redirects(
1335 response,
1336 data=data,
1337 content_type=content_type,
1338 headers=headers,
1339 query_params=query_params,
1340 **extra,
1341 )
1342 return response
1343
1344 def trace(
1345 self,
1346 path,
1347 data="",
1348 follow=False,
1349 secure=False,
1350 *,
1351 headers=None,
1352 query_params=None,
1353 **extra,
1354 ):
1355 """Send a TRACE request to the server."""
1356 self.extra = extra
1357 self.headers = headers
1358 response = super().trace(
1359 path,
1360 data=data,
1361 secure=secure,
1362 headers=headers,
1363 query_params=query_params,
1364 **extra,
1365 )
1366 if follow:
1367 response = self._handle_redirects(
1368 response, data=data, headers=headers, query_params=query_params, **extra
1369 )
1370 return response
1371
1372 def _handle_redirects(
1373 self,
1374 response,
1375 data="",
1376 content_type="",
1377 headers=None,
1378 query_params=None,
1379 **extra,
1380 ):
1381 """
1382 Follow any redirects by requesting responses from the server using GET.
1383 """
1384 response.redirect_chain = []
1385 while response.status_code in REDIRECT_STATUS_CODES:
1386 redirect_chain = response.redirect_chain
1387 response = self._follow_redirect(
1388 response,
1389 data=data,
1390 content_type=content_type,
1391 headers=headers,
1392 query_params=query_params,
1393 **extra,
1394 )
1395 response.redirect_chain = redirect_chain
1396 self._ensure_redirects_not_cyclic(response)
1397 return response
1398
1399
1400 class AsyncClient(ClientMixin, AsyncRequestFactory):
1401 """
1402 An async version of Client that creates ASGIRequests and calls through an
1403 async request path.
1404
1405 Does not currently support "follow" on its methods.
1406 """
1407
1408 def __init__(
1409 self,
1410 enforce_csrf_checks=False,
1411 raise_request_exception=True,
1412 *,
1413 headers=None,
1414 query_params=None,
1415 **defaults,
1416 ):
1417 super().__init__(headers=headers, query_params=query_params, **defaults)
1418 self.handler = AsyncClientHandler(enforce_csrf_checks)
1419 self.raise_request_exception = raise_request_exception
1420 self.exc_info = None
1421 self.extra = None
1422 self.headers = None
1423
1424 async def request(self, **request):
1425 """
1426 Make a generic request. Compose the scope dictionary and pass to the
1427 handler, return the result of the handler. Assume defaults for the
1428 query environment, which can be overridden using the arguments to the
1429 request.
1430 """
1431 scope = self._base_scope(**request)
1432 # Curry a data dictionary into an instance of the template renderer
1433 # callback function.
1434 data = {}
1435 on_template_render = partial(store_rendered_templates, data)
1436 signal_uid = "template-render-%s" % id(request)
1437 signals.template_rendered.connect(on_template_render, dispatch_uid=signal_uid)
1438 # Capture exceptions created by the handler.
1439 exception_uid = "request-exception-%s" % id(request)
1440 got_request_exception.connect(self.store_exc_info, dispatch_uid=exception_uid)
1441 try:
1442 response = await self.handler(scope)
1443 finally:
1444 signals.template_rendered.disconnect(dispatch_uid=signal_uid)
1445 got_request_exception.disconnect(dispatch_uid=exception_uid)
1446 # Check for signaled exceptions.
1447 self.check_exception(response)
1448 # Save the client and request that stimulated the response.
1449 response.client = self
1450 response.request = request
1451 # Add any rendered template detail to the response.
1452 response.templates = data.get("templates", [])
1453 response.context = data.get("context")
1454 response.json = partial(self._parse_json, response)
1455 # Attach the ResolverMatch instance to the response.
1456 urlconf = getattr(response.asgi_request, "urlconf", None)
1457 response.resolver_match = SimpleLazyObject(
1458 lambda: resolve(request["path"], urlconf=urlconf),
1459 )
1460 # Flatten a single context. Not really necessary anymore thanks to the
1461 # __getattr__ flattening in ContextList, but has some edge case
1462 # backwards compatibility implications.
1463 if response.context and len(response.context) == 1:
1464 response.context = response.context[0]
1465 # Update persistent cookie data.
1466 if response.cookies:
1467 self.cookies.update(response.cookies)
1468 return response
1469
1470 async def get(
1471 self,
1472 path,
1473 data=None,
1474 follow=False,
1475 secure=False,
1476 *,
1477 headers=None,
1478 query_params=None,
1479 **extra,
1480 ):
1481 """Request a response from the server using GET."""
1482 self.extra = extra
1483 self.headers = headers
1484 response = await super().get(
1485 path,
1486 data=data,
1487 secure=secure,
1488 headers=headers,
1489 query_params=query_params,
1490 **extra,
1491 )
1492 if follow:
1493 response = await self._ahandle_redirects(
1494 response, data=data, headers=headers, query_params=query_params, **extra
1495 )
1496 return response
1497
1498 async def post(
1499 self,
1500 path,
1501 data=None,
1502 content_type=MULTIPART_CONTENT,
1503 follow=False,
1504 secure=False,
1505 *,
1506 headers=None,
1507 query_params=None,
1508 **extra,
1509 ):
1510 """Request a response from the server using POST."""
1511 self.extra = extra
1512 self.headers = headers
1513 response = await super().post(
1514 path,
1515 data=data,
1516 content_type=content_type,
1517 secure=secure,
1518 headers=headers,
1519 query_params=query_params,
1520 **extra,
1521 )
1522 if follow:
1523 response = await self._ahandle_redirects(
1524 response,
1525 data=data,
1526 content_type=content_type,
1527 headers=headers,
1528 query_params=query_params,
1529 **extra,
1530 )
1531 return response
1532
1533 async def head(
1534 self,
1535 path,
1536 data=None,
1537 follow=False,
1538 secure=False,
1539 *,
1540 headers=None,
1541 query_params=None,
1542 **extra,
1543 ):
1544 """Request a response from the server using HEAD."""
1545 self.extra = extra
1546 self.headers = headers
1547 response = await super().head(
1548 path,
1549 data=data,
1550 secure=secure,
1551 headers=headers,
1552 query_params=query_params,
1553 **extra,
1554 )
1555 if follow:
1556 response = await self._ahandle_redirects(
1557 response, data=data, headers=headers, query_params=query_params, **extra
1558 )
1559 return response
1560
1561 async def options(
1562 self,
1563 path,
1564 data="",
1565 content_type="application/octet-stream",
1566 follow=False,
1567 secure=False,
1568 *,
1569 headers=None,
1570 query_params=None,
1571 **extra,
1572 ):
1573 """Request a response from the server using OPTIONS."""
1574 self.extra = extra
1575 self.headers = headers
1576 response = await super().options(
1577 path,
1578 data=data,
1579 content_type=content_type,
1580 secure=secure,
1581 headers=headers,
1582 query_params=query_params,
1583 **extra,
1584 )
1585 if follow:
1586 response = await self._ahandle_redirects(
1587 response,
1588 data=data,
1589 content_type=content_type,
1590 headers=headers,
1591 query_params=query_params,
1592 **extra,
1593 )
1594 return response
1595
1596 async def put(
1597 self,
1598 path,
1599 data="",
1600 content_type="application/octet-stream",
1601 follow=False,
1602 secure=False,
1603 *,
1604 headers=None,
1605 query_params=None,
1606 **extra,
1607 ):
1608 """Send a resource to the server using PUT."""
1609 self.extra = extra
1610 self.headers = headers
1611 response = await super().put(
1612 path,
1613 data=data,
1614 content_type=content_type,
1615 secure=secure,
1616 headers=headers,
1617 query_params=query_params,
1618 **extra,
1619 )
1620 if follow:
1621 response = await self._ahandle_redirects(
1622 response,
1623 data=data,
1624 content_type=content_type,
1625 headers=headers,
1626 query_params=query_params,
1627 **extra,
1628 )
1629 return response
1630
1631 async def patch(
1632 self,
1633 path,
1634 data="",
1635 content_type="application/octet-stream",
1636 follow=False,
1637 secure=False,
1638 *,
1639 headers=None,
1640 query_params=None,
1641 **extra,
1642 ):
1643 """Send a resource to the server using PATCH."""
1644 self.extra = extra
1645 self.headers = headers
1646 response = await super().patch(
1647 path,
1648 data=data,
1649 content_type=content_type,
1650 secure=secure,
1651 headers=headers,
1652 query_params=query_params,
1653 **extra,
1654 )
1655 if follow:
1656 response = await self._ahandle_redirects(
1657 response,
1658 data=data,
1659 content_type=content_type,
1660 headers=headers,
1661 query_params=query_params,
1662 **extra,
1663 )
1664 return response
1665
1666 async def delete(
1667 self,
1668 path,
1669 data="",
1670 content_type="application/octet-stream",
1671 follow=False,
1672 secure=False,
1673 *,
1674 headers=None,
1675 query_params=None,
1676 **extra,
1677 ):
1678 """Send a DELETE request to the server."""
1679 self.extra = extra
1680 self.headers = headers
1681 response = await super().delete(
1682 path,
1683 data=data,
1684 content_type=content_type,
1685 secure=secure,
1686 headers=headers,
1687 query_params=query_params,
1688 **extra,
1689 )
1690 if follow:
1691 response = await self._ahandle_redirects(
1692 response,
1693 data=data,
1694 content_type=content_type,
1695 headers=headers,
1696 query_params=query_params,
1697 **extra,
1698 )
1699 return response
1700
1701 async def trace(
1702 self,
1703 path,
1704 data="",
1705 follow=False,
1706 secure=False,
1707 *,
1708 headers=None,
1709 query_params=None,
1710 **extra,
1711 ):
1712 """Send a TRACE request to the server."""
1713 self.extra = extra
1714 self.headers = headers
1715 response = await super().trace(
1716 path,
1717 data=data,
1718 secure=secure,
1719 headers=headers,
1720 query_params=query_params,
1721 **extra,
1722 )
1723 if follow:
1724 response = await self._ahandle_redirects(
1725 response, data=data, headers=headers, query_params=query_params, **extra
1726 )
1727 return response
1728
1729 async def _ahandle_redirects(
1730 self,
1731 response,
1732 data="",
1733 content_type="",
1734 headers=None,
1735 query_params=None,
1736 **extra,
1737 ):
1738 """
1739 Follow any redirects by requesting responses from the server using GET.
1740 """
1741 response.redirect_chain = []
1742 while response.status_code in REDIRECT_STATUS_CODES:
1743 redirect_chain = response.redirect_chain
1744 response = await self._follow_redirect(
1745 response,
1746 data=data,
1747 content_type=content_type,
1748 headers=headers,
1749 query_params=query_params,
1750 **extra,
1751 )
1752 response.redirect_chain = redirect_chain
1753 self._ensure_redirects_not_cyclic(response)
1754 return response