def setUp(self):
        self.routing_table = TreeRoutingTable()
        self.routing_table.register_route(GET, PATH, RESOURCE_CLASS,
                                          ROUTE_METHOD)
        self.route_handler_factory = RouteHandlerFactory(
            ServiceLocator(), Deserializer(Registry()),
            [RoutingRule("/", self.routing_table)],
            CorsRequestHandlerFactory([CorsRule("/", {})]))

        self.request_builder = RequestBuilder().method("GET").path(PATH)
    def test_givenMissingOptionalResourceArgument_whenInvoking_thenCallEvenIfTheArgumentIsMissing(
            self):
        self.request = RequestBuilder().path(PATH + "/nullable-query").build()

        response = self.resource_invocator.invoke(self.request)

        self.assertEqual(None, response.body)
    def test_givenIncorrectRequestBody_whenFormattingParameter_thenRaiseException(
            self):
        request = RequestBuilder().build()

        with self.assertRaises(MissingRouteInvocationArgument):
            self.selector.format_parameter("param name", StreamingRequestBody,
                                           request)
Exemplo n.º 4
0
    def test_whenCreatingRouteHandlers_thenRewritePaths(self):
        request = RequestBuilder().path("/users/path").build()
        rule = RoutingRule("/users", self.routing_table, rewrite_path=True)

        handlers = [x for x in rule.create_route_handlers(request, None, None)]

        self.assertIsInstance(handlers[0], PathRewritingRouteHandlerDecorator)
    def test_givenAllowEverythingOriginHeader_whenHandlingPreflight_thenReturn200OK(
            self):
        request = RequestBuilder().headers({'Origin': 'some-origin'}).build()

        response = self.cors_handler.invoke(request)

        self.assertEqual(200, response.status)
Exemplo n.º 6
0
    def test_whenApplyingFilter_thenAddsAHeaderField(self):
        request = RequestBuilder().build()
        response = ResponseBuilder().build()

        self.filter.doFilter(request, response, self.filter_chain_mock)

        self.assertTrue("Jivago" in response.headers['X-POWERED-BY'])
    def test_givenRequestWithoutAForm_whenApplyingFilter_thenDoNothing(self):
        request = RequestBuilder().method("POST").body(FORM_BODY).build()

        self.formDeserializationFilter.doFilter(request, None,
                                                self.filterChainMock)

        self.assertEqual(FORM_BODY, request.body)
Exemplo n.º 8
0
    def test_givenShouldNotRewritePath_whenCreatingRouteHandlers_thenReturnStandardResourceInvokers(
            self):
        request = RequestBuilder().path("/users/path").build()
        rule = RoutingRule("/users", self.routing_table, rewrite_path=False)

        handlers = [x for x in rule.create_route_handlers(request, None, None)]

        self.assertIsInstance(handlers[0], ResourceInvoker)
Exemplo n.º 9
0
    def test_givenMissingHttpRange_whenHandlingContentRequest_thenReturn200OkStatus(
            self):
        request = RequestBuilder().build()

        response = self.partialContentHandler.handle_partial_content_request(
            request, TEST_FILE)

        self.assertEqual(200, response.status)
    def test_givenPresentOptionalResourceArgument_whenInvoking_thenCallResourceWithParameter(
            self):
        self.request = RequestBuilder().path(
            PATH + "/nullable-query").query_string("query=foo").build()

        response = self.resource_invocator.invoke(self.request)

        self.assertEqual("foo", response.body)
Exemplo n.º 11
0
    def test_whenInvoking_thenPassModifiedRequestWithModifiedPath(self):
        request = RequestBuilder().path("/old-path").build()

        self.route_handler.invoke(request)

        _, args, _ = self.decorated_route_handler.invoke.mock_calls[0]
        gotten_request = args[0]

        self.assertEqual(NEW_PATH, gotten_request.path)
    def test_givenMissingOrigin_whenHandlingPreflightRequest_thenReturn400BadRequest(
            self):
        request = RequestBuilder().headers({}).build()
        self.cors_handler = CorsPreflightRequestHandler(
            Headers({'Access-Control-Allow-Origin': 'http://api.jivago.io'}))

        response = self.cors_handler.invoke(request)

        self.assertEqual(400, response.status)
Exemplo n.º 13
0
    def test_givenTrailingSemiColonInContentType_whenApplyingFilter_thenMatchAnyway(self):
        request = RequestBuilder() \
            .headers({"Content-Type": "application/json; "}) \
            .body(b'{"name": "bar"}') \
            .build()

        self.filter.doFilter(request, ResponseBuilder().build(), self.filterChainMock)

        self.assertEqual({"name": "bar"}, request.body)
Exemplo n.º 14
0
    def test_givenMissingHttpRange_whenHandlingContentRequest_thenReturnTheWholeFile(
            self):
        request = RequestBuilder().build()

        response = self.partialContentHandler.handle_partial_content_request(
            request, TEST_FILE)

        with open(TEST_FILE, 'rb') as f:
            self.assertEqual(f.read(), response.body)
    def test_givenStreamingRequestBody_whenFormattingParameter_thenReturnResponseBody(
            self):
        body = StreamingRequestBody("dummy")
        request = RequestBuilder().body(body).build()

        parameter = self.selector.format_parameter("param name",
                                                   StreamingRequestBody,
                                                   request)

        self.assertEqual(body, parameter)
Exemplo n.º 16
0
    def test_givenHttpPartialRange_whenHandlingContentRequest_thenResponseHas206HttpStatus(
            self):
        partial_request = RequestBuilder().headers({
            "Range": "bytes=0-"
        }).build()

        response = self.partialContentHandler.handle_partial_content_request(
            partial_request, TEST_FILE)

        self.assertEqual(206, response.status)
Exemplo n.º 17
0
    def test_givenMultipleContentTypeDirectives_whenApplyingFilter_thenMatchOnMediaType(self):
        """https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type"""
        request = RequestBuilder() \
            .headers({"Content-Type": "application/json; charset=utf-8"}) \
            .body(b'{"name": "bar"}') \
            .build()

        self.filter.doFilter(request, ResponseBuilder().build(), self.filterChainMock)

        self.assertEqual({"name": "bar"}, request.body)
Exemplo n.º 18
0
    def test_givenApplicationJsonHeaderWithEmptyBody_whenApplyingFilter_thenDoNotDeserializeTheEmptyString(
            self):
        request = RequestBuilder().headers({
            "Content-Type": "application/json"
        }).body("").method("POST").build()

        self.filter.doFilter(A_REQUEST,
                             ResponseBuilder().build(), self.filterChainMock)

        self.assertEqual("", request.body)
    def test_givenResourceWithHeadersParameter_whenInvokingResource_thenInvokeRoutingMethodWithHeadersObject(
            self):
        self.request = RequestBuilder().path(PATH + "/headers").headers({
            "foo":
            "bar"
        }).build()

        response = self.resource_invocator.invoke(self.request)

        self.assertEqual([("foo", "bar")], Stream(response.body).toList())
    def test_givenRequestWithContentTypWwwForm_whenApplyingFilter_thenBodyGetsParsed(
            self):
        request = RequestBuilder().method('POST').headers({
            'CONTENT-TYPE':
            'application/x-www-form-urlencoded'
        }).body(FORM_BODY).build()

        self.formDeserializationFilter.doFilter(request, None,
                                                self.filterChainMock)

        self.assertEqual(PARSED_FORM_BODY, request.body)
    def test_givenSerializationError_whenInvokingResource_thenRaiseException(
            self):
        self.resource_invocator.deserializer = mock.create_autospec(
            Deserializer)
        self.resource_invocator.deserializer.deserialize.side_effect = SerializationException(
        )
        self.request = RequestBuilder().method("POST").path(PATH +
                                                            "/dto").build()

        with self.assertRaises(IncorrectResourceParametersException):
            self.resource_invocator.invoke(self.request)
    def test_givenOriginThatStartsWithAllowedHeader_whenHandlingPreflight_thenReturn200OKWithVaryHeader(
            self):
        self.cors_headers[
            'Access-Control-Allow-Origin'] = "http://api.jivago.io"
        request = RequestBuilder().headers({
            'Origin': 'http://api.jivago.io'
        }).build()
        self.cors_handler = CorsPreflightRequestHandler(self.cors_headers)

        response = self.cors_handler.invoke(request)

        self.assertEqual(200, response.status)
        self.assertEqual('Origin', response.headers['Vary'])
Exemplo n.º 23
0
    def test_givenStartingByteRange_whenHandlingContentRequest_thenReturnBytesStartingAtOffset(
            self):
        a_starting_offset = 6
        partial_request = RequestBuilder().headers({
            "Range":
            f"bytes={a_starting_offset}-"
        }).build()

        response = self.partialContentHandler.handle_partial_content_request(
            partial_request, TEST_FILE, max_block_size=1000000000)

        self.assertEqual(TEST_FILE_TOTAL_SIZE - a_starting_offset,
                         len(response.body))
        with open(TEST_FILE, 'rb') as f:
            f.seek(6)
            self.assertEqual(f.read(), response.body)
    def test_givenApplicationException_whenInvokingResource_thenLetTheExceptionRise(
            self):
        self.request = RequestBuilder().path(PATH + "/error").build()

        with self.assertRaises(AnException):
            self.resource_invocator.invoke(self.request)
Exemplo n.º 25
0
 def setUp(self):
     self.cors_handler_mock: CorsHandler = mock.create_autospec(CorsHandler)
     self.filter_chain_mock: FilterChain = mock.create_autospec(FilterChain)
     self.filter = CorsHeadersInjectionFilter(self.cors_handler_mock)
     self.request = RequestBuilder().build()
Exemplo n.º 26
0
import json
import unittest
from unittest import mock

from jivago.wsgi.filter.filter_chain import FilterChain
from jivago.wsgi.request.json_serialization_filter import JsonSerializationFilter
from test_utils.request_builder import RequestBuilder
from test_utils.response_builder import ResponseBuilder

A_REQUEST = RequestBuilder().build()


class JsonSerializationFilterTest(unittest.TestCase):
    def setUp(self):
        self.filter = JsonSerializationFilter()
        self.filterChainMock: FilterChain = mock.create_autospec(FilterChain)

    def test_givenADictionary_whenApplyingFilter_thenSerializeToJson(self):
        body = {"hello": "goodbye"}
        response = ResponseBuilder().body(body).build()

        self.filter.doFilter(A_REQUEST, response, self.filterChainMock)

        self.assertEqual(body, json.loads(response.body))

    def test_givenAList_whenApplyingFilter_thenSerializeToJson(self):
        body = ["hello"]
        response = ResponseBuilder().body(body).build()

        self.filter.doFilter(A_REQUEST, response, self.filterChainMock)
Exemplo n.º 27
0
    def test_givenAnyResponse_whenApplyingFilter_ShouldNotAddTransferEncodingHeader(self):
        response = ResponseBuilder().body("some body").build()

        self.filter.doFilter(RequestBuilder().build(), response, self.filterChainMock)

        self.assertIsNone(response.headers["Transfer-Encoding"])
Exemplo n.º 28
0
    def test_givenStreamingResponseBody_whenApplyingFilter_ShouldAddTransferEncodingHeader(self):
        response = ResponseBuilder().body(StreamingResponseBody([])).build()

        self.filter.doFilter(RequestBuilder().build(), response, self.filterChainMock)

        self.assertEqual("chunked", response.headers["Transfer-Encoding"])
Exemplo n.º 29
0
 def setUp(self):
     self.base_request = RequestBuilder().path("/api/path").build()
     self.modified_request = ModifiedPathFlyweightRequest(
         self.base_request, NEW_PATH)
class RouteHandlerFactoryTest(unittest.TestCase):
    def setUp(self):
        self.routing_table = TreeRoutingTable()
        self.routing_table.register_route(GET, PATH, RESOURCE_CLASS,
                                          ROUTE_METHOD)
        self.route_handler_factory = RouteHandlerFactory(
            ServiceLocator(), Deserializer(Registry()),
            [RoutingRule("/", self.routing_table)],
            CorsRequestHandlerFactory([CorsRule("/", {})]))

        self.request_builder = RequestBuilder().method("GET").path(PATH)

    def test_givenNoMatchingRoutes_whenCreatingRouteHandlers_thenRaiseUnknownPathException(
            self):
        request = self.request_builder.path("/unknown").build()

        with self.assertRaises(UnknownPathException):
            self.route_handler_factory.create_route_handlers(request)

    def test_givenDisallowedMethod_whenCreatingRouteHandlers_thenRaiseMethodNotAllowedException(
            self):
        request = self.request_builder.method("POST").build()

        with self.assertRaises(MethodNotAllowedException):
            self.route_handler_factory.create_route_handlers(request)

    def test_givenPrefixedRule_whenCreatingRouteHandlers_thenCreateResourceInvokerWithTruncatedPathForEveryRoute(
            self):
        request = self.request_builder.path("/prefix" + PATH).build()
        rule = RoutingRule("/prefix", self.routing_table)
        self.route_handler_factory = RouteHandlerFactory(
            ServiceLocator(), Deserializer(Registry()), [rule],
            CorsRequestHandlerFactory([CorsRule("/", {})]))

        handlers: List[PathRewritingRouteHandlerDecorator] = [
            x
            for x in self.route_handler_factory.create_route_handlers(request)
        ]

        self.assertEqual(1, len(handlers))
        # TODO do assertion which does not imply internal structure
        self.assertEqual(PATH, handlers[0].route_handler.new_path)

    def test_givenCorsRequestOnUnknownPath_whenCreatingRouteHandlers_thenRaiseUnknownPathException(
            self):
        request = self.request_builder.method("OPTIONS").path(
            "/unknown").build()

        with self.assertRaises(UnknownPathException):
            self.route_handler_factory.create_route_handlers(request)

    def test_givenCorsRequest_whenCreatingRouteHandlers_thenReturnSingleCorsHandler(
            self):
        request = self.request_builder.method("OPTIONS").build()

        handlers = [
            x
            for x in self.route_handler_factory.create_route_handlers(request)
        ]

        self.assertEqual(1, len(handlers))
        self.assertIsInstance(handlers[0], CorsPreflightRequestHandler)