-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathmode.py
More file actions
61 lines (48 loc) · 1.85 KB
/
mode.py
File metadata and controls
61 lines (48 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
from __future__ import annotations
from typing import TYPE_CHECKING, Any, ClassVar
from mocket.exceptions import StrictMocketException
from mocket.mocket import Mocket
if TYPE_CHECKING: # pragma: no cover
from typing import NoReturn
class _MocketMode:
__shared_state: ClassVar[dict[str, Any]] = {}
STRICT: ClassVar = None
STRICT_ALLOWED: ClassVar = None
def __init__(self) -> None:
self.__dict__ = self.__shared_state
def is_allowed(self, location: str | tuple[str, int]) -> bool:
"""
Checks if (`host`, `port`) or at least `host`
are allowed locations to perform real `socket` calls
"""
if not self.STRICT:
return True
host_allowed = False
if isinstance(location, tuple):
host_allowed = location[0] in self.STRICT_ALLOWED
return host_allowed or location in self.STRICT_ALLOWED
@staticmethod
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()
]
formatted_entries = "\n".join(
[f" {location}:\n {entries}" for location, entries in current_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"\nSent data: {preview}"
msg += f"\nRegistered entries:\n{formatted_entries}"
raise StrictMocketException(msg)
MocketMode = _MocketMode()