Example #1
0
    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"]))
Example #2
0
    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"]))
Example #3
0
    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"]))
Example #4
0
 def test_str_response_validation_failed(self):
     response = Response("1234")
     with self.assertRaises(ValidationError):
         ResponseSerializerService.validate_and_serialize_response_body(
             response, HttpAccept.from_accept_string("text/plain"),
             ResponseStatusParameter(200, "",
                                     {"text/plain": fields.Email()}))
Example #5
0
    def test_register_response_serializer(self):
        class MyResponseSerializer(ResponseSerializer):
            def get_response_data_type(self) -> type:
                return str

            def get_media_type_strings(self) -> List[str]:
                return ["my/type"]

            def validate_and_serialize(
                    self, response_input: Any,
                    response_status_parameter: Union[None,
                                                     ResponseStatusParameter],
                    can_handle_result: CanHandleResultType
            ) -> Tuple[bytes, str]:
                assert can_handle_result.mime_type.charset == "ascii"
                return "".join(reversed(response_input)).encode(
                    encoding=can_handle_result.mime_type.charset), "my/type"

        ResponseSerializerService.register_response_serializer(
            MyResponseSerializer())
        response = Response("Test")
        ResponseSerializerService.validate_and_serialize_response_body(
            response, HttpAccept.from_accept_string("my/type; charset=ascii"))

        self.assertEqual(b'tseT', response.content)
Example #6
0
    def test_dict_fallback_response_serializer(self):
        ResponseSerializerService.register_response_serializer(
            DictFallbackResponseSerializer())
        response = Response({"key": "value"})
        ResponseSerializerService.validate_and_serialize_response_body(
            response, HttpAccept.from_accept_string("wuff/miau"))

        self.assertEqual(b'{"key": "value"}', response.content)
        self.assertEqual("application/json", response._headers["Content-Type"])
Example #7
0
    def test_make_html_response_no_debug(self):
        response = self.response_maker.create_response(
            HttpAccept.from_accept_string("text/html"))

        self.assertEqual(500, response.status_code)
        self.assertIn("<title>500 Internal Server Error</title>",
                      response.text)
        self.assertIn("<h1>Internal Server Error</h1>", response.text)
        self.assertIn("<p>Something is not working</p>", response.text)
Example #8
0
    def test_string_fallback_response_serializer(self):
        ResponseSerializerService.register_response_serializer(
            StringFallbackResponseSerializer())
        response = Response("huhu")
        ResponseSerializerService.validate_and_serialize_response_body(
            response, HttpAccept.from_accept_string("wuff/miau"))

        self.assertEqual(b'huhu', response.content)
        self.assertEqual("text/plain", response._headers["Content-Type"])
Example #9
0
    def test_bytes_response_body_with_schema(self):
        response = Response(b"1234")
        ResponseSerializerService.validate_and_serialize_response_body(
            response, HttpAccept.from_accept_string("text/plain"),
            ResponseStatusParameter(200, "", {"text/plain": fields.Integer()}))

        self.assertEqual(b"1234", response.content)
        self.assertEqual("1234", response.text)
        self.assertEqual("text/plain", response.headers["Content-Type"])
Example #10
0
    def test_make_html_response_debug(self):
        response = HttpErrorResponseMaker(
            InternalServerError("Something is not working",
                                traceback="traceback"),
            debug=True).create_response(
                HttpAccept.from_accept_string("text/html"))

        self.assertEqual(500, response.status_code)
        self.assertIn("<title>500 Internal Server Error</title>",
                      response.text)
        self.assertIn("<h1>Internal Server Error</h1>", response.text)
        self.assertIn("Something is not working", response.text)
        self.assertIn("traceback", response.text)
Example #11
0
    def test_make_application_json_error(self):
        response = self.response_maker.create_response(
            HttpAccept.from_accept_string("application/json"))

        self.assertEqual(500, response.status_code)
        self.assertEqual(
            {
                'detail': 'Something is not working',
                'instance': None,
                'status': 500,
                'title': 'Internal Server Error',
                'type':
                'https://developer.mozilla.org/de/docs/Web/HTTP/Status/500'
            }, response.json())
Example #12
0
    def create_response(self, http_accept: HttpAccept) -> Response:
        supported_media_types = [
            "text/html", "application/xhtml+xml", "application/json", "application/problem+json"
        ]
        best_match = http_accept.get_best_match(supported_media_types)
        if best_match is None:
            response = self.create_plain_text_response()
        else:
            best_match = best_match[0]

            if best_match in ["text/html", "application/xhtml+xml"]:
                response = self.create_html_response()
            else:
                response = self.create_rfc7807_json_response()

        ResponseSerializerService.validate_and_serialize_response_body(response, http_accept, None)
        return response
Example #13
0
    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"])
Example #14
0
    def test_request_attributes(self):
        request = Request(self.wsgi_environment, {})

        self.assertEqual(b"1234567890", request.body)
        self.assertEqual("text/plain", request.content_type.to_string())
        self.assertEqual("gzip, deflate", request.content_encoding)
        self.assertEqual("utf-8", request.headers["Accept-Charset"])
        self.assertEqual("*/*", request.headers["Accept"])
        self.assertEqual("gzip, deflate", request.headers["Accept-Encoding"])
        self.assertEqual(HttpAccept.from_accept_string("*/*"),
                         request.http_accept_object)
        self.assertEqual("/path", request.path)
        self.assertEqual({
            "param": "value",
            "param2": "value2"
        }, request.query_parameters)
        self.assertEqual("http://localhost:8080", request.host)
        self.assertEqual(
            "http://localhost:8080/path?param=value&param2=value2",
            request.original_url)
        self.assertEqual("GET", request.request_method_name)
Example #15
0
    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])
Example #16
0
    def test_response_serializer_with_schema(self):
        class MySchema(Schema):
            field1 = fields.Integer()
            field2 = fields.String()

        response = Response({
            "field1": 1,
            "field2": "hello",
            "not_expected": "wuff"
        })
        ResponseSerializerService.validate_and_serialize_response_body(
            response, HttpAccept.from_accept_string("application/json"),
            ResponseStatusParameter(200, "", {"application/json": MySchema()}))

        self.assertIn('"field1": 1', response.text)
        self.assertIn('"field2": "hello"', response.text)
        self.assertNotIn("not_expected", response.text)
        self.assertIn(b'"field1": 1', response.content)
        self.assertIn(b'"field2": "hello"', response.content)
        self.assertNotIn(b"not_expected", response.content)
        self.assertEqual(200, response.status_code)
        self.assertEqual("application/json", response.headers["Content-Type"])
Example #17
0
 def can_handle_incoming_media_type(
         self, http_accept: HttpAccept) -> Union[None, CanHandleResultType]:
     best_match = http_accept.get_best_match(self.get_media_type_strings())
     if best_match is not None:
         return CanHandleResultType(best_match[0], best_match[1])
Example #18
0
 def http_accept_object(self) -> HttpAccept:
     return HttpAccept.from_accept_string(self.headers.get("Accept", "*/*"))
Example #19
0
    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))
Example #20
0
 def test_clear_all_default_serializer(self):
     ResponseSerializerService.clear_all_response_serializer()
     response = Response("Test")
     with self.assertRaises(NotAcceptable):
         ResponseSerializerService.validate_and_serialize_response_body(
             response, HttpAccept.from_accept_string("text/plain"))
Example #21
0
    def test_default_str_to_text(self):
        response = Response("Test")
        ResponseSerializerService.validate_and_serialize_response_body(
            response, HttpAccept.from_accept_string("text/plain"))

        self.assertEqual(b'Test', response.content)
Example #22
0
    def test_default_dict_to_text(self):
        response = Response({"key": "value"})
        ResponseSerializerService.validate_and_serialize_response_body(
            response, HttpAccept.from_accept_string("text/plain"))

        self.assertEqual(b'{"key": "value"}', response.content)
Example #23
0
    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)
Example #24
0
    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)
Example #25
0
 def test_fallback_text_error_response(self):
     response = self.response_maker.create_response(
         HttpAccept.from_accept_string("unknown/muh"))
     self.assertEqual(500, response.status_code)
     self.assertEqual("500 Internal Server Error: Something is not working",
                      response.text)
Example #26
0
 def test_response_body_type_not_supported(self):
     response = Response(1.0)
     with self.assertRaises(Response.ResponseBodyTypeNotSupportedException):
         ResponseSerializerService.validate_and_serialize_response_body(
             response, HttpAccept.from_accept_string("application/json"))