| 1 |
import os |
| 2 |
import socket |
| 3 |
import sys |
| 4 |
import tempfile |
| 5 |
from typing import TYPE_CHECKING |
| 6 |
|
| 7 |
import pytest |
| 8 |
|
| 9 |
from trio import Path, open_unix_socket |
| 10 |
from trio._highlevel_open_unix_stream import close_on_error |
| 11 |
|
| 12 |
assert not TYPE_CHECKING or sys.platform != "win32" |
| 13 |
|
| 14 |
skip_if_not_unix = pytest.mark.skipif( |
| 15 |
not hasattr(socket, "AF_UNIX"), |
| 16 |
reason="Needs unix socket support", |
| 17 |
) |
| 18 |
|
| 19 |
|
| 20 |
@skip_if_not_unix |
| 21 |
def test_close_on_error() -> None: |
| 22 |
class CloseMe: |
| 23 |
closed = False |
| 24 |
|
| 25 |
def close(self) -> None: |
| 26 |
self.closed = True |
| 27 |
|
| 28 |
with close_on_error(CloseMe()) as c: |
| 29 |
pass |
| 30 |
assert not c.closed |
| 31 |
|
| 32 |
with pytest.raises(RuntimeError): |
| 33 |
with close_on_error(CloseMe()) as c: |
| 34 |
raise RuntimeError |
| 35 |
assert c.closed |
| 36 |
|
| 37 |
|
| 38 |
@skip_if_not_unix |
| 39 |
@pytest.mark.parametrize("filename", [4, 4.5]) |
| 40 |
async def test_open_with_bad_filename_type(filename: float) -> None: |
| 41 |
with pytest.raises(TypeError): |
| 42 |
await open_unix_socket(filename) # type: ignore[arg-type] |
| 43 |
|
| 44 |
|
| 45 |
@skip_if_not_unix |
| 46 |
async def test_open_bad_socket() -> None: |
| 47 |
# mktemp is marked as insecure, but that's okay, we don't want the file to |
| 48 |
# exist |
| 49 |
name = tempfile.mktemp() |
| 50 |
with pytest.raises(FileNotFoundError): |
| 51 |
await open_unix_socket(name) |
| 52 |
|
| 53 |
|
| 54 |
@skip_if_not_unix |
| 55 |
async def test_open_unix_socket() -> None: |
| 56 |
for name_type in [Path, str]: |
| 57 |
name = tempfile.mktemp() |
| 58 |
serv_sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) |
| 59 |
with serv_sock: |
| 60 |
serv_sock.bind(name) |
| 61 |
try: |
| 62 |
serv_sock.listen(1) |
| 63 |
|
| 64 |
# The actual function we're testing |
| 65 |
unix_socket = await open_unix_socket(name_type(name)) |
| 66 |
|
| 67 |
async with unix_socket: |
| 68 |
client, _ = serv_sock.accept() |
| 69 |
with client: |
| 70 |
await unix_socket.send_all(b"test") |
| 71 |
assert client.recv(2048) == b"test" |
| 72 |
|
| 73 |
client.sendall(b"response") |
| 74 |
received = await unix_socket.receive_some(2048) |
| 75 |
assert received == b"response" |
| 76 |
finally: |
| 77 |
os.unlink(name) |
| 78 |
|
| 79 |
|
| 80 |
@pytest.mark.skipif(hasattr(socket, "AF_UNIX"), reason="Test for non-unix platforms") |
| 81 |
async def test_error_on_no_unix() -> None: |
| 82 |
with pytest.raises( |
| 83 |
RuntimeError, |
| 84 |
match=r"^Unix sockets are not supported on this platform$", |
| 85 |
): |
| 86 |
await open_unix_socket("") |