Skip to content

Commit e2f51b8

Browse files
authored
Output attempted address in strict mode (#296)
* Output attempted address in strict mode * Update test
1 parent 713ccd6 commit e2f51b8

File tree

3 files changed

+20
-5
lines changed

3 files changed

+20
-5
lines changed

mocket/mode.py

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,15 +31,28 @@ def is_allowed(self, location: str | tuple[str, int]) -> bool:
3131
return host_allowed or location in self.STRICT_ALLOWED
3232

3333
@staticmethod
34-
def raise_not_allowed() -> NoReturn:
34+
def raise_not_allowed(
35+
address: tuple[str, int] | None = None,
36+
data: bytes | None = None,
37+
) -> NoReturn:
3538
current_entries = [
3639
(location, "\n ".join(map(str, entries)))
3740
for location, entries in Mocket._entries.items()
3841
]
3942
formatted_entries = "\n".join(
4043
[f" {location}:\n {entries}" for location, entries in current_entries]
4144
)
42-
raise StrictMocketException(
43-
"Mocket tried to use the real `socket` module while STRICT mode was active.\n"
44-
f"Registered entries:\n{formatted_entries}"
45+
msg = (
46+
"Mocket tried to use the real `socket` module while STRICT mode was active."
4547
)
48+
if address:
49+
host, port = address
50+
msg += f"\nAttempted address: {host}:{port}"
51+
if data:
52+
from mocket.compat import decode_from_bytes
53+
54+
preview = decode_from_bytes(data).split("\r\n", 1)[0][:200]
55+
msg += f"\nFirst request line: {preview}"
56+
57+
msg += f"\nRegistered entries:\n{formatted_entries}"
58+
raise StrictMocketException(msg)

mocket/socket.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -229,7 +229,7 @@ def recv(self, buffersize: int, flags: int | None = None) -> bytes:
229229

230230
def true_sendall(self, data: bytes, *args: Any, **kwargs: Any) -> bytes:
231231
if not MocketMode().is_allowed(self._address):
232-
MocketMode.raise_not_allowed()
232+
MocketMode.raise_not_allowed(self._address, data)
233233

234234
# try to get the response from recordings
235235
if Mocket._record_storage:

tests/test_mode.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,8 @@ def test_strict_mode_error_message():
5252
str(exc_info.value)
5353
== """
5454
Mocket tried to use the real `socket` module while STRICT mode was active.
55+
Attempted address: httpbin.local:80
56+
First request line: GET /ip HTTP/1.1
5557
Registered entries:
5658
('httpbin.local', 80):
5759
Entry(method='GET', schema='http', location=('httpbin.local', 80), path='/user.agent', query='')

0 commit comments

Comments
 (0)