Skip to content

Commit

Permalink
Raise CannotParseBodyErrorAsJson when the body is invalid JSON.
Browse files Browse the repository at this point in the history
  • Loading branch information
DevL committed Mar 20, 2024
1 parent 6f8a1ff commit 74fe124
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
12 changes: 11 additions & 1 deletion src/requtests/parsed_request.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
import json
from json import JSONDecodeError
from typing import Any, Dict, List, Optional, Union
from urllib.parse import parse_qs, urlparse


class CannotParseBodyAsJson(RuntimeError):
def __init__(self, error):
super().__init__(error)
self.error = error


class ParsedRequest:
def __init__(self, prepared_request):
self.prepared_request = prepared_request
Expand All @@ -29,7 +36,10 @@ def json(self) -> Any:
"""
The body of the prepared request, parsed as JSON.
"""
return json.loads(self.prepared_request.body)
try:
return json.loads(self.prepared_request.body)
except (TypeError, JSONDecodeError) as e:
raise CannotParseBodyAsJson(e)

@property
def method(self) -> str:
Expand Down
15 changes: 10 additions & 5 deletions tests/parsed_request_test.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from json import JSONDecodeError
import re
import pytest
import re
from requtests import ParsedRequest
from requtests.parsed_request import CannotParseBodyAsJson
from tests.test_utils import build_request


Expand Down Expand Up @@ -50,15 +51,19 @@ def test_parsing_a_prepared_request(prepared_request):
def test_json_with_an_empty_body(parsed_request):
parsed_request.prepared_request.body = None
expected_message = "the JSON object must be str, bytes or bytearray, not NoneType"
with pytest.raises(TypeError, match=expected_message):
assert parsed_request.json
with pytest.raises(CannotParseBodyAsJson, match=expected_message) as exc_info:
parsed_request.json
underlying_error = exc_info.value.error
assert isinstance(underlying_error, TypeError)


def test_json_with_an_invalid_json_body(parsed_request):
parsed_request.prepared_request.body = '{"broken": "json'
expected_message = re.escape("Unterminated string starting at: line 1 column 12 (char 11)")
with pytest.raises(JSONDecodeError, match=expected_message):
assert parsed_request.json
with pytest.raises(CannotParseBodyAsJson, match=expected_message) as exc_info:
parsed_request.json
underlying_error = exc_info.value.error
assert isinstance(underlying_error, JSONDecodeError)


def test_text_with_an_empty_body(parsed_request):
Expand Down

0 comments on commit 74fe124

Please sign in to comment.