Exemple #1
0
    def test_parse_unicode_app(self):
        parser = RequestParser()
        parser.add_argument('foo')

        with self.app.test_request_context('/bubble?foo=barß'):
            args = parser.parse_args()
            self.assertEqual(args['foo'], 'barß')
    def test_parse_append_ignore(self, app):
        parser = RequestParser()
        parser.add_argument('foo', ignore=True, type=int, action='append',
                            store_missing=True),

        args = parser.parse_args()
        assert args['foo'] is None
    def test_parse_unicode(self, app):
        req = Request.from_values('/bubble?foo=barß')
        parser = RequestParser()
        parser.add_argument('foo')

        args = parser.parse_args(req)
        assert args['foo'] == 'barß'
    def test_passing_arguments_object(self, app):
        req = Request.from_values('/bubble?foo=bar')
        parser = RequestParser()
        parser.add_argument(Argument('foo'))

        args = parser.parse_args(req)
        assert args['foo'] == 'bar'
Exemple #5
0
    def test_passing_arguments_object(self):
        req = Request.from_values('/bubble?foo=bar')
        parser = RequestParser()
        parser.add_argument(Argument('foo'))

        args = parser.parse_args(req)
        self.assertEqual(args['foo'], 'bar')
Exemple #6
0
    def test_parse_lte(self):
        req = Request.from_values('/bubble?foo<=bar')
        parser = RequestParser()
        parser.add_argument('foo', operators=['<='])

        args = parser.parse_args(req)
        self.assertEqual(args['foo'], 'bar')
Exemple #7
0
def setup_parser(parser: RequestParser) -> RequestParser:
    """
    Setup request arguments parser.

    :param parser: app arguments parser
    :return: customized parser
    """
    parser.add_argument('file', location='files', type=FileStorage,
                        required=True, dest='file',
                        help='File to upload into the database.')

    parser.add_argument('--col', action='split', dest='col_names',
                        help='List of new column names in correct order '
                             'as a comma-separated string. The number '
                             'of names must match the number of columns '
                             'in the existing file.')

    parser.add_argument('--head', type=int, dest='header',
                        help='Row number to use as the column names (header).')

    parser.add_argument('--index', action='split', dest='index',
                        help='List of column names to set index on it '
                             '(as a comma-separated string).')

    parser.add_argument('--type', type=eval, dest='type',
                        help='Set data type to the column(s). Argument is '
                             'a dictionary {\'column name\': \'type\'}. '
                             'Available types: int, float, str, datetime.')

    return parser
Exemple #8
0
    def test_json_location(self):
        parser = RequestParser()
        parser.add_argument('foo', location='json', store_missing=True)

        with self.app.test_request_context('/bubble', method='post'):
            args = parser.parse_args()
            self.assertEqual(args['foo'], None)
    def test_not_json_location_and_content_type_json(self):
        parser = RequestParser()
        parser.add_argument('foo', location='args')

        with self.app.test_request_context('/bubble', method='get',
                                      content_type='application/json'):
            parser.parse_args()  # Should not raise a 400: BadRequest
    def test_parse_required(self):
        with self.app.app_context():
            req = Request.from_values('/bubble')

            parser = RequestParser()
            parser.add_argument('foo', required=True, location='values')

            expected = {
                'foo': 'Missing required parameter in the post body or the query string'
            }
            try:
                parser.parse_args(req)
            except BadRequest as e:
                self.assertEqual(e.data['message'], 'Input payload validation failed')
                self.assertEqual(e.data['errors'], expected)

            parser = RequestParser()
            parser.add_argument('bar', required=True, location=['values', 'cookies'])

            expected = {
                'bar': ("Missing required parameter in the post body or the query "
                "string or the request's cookies")
            }
            try:
                parser.parse_args(req)
            except BadRequest as e:
                self.assertEqual(e.data['message'], 'Input payload validation failed')
                self.assertEqual(e.data['errors'], expected)
Exemple #11
0
    def test_parse_required(self, app):
        parser = RequestParser()
        parser.add_argument('foo', required=True, location='values')

        expected = {
            'foo': 'Missing required parameter in the post body or the query string'
        }
        with pytest.raises(BadRequest) as cm:
            parser.parse_args()

        assert cm.value.data['message'] == 'Input payload validation failed'
        assert cm.value.data['errors'] == expected

        parser = RequestParser()
        parser.add_argument('bar', required=True, location=['values', 'cookies'])

        expected = {
            'bar': ("Missing required parameter in the post body or the query "
            "string or the request's cookies")
        }

        with pytest.raises(BadRequest) as cm:
            parser.parse_args()
        assert cm.value.data['message'] == 'Input payload validation failed'
        assert cm.value.data['errors'] == expected
Exemple #12
0
    def test_parse_unicode(self, app):
        req = Request.from_values('/bubble?foo=barß')
        parser = RequestParser()
        parser.add_argument('foo')

        args = parser.parse_args(req)
        assert args['foo'] == 'barß'
Exemple #13
0
    def test_parse_unicode_app(self, app):
        parser = RequestParser()
        parser.add_argument('foo')

        with app.test_request_context('/bubble?foo=barß'):
            args = parser.parse_args()
            assert args['foo'] == 'barß'
Exemple #14
0
    def test_parse_unicode(self):
        req = Request.from_values('/bubble?foo=barß')
        parser = RequestParser()
        parser.add_argument('foo')

        args = parser.parse_args(req)
        self.assertEqual(args['foo'], 'barß')
Exemple #15
0
    def test_parse_unicode_app(self, app):
        parser = RequestParser()
        parser.add_argument('foo')

        with app.test_request_context('/bubble?foo=barß'):
            args = parser.parse_args()
            assert args['foo'] == 'barß'
Exemple #16
0
    def test_passing_arguments_object(self, app):
        req = Request.from_values('/bubble?foo=bar')
        parser = RequestParser()
        parser.add_argument(Argument('foo'))

        args = parser.parse_args(req)
        assert args['foo'] == 'bar'
Exemple #17
0
class QueryPagination:
    """
    A query pagination class.

    Returns the paginated queryset of the given model and query using the request
    query parameters 'pageSize' and 'pageNumber'.
    """
    parser = None
    model = None

    def __init__(self, model=None, page_size_help='objects'):
        self.parser = RequestParser()
        self.model = model
        self.setup(page_size_help)

    def setup(self, page_size_help='objects'):
        """QueryPagination setup method"""
        self.parser.add_argument('pageSize',
                                 type=int,
                                 help=f'Number of {page_size_help} returned')
        self.parser.add_argument('pageNumber', type=int, help='Page number')

    def get_args(self):
        """Returns the pagination query parameters"""
        return self.parser.parse_args()

    def get_parser(self):
        """Returns the pagination RequestParser"""
        return self.parser

    def get_paginated_queryset(self, query={}):
        """
        Returns the paginated queryset according to the request parameters.

        If page size isn't provided but a page number was provided, the
        DEFAULT_PAGINATION_SIZE will be used.

        A BadRequest exception will be raised if the page number exceeds the
        actual maximum number of pages.
        """
        params = self.get_args()
        size = params['pageSize']
        data = []

        if params['pageNumber'] and not size:
            size = Config.DEFAULT_PAGINATION_SIZE

        try:
            if not query:
                data = self.model.query.paginate(params['pageNumber'],
                                                 size).items
            else:
                data = self.model.query.filter_by(**query).paginate(
                    params['pageNumber'], size).items
        except NotFound as err:
            raise BadRequest(
                "'pageNumber' parameter exceeds the actual maximum pages")

        return data
Exemple #18
0
    def test_parse_callable_default(self):
        req = Request.from_values('/bubble')

        parser = RequestParser()
        parser.add_argument('foo', default=lambda: 'bar', store_missing=True)

        args = parser.parse_args(req)
        self.assertEqual(args['foo'], 'bar')
Exemple #19
0
    def test_parse_choices_sensitive(self, app):
        req = Request.from_values('/bubble?foo=BAT')

        parser = RequestParser()
        parser.add_argument('foo', choices=['bat'], case_sensitive=True),

        with pytest.raises(BadRequest):
            parser.parse_args(req)
Exemple #20
0
    def test_type_callable(self):
        req = Request.from_values('/bubble?foo=1')

        parser = RequestParser()
        parser.add_argument('foo', type=lambda x: x, required=False),

        args = parser.parse_args(req)
        self.assertEqual(args['foo'], '1')
Exemple #21
0
    def test_parse_choices_correct(self):
        req = Request.from_values('/bubble?foo=bat')

        parser = RequestParser()
        parser.add_argument('foo', choices=['bat']),

        args = parser.parse_args(req)
        self.assertEqual(args['foo'], 'bat')
Exemple #22
0
 def test_unknown_type(self):
     parser = RequestParser()
     parser.add_argument('unknown', type=lambda v: v)
     assert parser.__schema__ == [{
         'name': 'unknown',
         'type': 'string',
         'in': 'query',
     }]
Exemple #23
0
    def test_parse_gte_lte_eq(self):
        parser = RequestParser()
        parser.add_argument('foo',
                            operators=['>=', '<=', '='],
                            action='append'),

        args = parser.parse_args()
        assert args['foo'] == ['bar', 'bat', 'foo']
Exemple #24
0
    def test_parse_none(self):
        req = Request.from_values('/bubble')

        parser = RequestParser()
        parser.add_argument('foo')

        args = parser.parse_args(req)
        self.assertEqual(args['foo'], None)
Exemple #25
0
    def test_parse_store_missing(self):
        req = Request.from_values('/bubble')

        parser = RequestParser()
        parser.add_argument('foo', store_missing=False)

        args = parser.parse_args(req)
        self.assertFalse('foo' in args)
Exemple #26
0
    def test_parse_ignore(self):
        req = Request.from_values('/bubble?foo=bar')

        parser = RequestParser()
        parser.add_argument('foo', type=int, ignore=True, store_missing=True),

        args = parser.parse_args(req)
        self.assertEqual(args['foo'], None)
Exemple #27
0
    def test_parse_choices_sensitive(self):
        with self.app.app_context():
            req = Request.from_values('/bubble?foo=BAT')

            parser = RequestParser()
            parser.add_argument('foo', choices=['bat'], case_sensitive=True),

            self.assertRaises(BadRequest, lambda: parser.parse_args(req))
Exemple #28
0
    def test_parse_append_single(self):
        req = Request.from_values('/bubble?foo=bar')

        parser = RequestParser()
        parser.add_argument('foo', action='append'),

        args = parser.parse_args(req)
        self.assertEqual(args['foo'], ['bar'])
Exemple #29
0
 def test_none_argument(self):
     parser = RequestParser()
     parser.add_argument('foo', location='json')
     with self.app.test_request_context('/bubble', method='post',
                                   data=json.dumps({'foo': None}),
                                   content_type='application/json'):
         args = parser.parse_args()
         self.assertEqual(args['foo'], None)
Exemple #30
0
    def test_parse_dest(self):
        req = Request.from_values('/bubble?foo=bar')

        parser = RequestParser()
        parser.add_argument('foo', dest='bat')

        args = parser.parse_args(req)
        self.assertEqual(args['bat'], 'bar')
Exemple #31
0
    def test_parse_append_default(self):
        req = Request.from_values('/bubble?')

        parser = RequestParser()
        parser.add_argument('foo', action='append', store_missing=True),

        args = parser.parse_args(req)
        self.assertEqual(args['foo'], None)
Exemple #32
0
 def test_unknown_type(self):
     parser = RequestParser()
     parser.add_argument('unknown', type=lambda v: v)
     assert parser.__schema__ == [{
         'name': 'unknown',
         'type': 'string',
         'in': 'query',
     }]
Exemple #33
0
    def test_parse_gte_lte_eq(self):
        req = Request.from_values('/bubble?foo>=bar&foo<=bat&foo=foo')

        parser = RequestParser()
        parser.add_argument('foo', operators=['>=', '<=', '='], action='append'),

        args = parser.parse_args(req)
        self.assertEqual(args['foo'], ['bar', 'bat', 'foo'])
Exemple #34
0
 def test_location_files(self):
     parser = RequestParser()
     parser.add_argument('in_files', type=FileStorage, location='files')
     self.assertEqual(parser.__schema__, [{
         'name': 'in_files',
         'type': 'file',
         'in': 'formData',
     }])
Exemple #35
0
    def test_parse_choices(self, app):
        req = Request.from_values('/bubble?foo=bar')

        parser = RequestParser()
        parser.add_argument('foo', choices=['bat']),

        with pytest.raises(BadRequest):
            parser.parse_args(req)
Exemple #36
0
 def test_location_form(self):
     parser = RequestParser()
     parser.add_argument('in_form', type=int, location='form')
     self.assertEqual(parser.__schema__, [{
         'name': 'in_form',
         'type': 'integer',
         'in': 'formData',
     }])
Exemple #37
0
 def test_location_json(self):
     parser = RequestParser()
     parser.add_argument('in_json', type=str, location='json')
     self.assertEqual(parser.__schema__, [{
         'name': 'in_json',
         'type': 'string',
         'in': 'body',
     }])
Exemple #38
0
class Pagination:
    """
    TO BE DEPRECATED IN FAVOR OF QueryPagination

    A simple pagination class.

    Returns the paginated results of a given list using the request query parameters
    'pageSize' and 'pageNumber'.
    """
    parser = None

    def __init__(self, page_size_help='objects'):
        self.parser = RequestParser()
        self.setup(page_size_help)

    def setup(self, page_size_help='objects'):
        """Pagination setup method"""
        self.parser.add_argument('pageSize',
                                 type=int,
                                 help=f'Number of {page_size_help} returned')
        self.parser.add_argument('pageNumber', type=int, help='Page number')

    def get_args(self):
        """Returns the pagination query parameters"""
        return self.parser.parse_args()

    def get_parser(self):
        """Returns the pagination RequestParser"""
        return self.parser

    def get_paginated_response(self, data):
        """
        Returns the paginated data according to the request parameters.

        If page size isn't provided, the DEFAULT_PAGINATION_SIZE will be used.

        A BadRequest exception will be raised if the page number exceeds the
        actual maximum number of pages.
        """
        params = self.get_args()
        start = 0
        end = None

        if params['pageNumber']:
            size = params['pageSize']
            if not size:
                size = Config.DEFAULT_PAGINATION_SIZE

            start = size * (params['pageNumber'] - 1)
            end = start + size

        if start > len(data):
            raise BadRequest(
                "'pageNumber' parameter exceeds the actual maximum pages")
        if end and end > len(data):
            end = None

        return data[start:end]
Exemple #39
0
 def test_default(self):
     parser = RequestParser()
     parser.add_argument('int', type=int, default=5)
     self.assertEqual(parser.__schema__, [{
         'name': 'int',
         'type': 'integer',
         'in': 'query',
         'default': 5,
     }])
Exemple #40
0
 def test_required(self):
     parser = RequestParser()
     parser.add_argument('int', type=int, required=True)
     self.assertEqual(parser.__schema__, [{
         'name': 'int',
         'type': 'integer',
         'in': 'query',
         'required': True,
     }])