diff --git a/mocket/mode.py b/mocket/mode.py index e1da795..06cd373 100644 --- a/mocket/mode.py +++ b/mocket/mode.py @@ -31,7 +31,10 @@ def is_allowed(self, location: str | tuple[str, int]) -> bool: return host_allowed or location in self.STRICT_ALLOWED @staticmethod - def raise_not_allowed() -> NoReturn: + def raise_not_allowed( + address: tuple[str, int] | None = None, + data: bytes | None = None, + ) -> NoReturn: current_entries = [ (location, "\n ".join(map(str, entries))) for location, entries in Mocket._entries.items() @@ -39,7 +42,17 @@ def raise_not_allowed() -> NoReturn: formatted_entries = "\n".join( [f" {location}:\n {entries}" for location, entries in current_entries] ) - raise StrictMocketException( - "Mocket tried to use the real `socket` module while STRICT mode was active.\n" - f"Registered entries:\n{formatted_entries}" + msg = ( + "Mocket tried to use the real `socket` module while STRICT mode was active." ) + if address: + host, port = address + msg += f"\nAttempted address: {host}:{port}" + if data: + from mocket.compat import decode_from_bytes + + preview = decode_from_bytes(data).split("\r\n", 1)[0][:200] + msg += f"\nFirst request line: {preview}" + + msg += f"\nRegistered entries:\n{formatted_entries}" + raise StrictMocketException(msg) diff --git a/mocket/socket.py b/mocket/socket.py index 496c912..cc498a5 100644 --- a/mocket/socket.py +++ b/mocket/socket.py @@ -229,7 +229,7 @@ def recv(self, buffersize: int, flags: int | None = None) -> bytes: def true_sendall(self, data: bytes, *args: Any, **kwargs: Any) -> bytes: if not MocketMode().is_allowed(self._address): - MocketMode.raise_not_allowed() + MocketMode.raise_not_allowed(self._address, data) # try to get the response from recordings if Mocket._record_storage: diff --git a/tests/test_mode.py b/tests/test_mode.py index ea5905b..7d4e212 100644 --- a/tests/test_mode.py +++ b/tests/test_mode.py @@ -52,6 +52,8 @@ def test_strict_mode_error_message(): str(exc_info.value) == """ Mocket tried to use the real `socket` module while STRICT mode was active. +Attempted address: httpbin.local:80 +First request line: GET /ip HTTP/1.1 Registered entries: ('httpbin.local', 80): Entry(method='GET', schema='http', location=('httpbin.local', 80), path='/user.agent', query='')