Skip to content

Commit 6dedf58

Browse files
Better Strict Mode (#298)
* Output attempted address in strict mode (#296) * Update test * Make it more HTTP-agnostic. --------- Co-authored-by: Wilhelm Klopp <wilhelmklopp@users.noreply.github.com>
1 parent 713ccd6 commit 6dedf58

File tree

4 files changed

+29
-11
lines changed

4 files changed

+29
-11
lines changed

mocket/decorators/mocketizer.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,9 @@ def __init__(
1515
self.instance = instance
1616
self.truesocket_recording_dir = truesocket_recording_dir
1717
self.namespace = namespace or str(id(self))
18-
MocketMode().STRICT = strict_mode
18+
MocketMode.STRICT = strict_mode
1919
if strict_mode:
20-
MocketMode().STRICT_ALLOWED = strict_mode_allowed or []
20+
MocketMode.STRICT_ALLOWED = strict_mode_allowed or []
2121
elif strict_mode_allowed:
2222
raise ValueError(
2323
"Allowed locations are only accepted when STRICT mode is active."

mocket/mode.py

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from typing import NoReturn
1010

1111

12-
class MocketMode:
12+
class _MocketMode:
1313
__shared_state: ClassVar[dict[str, Any]] = {}
1414
STRICT: ClassVar = None
1515
STRICT_ALLOWED: ClassVar = None
@@ -31,15 +31,31 @@ 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"\nSent data: {preview}"
56+
57+
msg += f"\nRegistered entries:\n{formatted_entries}"
58+
raise StrictMocketException(msg)
59+
60+
61+
MocketMode = _MocketMode()

mocket/socket.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -228,8 +228,8 @@ def recv(self, buffersize: int, flags: int | None = None) -> bytes:
228228
raise exc
229229

230230
def true_sendall(self, data: bytes, *args: Any, **kwargs: Any) -> bytes:
231-
if not MocketMode().is_allowed(self._address):
232-
MocketMode.raise_not_allowed()
231+
if not MocketMode.is_allowed(self._address):
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: 4 additions & 2 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+
Sent data: 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='')
@@ -67,5 +69,5 @@ def test_strict_mode_false_with_allowed_hosts():
6769
@pytest.mark.parametrize("strict_mode_on", (False, True))
6870
def test_strict_mode_allowed_or_not(strict_mode_on):
6971
with Mocketizer(strict_mode=strict_mode_on):
70-
assert MocketMode().is_allowed("foobar.com") is not strict_mode_on
71-
assert MocketMode().is_allowed(("foobar.com", 443)) is not strict_mode_on
72+
assert MocketMode.is_allowed("foobar.com") is not strict_mode_on
73+
assert MocketMode.is_allowed(("foobar.com", 443)) is not strict_mode_on

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy