Ejemplo n.º 1
0
async def test_handle_smart_errors(app):
    api = restplus.Api(app)
    view = restplus.Resource

    api.add_resource(view, '/foo', endpoint='bor')
    api.add_resource(view, '/fee', endpoint='bir')
    api.add_resource(view, '/fii', endpoint='ber')

    async with app.test_request_context('/faaaaa'):
        err = NotFound()
        response = await api.handle_error(err)
        assert response.status_code == 404
        assert json.loads(await response.get_data(False)) == {
            'message': err.description,
        }

    async with app.test_request_context('/fOo'):
        err = NotFound()
        response = await api.handle_error(err)
        assert response.status_code == 404
        assert 'did you mean /foo ?' in await response.get_data(False)

        app.config['ERROR_404_HELP'] = False

        err = NotFound()
        response = await api.handle_error(err)
        assert response.status_code == 404
        assert json.loads(await response.get_data(False)) == {
            'message': err.description
        }
Ejemplo n.º 2
0
def _get_slave_from_headers():
    auth: str = request.headers.get('Authorization', type=str)
    if auth.startswith('Bearer '):
        slave_token = auth[7:]
    else:
        raise NotFound()
    try:
        return MasterAPI.instance().get_storage_slave_by_token(slave_token)
    except:
        raise NotFound()
Ejemplo n.º 3
0
async def test_handle_include_error_message(app):
    api = restplus.Api(app)
    view = restplus.Resource

    api.add_resource(view, '/foo', endpoint='bor')

    async with app.test_request_context('/faaaaa'):
        response = await api.handle_error(NotFound())
        assert 'message' in json.loads(await response.get_data(False))
Ejemplo n.º 4
0
 async def dispatch_task_stacktrace(self, task_id: int):
     task = find_task_by_id(task_id)
     if task is None:
         raise NotFound()
     stack_summary = traceback.StackSummary.extract(
         walk_coro_stack(task.coro))
     return json.dumps({
         'stacktrace': [frame_summary_to_json(fs) for fs in stack_summary]
     })
Ejemplo n.º 5
0
 async def post(self, resource=None):
     try:
         data = await request.get_json()
     except:
         data = {}
     validation = await self.factory.validate(data)
     if validation is True:
         if resource is None:
             resource = await self.factory.create(**data)
         else:
             resource = await self.factory.create(resource, **data)
     else:
         resource = validation
     if resource is None:
         raise NotFound(HTTPStatus.NOT_FOUND)
     return await self.response_provider.provide(resource=resource)
Ejemplo n.º 6
0
    app = Quart(__name__)
    url_adapter = Mock()
    rule = Rule('/', ['GET'], 'index')
    url_adapter.match.return_value = (rule, {'arg': 'value'})
    app.create_url_adapter = lambda *_: url_adapter  # type: ignore
    request = Request('GET', 'http', '/', CIMultiDict())
    RequestContext(app, request)
    assert request.url_rule == rule
    assert request.view_args == {'arg': 'value'}


@pytest.mark.parametrize(
    'exception_type, exception_instance',
    [
        (MethodNotAllowed, MethodNotAllowed(['GET'])),
        (NotFound, NotFound()),
        (RedirectRequired, RedirectRequired('/')),
    ],
)
def test_request_context_matching_error(
    exception_type: Exception,
    exception_instance: Exception,
) -> None:
    app = Quart(__name__)
    url_adapter = Mock()
    url_adapter.match.side_effect = exception_instance
    app.create_url_adapter = lambda *_: url_adapter  # type: ignore
    request = Request('GET', 'http', '/', CIMultiDict())
    RequestContext(app, request)
    assert isinstance(request.routing_exception,
                      exception_type)  # type: ignore
Ejemplo n.º 7
0
 async def dispatch_request(self, *args, **kwargs):
     view = cls()
     handler = getattr(view, request.method.lower(), None)
     if handler is None:
         raise NotFound(HTTPStatus.NOT_FOUND)
     return await handler(*args, **kwargs)
Ejemplo n.º 8
0
 async def delete(self, *args, **kwargs):
     resource = await self.provider.provide(*args, **kwargs)
     if resource is None:
         raise NotFound()
     await resource.delete()
     return await self.response_provider.provide(resource)
Ejemplo n.º 9
0
 async def put(self, *args, **kwargs):
     resource = await self.provider.provide(*args, **kwargs)
     if resource is None:
         raise NotFound(HTTPStatus.NOT_FOUND)
     return await self.post(resource=resource)
Ejemplo n.º 10
0
Archivo: quart.py Proyecto: wsot/gino
 async def first_or_404(self, *args, **kwargs):
     rv = await self.first(*args, **kwargs)
     if rv is None:
         raise NotFound()
     return rv
Ejemplo n.º 11
0
Archivo: quart.py Proyecto: wsot/gino
 async def get_or_404(cls, *args, **kwargs):
     # noinspection PyUnresolvedReferences
     rv = await cls.get(*args, **kwargs)
     if rv is None:
         raise NotFound()
     return rv
Ejemplo n.º 12
0
 async def all_or_404(cls, *args, **kwargs):
     rv = await cls.query.where(**kwargs).all(*args)
     if rv == []:
         raise NotFound()
     return rv
Ejemplo n.º 13
0
 async def first_or_404(cls, *args, **kwargs):
     rv = await cls.query.where(**kwargs).first(*args)
     if rv is None:
         raise NotFound()
     return rv
Ejemplo n.º 14
0
def _get_upload(sid: UUID, token: str):
    try:
        slave = _get_slave_from_headers()
        return slave.get_upload(sid, token)
    except KeyError:
        raise NotFound()