-
Notifications
You must be signed in to change notification settings - Fork 141
/
test_sockets.py
1903 lines (1650 loc) · 69.8 KB
/
test_sockets.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
from __future__ import annotations
import array
import gc
import io
import os
import platform
import re
import socket
import sys
import tempfile
import threading
import time
from collections.abc import Generator, Iterable, Iterator
from contextlib import suppress
from pathlib import Path
from socket import AddressFamily
from ssl import SSLContext, SSLError
from threading import Thread
from typing import TYPE_CHECKING, Any, Literal, NoReturn, TypeVar, cast
import psutil
import pytest
from _pytest.fixtures import SubRequest
from _pytest.logging import LogCaptureFixture
from _pytest.monkeypatch import MonkeyPatch
from _pytest.tmpdir import TempPathFactory
from anyio import (
BrokenResourceError,
BusyResourceError,
ClosedResourceError,
EndOfStream,
Event,
TypedAttributeLookupError,
connect_tcp,
connect_unix,
create_connected_udp_socket,
create_connected_unix_datagram_socket,
create_task_group,
create_tcp_listener,
create_udp_socket,
create_unix_datagram_socket,
create_unix_listener,
fail_after,
getaddrinfo,
getnameinfo,
move_on_after,
wait_all_tasks_blocked,
wait_readable,
wait_socket_readable,
wait_socket_writable,
wait_writable,
)
from anyio.abc import (
IPSockAddrType,
Listener,
SocketAttribute,
SocketListener,
SocketStream,
)
from anyio.lowlevel import checkpoint
from anyio.streams.stapled import MultiListener
from .conftest import asyncio_params
if sys.version_info < (3, 11):
from exceptiongroup import ExceptionGroup
if TYPE_CHECKING:
from _typeshed import FileDescriptorLike
AnyIPAddressFamily = Literal[
AddressFamily.AF_UNSPEC, AddressFamily.AF_INET, AddressFamily.AF_INET6
]
pytestmark = pytest.mark.anyio
# If a socket can bind to ::1, the current environment has IPv6 properly configured
has_ipv6 = False
if socket.has_ipv6:
try:
s = socket.socket(AddressFamily.AF_INET6)
try:
s.bind(("::1", 0))
finally:
s.close()
del s
except OSError:
pass
else:
has_ipv6 = True
skip_ipv6_mark = pytest.mark.skipif(not has_ipv6, reason="IPv6 is not available")
skip_unix_abstract_mark = pytest.mark.skipif(
not sys.platform.startswith("linux"),
reason="Abstract namespace sockets is a Linux only feature",
)
@pytest.fixture
def fake_localhost_dns(monkeypatch: MonkeyPatch) -> None:
def fake_getaddrinfo(*args: Any, **kwargs: Any) -> object:
# Make it return IPv4 addresses first so we can test the IPv6 preference
results = real_getaddrinfo(*args, **kwargs)
return sorted(results, key=lambda item: item[0])
real_getaddrinfo = socket.getaddrinfo
monkeypatch.setattr("socket.getaddrinfo", fake_getaddrinfo)
@pytest.fixture(
params=[
pytest.param(AddressFamily.AF_INET, id="ipv4"),
pytest.param(AddressFamily.AF_INET6, id="ipv6", marks=[skip_ipv6_mark]),
]
)
def family(request: SubRequest) -> AnyIPAddressFamily:
return request.param
@pytest.fixture
def check_asyncio_bug(anyio_backend_name: str, family: AnyIPAddressFamily) -> None:
if (
anyio_backend_name == "asyncio"
and sys.platform == "win32"
and family == AddressFamily.AF_INET6
):
import asyncio
policy = asyncio.get_event_loop_policy()
if policy.__class__.__name__ == "WindowsProactorEventLoopPolicy":
pytest.skip("Does not work due to a known bug (39148)")
_T = TypeVar("_T")
def _identity(v: _T) -> _T:
return v
# _ProactorBasePipeTransport.abort() after _ProactorBasePipeTransport.close()
# does not cancel writes: https://bugs.python.org/issue44428
_ignore_win32_resource_warnings = (
pytest.mark.filterwarnings(
"ignore:unclosed <socket.socket:ResourceWarning",
"ignore:unclosed transport <_ProactorSocketTransport closing:ResourceWarning",
)
if sys.platform == "win32"
else _identity
)
@_ignore_win32_resource_warnings
class TestTCPStream:
@pytest.fixture
def server_sock(self, family: AnyIPAddressFamily) -> Iterator[socket.socket]:
sock = socket.socket(family, socket.SOCK_STREAM)
sock.settimeout(1)
sock.bind(("localhost", 0))
sock.listen()
yield sock
sock.close()
@pytest.fixture
def server_addr(self, server_sock: socket.socket) -> tuple[str, int]:
return server_sock.getsockname()[:2]
async def test_extra_attributes(
self,
server_sock: socket.socket,
server_addr: tuple[str, int],
family: AnyIPAddressFamily,
) -> None:
async with await connect_tcp(*server_addr) as stream:
raw_socket = stream.extra(SocketAttribute.raw_socket)
assert stream.extra(SocketAttribute.family) == family
assert (
stream.extra(SocketAttribute.local_address)
== raw_socket.getsockname()[:2]
)
assert (
stream.extra(SocketAttribute.local_port) == raw_socket.getsockname()[1]
)
assert stream.extra(SocketAttribute.remote_address) == server_addr
assert stream.extra(SocketAttribute.remote_port) == server_addr[1]
async def test_send_receive(
self, server_sock: socket.socket, server_addr: tuple[str, int]
) -> None:
async with await connect_tcp(*server_addr) as stream:
client, _ = server_sock.accept()
await stream.send(b"blah")
request = client.recv(100)
client.sendall(request[::-1])
response = await stream.receive()
client.close()
assert response == b"halb"
async def test_send_large_buffer(
self, server_sock: socket.socket, server_addr: tuple[str, int]
) -> None:
def serve() -> None:
client, _ = server_sock.accept()
client.sendall(buffer)
client.close()
buffer = (
b"\xff" * 1024 * 1024
) # should exceed the maximum kernel send buffer size
async with await connect_tcp(*server_addr) as stream:
thread = Thread(target=serve, daemon=True)
thread.start()
response = b""
while len(response) < len(buffer):
chunk = await stream.receive()
assert isinstance(chunk, bytes)
response += chunk
thread.join()
assert response == buffer
async def test_send_eof(
self, server_sock: socket.socket, server_addr: tuple[str, int]
) -> None:
def serve() -> None:
client, _ = server_sock.accept()
request = b""
while True:
data = client.recv(100)
request += data
if not data:
break
client.sendall(request[::-1])
client.close()
async with await connect_tcp(*server_addr) as stream:
thread = Thread(target=serve, daemon=True)
thread.start()
await stream.send(b"hello, ")
await stream.send(b"world\n")
await stream.send_eof()
response = await stream.receive()
thread.join()
assert response == b"\ndlrow ,olleh"
async def test_iterate(
self, server_sock: socket.socket, server_addr: tuple[str, int]
) -> None:
def serve() -> None:
client, _ = server_sock.accept()
client.sendall(b"bl")
event.wait(1)
client.sendall(b"ah")
client.close()
event = threading.Event()
thread = Thread(target=serve, daemon=True)
thread.start()
chunks = []
async with await connect_tcp(*server_addr) as stream:
async for chunk in stream:
chunks.append(chunk)
event.set()
thread.join()
assert chunks == [b"bl", b"ah"]
async def test_socket_options(
self, family: AnyIPAddressFamily, server_addr: tuple[str, int]
) -> None:
async with await connect_tcp(*server_addr) as stream:
raw_socket = stream.extra(SocketAttribute.raw_socket)
assert raw_socket.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY) != 0
@skip_ipv6_mark
@pytest.mark.parametrize(
"local_addr, expected_client_addr",
[
pytest.param("", "::1", id="dualstack"),
pytest.param("127.0.0.1", "127.0.0.1", id="ipv4"),
pytest.param("::1", "::1", id="ipv6"),
],
)
async def test_happy_eyeballs(
self, local_addr: str, expected_client_addr: str, fake_localhost_dns: None
) -> None:
client_addr = None, None
def serve() -> None:
nonlocal client_addr
client, client_addr = server_sock.accept()
client.close()
family = (
AddressFamily.AF_INET
if local_addr == "127.0.0.1"
else AddressFamily.AF_INET6
)
server_sock = socket.socket(family)
server_sock.bind((local_addr, 0))
server_sock.listen()
port = server_sock.getsockname()[1]
thread = Thread(target=serve, daemon=True)
thread.start()
async with await connect_tcp("localhost", port):
pass
thread.join()
server_sock.close()
assert client_addr[0] == expected_client_addr
@pytest.mark.parametrize(
"target, exception_class",
[
pytest.param(
"localhost", ExceptionGroup, id="multi", marks=[skip_ipv6_mark]
),
pytest.param("127.0.0.1", ConnectionRefusedError, id="single"),
],
)
async def test_connection_refused(
self,
target: str,
exception_class: type[ExceptionGroup] | type[ConnectionRefusedError],
fake_localhost_dns: None,
) -> None:
dummy_socket = socket.socket(AddressFamily.AF_INET6)
dummy_socket.bind(("::", 0))
free_port = dummy_socket.getsockname()[1]
dummy_socket.close()
with pytest.raises(OSError) as exc:
await connect_tcp(target, free_port)
assert exc.match("All connection attempts failed")
assert isinstance(exc.value.__cause__, exception_class)
if isinstance(exc.value.__cause__, ExceptionGroup):
for exception in exc.value.__cause__.exceptions:
assert isinstance(exception, ConnectionRefusedError)
async def test_receive_timeout(
self, server_sock: socket.socket, server_addr: tuple[str, int]
) -> None:
def serve() -> None:
conn, _ = server_sock.accept()
time.sleep(1)
conn.close()
thread = Thread(target=serve, daemon=True)
thread.start()
async with await connect_tcp(*server_addr) as stream:
start_time = time.monotonic()
with move_on_after(0.1):
while time.monotonic() - start_time < 0.3:
await stream.receive(1)
pytest.fail("The timeout was not respected")
async def test_concurrent_send(self, server_addr: tuple[str, int]) -> None:
async def send_data() -> NoReturn:
while True:
await stream.send(b"\x00" * 4096)
async with await connect_tcp(*server_addr) as stream:
async with create_task_group() as tg:
tg.start_soon(send_data)
await wait_all_tasks_blocked()
with pytest.raises(BusyResourceError) as exc:
await stream.send(b"foo")
exc.match("already writing to")
tg.cancel_scope.cancel()
async def test_concurrent_receive(self, server_addr: tuple[str, int]) -> None:
async with await connect_tcp(*server_addr) as client:
async with create_task_group() as tg:
tg.start_soon(client.receive)
await wait_all_tasks_blocked()
try:
with pytest.raises(BusyResourceError) as exc:
await client.receive()
exc.match("already reading from")
finally:
tg.cancel_scope.cancel()
async def test_close_during_receive(self, server_addr: tuple[str, int]) -> None:
async def interrupt() -> None:
await wait_all_tasks_blocked()
await stream.aclose()
async with await connect_tcp(*server_addr) as stream:
async with create_task_group() as tg:
tg.start_soon(interrupt)
with pytest.raises(ClosedResourceError):
await stream.receive()
async def test_receive_after_close(self, server_addr: tuple[str, int]) -> None:
stream = await connect_tcp(*server_addr)
await stream.aclose()
with pytest.raises(ClosedResourceError):
await stream.receive()
async def test_send_after_close(self, server_addr: tuple[str, int]) -> None:
stream = await connect_tcp(*server_addr)
await stream.aclose()
with pytest.raises(ClosedResourceError):
await stream.send(b"foo")
async def test_send_after_peer_closed(self, family: AnyIPAddressFamily) -> None:
def serve_once() -> None:
client_sock, _ = server_sock.accept()
client_sock.close()
server_sock.close()
server_sock = socket.socket(family, socket.SOCK_STREAM)
server_sock.settimeout(1)
server_sock.bind(("localhost", 0))
server_addr = server_sock.getsockname()[:2]
server_sock.listen()
thread = Thread(target=serve_once, daemon=True)
thread.start()
with pytest.raises(BrokenResourceError):
async with await connect_tcp(*server_addr) as stream:
for _ in range(1000):
await stream.send(b"foo")
thread.join()
async def test_connect_tcp_with_tls(
self,
server_context: SSLContext,
client_context: SSLContext,
server_sock: socket.socket,
server_addr: tuple[str, int],
) -> None:
def serve() -> None:
with suppress(socket.timeout):
client, addr = server_sock.accept()
client.settimeout(1)
client = server_context.wrap_socket(client, server_side=True)
data = client.recv(100)
client.sendall(data[::-1])
client.unwrap()
client.close()
# The TLSStream tests are more comprehensive than this one!
thread = Thread(target=serve, daemon=True)
thread.start()
async with await connect_tcp(
*server_addr, tls_hostname="localhost", ssl_context=client_context
) as stream:
await stream.send(b"hello")
response = await stream.receive()
assert response == b"olleh"
thread.join()
async def test_connect_tcp_with_tls_cert_check_fail(
self,
server_context: SSLContext,
server_sock: socket.socket,
server_addr: tuple[str, int],
) -> None:
thread_exception = None
def serve() -> None:
nonlocal thread_exception
client, addr = server_sock.accept()
with client:
client.settimeout(1)
try:
server_context.wrap_socket(client, server_side=True)
except OSError:
pass
except BaseException as exc:
thread_exception = exc
thread = Thread(target=serve, daemon=True)
thread.start()
with pytest.raises(SSLError):
await connect_tcp(*server_addr, tls_hostname="localhost")
thread.join()
assert thread_exception is None
@pytest.mark.parametrize("anyio_backend", asyncio_params)
async def test_unretrieved_future_exception_server_crash(
self, family: AnyIPAddressFamily, caplog: LogCaptureFixture
) -> None:
"""
Test that there won't be any leftover Futures that don't get their exceptions
retrieved.
See https://github.com/encode/httpcore/issues/382 for details.
"""
def serve() -> None:
sock, addr = server_sock.accept()
event.wait(3)
sock.close()
del sock
gc.collect()
with socket.socket(family, socket.SOCK_STREAM) as server_sock:
server_sock.settimeout(1)
server_sock.bind(("localhost", 0))
server_sock.listen()
server_addr = server_sock.getsockname()[:2]
event = threading.Event()
thread = Thread(target=serve)
thread.start()
async with await connect_tcp(*server_addr) as stream:
await stream.send(b"GET")
event.set()
with pytest.raises(BrokenResourceError):
await stream.receive()
thread.join()
gc.collect()
caplog_text = "\n".join(
msg
for msg in caplog.messages
if not re.search("took [0-9.]+ seconds", msg)
)
assert not caplog_text
@pytest.mark.network
class TestTCPListener:
async def test_extra_attributes(self, family: AnyIPAddressFamily) -> None:
async with await create_tcp_listener(
local_host="localhost", family=family
) as multi:
assert multi.extra(SocketAttribute.family) == family
for listener in multi.listeners:
raw_socket = listener.extra(SocketAttribute.raw_socket)
assert listener.extra(SocketAttribute.family) == family
assert (
listener.extra(SocketAttribute.local_address)
== raw_socket.getsockname()[:2]
)
assert (
listener.extra(SocketAttribute.local_port)
== raw_socket.getsockname()[1]
)
pytest.raises(
TypedAttributeLookupError,
listener.extra,
SocketAttribute.remote_address,
)
pytest.raises(
TypedAttributeLookupError,
listener.extra,
SocketAttribute.remote_port,
)
@pytest.mark.parametrize(
"family",
[
pytest.param(AddressFamily.AF_INET, id="ipv4"),
pytest.param(AddressFamily.AF_INET6, id="ipv6", marks=[skip_ipv6_mark]),
pytest.param(socket.AF_UNSPEC, id="both", marks=[skip_ipv6_mark]),
],
)
async def test_accept(self, family: AnyIPAddressFamily) -> None:
async with await create_tcp_listener(
local_host="localhost", family=family
) as multi:
for listener in multi.listeners:
client = socket.socket(listener.extra(SocketAttribute.family))
client.settimeout(1)
client.connect(listener.extra(SocketAttribute.local_address))
assert isinstance(listener, SocketListener)
stream = await listener.accept()
client.sendall(b"blah")
request = await stream.receive()
await stream.send(request[::-1])
assert client.recv(100) == b"halb"
client.close()
await stream.aclose()
async def test_accept_after_close(self, family: AnyIPAddressFamily) -> None:
async with await create_tcp_listener(
local_host="localhost", family=family
) as multi:
for listener in multi.listeners:
await listener.aclose()
assert isinstance(listener, SocketListener)
with pytest.raises(ClosedResourceError):
await listener.accept()
async def test_socket_options(self, family: AnyIPAddressFamily) -> None:
async with await create_tcp_listener(
local_host="localhost", family=family
) as multi:
for listener in multi.listeners:
raw_socket = listener.extra(SocketAttribute.raw_socket)
if sys.platform == "win32":
assert (
raw_socket.getsockopt(
socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE
)
!= 0
)
else:
assert (
raw_socket.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
!= 0
)
raw_socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 80000)
assert raw_socket.getsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF) in (
80000,
160000,
)
client = socket.socket(raw_socket.family)
client.settimeout(1)
client.connect(raw_socket.getsockname())
assert isinstance(listener, SocketListener)
async with await listener.accept() as stream:
raw_socket = stream.extra(SocketAttribute.raw_socket)
assert raw_socket.gettimeout() == 0
assert raw_socket.family == listener.extra(SocketAttribute.family)
assert (
raw_socket.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY)
!= 0
)
client.close()
@pytest.mark.skipif(
not hasattr(socket, "SO_REUSEPORT"), reason="SO_REUSEPORT option not supported"
)
async def test_reuse_port(self, family: AnyIPAddressFamily) -> None:
multi1 = await create_tcp_listener(
local_host="localhost", family=family, reuse_port=True
)
assert len(multi1.listeners) == 1
multi2 = await create_tcp_listener(
local_host="localhost",
local_port=multi1.listeners[0].extra(SocketAttribute.local_port),
family=family,
reuse_port=True,
)
assert len(multi2.listeners) == 1
assert multi1.listeners[0].extra(
SocketAttribute.local_address
) == multi2.listeners[0].extra(SocketAttribute.local_address)
await multi1.aclose()
await multi2.aclose()
async def test_close_from_other_task(self, family: AnyIPAddressFamily) -> None:
listener = await create_tcp_listener(local_host="localhost", family=family)
with pytest.raises(ExceptionGroup) as exc:
async with create_task_group() as tg:
tg.start_soon(listener.serve, lambda stream: None)
await wait_all_tasks_blocked()
await listener.aclose()
tg.cancel_scope.cancel()
assert len(exc.value.exceptions) == 1
assert isinstance(exc.value.exceptions[0], ExceptionGroup)
nested_grp = exc.value.exceptions[0]
assert len(nested_grp.exceptions) == 1
assert isinstance(nested_grp.exceptions[0], ExceptionGroup)
async def test_send_after_eof(self, family: AnyIPAddressFamily) -> None:
async def handle(stream: SocketStream) -> None:
async with stream:
await stream.send(b"Hello\n")
multi = await create_tcp_listener(family=family, local_host="localhost")
async with multi, create_task_group() as tg:
tg.start_soon(multi.serve, handle)
await wait_all_tasks_blocked()
with socket.socket(family) as client:
client.connect(multi.extra(SocketAttribute.local_address))
client.shutdown(socket.SHUT_WR)
client.setblocking(False)
with fail_after(1):
while True:
try:
message = client.recv(10)
except BlockingIOError:
await checkpoint()
else:
assert message == b"Hello\n"
break
tg.cancel_scope.cancel()
async def test_eof_after_send(self, family: AnyIPAddressFamily) -> None:
"""Regression test for #701."""
received_bytes = b""
async def handle(stream: SocketStream) -> None:
nonlocal received_bytes
async with stream:
received_bytes = await stream.receive()
with pytest.raises(EndOfStream), fail_after(1):
await stream.receive()
tg.cancel_scope.cancel()
multi = await create_tcp_listener(family=family, local_host="localhost")
async with multi, create_task_group() as tg:
with socket.socket(family) as client:
client.connect(multi.extra(SocketAttribute.local_address))
client.send(b"Hello")
client.shutdown(socket.SHUT_WR)
await multi.serve(handle)
assert received_bytes == b"Hello"
@skip_ipv6_mark
@pytest.mark.skipif(
sys.platform == "win32",
reason="Windows does not support interface name suffixes",
)
async def test_bind_link_local(self) -> None:
# Regression test for #554
link_local_ipv6_address = next(
(
addr.address
for addresses in psutil.net_if_addrs().values()
for addr in addresses
if addr.address.startswith("fe80::") and "%" in addr.address
),
None,
)
if link_local_ipv6_address is None:
pytest.fail("Could not find a link-local IPv6 interface")
async with await create_tcp_listener(local_host=link_local_ipv6_address):
pass
@pytest.mark.skipif(
sys.platform == "win32", reason="UNIX sockets are not available on Windows"
)
class TestUNIXStream:
@pytest.fixture(
params=[
"path",
pytest.param("abstract", marks=[skip_unix_abstract_mark]),
]
)
def socket_path(self, request: SubRequest) -> Generator[Path, None, None]:
# Use stdlib tempdir generation
# Fixes `OSError: AF_UNIX path too long` from pytest generated temp_path
with tempfile.TemporaryDirectory() as path:
if request.param == "path":
yield Path(path) / "socket"
else:
yield Path(f"\0{path}") / "socket"
@pytest.fixture(params=[False, True], ids=["str", "path"])
def socket_path_or_str(self, request: SubRequest, socket_path: Path) -> Path | str:
return socket_path if request.param else str(socket_path)
@pytest.fixture
def server_sock(self, socket_path: Path) -> Iterable[socket.socket]:
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.settimeout(1)
sock.bind(str(socket_path))
sock.listen()
yield sock
sock.close()
async def test_extra_attributes(
self, server_sock: socket.socket, socket_path: Path
) -> None:
async with await connect_unix(socket_path) as stream:
raw_socket = stream.extra(SocketAttribute.raw_socket)
assert stream.extra(SocketAttribute.family) == socket.AF_UNIX
assert (
stream.extra(SocketAttribute.local_address) == raw_socket.getsockname()
)
remote_addr = stream.extra(SocketAttribute.remote_address)
if isinstance(remote_addr, str):
assert stream.extra(SocketAttribute.remote_address) == str(socket_path)
else:
assert isinstance(remote_addr, bytes)
assert stream.extra(SocketAttribute.remote_address) == bytes(
socket_path
)
pytest.raises(
TypedAttributeLookupError, stream.extra, SocketAttribute.local_port
)
pytest.raises(
TypedAttributeLookupError, stream.extra, SocketAttribute.remote_port
)
async def test_send_receive(
self, server_sock: socket.socket, socket_path_or_str: Path | str
) -> None:
async with await connect_unix(socket_path_or_str) as stream:
client, _ = server_sock.accept()
await stream.send(b"blah")
request = client.recv(100)
client.sendall(request[::-1])
response = await stream.receive()
client.close()
assert response == b"halb"
async def test_receive_large_buffer(
self, server_sock: socket.socket, socket_path: Path
) -> None:
def serve() -> None:
client, _ = server_sock.accept()
client.sendall(buffer)
client.close()
buffer = (
b"\xff" * 1024 * 512 + b"\x00" * 1024 * 512
) # should exceed the maximum kernel send buffer size
async with await connect_unix(socket_path) as stream:
thread = Thread(target=serve, daemon=True)
thread.start()
response = b""
while len(response) < len(buffer):
response += await stream.receive()
thread.join()
assert response == buffer
async def test_send_large_buffer(
self, server_sock: socket.socket, socket_path: Path
) -> None:
response = b""
def serve() -> None:
nonlocal response
client, _ = server_sock.accept()
while True:
data = client.recv(1024)
if not data:
break
response += data
client.close()
buffer = (
b"\xff" * 1024 * 512 + b"\x00" * 1024 * 512
) # should exceed the maximum kernel send buffer size
async with await connect_unix(socket_path) as stream:
thread = Thread(target=serve, daemon=True)
thread.start()
await stream.send(buffer)
thread.join()
assert response == buffer
async def test_receive_fds(
self, server_sock: socket.socket, socket_path: Path, tmp_path: Path
) -> None:
def serve() -> None:
path1 = tmp_path / "file1"
path2 = tmp_path / "file2"
path1.write_text("Hello, ")
path2.write_text("World!")
with path1.open() as file1, path2.open() as file2:
fdarray = array.array("i", [file1.fileno(), file2.fileno()])
client, _ = server_sock.accept()
cmsg = (socket.SOL_SOCKET, socket.SCM_RIGHTS, fdarray)
with client:
client.sendmsg([b"test"], [cmsg])
async with await connect_unix(socket_path) as stream:
thread = Thread(target=serve, daemon=True)
thread.start()
message, fds = await stream.receive_fds(10, 2)
thread.join()
text = ""
for fd in fds:
with os.fdopen(fd) as file:
text += file.read()
assert message == b"test"
assert text == "Hello, World!"
async def test_receive_fds_bad_args(
self, server_sock: socket.socket, socket_path: Path
) -> None:
async with await connect_unix(socket_path) as stream:
for msglen in (-1, "foo"):
with pytest.raises(
ValueError, match="msglen must be a non-negative integer"
):
await stream.receive_fds(msglen, 0) # type: ignore[arg-type]
for maxfds in (0, "foo"):
with pytest.raises(
ValueError, match="maxfds must be a positive integer"
):
await stream.receive_fds(0, maxfds) # type: ignore[arg-type]
async def test_send_fds(
self, server_sock: socket.socket, socket_path: Path, tmp_path: Path
) -> None:
def serve() -> None:
fds = array.array("i")
client, _ = server_sock.accept()
msg, ancdata, *_ = client.recvmsg(10, socket.CMSG_LEN(2 * fds.itemsize))
client.close()
assert msg == b"test"
for cmsg_level, cmsg_type, cmsg_data in ancdata:
assert cmsg_level == socket.SOL_SOCKET
assert cmsg_type == socket.SCM_RIGHTS
fds.frombytes(
cmsg_data[: len(cmsg_data) - (len(cmsg_data) % fds.itemsize)]
)
text = ""
for fd in fds:
with os.fdopen(fd) as file:
text += file.read()
assert text == "Hello, World!"
path1 = tmp_path / "file1"
path2 = tmp_path / "file2"
path1.write_text("Hello, ")
path2.write_text("World!")
with path1.open() as file1, path2.open() as file2, fail_after(2):
assert isinstance(file1, io.TextIOWrapper)
assert isinstance(file2, io.TextIOWrapper)
async with await connect_unix(socket_path) as stream:
thread = Thread(target=serve, daemon=True)
thread.start()
await stream.send_fds(b"test", [file1, file2])
thread.join()
async def test_send_eof(
self, server_sock: socket.socket, socket_path: Path
) -> None:
def serve() -> None:
client, _ = server_sock.accept()
request = b""
while True:
data = client.recv(100)
request += data
if not data:
break
client.sendall(request[::-1])
client.close()
async with await connect_unix(socket_path) as stream:
thread = Thread(target=serve, daemon=True)
thread.start()
await stream.send(b"hello, ")
await stream.send(b"world\n")
await stream.send_eof()
response = await stream.receive()
thread.join()
assert response == b"\ndlrow ,olleh"
async def test_iterate(self, server_sock: socket.socket, socket_path: Path) -> None:
def serve() -> None:
client, _ = server_sock.accept()
client.sendall(b"bl")
time.sleep(0.05)
client.sendall(b"ah")
client.close()
thread = Thread(target=serve, daemon=True)
thread.start()
chunks = []
async with await connect_unix(socket_path) as stream:
async for chunk in stream:
chunks.append(chunk)
thread.join()
assert chunks == [b"bl", b"ah"]
async def test_send_fds_bad_args(
self, server_sock: socket.socket, socket_path: Path
) -> None:
async with await connect_unix(socket_path) as stream:
with pytest.raises(ValueError, match="message must not be empty"):
await stream.send_fds(b"", [0])