def test_arg_allowed_missing_when_none_is_passed(testapp): # 'last' argument is allowed to be missing args = {'first': Arg(str), 'last': Arg(allow_missing=True)} with testapp.test_request_context('/foo', method='post', data=json.dumps({ 'first': 'Fred', 'last': None }), content_type='application/json'): args = parser.parse(args) assert 'first' in args assert args['last'] is None
def test_it_should_parse_files_arguments(self): attrs = { 'string': Arg(str), 'integer': Arg(int, multiple=True) } request = make_files_request([ ('string', 'value'), ('integer', '1'), ('integer', '2') ]) parsed = parser.parse(attrs, request, targets=['files']) assert parsed['string'] == value assert parsed['integer'] == [1, 2]
def test_it_should_parse_form_arguments(self): attrs = { 'string': Arg(), 'integer': Arg(int, multiple=True) } request = make_form_request([ ('string', 'value'), ('integer', '1'), ('integer', '2') ]) parsed = parser.parse(attrs, request) assert parsed['integer'] == [1, 2] assert parsed['string'] == bvalue
def test_arg_specific_locations(app, testapp): testargs = { 'name': Arg(str, location='json'), 'age': Arg(int, location='querystring'), } @app.route('/echo', method=['POST']) def echo(): args = parser.parse(testargs, request) return args resp = testapp.post_json('/echo?age=42', {'name': 'Fred'}) assert resp.json['age'] == 42 assert resp.json['name'] == 'Fred'
def set_valid(cls): """ 设置banner是否有效 """ args_spec = { 'id': Arg(int), 'is_valid': Arg(int), } args = args_parser.parse(args_spec) if not len(args.values()) == 2 or args.get('is_valid') is None: # TODO raise incorrect args exception raise_user_exc(BANNER_ARGS_ERR) cls.update(args) return ''
def test_it_should_parse_header_arguments(self): attrs = { 'string': Arg(str), 'integer': Arg(int, multiple=True) } request = make_request(headers={ 'string': 'value', 'integer': ['1', '2'] }) parsed = parser.parse(attrs, request, targets=['headers']) assert parsed['string'] == value assert parsed['integer'] == [1, 2]
def test_it_should_parse_json_arguments(self): attrs = { 'string': Arg(str), 'integer': Arg(int, multiple=True) } request = make_json_request({ 'string': 'value', 'integer': [1, 2] }) parsed = parser.parse(attrs, request) assert parsed['integer'] == [1, 2] assert parsed['string'] == value
def gets_hongbao_exchange(): args = args_parser.parse({ 'phone': Arg(str, allow_missing=True), 'sn': Arg(str, allow_missing=True), 'status': Arg(int, allow_missing=True), 'from_datetime': Arg(str, allow_missing=True), 'to_datetime': Arg(str, allow_missing=True), }) page_no, page_size = get_paging_params() args.update(offset=(page_no - 1) * page_size, limit=page_size) hongbao_exchange_list, total_num = hongbao_base.gets_hongbao_exchange(args) return { 'hongbao_exchange_list': hongbao_exchange_list, 'total_num': total_num }
def test_use_kwargs_with_url_params(app, testapp): @app.route('/foo/<name>') @parser.use_kwargs({'myvalue': Arg(int)}) def foo(myvalue, name): return {'myvalue': myvalue} assert testapp.get('/foo/Fred?myvalue=42').json == {'myvalue': 42}
def test_arg2parameters_with_dest(self): args = { 'X-Neat-Header': Arg(str, location='headers', dest='neat_header') } result = swagger.args2parameters(args) header = result[0] assert header['name'] == 'X-Neat-Header'
def test_webargs_validation(self): def validator(val): raise ValidationError('oh no') a = Arg(validate=validator) with pytest.raises(WebargsValidationError): a.validated('', '')
class Bar(object): def __init__(self, request): self.request = request @parser.use_args({'myvalue': Arg(int)}) def __call__(self, args): return args
def set_order_valid(): args_spec = { 'order_id': Arg(int), } args = args_parser.parse(args_spec) order_id = args['order_id'] return order_base.set_valid(order_id)
def get_activities(cls): args_spec = { 'city_ids': Arg(int, multiple=True, allow_missing=True), } city_ids = args_parser.parse(args_spec).get('city_ids', []) if not city_ids: city_ids = cls.get_user_city_ids() today = get_today_date_str() rest_activities = rst_act_base.query( begin_date=today, end_date=today, city_ids=city_ids, is_valid=True) food_activities = food_act_base.query( begin_date=today, end_date=today, city_ids=city_ids, is_valid=True) rest_act_result = [] for act in rest_activities: rest_act_result.append({ 'activity_id': act.id, 'activity_name': RestaurantActivityMixin.get_name(act) }) food_act_result = [] for act in food_activities: food_act_result.append({ 'activity_id': act.id, 'activity_name': act.name }) return { 'food_activities': food_act_result, 'rest_activities': rest_act_result }
def test_use_args_decorator(app, testapp): @app.route('/foo/', method=['GET', 'POST']) @parser.use_args({'myvalue': Arg(int)}) def echo2(args): return args assert testapp.post('/foo/', {'myvalue': 23}).json == {'myvalue': 23}
class Handler(object): request = make_json_request({'foo': 41}) @use_kwargs({'foo': Arg(int)}, validate=lambda args: args['foo'] > 42) def get(self, args): return True
def test_it_should_return_missing_if_not_present(self): query = {} arg = Arg(multiple=False) request = make_json_request(query) result = parser.parse_json(request, name, arg) assert result is Missing
def test_it_should_return_empty_list_if_multiple_and_not_present(self): query = {} arg = Arg(multiple=True) request = make_json_request(query) result = parser.parse_json(request, name, arg) assert result is Missing
def test_it_should_get_single_values(self): query = {name: value} arg = Arg(multiple=False) request = make_json_request(query) result = parser.parse_json(request, name, arg) assert result == value
def test_it_should_get_multiple_values(self): query = {name: [value, value]} arg = Arg(multiple=True) request = make_json_request(query) result = parser.parse_json(request, name, arg) assert result == [value, value]
def query_restaurant_activity_for_admin(self): # todo 效验是否admin args_spec = { 'city_ids': Arg(), 'begin_date': Arg(str), 'end_date': Arg(str), 'offset': Arg(int), 'limit': Arg(int), } args = args_parser.parse(args_spec) q = thirdparty_svc.ers.TRestaurantActivityQuery() for k, v in args.iteritems(): setattr(q, k, v) with thrift_client('ers') as ers: result = ers.query_restaurant_activity_for_admin(q) return result
class Handler(webapp2.RequestHandler): @parser.use_args({'myfile': Arg(multiple=True)}, locations=('files', )) def post(self, args): self.response.content_type = 'application/json' _value = lambda f: f.getvalue().decode('utf-8') data = dict((i.filename, _value(i.file)) for i in args['myfile']) self.response.write(json.dumps(data))
class ReadingList(APIView): route_base = '/reading/' decorators = [jwt_required(realm=None)] ARGS = { 'book_id': Arg(int, required=True) } def _get_book_from_request(self): reqargs = self._parse_request() book = Book.get_by_id(reqargs['book_id']) if not book: raise NotFound(detail='Book with id {0!r} not found.'.format(book.id)) return book def get(self): """Get the reading list for the authenticated user.""" reading_list = current_user.reading_list.all() res = { 'result': serialize_book(reading_list, many=True).data, 'user': serialize_user(current_user._get_current_object()).data } return res def post(self): """Add a book to the authenticated user's reading list. :param-json int book_id: ID of the book to add. """ book = self._get_book_from_request() current_user.add_to_reading_list(book) current_user.save() return { 'result': serialize_book(book).data, 'user': serialize_user(current_user._get_current_object()).data, }, http.OK def put(self): """Toggle the ``read`` status of a book. :param-json int book_id: ID of the book to modify. """ book = self._get_book_from_request() current_user.toggle_read(book) current_user.save() has_read = current_user.has_read(book) return { 'result': serialize_book(book, extra={'read': has_read}).data, 'user': serialize_user(current_user._get_current_object()).data, }, http.OK def delete(self): """Remove a book from the user's reading list. :param-json int book_id: The ID of the book to remove. """ book = self._get_book_from_request() current_user.remove_from_reading_list(book, commit=True) return {}
def test_it_should_get_multiple_values(self): query = [(name, value), (name, value)] arg = Arg(multiple=True) request = make_form_request(query) result = parser.parse_form(request, name, arg) assert result == [bvalue, bvalue]
class Handler(object): request = make_json_request({'key': 'value'}) @use_kwargs({'key': Arg()}) def get(self, *args, **kwargs): assert args == () assert kwargs == {'key': 'value'} return True
def test_it_should_get_single_values(self): query = [(name, value)] arg = Arg(multiple=False) request = make_get_request(query) result = parser.parse_querystring(request, name, arg) assert result == bvalue
def test_parse_multiple_json(testapp): multargs = {'name': Arg(multiple=True)} with testapp.test_request_context('/foo', data=json.dumps({'name': 'steve'}), content_type='application/json', method='POST'): args = parser.parse(multargs, targets=('json', )) assert args['name'] == ['steve']
def test_abort_called_when_required_arg_not_present(mock_abort, testapp): args = {'required': Arg(required=True)} with testapp.test_request_context('/foo', method='post', data=json.dumps({}), content_type='application/json'): parser.parse(args) assert mock_abort.called_once_with(400)
def test_use_kwargs_doesnt_change_docstring(testapp): @testapp.route('/foo/', methods=['post', 'get']) @parser.use_kwargs({'myvalue': Arg(type_=int)}) def echo(args, id): """Echo docstring.""" return jsonify(args) assert echo.__doc__ == 'Echo docstring.'
def test_multiple_arg_required_int_conversion_required(mock_abort, testapp): args = {'ids': Arg(int, multiple=True, required=True)} with testapp.test_request_context(path='/foo', method='post', data=json.dumps({}), content_type='application/json'): args = parser.parse(args) mock_abort.assert_called_once