Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 9 additions & 11 deletions pytest_socket.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,11 @@


class SocketBlockedError(RuntimeError):
def __init__(self, *_args, **_kwargs):
super().__init__("A test tried to use socket.socket.")
pass


class SocketConnectBlockedError(RuntimeError):
def __init__(self, allowed, host, *_args, **_kwargs):
if allowed:
allowed = ",".join(allowed)
super().__init__(
"A test tried to use socket.socket.connect() "
f'with host "{host}" (allowed: "{allowed}").'
)
pass


def pytest_addoption(parser):
Expand Down Expand Up @@ -100,7 +93,7 @@ def __new__(cls, family=-1, type=-1, proto=-1, fileno=None):
if _is_unix_socket(family) and allow_unix_socket:
return super().__new__(cls, family, type, proto, fileno)

raise SocketBlockedError()
raise SocketBlockedError("A test tried to use socket.socket.")

socket.socket = GuardedSocket

Expand Down Expand Up @@ -283,7 +276,12 @@ def guarded_connect(inst, *args):
):
return _true_connect(inst, *args)

raise SocketConnectBlockedError(allowed_list, host)
allowed = ",".join(allowed_list) if allowed_list else "[]"
message = (
"A test tried to use socket.socket.connect() "
f'with host "{host}" (allowed: "{allowed}").'
)
raise SocketConnectBlockedError(message)

socket.socket.connect = guarded_connect

Expand Down
Loading