Skip to content

Commit 11a1761

Browse files
committed
fix: detect JSON responses by parsing body instead of content-type
1 parent ff522d6 commit 11a1761

2 files changed

Lines changed: 30 additions & 9 deletions

File tree

apick.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -525,14 +525,10 @@ def execute_request(
525525
print(f"\n{color}{resp.status_code} {resp.reason_phrase}\033[0m")
526526

527527
# Response body
528-
ct = resp.headers.get("content-type", "")
529-
if "json" in ct:
530-
try:
531-
formatted = json.dumps(resp.json(), indent=2)
532-
print(highlight_json(formatted))
533-
except Exception:
534-
print(resp.text)
535-
else:
528+
try:
529+
formatted = json.dumps(resp.json(), indent=2)
530+
print(highlight_json(formatted))
531+
except Exception:
536532
print(resp.text)
537533

538534
return resp.status_code

tests/test_apick.py

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -483,9 +483,34 @@ def test_returns_status_code(self):
483483
mock_resp = MagicMock()
484484
mock_resp.status_code = 200
485485
mock_resp.reason_phrase = "OK"
486-
mock_resp.headers = {"content-type": "text/plain"}
486+
mock_resp.json.side_effect = ValueError("not json")
487487
mock_resp.text = "ok"
488488

489489
with patch("apick.httpx.request", return_value=mock_resp):
490490
result = apick.execute_request("GET", "https://example.com", {})
491491
assert result == 200
492+
493+
def test_json_response_highlighted(self):
494+
mock_resp = MagicMock()
495+
mock_resp.status_code = 200
496+
mock_resp.reason_phrase = "OK"
497+
mock_resp.json.return_value = {"key": "value"}
498+
499+
with (
500+
patch("apick.httpx.request", return_value=mock_resp),
501+
patch("apick.highlight_json", return_value='{\n "key": "value"\n}') as mock_hl,
502+
):
503+
result = apick.execute_request("GET", "https://example.com", {})
504+
assert result == 200
505+
mock_hl.assert_called_once()
506+
507+
def test_invalid_json_falls_back_to_text(self, capsys):
508+
mock_resp = MagicMock()
509+
mock_resp.status_code = 200
510+
mock_resp.reason_phrase = "OK"
511+
mock_resp.json.side_effect = ValueError("not json")
512+
mock_resp.text = "plain text body"
513+
514+
with patch("apick.httpx.request", return_value=mock_resp):
515+
apick.execute_request("GET", "https://example.com", {})
516+
assert "plain text body" in capsys.readouterr().out

0 commit comments

Comments
 (0)