summaryrefslogtreecommitdiff
path: root/tests/asgi/tests.py
blob: d97022fc92d7a467058b0ad96f16b2e9ca2dbfb9 (plain)
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
import asyncio
import sys
import threading
import time
from io import BytesIO
from pathlib import Path

from asgiref.sync import sync_to_async
from asgiref.testing import ApplicationCommunicator

from django.contrib.staticfiles.handlers import ASGIStaticFilesHandler
from django.core.asgi import get_asgi_application
from django.core.exceptions import RequestDataTooBig
from django.core.handlers.asgi import ASGIHandler, ASGIRequest
from django.core.signals import request_finished, request_started
from django.db import close_old_connections
from django.http import HttpResponse, StreamingHttpResponse
from django.test import (
    AsyncRequestFactory,
    SimpleTestCase,
    ignore_warnings,
    modify_settings,
    override_settings,
)
from django.test.utils import captured_stderr
from django.urls import path
from django.utils.http import http_date
from django.views.decorators.csrf import csrf_exempt

from .urls import sync_waiter, test_filename

TEST_STATIC_ROOT = Path(__file__).parent / "project" / "static"
TOO_MUCH_DATA_MSG = "Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE."


class SignalHandler:
    """Helper class to track threads and kwargs when signals are dispatched."""

    def __init__(self):
        super().__init__()
        self.calls = []

    def __call__(self, signal, **kwargs):
        self.calls.append({"thread": threading.current_thread(), "kwargs": kwargs})


@override_settings(ROOT_URLCONF="asgi.urls")
class ASGITest(SimpleTestCase):
    async_request_factory = AsyncRequestFactory()

    def setUp(self):
        request_started.disconnect(close_old_connections)
        self.addCleanup(request_started.connect, close_old_connections)

    async def test_get_asgi_application(self):
        """
        get_asgi_application() returns a functioning ASGI callable.
        """
        application = get_asgi_application()
        # Construct HTTP request.
        scope = self.async_request_factory._base_scope(path="/")
        communicator = ApplicationCommunicator(application, scope)
        await communicator.send_input({"type": "http.request"})
        # Read the response.
        response_start = await communicator.receive_output()
        self.assertEqual(response_start["type"], "http.response.start")
        self.assertEqual(response_start["status"], 200)
        self.assertEqual(
            set(response_start["headers"]),
            {
                (b"Content-Length", b"12"),
                (b"Content-Type", b"text/html; charset=utf-8"),
            },
        )
        response_body = await communicator.receive_output()
        self.assertEqual(response_body["type"], "http.response.body")
        self.assertEqual(response_body["body"], b"Hello World!")
        # Allow response.close() to finish.
        await communicator.wait()

    # Python's file API is not async compatible. A third-party library such
    # as https://github.com/Tinche/aiofiles allows passing the file to
    # FileResponse as an async iterator. With a sync iterator
    # StreamingHTTPResponse triggers a warning when iterating the file.
    # assertWarnsMessage is not async compatible, so ignore_warnings for the
    # test.
    @ignore_warnings(module="django.http.response")
    async def test_file_response(self):
        """
        Makes sure that FileResponse works over ASGI.
        """
        application = get_asgi_application()
        # Construct HTTP request.
        scope = self.async_request_factory._base_scope(path="/file/")
        communicator = ApplicationCommunicator(application, scope)
        await communicator.send_input({"type": "http.request"})
        # Get the file content.
        with open(test_filename, "rb") as test_file:
            test_file_contents = test_file.read()
        # Read the response.
        with captured_stderr():
            response_start = await communicator.receive_output()
        self.assertEqual(response_start["type"], "http.response.start")
        self.assertEqual(response_start["status"], 200)
        headers = response_start["headers"]
        self.assertEqual(len(headers), 3)
        expected_headers = {
            b"Content-Length": str(len(test_file_contents)).encode("ascii"),
            b"Content-Type": b"text/x-python",
            b"Content-Disposition": b'inline; filename="urls.py"',
        }
        for key, value in headers:
            try:
                self.assertEqual(value, expected_headers[key])
            except AssertionError:
                # Windows registry may not be configured with correct
                # mimetypes.
                if sys.platform == "win32" and key == b"Content-Type":
                    self.assertEqual(value, b"text/plain")
                else:
                    raise

        # Warning ignored here.
        response_body = await communicator.receive_output()
        self.assertEqual(response_body["type"], "http.response.body")
        self.assertEqual(response_body["body"], test_file_contents)
        # Allow response.close() to finish.
        await communicator.wait()

    @modify_settings(INSTALLED_APPS={"append": "django.contrib.staticfiles"})
    @override_settings(
        STATIC_URL="static/",
        STATIC_ROOT=TEST_STATIC_ROOT,
        STATICFILES_DIRS=[TEST_STATIC_ROOT],
        STATICFILES_FINDERS=[
            "django.contrib.staticfiles.finders.FileSystemFinder",
        ],
    )
    async def test_static_file_response(self):
        application = ASGIStaticFilesHandler(get_asgi_application())
        # Construct HTTP request.
        scope = self.async_request_factory._base_scope(path="/static/file.txt")
        communicator = ApplicationCommunicator(application, scope)
        await communicator.send_input({"type": "http.request"})
        # Get the file content.
        file_path = TEST_STATIC_ROOT / "file.txt"
        with open(file_path, "rb") as test_file:
            test_file_contents = test_file.read()
        # Read the response.
        stat = file_path.stat()
        response_start = await communicator.receive_output()
        self.assertEqual(response_start["type"], "http.response.start")
        self.assertEqual(response_start["status"], 200)
        self.assertEqual(
            set(response_start["headers"]),
            {
                (b"Content-Length", str(len(test_file_contents)).encode("ascii")),
                (b"Content-Type", b"text/plain"),
                (b"Content-Disposition", b'inline; filename="file.txt"'),
                (b"Last-Modified", http_date(stat.st_mtime).encode("ascii")),
            },
        )
        response_body = await communicator.receive_output()
        self.assertEqual(response_body["type"], "http.response.body")
        self.assertEqual(response_body["body"], test_file_contents)
        # Allow response.close() to finish.
        await communicator.wait()

    async def test_headers(self):
        application = get_asgi_application()
        communicator = ApplicationCommunicator(
            application,
            self.async_request_factory._base_scope(
                path="/meta/",
                headers=[
                    [b"content-type", b"text/plain; charset=utf-8"],
                    [b"content-length", b"77"],
                    [b"referer", b"Scotland"],
                    [b"referer", b"Wales"],
                ],
            ),
        )
        await communicator.send_input({"type": "http.request"})
        response_start = await communicator.receive_output()
        self.assertEqual(response_start["type"], "http.response.start")
        self.assertEqual(response_start["status"], 200)
        self.assertEqual(
            set(response_start["headers"]),
            {
                (b"Content-Length", b"19"),
                (b"Content-Type", b"text/plain; charset=utf-8"),
            },
        )
        response_body = await communicator.receive_output()
        self.assertEqual(response_body["type"], "http.response.body")
        self.assertEqual(response_body["body"], b"From Scotland,Wales")
        # Allow response.close() to finish
        await communicator.wait()

    async def test_post_body(self):
        application = get_asgi_application()
        scope = self.async_request_factory._base_scope(
            method="POST",
            path="/post/",
            query_string="echo=1",
        )
        communicator = ApplicationCommunicator(application, scope)
        await communicator.send_input({"type": "http.request", "body": b"Echo!"})
        response_start = await communicator.receive_output()
        self.assertEqual(response_start["type"], "http.response.start")
        self.assertEqual(response_start["status"], 200)
        response_body = await communicator.receive_output()
        self.assertEqual(response_body["type"], "http.response.body")
        self.assertEqual(response_body["body"], b"Echo!")

    async def test_request_too_big_request_error(self):
        # Track request_finished signal.
        signal_handler = SignalHandler()
        request_finished.connect(signal_handler)
        self.addCleanup(request_finished.disconnect, signal_handler)

        # Request class that always fails creation with RequestDataTooBig.
        class TestASGIRequest(ASGIRequest):

            def __init__(self, scope, body_file):
                super().__init__(scope, body_file)
                raise RequestDataTooBig()

        # Handler to use the custom request class.
        class TestASGIHandler(ASGIHandler):
            request_class = TestASGIRequest

        application = TestASGIHandler()
        scope = self.async_request_factory._base_scope(path="/not-important/")
        communicator = ApplicationCommunicator(application, scope)

        # Initiate request.
        await communicator.send_input({"type": "http.request"})
        # Give response.close() time to finish.
        await communicator.wait()

        self.assertEqual(len(signal_handler.calls), 1)
        self.assertNotEqual(
            signal_handler.calls[0]["thread"], threading.current_thread()
        )

    async def test_meta_not_modified_with_repeat_headers(self):
        scope = self.async_request_factory._base_scope(path="/", http_version="2.0")
        scope["headers"] = [(b"foo", b"bar")] * 200_000

        setitem_count = 0

        class InstrumentedDict(dict):
            def __setitem__(self, *args, **kwargs):
                nonlocal setitem_count
                setitem_count += 1
                super().__setitem__(*args, **kwargs)

        class InstrumentedASGIRequest(ASGIRequest):
            @property
            def META(self):
                return self._meta

            @META.setter
            def META(self, value):
                self._meta = InstrumentedDict(**value)

        request = InstrumentedASGIRequest(scope, None)

        self.assertEqual(len(request.headers["foo"].split(",")), 200_000)
        self.assertLessEqual(setitem_count, 100)

    async def test_underscores_in_headers_ignored(self):
        scope = self.async_request_factory._base_scope(path="/", http_version="2.0")
        scope["headers"] = [(b"some_header", b"1")]
        request = ASGIRequest(scope, None)
        # No form of the header exists anywhere.
        self.assertNotIn("Some_Header", request.headers)
        self.assertNotIn("Some-Header", request.headers)
        self.assertNotIn("SOME_HEADER", request.META)
        self.assertNotIn("SOME-HEADER", request.META)
        self.assertNotIn("HTTP_SOME_HEADER", request.META)

    async def test_cancel_post_request_with_sync_processing(self):
        """
        The request.body object should be available and readable in view
        code, even if the ASGIHandler cancels processing part way through.
        """
        loop = asyncio.get_event_loop()
        # Events to monitor the view processing from the parent test code.
        view_started_event = asyncio.Event()
        view_finished_event = asyncio.Event()
        # Record received request body or exceptions raised in the test view
        outcome = []

        # This view will run in a new thread because it is wrapped in
        # sync_to_async. The view consumes the POST body data after a short
        # delay. The test will cancel the request using http.disconnect during
        # the delay, but because this is a sync view the code runs to
        # completion. There should be no exceptions raised inside the view
        # code.
        @csrf_exempt
        @sync_to_async
        def post_view(request):
            try:
                loop.call_soon_threadsafe(view_started_event.set)
                time.sleep(0.1)
                # Do something to read request.body after pause
                outcome.append({"request_body": request.body})
                return HttpResponse("ok")
            except Exception as e:
                outcome.append({"exception": e})
            finally:
                loop.call_soon_threadsafe(view_finished_event.set)

        # Request class to use the view.
        class TestASGIRequest(ASGIRequest):
            urlconf = (path("post/", post_view),)

        # Handler to use request class.
        class TestASGIHandler(ASGIHandler):
            request_class = TestASGIRequest

        application = TestASGIHandler()
        scope = self.async_request_factory._base_scope(
            method="POST",
            path="/post/",
        )
        communicator = ApplicationCommunicator(application, scope)

        await communicator.send_input({"type": "http.request", "body": b"Body data!"})

        # Wait until the view code has started, then send http.disconnect.
        await view_started_event.wait()
        await communicator.send_input({"type": "http.disconnect"})
        # Wait until view code has finished.
        await view_finished_event.wait()
        with self.assertRaises(asyncio.TimeoutError):
            await communicator.receive_output()

        self.assertEqual(outcome, [{"request_body": b"Body data!"}])

    async def test_untouched_request_body_gets_closed(self):
        application = get_asgi_application()
        scope = self.async_request_factory._base_scope(method="POST", path="/post/")
        communicator = ApplicationCommunicator(application, scope)
        await communicator.send_input({"type": "http.request"})
        response_start = await communicator.receive_output()
        self.assertEqual(response_start["type"], "http.response.start")
        self.assertEqual(response_start["status"], 204)
        response_body = await communicator.receive_output()
        self.assertEqual(response_body["type"], "http.response.body")
        self.assertEqual(response_body["body"], b"")
        # Allow response.close() to finish
        await communicator.wait()

    async def test_get_query_string(self):
        application = get_asgi_application()
        for query_string in (b"name=Andrew", "name=Andrew"):
            with self.subTest(query_string=query_string):
                scope = self.async_request_factory._base_scope(
                    path="/",
                    query_string=query_string,
                )
                communicator = ApplicationCommunicator(application, scope)
                await communicator.send_input({"type": "http.request"})
                response_start = await communicator.receive_output()
                self.assertEqual(response_start["type"], "http.response.start")
                self.assertEqual(response_start["status"], 200)
                response_body = await communicator.receive_output()
                self.assertEqual(response_body["type"], "http.response.body")
                self.assertEqual(response_body["body"], b"Hello Andrew!")
                # Allow response.close() to finish
                await communicator.wait()

    async def test_disconnect(self):
        application = get_asgi_application()
        scope = self.async_request_factory._base_scope(path="/")
        communicator = ApplicationCommunicator(application, scope)
        await communicator.send_input({"type": "http.disconnect"})
        with self.assertRaises(asyncio.TimeoutError):
            await communicator.receive_output()

    async def test_disconnect_both_return(self):
        # Force both the disconnect listener and the task that sends the
        # response to finish at the same time.
        application = get_asgi_application()
        scope = self.async_request_factory._base_scope(path="/")
        communicator = ApplicationCommunicator(application, scope)
        await communicator.send_input({"type": "http.request", "body": b"some body"})
        # Fetch response headers (this yields to asyncio and causes
        # ASGHandler.send_response() to dump the body of the response in the
        # queue).
        await communicator.receive_output()
        # Fetch response body (there's already some data queued up, so this
        # doesn't actually yield to the event loop, it just succeeds
        # instantly).
        await communicator.receive_output()
        # Send disconnect at the same time that response finishes (this just
        # puts some info in a queue, it doesn't have to yield to the event
        # loop).
        await communicator.send_input({"type": "http.disconnect"})
        # Waiting for the communicator _does_ yield to the event loop, since
        # ASGIHandler.send_response() is still waiting to do response.close().
        # It so happens that there are enough remaining yield points in both
        # tasks that they both finish while the loop is running.
        await communicator.wait()

    async def test_disconnect_with_body(self):
        application = get_asgi_application()
        scope = self.async_request_factory._base_scope(path="/")
        communicator = ApplicationCommunicator(application, scope)
        await communicator.send_input({"type": "http.request", "body": b"some body"})
        await communicator.send_input({"type": "http.disconnect"})
        with self.assertRaises(asyncio.TimeoutError):
            await communicator.receive_output()

    async def test_assert_in_listen_for_disconnect(self):
        application = get_asgi_application()
        scope = self.async_request_factory._base_scope(path="/")
        communicator = ApplicationCommunicator(application, scope)
        await communicator.send_input({"type": "http.request"})
        await communicator.send_input({"type": "http.not_a_real_message"})
        msg = "Invalid ASGI message after request body: http.not_a_real_message"
        with self.assertRaisesMessage(AssertionError, msg):
            await communicator.wait()

    async def test_delayed_disconnect_with_body(self):
        application = get_asgi_application()
        scope = self.async_request_factory._base_scope(path="/delayed_hello/")
        communicator = ApplicationCommunicator(application, scope)
        await communicator.send_input({"type": "http.request", "body": b"some body"})
        await communicator.send_input({"type": "http.disconnect"})
        with self.assertRaises(asyncio.TimeoutError):
            await communicator.receive_output()

    async def test_wrong_connection_type(self):
        application = get_asgi_application()
        scope = self.async_request_factory._base_scope(path="/", type="other")
        communicator = ApplicationCommunicator(application, scope)
        await communicator.send_input({"type": "http.request"})
        msg = "Django can only handle ASGI/HTTP connections, not other."
        with self.assertRaisesMessage(ValueError, msg):
            await communicator.receive_output()

    async def test_non_unicode_query_string(self):
        application = get_asgi_application()
        scope = self.async_request_factory._base_scope(path="/", query_string=b"\xff")
        communicator = ApplicationCommunicator(application, scope)
        await communicator.send_input({"type": "http.request"})
        response_start = await communicator.receive_output()
        self.assertEqual(response_start["type"], "http.response.start")
        self.assertEqual(response_start["status"], 400)
        response_body = await communicator.receive_output()
        self.assertEqual(response_body["type"], "http.response.body")
        self.assertEqual(response_body["body"], b"")

    async def test_request_lifecycle_signals_dispatched_with_thread_sensitive(self):
        # Track request_started and request_finished signals.
        signal_handler = SignalHandler()
        request_started.connect(signal_handler)
        self.addCleanup(request_started.disconnect, signal_handler)
        request_finished.connect(signal_handler)
        self.addCleanup(request_finished.disconnect, signal_handler)

        # Perform a basic request.
        application = get_asgi_application()
        scope = self.async_request_factory._base_scope(path="/")
        communicator = ApplicationCommunicator(application, scope)
        await communicator.send_input({"type": "http.request"})
        response_start = await communicator.receive_output()
        self.assertEqual(response_start["type"], "http.response.start")
        self.assertEqual(response_start["status"], 200)
        response_body = await communicator.receive_output()
        self.assertEqual(response_body["type"], "http.response.body")
        self.assertEqual(response_body["body"], b"Hello World!")
        # Give response.close() time to finish.
        await communicator.wait()

        # AsyncToSync should have executed the signals in the same thread.
        self.assertEqual(len(signal_handler.calls), 2)
        request_started_call, request_finished_call = signal_handler.calls
        self.assertEqual(
            request_started_call["thread"], request_finished_call["thread"]
        )

    async def test_concurrent_async_uses_multiple_thread_pools(self):
        sync_waiter.active_threads.clear()

        # Send 2 requests concurrently
        application = get_asgi_application()
        scope = self.async_request_factory._base_scope(path="/wait/")
        communicators = []
        for _ in range(2):
            communicators.append(ApplicationCommunicator(application, scope))
            await communicators[-1].send_input({"type": "http.request"})

        # Each request must complete with a status code of 200
        # If requests aren't scheduled concurrently, the barrier in the
        # sync_wait view will time out, resulting in a 500 status code.
        for communicator in communicators:
            response_start = await communicator.receive_output()
            self.assertEqual(response_start["type"], "http.response.start")
            self.assertEqual(response_start["status"], 200)
            response_body = await communicator.receive_output()
            self.assertEqual(response_body["type"], "http.response.body")
            self.assertEqual(response_body["body"], b"Hello World!")
            # Give response.close() time to finish.
            await communicator.wait()

        # The requests should have scheduled on different threads. Note
        # active_threads is a set (a thread can only appear once), therefore
        # length is a sufficient check.
        self.assertEqual(len(sync_waiter.active_threads), 2)

        sync_waiter.active_threads.clear()

    async def test_asyncio_cancel_error(self):
        view_started = asyncio.Event()
        # Flag to check if the view was cancelled.
        view_did_cancel = False
        # Track request_finished signal.
        signal_handler = SignalHandler()
        request_finished.connect(signal_handler)
        self.addCleanup(request_finished.disconnect, signal_handler)

        # A view that will listen for the cancelled error.
        async def view(request):
            nonlocal view_did_cancel
            view_started.set()
            try:
                await asyncio.sleep(0.1)
                return HttpResponse("Hello World!")
            except asyncio.CancelledError:
                # Set the flag.
                view_did_cancel = True
                raise

        # Request class to use the view.
        class TestASGIRequest(ASGIRequest):
            urlconf = (path("cancel/", view),)

        # Handler to use request class.
        class TestASGIHandler(ASGIHandler):
            request_class = TestASGIRequest

        # Request cycle should complete since no disconnect was sent.
        application = TestASGIHandler()
        scope = self.async_request_factory._base_scope(path="/cancel/")
        communicator = ApplicationCommunicator(application, scope)
        await communicator.send_input({"type": "http.request"})
        response_start = await communicator.receive_output()
        self.assertEqual(response_start["type"], "http.response.start")
        self.assertEqual(response_start["status"], 200)
        response_body = await communicator.receive_output()
        self.assertEqual(response_body["type"], "http.response.body")
        self.assertEqual(response_body["body"], b"Hello World!")
        # Give response.close() time to finish.
        await communicator.wait()
        self.assertIs(view_did_cancel, False)
        # Exactly one call to request_finished handler.
        self.assertEqual(len(signal_handler.calls), 1)
        handler_call = signal_handler.calls.pop()
        # It was NOT on the async thread.
        self.assertNotEqual(handler_call["thread"], threading.current_thread())
        # The signal sender is the handler class.
        self.assertEqual(handler_call["kwargs"], {"sender": TestASGIHandler})
        view_started.clear()

        # Request cycle with a disconnect before the view can respond.
        application = TestASGIHandler()
        scope = self.async_request_factory._base_scope(path="/cancel/")
        communicator = ApplicationCommunicator(application, scope)
        await communicator.send_input({"type": "http.request"})
        # Let the view actually start.
        await view_started.wait()
        # Disconnect the client.
        await communicator.send_input({"type": "http.disconnect"})
        # The handler should not send a response.
        with self.assertRaises(asyncio.TimeoutError):
            await communicator.receive_output()
        await communicator.wait()
        self.assertIs(view_did_cancel, True)
        # Exactly one call to request_finished handler.
        self.assertEqual(len(signal_handler.calls), 1)
        handler_call = signal_handler.calls.pop()
        # It was NOT on the async thread.
        self.assertNotEqual(handler_call["thread"], threading.current_thread())
        # The signal sender is the handler class.
        self.assertEqual(handler_call["kwargs"], {"sender": TestASGIHandler})

    async def test_asyncio_streaming_cancel_error(self):
        # Similar to test_asyncio_cancel_error(), but during a streaming
        # response.
        view_did_cancel = False
        # Track request_finished signals.
        signal_handler = SignalHandler()
        request_finished.connect(signal_handler)
        self.addCleanup(request_finished.disconnect, signal_handler)

        async def streaming_response():
            nonlocal view_did_cancel
            try:
                await asyncio.sleep(0.2)
                yield b"Hello World!"
            except asyncio.CancelledError:
                # Set the flag.
                view_did_cancel = True
                raise

        async def view(request):
            return StreamingHttpResponse(streaming_response())

        class TestASGIRequest(ASGIRequest):
            urlconf = (path("cancel/", view),)

        class TestASGIHandler(ASGIHandler):
            request_class = TestASGIRequest

        # With no disconnect, the request cycle should complete in the same
        # manner as the non-streaming response.
        application = TestASGIHandler()
        scope = self.async_request_factory._base_scope(path="/cancel/")
        communicator = ApplicationCommunicator(application, scope)
        await communicator.send_input({"type": "http.request"})
        response_start = await communicator.receive_output()
        self.assertEqual(response_start["type"], "http.response.start")
        self.assertEqual(response_start["status"], 200)
        response_body = await communicator.receive_output()
        self.assertEqual(response_body["type"], "http.response.body")
        self.assertEqual(response_body["body"], b"Hello World!")
        await communicator.wait()
        self.assertIs(view_did_cancel, False)
        # Exactly one call to request_finished handler.
        self.assertEqual(len(signal_handler.calls), 1)
        handler_call = signal_handler.calls.pop()
        # It was NOT on the async thread.
        self.assertNotEqual(handler_call["thread"], threading.current_thread())
        # The signal sender is the handler class.
        self.assertEqual(handler_call["kwargs"], {"sender": TestASGIHandler})

        # Request cycle with a disconnect.
        application = TestASGIHandler()
        scope = self.async_request_factory._base_scope(path="/cancel/")
        communicator = ApplicationCommunicator(application, scope)
        await communicator.send_input({"type": "http.request"})
        response_start = await communicator.receive_output()
        # Fetch the start of response so streaming can begin
        self.assertEqual(response_start["type"], "http.response.start")
        self.assertEqual(response_start["status"], 200)
        await asyncio.sleep(0.1)
        # Now disconnect the client.
        await communicator.send_input({"type": "http.disconnect"})
        # This time the handler should not send a response.
        with self.assertRaises(asyncio.TimeoutError):
            await communicator.receive_output()
        await communicator.wait()
        self.assertIs(view_did_cancel, True)
        # Exactly one call to request_finished handler.
        self.assertEqual(len(signal_handler.calls), 1)
        handler_call = signal_handler.calls.pop()
        # It was NOT on the async thread.
        self.assertNotEqual(handler_call["thread"], threading.current_thread())
        # The signal sender is the handler class.
        self.assertEqual(handler_call["kwargs"], {"sender": TestASGIHandler})

    async def test_streaming(self):
        scope = self.async_request_factory._base_scope(
            path="/streaming/", query_string=b"sleep=0.001"
        )
        application = get_asgi_application()
        communicator = ApplicationCommunicator(application, scope)
        await communicator.send_input({"type": "http.request"})
        # Fetch http.response.start.
        await communicator.receive_output(timeout=1)
        # Fetch the 'first' and 'last'.
        first_response = await communicator.receive_output(timeout=1)
        self.assertEqual(first_response["body"], b"first\n")
        second_response = await communicator.receive_output(timeout=1)
        self.assertEqual(second_response["body"], b"last\n")
        # Fetch the rest of the response so that coroutines are cleaned up.
        await communicator.receive_output(timeout=1)
        with self.assertRaises(asyncio.TimeoutError):
            await communicator.receive_output(timeout=1)

    async def test_streaming_disconnect(self):
        scope = self.async_request_factory._base_scope(
            path="/streaming/", query_string=b"sleep=0.1"
        )
        application = get_asgi_application()
        communicator = ApplicationCommunicator(application, scope)
        await communicator.send_input({"type": "http.request"})
        await communicator.receive_output(timeout=1)
        first_response = await communicator.receive_output(timeout=1)
        self.assertEqual(first_response["body"], b"first\n")
        # Disconnect the client.
        await communicator.send_input({"type": "http.disconnect"})
        # 'last\n' isn't sent.
        with self.assertRaises(asyncio.TimeoutError):
            await communicator.receive_output(timeout=0.2)


class DataUploadMaxMemorySizeASGITests(SimpleTestCase):

    def make_request(
        self,
        body,
        content_type=b"application/octet-stream",
        content_length=None,
        stream=None,
    ):
        scope = AsyncRequestFactory()._base_scope(method="POST", path="/")
        scope["headers"] = [(b"content-type", content_type)]
        if content_length is not None:
            scope["headers"].append((b"content-length", str(content_length).encode()))
        return ASGIRequest(scope, stream if stream is not None else BytesIO(body))

    def test_body_size_not_exceeded_without_content_length(self):
        body = b"x" * 5
        with self.settings(DATA_UPLOAD_MAX_MEMORY_SIZE=5):
            self.assertEqual(self.make_request(body).body, body)

    def test_body_size_exceeded_without_content_length(self):
        request = self.make_request(b"x" * 10)
        with (
            self.settings(DATA_UPLOAD_MAX_MEMORY_SIZE=5),
            self.assertRaisesMessage(RequestDataTooBig, TOO_MUCH_DATA_MSG),
        ):
            request.body

    def test_body_size_check_fires_before_read(self):
        # The seekable size check rejects oversized bodies before reading
        # them into memory (i.e. before calling self.read()).
        class TrackingBytesIO(BytesIO):
            calls = []

            def read(self, *args, **kwargs):
                self.calls.append((args, kwargs))
                return super().read(*args, **kwargs)

        stream = TrackingBytesIO(b"x" * 10)
        request = self.make_request(b"x" * 10, stream=stream)
        with (
            self.settings(DATA_UPLOAD_MAX_MEMORY_SIZE=5),
            self.assertRaisesMessage(RequestDataTooBig, TOO_MUCH_DATA_MSG),
        ):
            request.body

        self.assertEqual(stream.calls, [])

    def test_post_size_exceeded_without_content_length(self):
        request = self.make_request(
            b"a=" + b"x" * 10,
            content_type=b"application/x-www-form-urlencoded",
        )
        with (
            self.settings(DATA_UPLOAD_MAX_MEMORY_SIZE=5),
            self.assertRaisesMessage(RequestDataTooBig, TOO_MUCH_DATA_MSG),
        ):
            request.POST

    def test_no_limit(self):
        body = b"x" * 100
        with self.settings(DATA_UPLOAD_MAX_MEMORY_SIZE=None):
            self.assertEqual(self.make_request(body).body, body)

    async def test_read_body_no_limit(self):
        chunks = [
            {"type": "http.request", "body": b"x" * 100, "more_body": True},
            {"type": "http.request", "body": b"x" * 100, "more_body": False},
        ]

        async def receive():
            return chunks.pop(0)

        handler = ASGIHandler()
        with self.settings(DATA_UPLOAD_MAX_MEMORY_SIZE=None):
            body_file = await handler.read_body(receive)
            self.addCleanup(body_file.close)

        body_file.seek(0)
        self.assertEqual(body_file.read(), b"x" * 200)

    def test_non_multipart_body_size_enforced(self):
        # DATA_UPLOAD_MAX_MEMORY_SIZE is enforced on non-multipart bodies.
        request = self.make_request(b"x" * 100)
        with (
            self.settings(DATA_UPLOAD_MAX_MEMORY_SIZE=10),
            self.assertRaisesMessage(RequestDataTooBig, TOO_MUCH_DATA_MSG),
        ):
            request.body

    def test_multipart_file_upload_not_limited_by_data_upload_max(self):
        # DATA_UPLOAD_MAX_MEMORY_SIZE applies to non-file fields only; a file
        # upload whose total body exceeds the limit must still succeed.
        boundary = "testboundary"
        file_content = b"x" * 100
        body = (
            (
                f"--{boundary}\r\n"
                f'Content-Disposition: form-data; name="file"; filename="test.txt"\r\n'
                f"Content-Type: application/octet-stream\r\n"
                f"\r\n"
            ).encode()
            + file_content
            + f"\r\n--{boundary}--\r\n".encode()
        )
        request = self.make_request(
            body,
            content_type=f"multipart/form-data; boundary={boundary}".encode(),
            content_length=len(body),
        )
        with self.settings(
            DATA_UPLOAD_MAX_MEMORY_SIZE=10, FILE_UPLOAD_MAX_MEMORY_SIZE=10
        ):
            files = request.FILES
        self.assertEqual(len(files), 1)
        uploaded = files["file"]
        self.addCleanup(uploaded.close)
        self.assertEqual(uploaded.read(), file_content)

    async def test_read_body_buffers_all_chunks(self):
        # read_body() consumes all chunks regardless of
        # DATA_UPLOAD_MAX_MEMORY_SIZE; the limit is enforced later when
        # HttpRequest.body is accessed.
        chunks = [
            {"type": "http.request", "body": b"x" * 10, "more_body": True},
            {"type": "http.request", "body": b"y" * 10, "more_body": True},
            {"type": "http.request", "body": b"z" * 10, "more_body": False},
        ]

        async def receive():
            return chunks.pop(0)

        handler = ASGIHandler()
        with self.settings(DATA_UPLOAD_MAX_MEMORY_SIZE=15):
            body_file = await handler.read_body(receive)
            self.addCleanup(body_file.close)

        self.assertEqual(len(chunks), 0)  # All chunks were consumed.
        body_file.seek(0)
        self.assertEqual(body_file.read(), b"x" * 10 + b"y" * 10 + b"z" * 10)

    async def test_read_body_multipart_not_limited(self):
        # All chunks are consumed regardless of DATA_UPLOAD_MAX_MEMORY_SIZE;
        # multipart size enforcement happens inside MultiPartParser, not here.
        chunks = [
            {"type": "http.request", "body": b"x" * 10, "more_body": True},
            {"type": "http.request", "body": b"y" * 10, "more_body": True},
            {"type": "http.request", "body": b"z" * 10, "more_body": False},
        ]

        async def receive():
            return chunks.pop(0)

        handler = ASGIHandler()
        with self.settings(DATA_UPLOAD_MAX_MEMORY_SIZE=15):
            body_file = await handler.read_body(receive)
            self.addCleanup(body_file.close)

        self.assertEqual(len(chunks), 0)  # All chunks were consumed.
        body_file.seek(0)
        self.assertEqual(body_file.read(), b"x" * 10 + b"y" * 10 + b"z" * 10)