1
1
import asyncio
2
2
import contextlib
3
3
import gc
4
+ import socket
4
5
import sys
5
6
6
7
from aiohttp import ClientError , ClientSession , web
7
- from aiohttp .test_utils import get_unused_port_socket
8
+ from aiohttp .test_utils import REUSE_ADDRESS
8
9
9
10
gc .set_debug (gc .DEBUG_LEAK )
10
11
@@ -18,30 +19,32 @@ async def stream_handler(request: web.Request) -> web.Response:
18
19
return web .Response ()
19
20
20
21
app .router .add_get ("/stream" , stream_handler )
21
- sock = get_unused_port_socket ("127.0.0.1" )
22
- port = sock .getsockname ()[1 ]
23
-
24
- runner = web .AppRunner (app )
25
- await runner .setup ()
26
- site = web .SockSite (runner , sock )
27
- await site .start ()
28
-
29
- session = ClientSession ()
30
-
31
- async def fetch_stream (url : str ) -> None :
32
- """Fetch a stream and read a few bytes from it."""
33
- with contextlib .suppress (ClientError ):
34
- await session .get (url )
35
-
36
- client_task = asyncio .create_task (fetch_stream (f"http://localhost:{ port } /stream" ))
37
- await client_task
38
- gc .collect ()
39
- client_response_present = any (
40
- type (obj ).__name__ == "ClientResponse" for obj in gc .garbage
41
- )
42
- await session .close ()
43
- await runner .cleanup ()
44
- sys .exit (1 if client_response_present else 0 )
22
+ with socket .create_server (("127.0.0.1" , 0 ), reuse_port = REUSE_ADDRESS ) as sock :
23
+ port = sock .getsockname ()[1 ]
24
+
25
+ runner = web .AppRunner (app )
26
+ await runner .setup ()
27
+ site = web .SockSite (runner , sock )
28
+ await site .start ()
29
+
30
+ session = ClientSession ()
31
+
32
+ async def fetch_stream (url : str ) -> None :
33
+ """Fetch a stream and read a few bytes from it."""
34
+ with contextlib .suppress (ClientError ):
35
+ await session .get (url )
36
+
37
+ client_task = asyncio .create_task (
38
+ fetch_stream (f"http://localhost:{ port } /stream" )
39
+ )
40
+ await client_task
41
+ gc .collect ()
42
+ client_response_present = any (
43
+ type (obj ).__name__ == "ClientResponse" for obj in gc .garbage
44
+ )
45
+ await session .close ()
46
+ await runner .cleanup ()
47
+ sys .exit (1 if client_response_present else 0 )
45
48
46
49
47
50
asyncio .run (main ())
0 commit comments