Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Recording: allow for storing recorded responses in human-readable form #270

Closed
wants to merge 12 commits into from
Prev Previous commit
Next Next commit
[feature/use_hex_encoding]
wojciak committed Nov 22, 2024
commit a8ca787f2c76c4a6041ea36e4b4c463160a08514
23 changes: 9 additions & 14 deletions mocket/socket.py
Original file line number Diff line number Diff line change
@@ -12,7 +12,7 @@
from datetime import datetime, timedelta
from json.decoder import JSONDecodeError

from mocket.compat import decode_from_bytes, encode_to_bytes
from mocket.compat import decode_from_bytes, encode_to_bytes, ENCODING
from mocket.inject import (
true_gethostbyname,
true_socket,
@@ -23,7 +23,6 @@
from mocket.mode import MocketMode
from mocket.utils import hexdump, hexload


logger = logging.getLogger(__name__)
xxh32 = None
try:
@@ -275,8 +274,8 @@ def true_sendall(self, data, *args, **kwargs):
else:
headers, body = response.split("\r\n\r\n", 1)

headers_bytes = headers.encode("utf-8")
body_bytes = body.encode("utf-8")
headers_bytes = headers.encode(ENCODING)
body_bytes = body.encode(ENCODING)

if "content-encoding: gzip" in headers.lower():
body_bytes = gzip.compress(body_bytes)
@@ -316,18 +315,14 @@ def true_sendall(self, data, *args, **kwargs):
if Mocket.get_use_hex_encoding():
response_dict["response"] = hexdump(encoded_response)
else:
try:
headers, body = encoded_response.split(b"\r\n\r\n", 1)

if b"content-encoding: gzip" in headers.lower():
body = gzip.decompress(body)
headers, body = encoded_response.split(b"\r\n\r\n", 1)

response_dict["response"] = (
headers + b"\r\n\r\n" + body
).decode("utf-8")
if b"content-encoding: gzip" in headers.lower():
body = gzip.decompress(body)

except UnicodeDecodeError as e:
logger.warning("Mocket: Response not recorded: %s", e)
response_dict["response"] = (headers + b"\r\n\r\n" + body).decode(
ENCODING
)

with open(path, mode="w") as f:
f.write(