diff --git a/mailtrap/http.py b/mailtrap/http.py index 60b474d..d67634b 100644 --- a/mailtrap/http.py +++ b/mailtrap/http.py @@ -55,6 +55,12 @@ def _process_response(self, response: Response) -> Any: if not response.content.strip(): return None + content_type = response.headers.get("Content-Type", "") + media_type = content_type.partition(";")[0].strip().lower() + is_json = media_type == "application/json" or media_type.endswith("+json") + if content_type and not is_json: + return response.text + try: return response.json() except (JSONDecodeError, ValueError): diff --git a/tests/unit/api/sandbox/test_messages.py b/tests/unit/api/sandbox/test_messages.py index 9828069..6835d11 100644 --- a/tests/unit/api/sandbox/test_messages.py +++ b/tests/unit/api/sandbox/test_messages.py @@ -609,6 +609,33 @@ def test_get_text_message_should_return_text_content( assert result == text_content + @pytest.mark.parametrize( + "text_content,content_type", + [ + ("123456", "text/plain"), + ("true", "text/plain"), + ("null", "text/plain"), + ('{"code": 123456}', "text/plain"), + ('"quoted"', "text/plain"), + ("123456", 'text/plain; name="body.json"'), + ], + ) + @responses.activate + def test_get_text_message_should_not_parse_json_looking_text( + self, client: MessagesApi, text_content: str, content_type: str + ) -> None: + url = f"{BASE_MESSAGES_URL}/{MESSAGE_ID}/body.txt" + responses.get( + url, + body=text_content, + status=200, + content_type=content_type, + ) + + result = client.get_text_message(INBOX_ID, MESSAGE_ID) + + assert result == text_content + @pytest.mark.parametrize( "status_code,response_body,expected_error_message,content_type", [