Ejemplo n.º 1
0
    def test_exception_header_forwarding_doesnt_duplicate_headers(self, api):
        """Test that HTTPException's headers do not add a duplicate
        Content-Length header

        https://github.com/quart-restful/quart-restful/issues/534
        """
        r = api.handle_error(BadRequest())
        assert len(r.headers.getlist('Content-Length')) == 1
Ejemplo n.º 2
0
async def finish_upload(sid: UUID, token: str):
    try:
        upload = _get_upload(sid, token)
        p = FinishUploadPacket(await request.get_json())
        p.validate()
        upload.finish(p)
    except DataError:
        raise BadRequest()
Ejemplo n.º 3
0
async def process_request():
    """Main request processing logic - accepts a JSON request and returns a JSON response."""
    ctype, type_params = cgi.parse_header(request.content_type)
    if ctype == 'text/plain':
        content = await get_text_content(request, type_params.get('charset', 'utf-8'))
    elif ctype == 'application/json':
        data = await request.get_json()
        # sanity checks on the request message
        if (data.get('type') != 'text') or ('content' not in data):
            raise BadRequest()
        content = data['content']
    else:
        raise BadRequest()

    annotations = dict()

    tweets_by_id = {}

    print(content)

    for tweet in iter_json(content):
        tweet_id = tweet.json.get("id_str")
        if tweet_id in tweets_by_id:
            warnings.warn("Tweet id {} has been duplicated".format(tweet_id))
        tweets_by_id[tweet_id] = tweet

    replies = filter_replies([tw.json for tw in tweets_by_id.values()])

    for reply in replies:
        embedded = tweets_by_id[reply.get("id_str")]
        tweet_id = embedded.json.get("id_str")
        in_reply_to = embedded.json.get("in_reply_to_status_id_str")

        original = tweets_by_id[in_reply_to]

        classification, scores = await run_sync(classifier.classify)(original.json, embedded.json)

        features = stance_classification_as_features(classification, scores)
        features["tweet_id"] = tweet_id
        features["in_reply_to"] = in_reply_to

        annot = {"start": embedded.begin, "end": embedded.end, "features": features}
        annotations.setdefault("TweetStance", []).append(annot)

    return dict(response = { 'type':'annotations', 'annotations':annotations,  })
Ejemplo n.º 4
0
def test_bad_request_if_websocket_route() -> None:
    app = Quart(__name__)
    url_adapter = Mock()
    url_adapter.match.side_effect = BadRequest()
    app.create_url_adapter = lambda *_: url_adapter  # type: ignore
    request = Request(
        "GET", "http", "/", b"", CIMultiDict(), "", "1.1", send_push_promise=no_op_push
    )
    RequestContext(app, request)
    assert isinstance(request.routing_exception, BadRequest)
Ejemplo n.º 5
0
async def test_handle_error(app):
    api = restplus.Api(app)

    async with app.test_request_context():
        err = BadRequest()
        response = await api.handle_error(err)
        assert response.status_code == 400
        assert json.loads(await response.get_data(False)) == {
            'message': err.description,
        }
Ejemplo n.º 6
0
async def main():
    data = await request.get_json()
    if data is None:
        raise BadRequest()
    logger.debug('Received data payload %s' % data)
    try:
        new_course = Course(**data)
        await new_course.setup()
        update_jupyterhub_config(new_course)

    except Exception as e:
        logger.error("Unable to complete course setup", exc_info=True)
        return {'error': 500, 'detail': str(e)}
    return {'message': 'OK', 'is_new_setup': new_course.is_new_setup}
Ejemplo n.º 7
0
 async def test_no_help(self, app, mocker):
     abort = mocker.patch('quart_restplus.reqparse.abort',
                          side_effect=BadRequest())
     parser = RequestParser()
     parser.add_argument('foo', choices=['one', 'two'])
     req = mocker.Mock(['values'])
     req.values = MultiDict([('foo', 'three')])
     async with app.test_request_context():
         with pytest.raises(BadRequest):
             await parser.parse_args(req)
     expected = {
         'foo': 'The value \'three\' is not a valid choice for \'foo\'.'
     }
     abort.assert_called_with(400,
                              'Input payload validation failed',
                              errors=expected)
Ejemplo n.º 8
0
async def test_handle_error_signal(app):
    api = restplus.Api(app)
    exception = BadRequest()
    recorded = []

    def record(sender, exception):
        recorded.append(exception)

    async with app.test_request_context():
        got_request_exception.connect(record, app, weak=False)
        try:
            await api.handle_error(exception)
            assert len(recorded) == 1
            assert exception is recorded[0]
        finally:
            got_request_exception.disconnect(record, app)
Ejemplo n.º 9
0
async def test_errorhandler_for_httpexception(app, client):
    api = restplus.Api(app)

    @api.route('/test/', endpoint='test')
    class TestResource(restplus.Resource):
        async def get(self):
            raise BadRequest()

    @api.errorhandler(BadRequest)
    def handle_badrequest_exception(error):
        return {'message': str(error), 'test': 'value'}, 400

    response = await client.get('/test/')
    assert response.status_code == 400
    assert response.content_type == 'application/json'

    data = json.loads(await response.get_data(False))
    assert data == {
        'message': str(BadRequest()),
        'test': 'value',
    }
Ejemplo n.º 10
0
    def test_handle_error_does_not_swallow_exceptions(self, api):
        exception = BadRequest('x')

        resp = api.handle_error(exception)
        assert resp.status_code == 400
        assert resp.get_data() == b'{"message": "x"}\n'
Ejemplo n.º 11
0
async def test_handle_error_does_not_duplicate_content_length(app):
    api = restplus.Api(app)

    async with app.test_request_context():
        response = await api.handle_error(BadRequest())
        assert len(response.headers.getlist('Content-Length')) == 1
Ejemplo n.º 12
0
 async def get(self):
     raise BadRequest()