-
-
Notifications
You must be signed in to change notification settings - Fork 2k
/
test_run_app.py
1362 lines (1158 loc) · 40.4 KB
/
test_run_app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
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
import asyncio
import contextlib
import logging
import os
import platform
import signal
import socket
import ssl
import subprocess
import sys
import time
from typing import (
Any,
AsyncIterator,
Awaitable,
Callable,
Coroutine,
Dict,
Iterator,
List,
NoReturn,
Optional,
Set,
Tuple,
)
from unittest import mock
from uuid import uuid4
import pytest
from pytest_mock import MockerFixture
from aiohttp import ClientConnectorError, ClientSession, ClientTimeout, WSCloseCode, web
from aiohttp.log import access_logger
from aiohttp.test_utils import make_mocked_coro
from aiohttp.web_protocol import RequestHandler
from aiohttp.web_runner import BaseRunner
_has_unix_domain_socks = hasattr(socket, "AF_UNIX")
if _has_unix_domain_socks:
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as _abstract_path_sock:
try:
_abstract_path_sock.bind(b"\x00" + uuid4().hex.encode("ascii"))
except FileNotFoundError:
_abstract_path_failed = True
else:
_abstract_path_failed = False
finally:
del _abstract_path_sock
else:
_abstract_path_failed = True
skip_if_no_abstract_paths = pytest.mark.skipif(
_abstract_path_failed, reason="Linux-style abstract paths are not supported."
)
skip_if_no_unix_socks = pytest.mark.skipif(
not _has_unix_domain_socks, reason="Unix domain sockets are not supported"
)
del _has_unix_domain_socks, _abstract_path_failed
HAS_IPV6: bool = socket.has_ipv6
if HAS_IPV6:
# The socket.has_ipv6 flag may be True if Python was built with IPv6
# support, but the target system still may not have it.
# So let's ensure that we really have IPv6 support.
try:
with socket.socket(socket.AF_INET6, socket.SOCK_STREAM):
pass
except OSError:
HAS_IPV6 = False
def skip_if_on_windows() -> None:
if platform.system() == "Windows":
pytest.skip("the test is not valid for Windows")
@pytest.fixture
def patched_loop(
loop: asyncio.AbstractEventLoop,
) -> Iterator[asyncio.AbstractEventLoop]:
server = mock.create_autospec(asyncio.Server, spec_set=True, instance=True)
server.wait_closed.return_value = None
unix_server = mock.create_autospec(asyncio.Server, spec_set=True, instance=True)
unix_server.wait_closed.return_value = None
with mock.patch.object(
loop, "create_server", autospec=True, spec_set=True, return_value=server
):
with mock.patch.object(
loop,
"create_unix_server",
autospec=True,
spec_set=True,
return_value=unix_server,
):
asyncio.set_event_loop(loop)
yield loop
def stopper(loop: asyncio.AbstractEventLoop) -> Callable[[], None]:
def raiser() -> NoReturn:
raise KeyboardInterrupt
def f(*args: object) -> None:
loop.call_soon(raiser)
return f
def test_run_app_http(patched_loop: asyncio.AbstractEventLoop) -> None:
app = web.Application()
startup_handler = make_mocked_coro()
app.on_startup.append(startup_handler)
cleanup_handler = make_mocked_coro()
app.on_cleanup.append(cleanup_handler)
web.run_app(app, print=stopper(patched_loop), loop=patched_loop)
patched_loop.create_server.assert_called_with( # type: ignore[attr-defined]
mock.ANY, None, 8080, ssl=None, backlog=128, reuse_address=None, reuse_port=None
)
startup_handler.assert_called_once_with(app)
cleanup_handler.assert_called_once_with(app)
def test_run_app_close_loop(patched_loop: asyncio.AbstractEventLoop) -> None:
app = web.Application()
web.run_app(app, print=stopper(patched_loop), loop=patched_loop)
patched_loop.create_server.assert_called_with( # type: ignore[attr-defined]
mock.ANY, None, 8080, ssl=None, backlog=128, reuse_address=None, reuse_port=None
)
assert patched_loop.is_closed()
mock_unix_server_single = [
mock.call(mock.ANY, "/tmp/testsock1.sock", ssl=None, backlog=128),
]
mock_unix_server_multi = [
mock.call(mock.ANY, "/tmp/testsock1.sock", ssl=None, backlog=128),
mock.call(mock.ANY, "/tmp/testsock2.sock", ssl=None, backlog=128),
]
mock_server_single = [
mock.call(
mock.ANY,
"127.0.0.1",
8080,
ssl=None,
backlog=128,
reuse_address=None,
reuse_port=None,
),
]
mock_server_multi = [
mock.call(
mock.ANY,
"127.0.0.1",
8080,
ssl=None,
backlog=128,
reuse_address=None,
reuse_port=None,
),
mock.call(
mock.ANY,
"192.168.1.1",
8080,
ssl=None,
backlog=128,
reuse_address=None,
reuse_port=None,
),
]
mock_server_default_8989 = [
mock.call(
mock.ANY, None, 8989, ssl=None, backlog=128, reuse_address=None, reuse_port=None
)
]
mock_socket = mock.Mock(getsockname=lambda: ("mock-socket", 123))
mixed_bindings_tests: Tuple[
Tuple[str, Dict[str, Any], List[mock._Call], List[mock._Call]], ...
] = (
(
"Nothing Specified",
{},
[
mock.call(
mock.ANY,
None,
8080,
ssl=None,
backlog=128,
reuse_address=None,
reuse_port=None,
)
],
[],
),
("Port Only", {"port": 8989}, mock_server_default_8989, []),
("Multiple Hosts", {"host": ("127.0.0.1", "192.168.1.1")}, mock_server_multi, []),
(
"Multiple Paths",
{"path": ("/tmp/testsock1.sock", "/tmp/testsock2.sock")},
[],
mock_unix_server_multi,
),
(
"Multiple Paths, Port",
{"path": ("/tmp/testsock1.sock", "/tmp/testsock2.sock"), "port": 8989},
mock_server_default_8989,
mock_unix_server_multi,
),
(
"Multiple Paths, Single Host",
{"path": ("/tmp/testsock1.sock", "/tmp/testsock2.sock"), "host": "127.0.0.1"},
mock_server_single,
mock_unix_server_multi,
),
(
"Single Path, Single Host",
{"path": "/tmp/testsock1.sock", "host": "127.0.0.1"},
mock_server_single,
mock_unix_server_single,
),
(
"Single Path, Multiple Hosts",
{"path": "/tmp/testsock1.sock", "host": ("127.0.0.1", "192.168.1.1")},
mock_server_multi,
mock_unix_server_single,
),
(
"Single Path, Port",
{"path": "/tmp/testsock1.sock", "port": 8989},
mock_server_default_8989,
mock_unix_server_single,
),
(
"Multiple Paths, Multiple Hosts, Port",
{
"path": ("/tmp/testsock1.sock", "/tmp/testsock2.sock"),
"host": ("127.0.0.1", "192.168.1.1"),
"port": 8000,
},
[
mock.call(
mock.ANY,
"127.0.0.1",
8000,
ssl=None,
backlog=128,
reuse_address=None,
reuse_port=None,
),
mock.call(
mock.ANY,
"192.168.1.1",
8000,
ssl=None,
backlog=128,
reuse_address=None,
reuse_port=None,
),
],
mock_unix_server_multi,
),
(
"Only socket",
{"sock": [mock_socket]},
[mock.call(mock.ANY, ssl=None, sock=mock_socket, backlog=128)],
[],
),
(
"Socket, port",
{"sock": [mock_socket], "port": 8765},
[
mock.call(
mock.ANY,
None,
8765,
ssl=None,
backlog=128,
reuse_address=None,
reuse_port=None,
),
mock.call(mock.ANY, sock=mock_socket, ssl=None, backlog=128),
],
[],
),
(
"Socket, Host, No port",
{"sock": [mock_socket], "host": "localhost"},
[
mock.call(
mock.ANY,
"localhost",
8080,
ssl=None,
backlog=128,
reuse_address=None,
reuse_port=None,
),
mock.call(mock.ANY, sock=mock_socket, ssl=None, backlog=128),
],
[],
),
(
"reuse_port",
{"reuse_port": True},
[
mock.call(
mock.ANY,
None,
8080,
ssl=None,
backlog=128,
reuse_address=None,
reuse_port=True,
)
],
[],
),
(
"reuse_address",
{"reuse_address": False},
[
mock.call(
mock.ANY,
None,
8080,
ssl=None,
backlog=128,
reuse_address=False,
reuse_port=None,
)
],
[],
),
(
"reuse_port, reuse_address",
{"reuse_address": True, "reuse_port": True},
[
mock.call(
mock.ANY,
None,
8080,
ssl=None,
backlog=128,
reuse_address=True,
reuse_port=True,
)
],
[],
),
(
"Port, reuse_port",
{"port": 8989, "reuse_port": True},
[
mock.call(
mock.ANY,
None,
8989,
ssl=None,
backlog=128,
reuse_address=None,
reuse_port=True,
)
],
[],
),
(
"Multiple Hosts, reuse_port",
{"host": ("127.0.0.1", "192.168.1.1"), "reuse_port": True},
[
mock.call(
mock.ANY,
"127.0.0.1",
8080,
ssl=None,
backlog=128,
reuse_address=None,
reuse_port=True,
),
mock.call(
mock.ANY,
"192.168.1.1",
8080,
ssl=None,
backlog=128,
reuse_address=None,
reuse_port=True,
),
],
[],
),
(
"Multiple Paths, Port, reuse_address",
{
"path": ("/tmp/testsock1.sock", "/tmp/testsock2.sock"),
"port": 8989,
"reuse_address": False,
},
[
mock.call(
mock.ANY,
None,
8989,
ssl=None,
backlog=128,
reuse_address=False,
reuse_port=None,
)
],
mock_unix_server_multi,
),
(
"Multiple Paths, Single Host, reuse_address, reuse_port",
{
"path": ("/tmp/testsock1.sock", "/tmp/testsock2.sock"),
"host": "127.0.0.1",
"reuse_address": True,
"reuse_port": True,
},
[
mock.call(
mock.ANY,
"127.0.0.1",
8080,
ssl=None,
backlog=128,
reuse_address=True,
reuse_port=True,
),
],
mock_unix_server_multi,
),
)
mixed_bindings_test_ids = [test[0] for test in mixed_bindings_tests]
mixed_bindings_test_params = [test[1:] for test in mixed_bindings_tests]
@pytest.mark.parametrize(
"run_app_kwargs, expected_server_calls, expected_unix_server_calls",
mixed_bindings_test_params,
ids=mixed_bindings_test_ids,
)
def test_run_app_mixed_bindings(
run_app_kwargs: Dict[str, Any],
expected_server_calls: List[mock._Call],
expected_unix_server_calls: List[mock._Call],
patched_loop: asyncio.AbstractEventLoop,
) -> None:
app = web.Application()
web.run_app(app, print=stopper(patched_loop), **run_app_kwargs, loop=patched_loop)
assert patched_loop.create_unix_server.mock_calls == expected_unix_server_calls # type: ignore[attr-defined]
assert patched_loop.create_server.mock_calls == expected_server_calls # type: ignore[attr-defined]
def test_run_app_https(patched_loop: asyncio.AbstractEventLoop) -> None:
app = web.Application()
ssl_context = ssl.create_default_context()
web.run_app(
app, ssl_context=ssl_context, print=stopper(patched_loop), loop=patched_loop
)
patched_loop.create_server.assert_called_with( # type: ignore[attr-defined]
mock.ANY,
None,
8443,
ssl=ssl_context,
backlog=128,
reuse_address=None,
reuse_port=None,
)
def test_run_app_nondefault_host_port(
patched_loop: asyncio.AbstractEventLoop, unused_port_socket: socket.socket
) -> None:
port = unused_port_socket.getsockname()[1]
host = "127.0.0.1"
app = web.Application()
web.run_app(
app, host=host, port=port, print=stopper(patched_loop), loop=patched_loop
)
patched_loop.create_server.assert_called_with( # type: ignore[attr-defined]
mock.ANY, host, port, ssl=None, backlog=128, reuse_address=None, reuse_port=None
)
def test_run_app_with_sock(
patched_loop: asyncio.AbstractEventLoop, unused_port_socket: socket.socket
) -> None:
sock = unused_port_socket
app = web.Application()
web.run_app(
app,
sock=sock,
print=stopper(patched_loop),
loop=patched_loop,
)
patched_loop.create_server.assert_called_with( # type: ignore[attr-defined]
mock.ANY, sock=sock, ssl=None, backlog=128
)
def test_run_app_multiple_hosts(patched_loop: asyncio.AbstractEventLoop) -> None:
hosts = ("127.0.0.1", "127.0.0.2")
app = web.Application()
web.run_app(app, host=hosts, print=stopper(patched_loop), loop=patched_loop)
calls = map(
lambda h: mock.call(
mock.ANY,
h,
8080,
ssl=None,
backlog=128,
reuse_address=None,
reuse_port=None,
),
hosts,
)
patched_loop.create_server.assert_has_calls(calls) # type: ignore[attr-defined]
def test_run_app_custom_backlog(patched_loop: asyncio.AbstractEventLoop) -> None:
app = web.Application()
web.run_app(app, backlog=10, print=stopper(patched_loop), loop=patched_loop)
patched_loop.create_server.assert_called_with( # type: ignore[attr-defined]
mock.ANY, None, 8080, ssl=None, backlog=10, reuse_address=None, reuse_port=None
)
def test_run_app_custom_backlog_unix(patched_loop: asyncio.AbstractEventLoop) -> None:
app = web.Application()
web.run_app(
app,
path="/tmp/tmpsock.sock",
backlog=10,
print=stopper(patched_loop),
loop=patched_loop,
)
patched_loop.create_unix_server.assert_called_with( # type: ignore[attr-defined]
mock.ANY, "/tmp/tmpsock.sock", ssl=None, backlog=10
)
@skip_if_no_unix_socks
def test_run_app_http_unix_socket(
patched_loop: asyncio.AbstractEventLoop, unix_sockname: str
) -> None:
app = web.Application()
printer = mock.Mock(wraps=stopper(patched_loop))
web.run_app(app, path=unix_sockname, print=printer, loop=patched_loop)
patched_loop.create_unix_server.assert_called_with( # type: ignore[attr-defined]
mock.ANY, unix_sockname, ssl=None, backlog=128
)
assert f"http://unix:{unix_sockname}:" in printer.call_args[0][0]
@skip_if_no_unix_socks
def test_run_app_https_unix_socket(
patched_loop: asyncio.AbstractEventLoop, unix_sockname: str
) -> None:
app = web.Application()
ssl_context = ssl.create_default_context()
printer = mock.Mock(wraps=stopper(patched_loop))
web.run_app(
app,
path=unix_sockname,
ssl_context=ssl_context,
print=printer,
loop=patched_loop,
)
patched_loop.create_unix_server.assert_called_with( # type: ignore[attr-defined]
mock.ANY, unix_sockname, ssl=ssl_context, backlog=128
)
assert f"https://unix:{unix_sockname}:" in printer.call_args[0][0]
@pytest.mark.skipif(not hasattr(socket, "AF_UNIX"), reason="requires UNIX sockets")
@skip_if_no_abstract_paths
def test_run_app_abstract_linux_socket(patched_loop: asyncio.AbstractEventLoop) -> None:
sock_path = b"\x00" + uuid4().hex.encode("ascii")
app = web.Application()
web.run_app(
app,
path=sock_path.decode("ascii", "ignore"),
print=stopper(patched_loop),
loop=patched_loop,
)
patched_loop.create_unix_server.assert_called_with( # type: ignore[attr-defined]
mock.ANY, sock_path.decode("ascii"), ssl=None, backlog=128
)
def test_run_app_preexisting_inet_socket(
patched_loop: asyncio.AbstractEventLoop, mocker: MockerFixture
) -> None:
app = web.Application()
sock = socket.socket()
with contextlib.closing(sock):
sock.bind(("127.0.0.1", 0))
_, port = sock.getsockname()
printer = mock.Mock(wraps=stopper(patched_loop))
web.run_app(app, sock=sock, print=printer, loop=patched_loop)
patched_loop.create_server.assert_called_with( # type: ignore[attr-defined]
mock.ANY, sock=sock, backlog=128, ssl=None
)
assert f"http://127.0.0.1:{port}" in printer.call_args[0][0]
@pytest.mark.skipif(not HAS_IPV6, reason="IPv6 is not available")
def test_run_app_preexisting_inet6_socket(
patched_loop: asyncio.AbstractEventLoop,
) -> None:
app = web.Application()
sock = socket.socket(socket.AF_INET6)
with contextlib.closing(sock):
sock.bind(("::1", 0))
port = sock.getsockname()[1]
printer = mock.Mock(wraps=stopper(patched_loop))
web.run_app(app, sock=sock, print=printer, loop=patched_loop)
patched_loop.create_server.assert_called_with( # type: ignore[attr-defined]
mock.ANY, sock=sock, backlog=128, ssl=None
)
assert f"http://[::1]:{port}" in printer.call_args[0][0]
@skip_if_no_unix_socks
def test_run_app_preexisting_unix_socket(
patched_loop: asyncio.AbstractEventLoop, mocker: MockerFixture
) -> None:
app = web.Application()
sock_path = "/tmp/test_preexisting_sock1"
sock = socket.socket(socket.AF_UNIX)
with contextlib.closing(sock):
sock.bind(sock_path)
os.unlink(sock_path)
printer = mock.Mock(wraps=stopper(patched_loop))
web.run_app(app, sock=sock, print=printer, loop=patched_loop)
patched_loop.create_server.assert_called_with( # type: ignore[attr-defined]
mock.ANY, sock=sock, backlog=128, ssl=None
)
assert f"http://unix:{sock_path}:" in printer.call_args[0][0]
def test_run_app_multiple_preexisting_sockets(
patched_loop: asyncio.AbstractEventLoop,
) -> None:
app = web.Application()
sock1 = socket.socket()
sock2 = socket.socket()
with contextlib.closing(sock1), contextlib.closing(sock2):
sock1.bind(("localhost", 0))
_, port1 = sock1.getsockname()
sock2.bind(("localhost", 0))
_, port2 = sock2.getsockname()
printer = mock.Mock(wraps=stopper(patched_loop))
web.run_app(app, sock=(sock1, sock2), print=printer, loop=patched_loop)
patched_loop.create_server.assert_has_calls( # type: ignore[attr-defined]
[
mock.call(mock.ANY, sock=sock1, backlog=128, ssl=None),
mock.call(mock.ANY, sock=sock2, backlog=128, ssl=None),
]
)
assert f"http://127.0.0.1:{port1}" in printer.call_args[0][0]
assert f"http://127.0.0.1:{port2}" in printer.call_args[0][0]
_script_test_signal = """
from aiohttp import web
app = web.Application()
web.run_app(app, host=())
"""
def test_sigint() -> None:
skip_if_on_windows()
with subprocess.Popen(
[sys.executable, "-u", "-c", _script_test_signal],
stdout=subprocess.PIPE,
) as proc:
for line in proc.stdout: # type: ignore[union-attr]
if line.startswith(b"======== Running on"):
break
proc.send_signal(signal.SIGINT)
assert proc.wait() == 0
def test_sigterm() -> None:
skip_if_on_windows()
with subprocess.Popen(
[sys.executable, "-u", "-c", _script_test_signal],
stdout=subprocess.PIPE,
) as proc:
for line in proc.stdout: # type: ignore[union-attr]
if line.startswith(b"======== Running on"):
break
proc.terminate()
assert proc.wait() == 0
def test_startup_cleanup_signals_even_on_failure(
patched_loop: asyncio.AbstractEventLoop,
) -> None:
patched_loop.create_server.side_effect = RuntimeError() # type: ignore[attr-defined]
app = web.Application()
startup_handler = make_mocked_coro()
app.on_startup.append(startup_handler)
cleanup_handler = make_mocked_coro()
app.on_cleanup.append(cleanup_handler)
with pytest.raises(RuntimeError):
web.run_app(app, print=stopper(patched_loop), loop=patched_loop)
startup_handler.assert_called_once_with(app)
cleanup_handler.assert_called_once_with(app)
def test_run_app_coro(patched_loop: asyncio.AbstractEventLoop) -> None:
startup_handler = cleanup_handler = None
async def make_app() -> web.Application:
nonlocal startup_handler, cleanup_handler
app = web.Application()
startup_handler = make_mocked_coro()
app.on_startup.append(startup_handler)
cleanup_handler = make_mocked_coro()
app.on_cleanup.append(cleanup_handler)
return app
web.run_app(make_app(), print=stopper(patched_loop), loop=patched_loop)
patched_loop.create_server.assert_called_with( # type: ignore[attr-defined]
mock.ANY, None, 8080, ssl=None, backlog=128, reuse_address=None, reuse_port=None
)
assert startup_handler is not None
assert cleanup_handler is not None
startup_handler.assert_called_once_with(mock.ANY)
cleanup_handler.assert_called_once_with(mock.ANY)
def test_run_app_default_logger(
monkeypatch: pytest.MonkeyPatch, patched_loop: asyncio.AbstractEventLoop
) -> None:
logger = access_logger
attrs = {
"hasHandlers.return_value": False,
"level": logging.NOTSET,
"name": "aiohttp.access",
}
mock_logger = mock.create_autospec(logger, name="mock_access_logger")
mock_logger.configure_mock(**attrs)
app = web.Application()
web.run_app(
app,
debug=True,
print=stopper(patched_loop),
access_log=mock_logger,
loop=patched_loop,
)
mock_logger.setLevel.assert_any_call(logging.DEBUG)
mock_logger.hasHandlers.assert_called_with()
assert isinstance(mock_logger.addHandler.call_args[0][0], logging.StreamHandler)
def test_run_app_default_logger_setup_requires_debug(
patched_loop: asyncio.AbstractEventLoop,
) -> None:
logger = access_logger
attrs = {
"hasHandlers.return_value": False,
"level": logging.NOTSET,
"name": "aiohttp.access",
}
mock_logger = mock.create_autospec(logger, name="mock_access_logger")
mock_logger.configure_mock(**attrs)
app = web.Application()
web.run_app(
app,
debug=False,
print=stopper(patched_loop),
access_log=mock_logger,
loop=patched_loop,
)
mock_logger.setLevel.assert_not_called()
mock_logger.hasHandlers.assert_not_called()
mock_logger.addHandler.assert_not_called()
def test_run_app_default_logger_setup_requires_default_logger(
patched_loop: asyncio.AbstractEventLoop,
) -> None:
logger = access_logger
attrs = {
"hasHandlers.return_value": False,
"level": logging.NOTSET,
"name": None,
}
mock_logger = mock.create_autospec(logger, name="mock_access_logger")
mock_logger.configure_mock(**attrs)
app = web.Application()
web.run_app(
app,
debug=True,
print=stopper(patched_loop),
access_log=mock_logger,
loop=patched_loop,
)
mock_logger.setLevel.assert_not_called()
mock_logger.hasHandlers.assert_not_called()
mock_logger.addHandler.assert_not_called()
def test_run_app_default_logger_setup_only_if_unconfigured(
patched_loop: asyncio.AbstractEventLoop,
) -> None:
logger = access_logger
attrs = {
"hasHandlers.return_value": True,
"level": None,
"name": "aiohttp.access",
}
mock_logger = mock.create_autospec(logger, name="mock_access_logger")
mock_logger.configure_mock(**attrs)
app = web.Application()
web.run_app(
app,
debug=True,
print=stopper(patched_loop),
access_log=mock_logger,
loop=patched_loop,
)
mock_logger.setLevel.assert_not_called()
mock_logger.hasHandlers.assert_called_with()
mock_logger.addHandler.assert_not_called()
def test_run_app_cancels_all_pending_tasks(
patched_loop: asyncio.AbstractEventLoop,
) -> None:
app = web.Application()
task = None
async def on_startup(app: web.Application) -> None:
nonlocal task
loop = asyncio.get_event_loop()
task = loop.create_task(asyncio.sleep(1000))
app.on_startup.append(on_startup)
web.run_app(app, print=stopper(patched_loop), loop=patched_loop)
assert task is not None
assert task.cancelled()
def test_run_app_cancels_done_tasks(patched_loop: asyncio.AbstractEventLoop) -> None:
app = web.Application()
task = None
async def coro() -> int:
return 123
async def on_startup(app: web.Application) -> None:
nonlocal task
loop = asyncio.get_event_loop()
task = loop.create_task(coro())
app.on_startup.append(on_startup)
web.run_app(app, print=stopper(patched_loop), loop=patched_loop)
assert task is not None
assert task.done()
def test_run_app_cancels_failed_tasks(patched_loop: asyncio.AbstractEventLoop) -> None:
app = web.Application()
task = None
exc = RuntimeError("FAIL")
async def fail() -> None:
try:
await asyncio.sleep(1000)
except asyncio.CancelledError:
raise exc
async def on_startup(app: web.Application) -> None:
nonlocal task
loop = asyncio.get_event_loop()
task = loop.create_task(fail())
await asyncio.sleep(0.01)
app.on_startup.append(on_startup)
exc_handler = mock.Mock()
patched_loop.set_exception_handler(exc_handler)
web.run_app(app, print=stopper(patched_loop), loop=patched_loop)
assert task is not None
assert task.done()
msg = {
"message": "unhandled exception during asyncio.run() shutdown",
"exception": exc,
"task": task,
}
exc_handler.assert_called_with(patched_loop, msg)
def test_run_app_keepalive_timeout(
patched_loop: asyncio.AbstractEventLoop,
mocker: MockerFixture,
monkeypatch: pytest.MonkeyPatch,
) -> None:
new_timeout = 1234
base_runner_init_orig = BaseRunner.__init__
def base_runner_init_spy(
self: BaseRunner[web.Request], *args: Any, **kwargs: Any
) -> None:
assert kwargs["keepalive_timeout"] == new_timeout
base_runner_init_orig(self, *args, **kwargs)
app = web.Application()
monkeypatch.setattr(BaseRunner, "__init__", base_runner_init_spy)
web.run_app(
app,
keepalive_timeout=new_timeout,
print=stopper(patched_loop),
loop=patched_loop,
)
def test_run_app_context_vars(patched_loop: asyncio.AbstractEventLoop) -> None:
from contextvars import ContextVar
count = 0
VAR = ContextVar("VAR", default="default")
async def on_startup(app: web.Application) -> None:
nonlocal count
assert "init" == VAR.get()
VAR.set("on_startup")
count += 1
async def on_cleanup(app: web.Application) -> None:
nonlocal count
assert "on_startup" == VAR.get()
count += 1
async def init() -> web.Application:
nonlocal count
assert "default" == VAR.get()
VAR.set("init")
app = web.Application()
app.on_startup.append(on_startup)
app.on_cleanup.append(on_cleanup)
count += 1
return app
web.run_app(init(), print=stopper(patched_loop), loop=patched_loop)
assert count == 3
def test_run_app_raises_exception(patched_loop: asyncio.AbstractEventLoop) -> None:
async def context(app: web.Application) -> AsyncIterator[None]: