def test_to_string(self): mime_type = MIMEType("application", "json", 0.9, {"v": "b3"}) self.assertEqual("application/json", mime_type.to_string(with_details=False)) self.assertEqual("application/json;v=b3;q=0.9", mime_type.to_string(with_details=True))
def test_get_best_match_wildcard_in_input(self): http_accept = HttpAccept([ MIMEType("text", "html"), MIMEType("application", "xml", 0.9), ]) self.assertEqual( ("text/*", MIMEType("text", "html")), http_accept.get_best_match(["text/*", "application/xml"]))
def test_get_best_match_wildcard(self): http_accept = HttpAccept([ MIMEType("text", "*"), MIMEType("application", "xml"), ]) self.assertEqual( ("text/html", MIMEType("text", "*")), http_accept.get_best_match(["text/html", "application/json"]))
def test_get_best_match(self): http_accept = HttpAccept([ MIMEType("application", "json", 0.8), MIMEType("application", "xml", 0.9), ]) self.assertEqual( ("application/xml", MIMEType("application", "xml", 0.9)), http_accept.get_best_match(["application/json", "application/xml"]))
def test_matches_mime_type_string(self): self.assertTrue( MIMEType("text", "html").matches_mime_type_string("text/html")) self.assertTrue( MIMEType("text", "*").matches_mime_type_string("text/html")) self.assertTrue( MIMEType("text", "html").matches_mime_type_string("text/*")) self.assertTrue(MIMEType("*", "*").matches_mime_type_string("text/*")) self.assertFalse( MIMEType("text", "*").matches_mime_type_string("application/json"))
def test_application_json_to_dict(self): json_bytes = json.dumps({"key": "value"}).encode() json_dict = RequestDeserializerService.deserialize_request_body( json_bytes, MIMEType.from_string("application/json"), dict) self.assertEqual(json_dict, {"key": "value"})
def test_create_from_string(self): mime_type_string = "application/signed-exchange+xml;v=b3;q=0.9" mime_type = MIMEType.from_string(mime_type_string) self.assertEqual("application", mime_type.type) self.assertEqual("signed-exchange+xml", mime_type.subtype) self.assertEqual(0.9, mime_type.quality) self.assertEqual("b3", mime_type.details["v"])
def test_create_from_string_without_details(self): mime_type_string = "text/html" mime_type = MIMEType.from_string(mime_type_string) self.assertEqual("text", mime_type.type) self.assertEqual("html", mime_type.subtype) self.assertEqual(1.0, mime_type.quality) self.assertEqual({}, mime_type.details)
def test_prioritize_media_type(self): http_accept = HttpAccept( [MIMEType("application", "json"), MIMEType("text", "plain", 0.7)]) ResponseSerializerService.clear_all_response_serializer() ResponseSerializerService.register_response_serializer( DefaultDictJsonResponseSerializer()) ResponseSerializerService.register_response_serializer( DefaultDictTextResponseSerializer()) response = Response({"key": "value"}) ResponseSerializerService.validate_and_serialize_response_body( response, http_accept) self.assertEqual(b'{"key": "value"}', response.content) self.assertEqual("application/json", response._headers["Content-Type"])
def can_handle(self, content_type: MIMEType, python_type: Type) -> bool: if self.get_content_type_list() is None: return python_type == self.get_deserialized_python_type() for content_type_string in self.get_content_type_list(): if content_type.matches_mime_type_string(content_type_string) and \ python_type == self.get_deserialized_python_type(): return True return False
def test_request_deserializer_content_type_fallback(self): json_bytes = json.dumps({"key": "value"}).encode() with self.assertLogs(level="WARNING") as log: RequestDeserializerService.deserialize_request_body( json_bytes, MIMEType.from_string("whats/up"), dict) self.assertIn( 'WARNING:restit.internal.default_request_deserializer.default_fallback_dict_deserializer:Trying to ' 'parse JSON from content type != application/json', log.output)
def test_not_implemented(self): response_serializer = ResponseSerializer() with self.assertRaises(NotImplementedError): response_serializer.get_media_type_strings() with self.assertRaises(NotImplementedError): response_serializer.get_response_data_type() with self.assertRaises(NotImplementedError): response_serializer.validate_and_serialize( "", None, CanHandleResultType("", MIMEType.from_string("*/*")))
def test_request_deserializer_not_found_for_python_type(self): json_bytes = json.dumps({"key": "value"}).encode() with self.assertRaises( RequestDeserializerService.NoRequestDeserializerFoundException ) as exception: RequestDeserializerService.deserialize_request_body( json_bytes, MIMEType.from_string("application/json"), datetime) self.assertEqual( "Unable to find a request deserializer for content type MIMEType(type=application, subtype=json, " "quality=1.0, details={}) to type " "<class 'datetime.datetime'>", str(exception.exception))
def test_custom_request_deserializer(self): class MyRequestDeserializer(RequestDeserializer): def get_content_type_list(self) -> Union[List[str], None]: return ["whats/up"] def get_deserialized_python_type(self) -> Type: return str def deserialize(self, request_input: bytes, encoding: str = None) -> str: return "".join(reversed(request_input.decode())) RequestDeserializerService.register_request_deserializer( MyRequestDeserializer()) deserialized_value = RequestDeserializerService.deserialize_request_body( b"hello", MIMEType.from_string("whats/up"), str) self.assertEqual("olleh", deserialized_value)
def test_create_http_accept_from_string(self): http_accept_string = \ 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,' \ '*/*;q=0.8,application/signed-exchange;v=b3;q=0.9' http_accept = HttpAccept.from_accept_string(http_accept_string) self.assertEqual(7, len(http_accept.mime_types)) self.assertEqual(MIMEType("text", "html"), http_accept.mime_types[0]) self.assertEqual(MIMEType("application", "xhtml+xml"), http_accept.mime_types[1]) self.assertEqual(MIMEType("image", "webp"), http_accept.mime_types[2]) self.assertEqual(MIMEType("image", "apng"), http_accept.mime_types[3]) self.assertEqual(MIMEType("application", "xml", 0.9, {"q": "0.9"}), http_accept.mime_types[4]) self.assertEqual( MIMEType("application", "signed-exchange", 0.9, { "v": "b3", "q": "0.9" }), http_accept.mime_types[5]) self.assertEqual(MIMEType("*", "*", 0.8, {"q": "0.8"}), http_accept.mime_types[6])
def test_parse_wildcard(self): mime_type = MIMEType.from_string("*/*;q=0.8") self.assertIsNone(mime_type.type) self.assertIsNone(mime_type.subtype) self.assertEqual(0.8, mime_type.quality)
def test_with_charset(self): mime_type = MIMEType.from_string("application/json; charset=utf-8") self.assertEqual("utf-8", mime_type.charset)
def test_str_hook(self): http_accept = HttpAccept([MIMEType("text", "html")]) self.assertEqual( "HttpAccept(['MIMEType(type=text, subtype=html, quality=1.0, details={})'])", str(http_accept))
def test_quality_compare(self): mime_type1 = MIMEType("application", "json") mime_type2 = MIMEType("text", "html", 0.9) self.assertGreater(mime_type1, mime_type2) self.assertLess(mime_type2, mime_type1)
def test_mime_type_equal(self): mime_type1 = MIMEType("application", "json", 0.9) mime_type2 = MIMEType("application", "json", 0.9) self.assertEqual(mime_type1, mime_type2)
def test_parse_with_trailing_whitespaces(self): MIMEType.from_string(" image/jpeg")
def test_form_data_to_dict(self): json_dict = RequestDeserializerService.deserialize_request_body( b"key=value&key2=value", MIMEType.from_string("application/x-www-form-urlencoded"), dict) self.assertEqual({'key': 'value', 'key2': 'value'}, json_dict)
def get_schema_for_content_type(self, content_type: MIMEType) -> Union[Schema, Type]: try: return self.content_types[content_type.to_string()] except KeyError: raise UnsupportedMediaType()
def test_default_dict_to_json(self): response = Response({"key": "value"}) ResponseSerializerService.validate_and_serialize_response_body( response, HttpAccept([MIMEType("application", "json")])) self.assertEqual(b'{"key": "value"}', response.content)
def test_default_list_to_json(self): response = Response(["1", 2]) ResponseSerializerService.validate_and_serialize_response_body( response, HttpAccept([MIMEType("application", "json")])) self.assertEqual(b'["1", 2]', response.content)
def test_incorrect_wildcard_order(self): with self.assertRaises(MIMEType.MIMETypeWildcardHierarchyException): MIMEType.from_string("*/html")
def content_type(self) -> MIMEType: return MIMEType.from_string( self._headers.get("Content-Type") or "text/plain")
def test_parsing_failed(self): with self.assertRaises(MIMEType.MIMETypeParsingException): MIMEType.from_string("can not parse me")