Exemple #1
0
    def test_default_exp_handler(self):
        """ Test default exception handler without a callable. """
        class TestExpHandler(object):
            code = 500
            content_type = "text/plain"
            content = "An error occured"
            headers = {}

        def handler():
            raise Exception(500)

        sp = ServicePublisher(
            options={"default_error_handler": TestExpHandler})
        sp.add_endpoint(
            Endpoint(
                name='test',
                method='GET',
                uri='/location',
                function=handler,
            ))
        req = create_req('GET', '/location')
        resp = MockResponse(req, 500)
        result = sp(req, resp.start_response)
        resp.write(result)
        self.assertEqual(
            req._buffer,
            response_buf(
                http_status=500,
                content="An error occured",
                content_type="text/plain",
            ))
Exemple #2
0
    def test_custom_exp_handler(self):
        """ Test a custom exception handler without a callable. Map to our
            endpoint, and do not use a default handler (will default to
            JsonErrorHandler) """
        class TestExpHandler(object):
            code = 500
            content_type = "text/plain"
            content = "Default error message"
            headers = {}

        def handler():
            raise Exception("New Message")

        sp = ServicePublisher()
        sp.add_endpoint(
            Endpoint(name='test',
                     method='GET',
                     uri='/location',
                     function=handler,
                     exceptions={Exception: TestExpHandler()}))
        req = create_req('GET', '/location')
        resp = MockResponse(req, 500)
        result = sp(req, resp.start_response)
        resp.write(result)
        self.assertEqual(
            req._buffer,
            response_buf(
                http_status=500,
                content="Default error message",
                content_type="text/plain",
            ))
Exemple #3
0
    def test_custom_exp_handler_with_callable(self):
        """ Test a custom exception handler with a callable that will return
            the exception message instead of default. Map to our
            endpoint, and do not use a default handler (will default to
            JsonErrorHandler) """
        class TestExpHandler(object):
            code = 500
            content_type = "text/plain"
            content = "Default error message"
            headers = {}
            def __call__(self, exp):
                return (self.code, self.content_type, exp.message, self.headers)


        def handler():
            raise Exception("New Message")
        
        sp = ServicePublisher()
        sp.add_endpoint(Endpoint(
            name='test', 
            method='GET', 
            uri='/location', 
            function=handler,
            exceptions={Exception:TestExpHandler()}
        ))
        req = create_req('GET', '/location')
        resp = MockResponse(req, 500)
        result = sp(req, resp.start_response)
        resp.write(result)
        self.assertEqual(req._buffer, response_buf(
            http_status=500,
            content="New Message",
            content_type="text/plain",
        ))
Exemple #4
0
    def test_default_exp_handler_with_call(self):
        """ Test default exception handler with a callable that will change
            message. """
        class TestExpHandler(object):
            code = 500
            content_type = "text/plain"
            content = "An error occured"
            headers = {}
            def __call__(self, exp):
                return (self.code, self.content_type, exp.message, self.headers)

        def handler():
            raise Exception("New Message")
        
        sp = ServicePublisher(
                options={"default_error_handler": TestExpHandler()})
        sp.add_endpoint(Endpoint(
            name='test', 
            method='GET', 
            uri='/location', 
            function=handler,
        ))
        req = create_req('GET', '/location')
        resp = MockResponse(req, 500)
        result = sp(req, resp.start_response)
        resp.write(result)
        self.assertEqual(req._buffer, response_buf(
            http_status=500,
            content="New Message",
            content_type="text/plain",
        ))
Exemple #5
0
    def test_renderer_fail(self):
        def handler():
            return "new_location"

        def renderer(result):
            return Result(
                content='moved',
                content_type='text/html',
                headers={'Location': result},
                http_status=302,
            )

        sp = ServicePublisher()
        sp.add_endpoint(
            Endpoint(name='',
                     method='GET',
                     uri='/location',
                     function=handler,
                     renderer=renderer))
        req = create_req('GET', '/location')
        resp = MockResponse(req, 200)
        result = sp(req, resp.start_response)
        resp.write(result)
        self.assertEqual(
            req._buffer,
            response_buf(302,
                         'moved',
                         content_type='text/html',
                         headers={'Location': 'new_location'}))
Exemple #6
0
    def test_success(self):
        """ Control test. Default content type (json) """
        def handler():
            return "basic string"

        sp = ServicePublisher()
        sp.add_endpoint(
            Endpoint(name='test',
                     method='GET',
                     uri='/location',
                     function=handler))
        req = create_req('GET', '/location')
        resp = MockResponse(req, 200)
        result = sp(req, resp.start_response)
        resp.write(result)
        self.assertEqual(req._buffer, response_buf(200, '"basic string"'))
Exemple #7
0
    def test_multiuri_handler_query_arg(self):
        def handler(user):
            return dict(name=user)

        sp = ServicePublisher()
        sp.add_endpoint(
            Endpoint(name='',
                     method='GET',
                     uris=[
                         '/(?P<user>.*)/profile',
                         '/profiles/(?P<user>.*)',
                     ],
                     args=([args.String('user')], {}),
                     function=handler))
        req = create_req('GET', '/oneuser/profile')
        resp = MockResponse(req, 200)
        result = sp(req, resp.start_response)
        resp.write(result)
        self.assertEqual(req._buffer, response_buf(200, '{"name": "oneuser"}'))

        req = create_req('GET', '/profiles/other_user')
        resp = MockResponse(req, 200)
        result = sp(req, resp.start_response)
        resp.write(result)
        self.assertEqual(req._buffer,
                         response_buf(200, '{"name": "other_user"}'))
Exemple #8
0
    def test_custom_exp_handler_precidence(self):
        """ Test a custom exception handler without a callable. Map to our
            endpoint, and do not use a default handler (will default to
            JsonErrorHandler) """
        class TestExpHandler(object):
            code = 500
            content_type = "text/plain"
            content = "Default error message"
            headers = {}

        class SpecificExpHandler(object):
            code = 502
            content_type = "text/plain"
            content = "Specific Error Message"
            headers = {}

        class SpecificException(Exception):
            pass

        class MoreSpecificException(SpecificException):
            pass

        def handler():
            raise MoreSpecificException("New Message")
        
        sp = ServicePublisher()
        sp.add_endpoint(Endpoint(
            name='test', 
            method='GET', 
            uri='/location', 
            function=handler,
            exceptions={
                Exception:TestExpHandler(),
                SpecificException:SpecificExpHandler(),
            }
        ))
        req = create_req('GET', '/location')
        resp = MockResponse(req, 500)
        result = sp(req, resp.start_response)
        resp.write(result)
        self.assertEqual(req._buffer, response_buf(
            http_status=502,
            content="Specific Error Message",
            content_type="text/plain",
        ))
Exemple #9
0
    def test_success(self):
        """ Control test. Default content type (json) """

        def handler(): 
            return "basic string"
        
        sp = ServicePublisher()
        sp.add_endpoint(Endpoint(
            name='test', 
            method='GET', 
            uri='/location', 
            function=handler
        ))
        req = create_req('GET', '/location')
        resp = MockResponse(req, 200)
        result = sp(req, resp.start_response)
        resp.write(result)
        self.assertEqual(req._buffer,response_buf(200, '"basic string"'))
Exemple #10
0
    def test_assertion_exp(self):
        """ Test throwing an assertion error which will result in 400 and
            return the actual exception message. """

        def handler(): 
            raise AssertionError("Someone screwed the pooch")
        
        sp = ServicePublisher()
        sp.add_endpoint(Endpoint(
            name='test', 
            method='GET', 
            uri='/location', 
            function=handler,
        ))
        req = create_req('GET', '/location')
        resp = MockResponse(req, 400)
        result = sp(req, resp.start_response)
        resp.write(result)
        self.assertEqual(req._buffer,response_buf(
            400, '{"message": "Someone screwed the pooch", "code": 400}'))
Exemple #11
0
    def test_default_exp(self):
        """ Test the base exception handling where we dont have a callable
            function, but we have some defaults to use """

        def handler(): 
            raise Exception("Someone screwed the pooch")
        
        sp = ServicePublisher()
        sp.add_endpoint(Endpoint(
            name='test', 
            method='GET', 
            uri='/location', 
            function=handler,
        ))
        req = create_req('GET', '/location')
        resp = MockResponse(req, 500)
        result = sp(req, resp.start_response)
        resp.write(result)
        self.assertEqual(req._buffer,response_buf(
            500, '{"message": "%s", "code": 500}' % (responses[500])))
Exemple #12
0
    def test_noargs_handlersuccess(self):
        def handler():
            return dict(called=1)

        sp = ServicePublisher()
        sp.add_endpoint(
            Endpoint(name='', method='GET', uri='/location', function=handler))
        req = create_req('GET', '/location')
        resp = MockResponse(req, 200)
        result = sp(req, resp.start_response)
        resp.write(result)
        self.assertEqual(req._buffer, response_buf(200, '{"called": 1}'))
Exemple #13
0
    def test_http_exp_without_msg(self):
        """ Test using HTTPException which will give back an actual
            http code and a default message """
        def handler():
            raise HTTPException(503)

        sp = ServicePublisher()
        sp.add_endpoint(
            Endpoint(
                name='test',
                method='GET',
                uri='/location',
                function=handler,
            ))
        req = create_req('GET', '/location')
        resp = MockResponse(req, 503)
        result = sp(req, resp.start_response)
        resp.write(result)
        self.assertEqual(req._buffer,response_buf(
            503, '{"message": "%s", "code": 503}' % \
            (responses[503])))
Exemple #14
0
    def test_http_exp_without_msg(self):
        """ Test using HTTPException which will give back an actual
            http code and a default message """

        def handler(): 
            raise HTTPException(503)
        
        sp = ServicePublisher()
        sp.add_endpoint(Endpoint(
            name='test', 
            method='GET', 
            uri='/location', 
            function=handler,
        ))
        req = create_req('GET', '/location')
        resp = MockResponse(req, 503)
        result = sp(req, resp.start_response)
        resp.write(result)
        self.assertEqual(req._buffer,response_buf(
            503, '{"message": "%s", "code": 503}' % \
            (responses[503])))
Exemple #15
0
    def test_assertion_exp(self):
        """ Test throwing an assertion error which will result in 400 and
            return the actual exception message. """
        def handler():
            raise AssertionError("Someone screwed the pooch")

        sp = ServicePublisher()
        sp.add_endpoint(
            Endpoint(
                name='test',
                method='GET',
                uri='/location',
                function=handler,
            ))
        req = create_req('GET', '/location')
        resp = MockResponse(req, 400)
        result = sp(req, resp.start_response)
        resp.write(result)
        self.assertEqual(
            req._buffer,
            response_buf(
                400, '{"message": "Someone screwed the pooch", "code": 400}'))
Exemple #16
0
    def test_default_exp(self):
        """ Test the base exception handling where we dont have a callable
            function, but we have some defaults to use """
        def handler():
            raise Exception("Someone screwed the pooch")

        sp = ServicePublisher()
        sp.add_endpoint(
            Endpoint(
                name='test',
                method='GET',
                uri='/location',
                function=handler,
            ))
        req = create_req('GET', '/location')
        resp = MockResponse(req, 500)
        result = sp(req, resp.start_response)
        resp.write(result)
        self.assertEqual(
            req._buffer,
            response_buf(500,
                         '{"message": "%s", "code": 500}' % (responses[500])))
Exemple #17
0
    def test_matchfailure(self):
        def handler():
            pass

        sp = ServicePublisher()
        sp.add_endpoint(
            Endpoint(name='', method='GET', uri='/location', function=handler))
        req = create_req('GET', '/blah')
        resp = MockResponse(req, 200)
        result = sp(req, resp.start_response)
        resp.write(result)
        self.assertEqual(
            req._buffer,
            response_buf(404, '{"message": "Not Found", "code": 404}'))
Exemple #18
0
    def test_noargs_but_method_handlersuccess(self):
        def handler():
            return dict(arg1=1)

        sp = ServicePublisher()
        sp.add_endpoint(
            Endpoint(name='',
                     method='DELETE',
                     uri='/location',
                     function=handler))
        req = create_req('DELETE',
                         '/location',
                         arguments=dict(_method=['delete']))
        resp = MockResponse(req, 200)
        result = sp(req, resp.start_response)
        resp.write(result)
        self.assertEqual(req._buffer, response_buf(200, '{"arg1": 1}'))
Exemple #19
0
    def test_fallback_app_not_used(self):

        endpoints = [
            Endpoint(
                name='',
                method='GET',
                uri='/test',
                function=self._nudge_func,
            )
        ]

        sp = ServicePublisher(endpoints=endpoints,
                              fallbackapp=self._fallback_app)
        req = create_req('GET', '/test')
        resp = MockResponse(req, 200)
        result = sp(req, resp.start_response)

        self.assertEqual({'nudge': True}, json.json_decode(result[0]))
Exemple #20
0
    def test_prevent_json_array(self):
        def handler():
            return [1, 2, 3]

        sp = ServicePublisher()
        sp.add_endpoint(
            Endpoint(name='', method='POST', uri='/location',
                     function=handler))
        req = create_req(
            'POST',
            '/location',
        )
        resp = MockResponse(req, 200)
        result = sp(req, resp.start_response)
        resp.write(result)
        self.assertEqual(
            req._buffer,
            response_buf(500,
                         '{"message": "Internal Server Error", "code": 500}'))
Exemple #21
0
    def test_arg_handlersuccess_nested_json(self):
        def handler(*args, **kwargs):
            return dict(arg1=1)

        sp = ServicePublisher()
        sp.add_endpoint(
            Endpoint(name='',
                     method='POST',
                     uri='/location',
                     args=([args.String('test')], {}),
                     function=handler))
        req = create_req('POST',
                         '/location',
                         arguments=dict(test="blah"),
                         headers={"Content-Type": "application/json"},
                         body='{"test":"foo", "spam":{"wonderful":true}}')
        resp = MockResponse(req, 200)
        result = sp(req, resp.start_response)
        resp.write(result)
        self.assertEqual(req._buffer, response_buf(200, '{"arg1": 1}'))
Exemple #22
0
    def test_fallback_app_used_post_body(self):

        endpoints = [
            Endpoint(
                name='',
                method='GET',
                uri='/test',
                function=self._nudge_func,
            )
        ]

        sp = ServicePublisher(endpoints=endpoints,
                              fallbackapp=self._fallback_app)

        body = json.json_encode({'success': True}) + '\r\n'
        req = create_req('POST', '/not-test', body=body)
        resp = MockResponse(req, 200)
        result = sp(req, resp.start_response)

        self.assertEqual({'success': True}, json.json_decode(result[0]))
Exemple #23
0
    def test_arg_handlersuccess_part_tre(self):
        def handler(*args, **kwargs):
            return dict(arg1=1)

        sp = ServicePublisher()
        sp.add_endpoint(
            Endpoint(name='',
                     method='POST',
                     uri='/location',
                     args=([args.String('test')], {}),
                     function=handler))
        req = create_req('POST',
                         '/location',
                         arguments=dict(test="blah"),
                         headers={"Content-Type": "application/json"},
                         body='{"test"="foo"}')
        resp = MockResponse(req, 500)
        result = sp(req, resp.start_response)
        resp.write(result)
        self.assertEqual(
            req._buffer,
            response_buf(400, '{"message": "body is not JSON", "code": 400}'))
Exemple #24
0
    def test_custom_exp_handler_with_callable_fail(self):
        """ Test a custom exception handler with a callable that will raise
            an exception and force SP to use the default exception handling. Map to our
            endpoint, and do not use a default handler (will default to
            JsonErrorHandler) """
        class TestExpHandler(object):
            code = 500
            content_type = "text/plain"
            content = "Default error message"
            headers = {}

            def __call__(self, exp):
                """ Note that doing this now hides the original exception """
                raise Exception("Something really bad happened")

        def handler():
            raise Exception("New Message")

        sp = ServicePublisher(debug=True,
                              endpoints=[
                                  Endpoint(
                                      name='test',
                                      method='GET',
                                      uri='/location',
                                      function=handler,
                                      exceptions={Exception: TestExpHandler()})
                              ])
        req = create_req('GET', '/location')
        resp = MockResponse(req, 500)
        result = sp(req, resp.start_response)
        resp.write(result)
        self.assertEqual(
            req._buffer,
            response_buf(
                http_status=500,
                content='{"message": "%s", "code": 500}' % (responses[500]),
            ))
Exemple #25
0
    def test_cookie(self):
        def handler(chocolate, hazel):
            return {'chocolate': chocolate, 'hazel': hazel}

        sp = ServicePublisher()
        sp.add_endpoint(
            Endpoint(name='',
                     method='GET',
                     uri='/cooookies',
                     function=handler,
                     args=Args(
                         chocolate=args.Cookie('chocolate'),
                         hazel=args.Cookie('hazel'),
                     )))
        req = create_req('GET',
                         '/cooookies',
                         headers={'cookie': 'chocolate=chip;hazel=nut'})
        resp = MockResponse(req, 200)
        result = sp(req, resp.start_response)

        self.assertEqual({
            'chocolate': 'chip',
            'hazel': 'nut'
        }, json.json_decode(result[0]))
Exemple #26
0
                description="Cms HTML example section",
                endpoints=service_description,
                options=None,
            )
        ]
        # This will generate all docs/clients
        project = Project(
            name="Cms Example",
            identifier="cms",
            description="Cms Example description",
            sections=sections,
            destination_dir="/tmp/cms_gen/",
            generators=[SphinxDocs(), JSClient()]
        )
        sys.exit(0)

    wsgi_application = ServicePublisher(
        endpoints=service_description,
        # Enable colored (and more) logging
        debug=True,
        #
        # default_error_handler is a very important option as it changes the
        # what is returned when there is an unhandled exception. Nudge by
        # default will return HTTP code 500 with a simple json dict (type json)
        #
        options={"default_error_handler":DefaultErrorHandler()}
    )
    from google.appengine.ext.webapp.util import run_wsgi_app
    run_wsgi_app(wsgi_application)

Exemple #27
0
    def test_custom_default_exp_handler(self):
        class VerboseJsonException(object):
            content_type = "application/json; charset=UTF-8"
            content = "Unknown Error"
            headers = {}
            code = 500

            def __init__(self, code=None):
                if code:
                    self.code = code

            def __call__(self, exception):
                resp = exception.__dict__
                code = self.code
                if hasattr(exception, 'status_code'):
                    code = exception.status_code
                resp['code'] = code
                if hasattr(exception, 'message'):
                    resp['message'] = exception.message
                if not resp.get('message'):
                    _log.debug("Exception: {0}".format(exception))
                    resp['message'] = str(exception)
                return (
                    code,
                    self.content_type,
                    nudge.json.json_encode(resp),
                    {},
                )

        def handler():
            raise Exception("New Message")

        sp = ServicePublisher(debug=True,
                              endpoints=[
                                  Endpoint(name='test',
                                           method='GET',
                                           uri='/location503',
                                           function=handler,
                                           exceptions={Exception: 503}),
                                  Endpoint(
                                      name='test',
                                      method='GET',
                                      uri='/location500',
                                      function=handler,
                                  )
                              ],
                              default_error_handler=VerboseJsonException)

        req = create_req('GET', '/location503')
        resp = MockResponse(req, 503)
        result = sp(req, resp.start_response)
        resp.write(result)
        self.assertEqual(
            req._buffer,
            response_buf(
                http_status=503,
                content='{"message": "New Message", "code": 503}',
            ))

        req = create_req('GET', '/location500')
        resp = MockResponse(req, 500)
        result = sp(req, resp.start_response)
        resp.write(result)
        self.assertEqual(
            req._buffer,
            response_buf(
                http_status=500,
                content='{"message": "New Message", "code": 500}',
            ))