File: test_sync.py

package info (click to toggle)
python-asgiref 3.9.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 428 kB
  • sloc: python: 2,635; makefile: 19
file content (1283 lines) | stat: -rw-r--r-- 35,023 bytes parent folder | download
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
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
import asyncio
import functools
import multiprocessing
import sys
import threading
import time
import warnings
from concurrent.futures import ThreadPoolExecutor
from functools import wraps
from typing import Any
from unittest import TestCase

import pytest

from asgiref.sync import (
    ThreadSensitiveContext,
    async_to_sync,
    iscoroutinefunction,
    sync_to_async,
)
from asgiref.timeout import timeout


@pytest.mark.asyncio
async def test_sync_to_async():
    """
    Tests we can call sync functions from an async thread
    (even if the number of thread workers is less than the number of calls)
    """
    # Define sync function
    def sync_function():
        time.sleep(1)
        return 42

    # Ensure outermost detection works
    # Wrap it
    async_function = sync_to_async(sync_function)
    # Check it works right
    start = time.monotonic()
    result = await async_function()
    end = time.monotonic()
    assert result == 42
    assert end - start >= 1
    # Set workers to 1, call it twice and make sure that works right
    loop = asyncio.get_running_loop()
    old_executor = loop._default_executor or ThreadPoolExecutor()
    loop.set_default_executor(ThreadPoolExecutor(max_workers=1))
    try:
        start = time.monotonic()
        await asyncio.wait(
            [
                asyncio.create_task(async_function()),
                asyncio.create_task(async_function()),
            ]
        )
        end = time.monotonic()
        # It should take at least 2 seconds as there's only one worker.
        assert end - start >= 2
    finally:
        loop.set_default_executor(old_executor)


def test_sync_to_async_fail_non_function():
    """
    async_to_sync raises a TypeError when called with a non-function.
    """
    with pytest.raises(TypeError) as excinfo:
        sync_to_async(1)

    assert excinfo.value.args == (
        "sync_to_async can only be applied to sync functions.",
    )


@pytest.mark.asyncio
async def test_sync_to_async_fail_async():
    """
    sync_to_async raises a TypeError when applied to a sync function.
    """
    with pytest.raises(TypeError) as excinfo:

        @sync_to_async
        async def test_function():
            pass

    assert excinfo.value.args == (
        "sync_to_async can only be applied to sync functions.",
    )


@pytest.mark.asyncio
async def test_async_to_sync_fail_partial():
    """
    sync_to_async raises a TypeError when applied to a sync partial.
    """
    with pytest.raises(TypeError) as excinfo:

        async def test_function(*args):
            pass

        partial_function = functools.partial(test_function, 42)
        sync_to_async(partial_function)

    assert excinfo.value.args == (
        "sync_to_async can only be applied to sync functions.",
    )


@pytest.mark.asyncio
async def test_sync_to_async_raises_typeerror_for_async_callable_instance():
    class CallableClass:
        async def __call__(self):
            return None

    with pytest.raises(
        TypeError, match="sync_to_async can only be applied to sync functions."
    ):
        sync_to_async(CallableClass())


@pytest.mark.asyncio
async def test_sync_to_async_decorator():
    """
    Tests sync_to_async as a decorator
    """
    # Define sync function
    @sync_to_async
    def test_function():
        time.sleep(1)
        return 43

    # Check it works right
    result = await test_function()
    assert result == 43


@pytest.mark.asyncio
async def test_nested_sync_to_async_retains_wrapped_function_attributes():
    """
    Tests that attributes of functions wrapped by sync_to_async are retained
    """

    def enclosing_decorator(attr_value):
        @wraps(attr_value)
        def wrapper(f):
            f.attr_name = attr_value
            return f

        return wrapper

    @enclosing_decorator("test_name_attribute")
    @sync_to_async
    def test_function():
        pass

    assert test_function.attr_name == "test_name_attribute"
    assert test_function.__name__ == "test_function"


@pytest.mark.asyncio
async def test_sync_to_async_method_decorator():
    """
    Tests sync_to_async as a method decorator
    """
    # Define sync function
    class TestClass:
        @sync_to_async
        def test_method(self):
            time.sleep(1)
            return 44

    # Check it works right
    instance = TestClass()
    result = await instance.test_method()
    assert result == 44


@pytest.mark.asyncio
async def test_sync_to_async_method_self_attribute():
    """
    Tests sync_to_async on a method copies __self__
    """

    # Define sync function
    class TestClass:
        def test_method(self):
            time.sleep(0.1)
            return 45

    # Check it works right
    instance = TestClass()
    method = sync_to_async(instance.test_method)
    result = await method()
    assert result == 45

    # Check __self__ has been copied
    assert method.__self__ == instance


@pytest.mark.asyncio
async def test_async_to_sync_to_async():
    """
    Tests we can call async functions from a sync thread created by async_to_sync
    (even if the number of thread workers is less than the number of calls)
    """
    result = {}

    # Define async function
    async def inner_async_function():
        result["worked"] = True
        result["thread"] = threading.current_thread()
        return 65

    # Define sync function
    def sync_function():
        return async_to_sync(inner_async_function)()

    # Wrap it
    async_function = sync_to_async(sync_function)
    # Check it works right
    number = await async_function()
    assert number == 65
    assert result["worked"]
    # Make sure that it didn't needlessly make a new async loop
    assert result["thread"] == threading.current_thread()


@pytest.mark.asyncio
async def test_async_to_sync_to_async_decorator():
    """
    Test async_to_sync as a function decorator uses the outer thread
    when used inside sync_to_async.
    """
    result = {}

    # Define async function
    @async_to_sync
    async def inner_async_function():
        result["worked"] = True
        result["thread"] = threading.current_thread()
        return 42

    # Define sync function
    @sync_to_async
    def sync_function():
        return inner_async_function()

    # Check it works right
    number = await sync_function()
    assert number == 42
    assert result["worked"]
    # Make sure that it didn't needlessly make a new async loop
    assert result["thread"] == threading.current_thread()


@pytest.mark.asyncio
@pytest.mark.skipif(sys.version_info < (3, 9), reason="requires python3.9")
async def test_async_to_sync_to_thread_decorator():
    """
    Test async_to_sync as a function decorator uses the outer thread
    when used inside another sync thread.
    """
    result = {}

    # Define async function
    @async_to_sync
    async def inner_async_function():
        result["worked"] = True
        result["thread"] = threading.current_thread()
        return 42

    # Check it works right
    number = await asyncio.to_thread(inner_async_function)
    assert number == 42
    assert result["worked"]
    # Make sure that it didn't needlessly make a new async loop
    assert result["thread"] == threading.current_thread()


def test_async_to_sync_fail_non_function():
    """
    async_to_sync raises a TypeError when applied to a non-function.
    """
    with pytest.warns(UserWarning) as warnings:
        async_to_sync(1)

    assert warnings[0].message.args == (
        "async_to_sync was passed a non-async-marked callable",
    )


def test_async_to_sync_fail_sync():
    """
    async_to_sync raises a TypeError when applied to a sync function.
    """
    with pytest.warns(UserWarning) as warnings:

        @async_to_sync
        def test_function(self):
            pass

    assert warnings[0].message.args == (
        "async_to_sync was passed a non-async-marked callable",
    )


def test_async_to_sync():
    """
    Tests we can call async_to_sync outside of an outer event loop.
    """
    result = {}

    # Define async function
    async def inner_async_function():
        await asyncio.sleep(0)
        result["worked"] = True
        return 84

    # Run it
    sync_function = async_to_sync(inner_async_function)
    number = sync_function()
    assert number == 84
    assert result["worked"]


def test_async_to_sync_decorator():
    """
    Tests we can call async_to_sync as a function decorator
    """
    result = {}

    # Define async function
    @async_to_sync
    async def test_function():
        await asyncio.sleep(0)
        result["worked"] = True
        return 85

    # Run it
    number = test_function()
    assert number == 85
    assert result["worked"]


def test_async_to_sync_method_decorator():
    """
    Tests we can call async_to_sync as a function decorator
    """
    result = {}

    # Define async function
    class TestClass:
        @async_to_sync
        async def test_function(self):
            await asyncio.sleep(0)
            result["worked"] = True
            return 86

    # Run it
    instance = TestClass()
    number = instance.test_function()
    assert number == 86
    assert result["worked"]


@pytest.mark.asyncio
async def test_async_to_sync_in_async():
    """
    Makes sure async_to_sync bails if you try to call it from an async loop
    """

    # Define async function
    async def inner_async_function():
        return 84

    # Run it
    sync_function = async_to_sync(inner_async_function)
    with pytest.raises(RuntimeError):
        sync_function()


def test_async_to_sync_in_thread():
    """
    Tests we can call async_to_sync inside a thread
    """
    result = {}

    # Define async function
    @async_to_sync
    async def test_function():
        await asyncio.sleep(0)
        result["worked"] = True

    # Make a thread and run it
    thread = threading.Thread(target=test_function)
    thread.start()
    thread.join()
    assert result["worked"]


def test_async_to_sync_in_except():
    """
    Tests we can call async_to_sync inside an except block without it
    re-propagating the exception.
    """

    # Define async function
    @async_to_sync
    async def test_function():
        return 42

    # Run inside except
    try:
        raise ValueError("Boom")
    except ValueError:
        assert test_function() == 42


def test_async_to_sync_partial():
    """
    Tests we can call async_to_sync on an async partial.
    """
    result = {}

    # Define async function
    async def inner_async_function(*args):
        await asyncio.sleep(0)
        result["worked"] = True
        return [*args]

    partial_function = functools.partial(inner_async_function, 42)

    # Run it
    sync_function = async_to_sync(partial_function)
    out = sync_function(84)
    assert out == [42, 84]
    assert result["worked"]


def test_async_to_sync_on_callable_object():
    """
    Tests async_to_sync on a callable class instance
    """

    result = {}

    class CallableClass:
        async def __call__(self, value):
            await asyncio.sleep(0)
            result["worked"] = True
            return value

    # Run it (without warnings)
    with warnings.catch_warnings():
        warnings.simplefilter("error")
        sync_function = async_to_sync(CallableClass())
        out = sync_function(42)

    assert out == 42
    assert result["worked"] is True


def test_async_to_sync_method_self_attribute():
    """
    Tests async_to_sync on a method copies __self__.
    """
    # Define async function.
    class TestClass:
        async def test_function(self):
            await asyncio.sleep(0)
            return 45

    # Check it works right.
    instance = TestClass()
    sync_function = async_to_sync(instance.test_function)
    number = sync_function()
    assert number == 45

    # Check __self__ has been copied.
    assert sync_function.__self__ is instance


def test_thread_sensitive_outside_sync():
    """
    Tests that thread_sensitive SyncToAsync where the outside is sync code runs
    in the main thread.
    """

    result = {}

    # Middle async function
    @async_to_sync
    async def middle():
        await inner()
        await asyncio.create_task(inner_task())

    # Inner sync functions
    @sync_to_async
    def inner():
        result["thread"] = threading.current_thread()

    @sync_to_async
    def inner_task():
        result["thread2"] = threading.current_thread()

    # Run it
    middle()
    assert result["thread"] == threading.current_thread()
    assert result["thread2"] == threading.current_thread()


@pytest.mark.asyncio
async def test_thread_sensitive_outside_async():
    """
    Tests that thread_sensitive SyncToAsync where the outside is async code runs
    in a single, separate thread.
    """

    result_1 = {}
    result_2 = {}

    # Outer sync function
    @sync_to_async
    def outer(result):
        middle(result)

    # Middle async function
    @async_to_sync
    async def middle(result):
        await inner(result)

    # Inner sync function
    @sync_to_async
    def inner(result):
        result["thread"] = threading.current_thread()

    # Run it (in supposed parallel!)
    await asyncio.wait(
        [asyncio.create_task(outer(result_1)), asyncio.create_task(inner(result_2))]
    )

    # They should not have run in the main thread, but in the same thread
    assert result_1["thread"] != threading.current_thread()
    assert result_1["thread"] == result_2["thread"]


@pytest.mark.asyncio
async def test_thread_sensitive_with_context_matches():
    result_1 = {}
    result_2 = {}

    def store_thread(result):
        result["thread"] = threading.current_thread()

    store_thread_async = sync_to_async(store_thread)

    async def fn():
        async with ThreadSensitiveContext():
            # Run it (in supposed parallel!)
            await asyncio.wait(
                [
                    asyncio.create_task(store_thread_async(result_1)),
                    asyncio.create_task(store_thread_async(result_2)),
                ]
            )

    await fn()

    # They should not have run in the main thread, and on the same threads
    assert result_1["thread"] != threading.current_thread()
    assert result_1["thread"] == result_2["thread"]


@pytest.mark.asyncio
async def test_thread_sensitive_nested_context():
    result_1 = {}
    result_2 = {}

    @sync_to_async
    def store_thread(result):
        result["thread"] = threading.current_thread()

    async with ThreadSensitiveContext():
        await store_thread(result_1)
        async with ThreadSensitiveContext():
            await store_thread(result_2)

    # They should not have run in the main thread, and on the same threads
    assert result_1["thread"] != threading.current_thread()
    assert result_1["thread"] == result_2["thread"]


@pytest.mark.asyncio
async def test_thread_sensitive_context_without_sync_work():
    async with ThreadSensitiveContext():
        pass


def test_thread_sensitive_double_nested_sync():
    """
    Tests that thread_sensitive SyncToAsync nests inside itself where the
    outside is sync.
    """

    result = {}

    # Async level 1
    @async_to_sync
    async def level1():
        await level2()

    # Sync level 2
    @sync_to_async
    def level2():
        level3()

    # Async level 3
    @async_to_sync
    async def level3():
        await level4()

    # Sync level 2
    @sync_to_async
    def level4():
        result["thread"] = threading.current_thread()

    # Run it
    level1()
    assert result["thread"] == threading.current_thread()


@pytest.mark.asyncio
async def test_thread_sensitive_double_nested_async():
    """
    Tests that thread_sensitive SyncToAsync nests inside itself where the
    outside is async.
    """

    result = {}

    # Sync level 1
    @sync_to_async
    def level1():
        level2()

    # Async level 2
    @async_to_sync
    async def level2():
        await level3()

    # Sync level 3
    @sync_to_async
    def level3():
        level4()

    # Async level 4
    @async_to_sync
    async def level4():
        result["thread"] = threading.current_thread()

    # Run it
    await level1()
    assert result["thread"] == threading.current_thread()


def test_thread_sensitive_disabled():
    """
    Tests that we can disable thread sensitivity and make things run in
    separate threads.
    """

    result = {}

    # Middle async function
    @async_to_sync
    async def middle():
        await inner()

    # Inner sync function
    @sync_to_async(thread_sensitive=False)
    def inner():
        result["thread"] = threading.current_thread()

    # Run it
    middle()
    assert result["thread"] != threading.current_thread()


class ASGITest(TestCase):
    """
    Tests collection of async cases inside classes
    """

    @async_to_sync
    async def test_wrapped_case_is_collected(self):
        self.assertTrue(True)


def test_sync_to_async_detected_as_coroutinefunction():
    """
    Tests that SyncToAsync functions are detected as coroutines.
    """

    def sync_func():
        return

    assert not iscoroutinefunction(sync_to_async)
    assert iscoroutinefunction(sync_to_async(sync_func))


async def async_process(queue):
    queue.put(42)


def sync_process(queue):
    """Runs async_process synchronously"""
    async_to_sync(async_process)(queue)


def fork_first():
    """Forks process before running sync_process"""
    queue = multiprocessing.Queue()
    fork = multiprocessing.Process(target=sync_process, args=[queue])
    fork.start()
    fork.join(3)
    # Force cleanup in failed test case
    if fork.is_alive():
        fork.terminate()
    return queue.get(True, 1)


@pytest.mark.asyncio
async def test_multiprocessing():
    """
    Tests that a forked process can use async_to_sync without it looking for
    the event loop from the parent process.
    """
    assert await sync_to_async(fork_first)() == 42


@pytest.mark.asyncio
async def test_sync_to_async_uses_executor():
    """
    Tests that SyncToAsync uses the passed in executor correctly.
    """

    class CustomExecutor:
        def __init__(self):
            self.executor = ThreadPoolExecutor(max_workers=1)
            self.times_submit_called = 0

        def submit(self, callable_, *args, **kwargs):
            self.times_submit_called += 1
            return self.executor.submit(callable_, *args, **kwargs)

    expected_result = "expected_result"

    def sync_func():
        return expected_result

    custom_executor = CustomExecutor()
    async_function = sync_to_async(
        sync_func, thread_sensitive=False, executor=custom_executor
    )
    actual_result = await async_function()
    assert actual_result == expected_result
    assert custom_executor.times_submit_called == 1

    pytest.raises(
        TypeError,
        sync_to_async,
        sync_func,
        thread_sensitive=True,
        executor=custom_executor,
    )


def test_sync_to_async_deadlock_ignored_with_exception():
    """
    Ensures that throwing an exception from inside a deadlock-protected block
    still resets the deadlock detector's status.
    """

    def view():
        raise ValueError()

    async def server_entry():
        try:
            await sync_to_async(view)()
        except ValueError:
            pass
        try:
            await sync_to_async(view)()
        except ValueError:
            pass

    asyncio.run(server_entry())


@pytest.mark.asyncio
@pytest.mark.xfail
async def test_sync_to_async_with_blocker_thread_sensitive():
    """
    Tests sync_to_async running on a long-time blocker in a thread_sensitive context.
    Expected to fail at the moment.
    """

    delay = 1  # second
    event = multiprocessing.Event()

    async def async_process_waiting_on_event():
        """Wait for the event to be set."""
        await sync_to_async(event.wait)()
        return 42

    async def async_process_that_triggers_event():
        """Sleep, then set the event."""
        await asyncio.sleep(delay)
        await sync_to_async(event.set)()

    # Run the event setter as a task.
    trigger_task = asyncio.ensure_future(async_process_that_triggers_event())

    try:
        # wait on the event waiter, which is now blocking the event setter.
        async with timeout(delay + 1):
            assert await async_process_waiting_on_event() == 42
    except asyncio.TimeoutError:
        # In case of timeout, set the event to unblock things, else
        # downstream tests will get fouled up.
        event.set()
        raise
    finally:
        await trigger_task


@pytest.mark.asyncio
async def test_sync_to_async_with_blocker_non_thread_sensitive():
    """
    Tests sync_to_async running on a long-time blocker in a non_thread_sensitive context.
    """

    delay = 1  # second
    event = multiprocessing.Event()

    async def async_process_waiting_on_event():
        """Wait for the event to be set."""
        await sync_to_async(event.wait, thread_sensitive=False)()
        return 42

    async def async_process_that_triggers_event():
        """Sleep, then set the event."""
        await asyncio.sleep(1)
        await sync_to_async(event.set)()

    # Run the event setter as a task.
    trigger_task = asyncio.ensure_future(async_process_that_triggers_event())

    try:
        # wait on the event waiter, which is now blocking the event setter.
        async with timeout(delay + 1):
            assert await async_process_waiting_on_event() == 42
    except asyncio.TimeoutError:
        # In case of timeout, set the event to unblock things, else
        # downstream tests will get fouled up.
        event.set()
        raise
    finally:
        await trigger_task


@pytest.mark.asyncio
async def test_sync_to_async_within_create_task():
    """
    Test a stack of sync_to_async/async_to_sync/sync_to_async works even when last
    sync_to_async is wrapped in asyncio.wait_for.
    """
    main_thread = threading.current_thread()
    sync_thread = None

    # Hypothetical Django scenario - middleware function is sync and will run
    # in a new thread created by sync_to_async
    def sync_middleware():
        nonlocal sync_thread
        sync_thread = threading.current_thread()
        assert sync_thread != main_thread
        # View is async and wrapped with async_to_sync.
        async_to_sync(async_view)()

    async def async_view():
        # Call a sync function using sync_to_async, but asyncio.wait_for it
        # rather than directly await it.
        await asyncio.wait_for(sync_to_async(sync_task)(), timeout=1)

    task_executed = False

    def sync_task():
        nonlocal task_executed, sync_thread
        assert sync_thread == threading.current_thread()
        task_executed = True

    async with ThreadSensitiveContext():
        await sync_to_async(sync_middleware)()

    assert task_executed


@pytest.mark.asyncio
async def test_inner_shield_sync_middleware():
    """
    Tests that asyncio.shield is capable of preventing http.disconnect from
    cancelling a django request task when using sync middleware.
    """

    # Hypothetical Django scenario - middleware function is sync
    def sync_middleware():
        async_to_sync(async_view)()

    task_complete = False
    task_cancel_caught = False

    # Future that completes when subtask cancellation attempt is caught
    task_blocker = asyncio.Future()

    async def async_view():
        """Async view with a task that is shielded from cancellation."""
        nonlocal task_complete, task_cancel_caught, task_blocker
        task = asyncio.create_task(async_task())
        try:
            await asyncio.shield(task)
        except asyncio.CancelledError:
            task_cancel_caught = True
            task_blocker.set_result(True)
            await task
            task_complete = True

    task_executed = False

    # Future that completes after subtask is created
    task_started_future = asyncio.Future()

    async def async_task():
        """Async subtask that should not be canceled when parent is canceled."""
        nonlocal task_started_future, task_executed, task_blocker
        task_started_future.set_result(True)
        await task_blocker
        task_executed = True

    task_cancel_propagated = False

    async with ThreadSensitiveContext():
        task = asyncio.create_task(sync_to_async(sync_middleware)())
        await task_started_future
        task.cancel()
        try:
            await task
        except asyncio.CancelledError:
            task_cancel_propagated = True
        assert not task_cancel_propagated
        assert task_cancel_caught
        assert task_complete

    assert task_executed


@pytest.mark.asyncio
async def test_inner_shield_async_middleware():
    """
    Tests that asyncio.shield is capable of preventing http.disconnect from
    cancelling a django request task when using async middleware.
    """

    # Hypothetical Django scenario - middleware function is async
    async def async_middleware():
        await async_view()

    task_complete = False
    task_cancel_caught = False

    # Future that completes when subtask cancellation attempt is caught
    task_blocker = asyncio.Future()

    async def async_view():
        """Async view with a task that is shielded from cancellation."""
        nonlocal task_complete, task_cancel_caught, task_blocker
        task = asyncio.create_task(async_task())
        try:
            await asyncio.shield(task)
        except asyncio.CancelledError:
            task_cancel_caught = True
            task_blocker.set_result(True)
            await task
            task_complete = True

    task_executed = False

    # Future that completes after subtask is created
    task_started_future = asyncio.Future()

    async def async_task():
        """Async subtask that should not be canceled when parent is canceled."""
        nonlocal task_started_future, task_executed, task_blocker
        task_started_future.set_result(True)
        await task_blocker
        task_executed = True

    task_cancel_propagated = False

    async with ThreadSensitiveContext():
        task = asyncio.create_task(async_middleware())
        await task_started_future
        task.cancel()
        try:
            await task
        except asyncio.CancelledError:
            task_cancel_propagated = True
        assert not task_cancel_propagated
        assert task_cancel_caught
        assert task_complete

    assert task_executed


@pytest.mark.asyncio
async def test_inner_shield_sync_and_async_middleware():
    """
    Tests that asyncio.shield is capable of preventing http.disconnect from
    cancelling a django request task when using sync and middleware chained
    together.
    """

    # Hypothetical Django scenario - middleware function is sync
    def sync_middleware_1():
        async_to_sync(async_middleware_2)()

    # Hypothetical Django scenario - middleware function is async
    async def async_middleware_2():
        await sync_to_async(sync_middleware_3)()

    # Hypothetical Django scenario - middleware function is sync
    def sync_middleware_3():
        async_to_sync(async_middleware_4)()

    # Hypothetical Django scenario - middleware function is async
    async def async_middleware_4():
        await sync_to_async(sync_middleware_5)()

    # Hypothetical Django scenario - middleware function is sync
    def sync_middleware_5():
        async_to_sync(async_view)()

    task_complete = False
    task_cancel_caught = False

    # Future that completes when subtask cancellation attempt is caught
    task_blocker = asyncio.Future()

    async def async_view():
        """Async view with a task that is shielded from cancellation."""
        nonlocal task_complete, task_cancel_caught, task_blocker
        task = asyncio.create_task(async_task())
        try:
            await asyncio.shield(task)
        except asyncio.CancelledError:
            task_cancel_caught = True
            task_blocker.set_result(True)
            await task
            task_complete = True

    task_executed = False

    # Future that completes after subtask is created
    task_started_future = asyncio.Future()

    async def async_task():
        """Async subtask that should not be canceled when parent is canceled."""
        nonlocal task_started_future, task_executed, task_blocker
        task_started_future.set_result(True)
        await task_blocker
        task_executed = True

    task_cancel_propagated = False

    async with ThreadSensitiveContext():
        task = asyncio.create_task(sync_to_async(sync_middleware_1)())
        await task_started_future
        task.cancel()
        try:
            await task
        except asyncio.CancelledError:
            task_cancel_propagated = True
        assert not task_cancel_propagated
        assert task_cancel_caught
        assert task_complete

    assert task_executed


@pytest.mark.asyncio
async def test_inner_shield_sync_and_async_middleware_sync_task():
    """
    Tests that asyncio.shield is capable of preventing http.disconnect from
    cancelling a django request task when using sync and middleware chained
    together with an async view calling a sync function calling an async task.

    This test ensures that a parent initiated task cancellation will not
    propagate to a shielded subtask.
    """

    # Hypothetical Django scenario - middleware function is sync
    def sync_middleware_1():
        async_to_sync(async_middleware_2)()

    # Hypothetical Django scenario - middleware function is async
    async def async_middleware_2():
        await sync_to_async(sync_middleware_3)()

    # Hypothetical Django scenario - middleware function is sync
    def sync_middleware_3():
        async_to_sync(async_middleware_4)()

    # Hypothetical Django scenario - middleware function is async
    async def async_middleware_4():
        await sync_to_async(sync_middleware_5)()

    # Hypothetical Django scenario - middleware function is sync
    def sync_middleware_5():
        async_to_sync(async_view)()

    task_complete = False
    task_cancel_caught = False

    # Future that completes when subtask cancellation attempt is caught
    task_blocker = asyncio.Future()

    async def async_view():
        """Async view with a task that is shielded from cancellation."""
        nonlocal task_complete, task_cancel_caught, task_blocker
        task = asyncio.create_task(sync_to_async(sync_parent)())
        try:
            await asyncio.shield(task)
        except asyncio.CancelledError:
            task_cancel_caught = True
            task_blocker.set_result(True)
            await task
            task_complete = True

    task_executed = False

    # Future that completes after subtask is created
    task_started_future = asyncio.Future()

    def sync_parent():
        async_to_sync(async_task)()

    async def async_task():
        """Async subtask that should not be canceled when parent is canceled."""
        nonlocal task_started_future, task_executed, task_blocker
        task_started_future.set_result(True)
        await task_blocker
        task_executed = True

    task_cancel_propagated = False

    async with ThreadSensitiveContext():
        task = asyncio.create_task(sync_to_async(sync_middleware_1)())
        await task_started_future
        task.cancel()
        try:
            await task
        except asyncio.CancelledError:
            task_cancel_propagated = True
        assert not task_cancel_propagated
        assert task_cancel_caught
        assert task_complete

    assert task_executed


def test_async_to_sync_overlapping_kwargs() -> None:
    """
    Tests that AsyncToSync correctly passes through kwargs to the wrapped function,
    particularly in the case where the wrapped function uses same names for the parameters
    as the wrapper.
    """

    @async_to_sync
    async def test_function(**kwargs: Any) -> None:
        assert kwargs

    # AsyncToSync.main_wrap has a param named `context`.
    # So we pass the same argument here to test for the error
    # "AsyncToSync.main_wrap() got multiple values for argument '<kwarg>'"
    test_function(context=1)


@pytest.mark.asyncio
async def test_sync_to_async_overlapping_kwargs() -> None:
    """
    Tests that SyncToAsync correctly passes through kwargs to the wrapped function,
    particularly in the case where the wrapped function uses same names for the parameters
    as the wrapper.
    """

    @sync_to_async
    def test_function(**kwargs: Any) -> None:
        assert kwargs

    # SyncToAsync.__call__.loop.run_in_executor has a param named `task_context`.
    await test_function(task_context=1)


def test_nested_task() -> None:
    async def inner() -> asyncio.Task[None]:
        return asyncio.create_task(sync_to_async(print)("inner"))

    async def main() -> None:
        task = await sync_to_async(async_to_sync(inner))()
        await task

    async_to_sync(main)()


def test_nested_task_later() -> None:
    def later(fut: asyncio.Future[asyncio.Task[None]]) -> None:
        task = asyncio.create_task(sync_to_async(print)("later"))
        fut.set_result(task)

    async def inner() -> asyncio.Future[asyncio.Task[None]]:
        loop = asyncio.get_running_loop()
        fut = loop.create_future()
        loop.call_later(0.1, later, fut)
        return fut

    async def main() -> None:
        fut = await sync_to_async(async_to_sync(inner))()
        task = await fut
        await task

    async_to_sync(main)()


def test_double_nested_task() -> None:
    async def inner() -> asyncio.Task[None]:
        return asyncio.create_task(sync_to_async(print)("inner"))

    async def outer() -> asyncio.Task[asyncio.Task[None]]:
        return asyncio.create_task(sync_to_async(async_to_sync(inner))())

    async def main() -> None:
        outer_task = await sync_to_async(async_to_sync(outer))()
        inner_task = await outer_task
        await inner_task

    async_to_sync(main)()


# asyncio.Barrier is new in Python 3.11. Nest definition (rather than using
# skipIf) to avoid mypy error.
if sys.version_info >= (3, 11):

    def test_two_nested_tasks_with_asyncio_run() -> None:
        barrier = asyncio.Barrier(3)
        event = threading.Event()

        async def inner() -> None:
            task = asyncio.create_task(sync_to_async(event.wait)())
            await barrier.wait()
            await task

        async def outer() -> tuple[asyncio.Task[None], asyncio.Task[None]]:
            task0 = asyncio.create_task(inner())
            task1 = asyncio.create_task(inner())
            await barrier.wait()
            event.set()
            return task0, task1

        async def main() -> None:
            task0, task1 = await sync_to_async(async_to_sync(outer))()
            await task0
            await task1

        asyncio.run(main())