def test_nested_use(self): arg = Arg({ 'foo': Arg(use=lambda v: v.upper()), 'bar': Arg(use=lambda v: v.lower()) }) in_data = {'foo': 'hErP', 'bar': 'dErP'} assert arg.validated('', in_data) == {'foo': 'HERP', 'bar': 'derp'}
def test_full_input_validation_with_multiple_validators(web_request, parser): def validate1(args): if args['a'] > args['b']: raise ValidationError('b must be > a') def validate2(args): if args['b'] > args['a']: raise ValidationError('a must be > b') args = {'a': Arg(int), 'b': Arg(int)} web_request.json = {'a': 2, 'b': 1} validators = [validate1, validate2] with pytest.raises(ValidationError) as excinfo: parser.parse(args, web_request, targets=('json', ), validate=validators) assert 'b must be > a' in str(excinfo) web_request.json = {'a': 1, 'b': 2} with pytest.raises(ValidationError) as excinfo: parser.parse(args, web_request, targets=('json', ), validate=validators) assert 'a must be > b' in str(excinfo)
def test_validated_non_nullable_types(self, arg_type): print(arg_type) arg = Arg(type_=arg_type) with pytest.raises(ValidationError) as excinfo: arg.validated('foo', None) assert 'Expected type "{0}" for foo, got "null"'.format( __type_map__[arg_type]) in str(excinfo)
def test_parse_with_source(web_request): web_request.json = {'foo': 41, 'bar': 42} parser = MockRequestParser() args = {'foo': Arg(int), 'baz': Arg(int, source='bar')} parsed = parser.parse(args, web_request, locations=('json', )) assert parsed == {'foo': 41, 'baz': 42}
def add_new_meta_result(): args = { 'page_type': Arg(str, required=True), 'url': Arg(str, default=None), 'page_param': Arg(str, default=None), 'h1': Arg(str, default=None), 'meta_title': Arg(str, default=None), 'meta_description': Arg(str, default=None), 'meta_keywords': Arg(str, default=None), 'og_tags': Arg(str, default='{}'), 'twitter_cards': Arg(str, default='{}'), 'gplus_tags': Arg(str, default='{}') } data = parser.parse(args, request) r = requests.post(api_base_url + '/seo/meta_data/add_meta_data', data) message = "Error while adding meta data for " + data[ 'page_type'] + ". Review the content and other parameters once, contact admin if that doesn't help!" message_color = "red" if json.loads(r.text)['result'] and json.loads( r.text)['result'] == 'Success': message = "Meta data for " + data[ 'page_type'] + " has been added successfully!" message_color = "green" return render_template('result.html', message=message, message_color=message_color)
def test_validated_unknown_type(self): arg = Arg(type_=UUID) assert (arg.validated('foo', '12345678123456781234567812345678') == UUID('12345678-1234-5678-1234-567812345678')) with pytest.raises(ValidationError) as excinfo: arg.validated('foo', None) assert 'Expected type "UUID" for foo, got "null"' in str(excinfo)
def test_passing_exception_as_error_argument(): arg = Arg(int, validate=lambda n: n == 42, error=AttributeError('an error occurred.')) with pytest.raises(ValidationError) as excinfo: arg.validated(41) assert 'an error occurred' in str(excinfo)
def test_parse_nested_with_default(web_request): parser = MockRequestParser() web_request.json = dict(nested_arg=dict()) args = dict(nested_arg=Arg(dict(missing=Arg(default=False)))) parsed = parser.parse(args, web_request, locations=('json',)) assert parsed == dict(nested_arg=dict(missing=False))
def test_outer_use(self): arg = Arg({ 'foo': Arg() }, use=json.loads) # has extra args in_data = json.dumps({'foo': 42, 'bar': 24}) assert arg.validated('', in_data) == {'foo': 42}
def test_extra_arguments_are_excluded(self): arg = Arg({ 'foo': Arg(), }) in_data = {'foo': 42, 'bar': 24} assert arg.validated('', in_data) == {'foo': 42}
def test_parse_with_source(request): request.json = {'foo': 41, 'bar': 42} parser = MockRequestParser() args = {'foo': Arg(int), 'baz': Arg(int, source='bar')} parsed = parser.parse(args, request, targets=('json', )) assert parsed == {'foo': 41, 'baz': 42}
def test_nested_argdict_has_type_dict(self): arg = Arg({'foo': Arg()}) assert arg.type == dict with pytest.raises(ValidationError) as excinfo: arg.validated('myarg', 'notadict') assert 'Expected type "object" for myarg, got "string"' in str(excinfo)
def test_parse_nested_with_missing_key_and_dest(web_request): parser = MockRequestParser() web_request.json = dict(nested_arg=dict(payload='OK')) args = dict(nested_arg=Arg(dict(missing=Arg(dest='found')))) parsed = parser.parse(args, web_request, locations=('json',)) assert parsed == dict(nested_arg=dict(found=None))
def test_parse_nested_with_dest(web_request): parser = MockRequestParser() web_request.json = dict(nested_arg=dict(wrong='OK')) args = dict(nested_arg=Arg(dict(wrong=Arg(dest='right')))) parsed = parser.parse(args, web_request, locations=('json',)) assert parsed == dict(nested_arg=dict(right='OK'))
def test_nested_required_unicode_error_message_override(self): arg = Arg({ 'foo': Arg(required=u'We need foo') }) with pytest.raises(RequiredArgMissingError) as excinfo: arg.validated('', {}) assert 'We need foo' in excinfo.value.message assert 'foo' in excinfo.value.arg_name
def test_handle_error_called_when_parsing_raises_error(parse_json, handle_error, web_request): val_err = ValidationError('error occurred') parse_json.side_effect = val_err p = Parser() p.parse({'foo': Arg()}, web_request, locations=('json',)) handle_error.assert_called parse_json.side_effect = ValidationError('another exception') p.parse({'foo': Arg()}, web_request, locations=('json',)) assert handle_error.call_count == 2
def test_parse(parse_json, web_request): parse_json.return_value = 42 argmap = { 'username': Arg(), 'password': Arg() } p = Parser() ret = p.parse(argmap, web_request) assert {'username': 42, 'password': 42} == ret
def test_deep_nesting_validation(self): arg = Arg({ 'foo': Arg({ 'bar': Arg(validate=lambda v: v <= 42) }) }) valid = {'foo': {'bar': 42}} assert arg.validated('myarg', valid) == valid
def test_use_args(web_request, parser): user_args = {'username': Arg(str), 'password': Arg(str)} web_request.json = {'username': '******', 'password': '******'} @parser.use_args(user_args, web_request) def viewfunc(args): return args assert viewfunc() == {'username': '******', 'password': '******'}
def test_handle_error_called_when_parsing_raises_error(parse_json, handle_error, request): val_err = ValidationError('error occurred') parse_json.side_effect = val_err p = Parser() p.parse({'foo': Arg()}, request, targets=('json', )) assert handle_error.called parse_json.side_effect = Exception('generic exception') p.parse({'foo': Arg()}, request, targets=('json', )) assert handle_error.call_count == 2
def test_full_input_validation(web_request): web_request.json = {'foo': 41, 'bar': 42} parser = MockRequestParser() args = {'foo': Arg(int), 'bar': Arg(int)} with pytest.raises(ValidationError): # Test that `validate` receives dictionary of args parser.parse(args, web_request, locations=('json', ), validate=lambda args: args['foo'] > args['bar'])
def test_use_kwargs_with_arg_allowed_missing(web_request, parser): user_args = { 'username': Arg(str), 'password': Arg(str, allow_missing=True), } web_request.json = {'username': '******'} @parser.use_kwargs(user_args, web_request) def viewfunc(username, password): return {'username': username, 'password': password} assert viewfunc() == {'username': '******', 'password': None}
def test_use_kwargs_with_arg_missing(request, parser): user_args = { 'username': Arg(str), 'password': Arg(str), } request.json = {'username': '******'} @parser.use_kwargs(user_args, request) def viewfunc(username, password): return {'username': username, 'password': password} assert viewfunc() == {'username': '******', 'password': None}
def test_value_error_raised_if_invalid_target(request): arg = Arg() p = Parser() with pytest.raises(ValueError) as excinfo: p.parse_arg('foo', arg, request, targets=('invalidtarget', 'headers')) assert 'Invalid targets arguments: {0}'.format(['invalidtarget' ]) in str(excinfo)
def test_parse_cookies_called_when_cookies_is_a_target(parse_cookies, request): arg = Arg() p = Parser() p.parse_arg('foo', arg, request) assert parse_cookies.call_count == 0 p.parse_arg('foo', arg, request, targets=('cookies', )) assert parse_cookies.called
def test_parse_with_dest(web_request): web_request.json = {'Content-Type': 'application/json'} parser = MockRequestParser() args = {'Content-Type': Arg(dest='content_type')} parsed = parser.parse(args, web_request, locations=('json', )) assert parsed == {'content_type': 'application/json'}
def test_parse_required_arg_raises_validation_error(parse_json, web_request): arg = Arg(required=True) p = Parser() parse_json.return_value = Missing with pytest.raises(ValidationError) as excinfo: p.parse_arg('foo', arg, web_request) assert 'Required parameter "foo" not found.' in str(excinfo)
def test_type_conversion_with_multiple_and_arg_missing(web_request, parser): # arg missing in request web_request.json = {} args = {'ids': Arg(int, multiple=True)} result = parser.parse(args, web_request) assert 'ids' in result
def test_repr(self): arg = Arg(str, default='foo', required=True) r = repr(arg) assert 'str' in r assert '<webargs.core.Arg' in r assert 'foo' in r assert 'required=True' in r
def test_arg_location_param(web_request, parser): web_request.cookies = {'foo': 42} args = {'foo': Arg(location='cookies')} parsed = parser.parse(args, web_request) assert parsed['foo'] == 42
def test_convert_and_use_params(): arg = Arg(float, use=lambda val: val + 1) assert arg.validated(41) == 42.0
def test_use_param(): arg = Arg(use=lambda x: x.upper()) assert arg.validated('foo') == 'FOO'
def test_conversion_to_str(): arg = Arg(str) assert arg.validated(42) == '42'
def test_default_valdation_msg(): arg = Arg(validate=lambda x: x == 42) with pytest.raises(ValidationError) as excinfo: arg.validated(1) assert 'Validator <lambda>(1) is not True' in str(excinfo)
def test_custom_error(): arg = Arg(type_=int, error='not an int!') with pytest.raises(ValidationError) as excinfo: arg.validated('badinput') assert 'not an int!' in str(excinfo)
def test_validated_with_bad_type(): arg = Arg(type_=int) assert arg.validated(42) == 42 with pytest.raises(ValidationError): arg.validated('nonint')
def test_validated_with_conversion(): arg = Arg(validate=lambda x: x == 42, type_=int) assert arg.validated('42') == 42
def test_validated(): arg = Arg(validate=lambda x: x == 42) assert arg.validated(42) == 42 with pytest.raises(ValidationError): arg.validated(32)
def test_multiple_with_type_arg(): arg = Arg(int, multiple=True) assert arg.validated(['1', 2, 3.0]) == [1, 2, 3]
def test_use_is_called_before_validate(): arg = Arg(use=lambda x: x + 1, validate=lambda x: x == 41) with pytest.raises(ValidationError): arg.validated(41)
def test_validate_can_be_none(): arg = Arg(validate=None) assert arg.validated(41) == 41
def test_validated_with_nonascii_input(): arg = Arg(validate=lambda t: False) text = u'øˆ∆´ƒº' with pytest.raises(ValidationError) as excinfo: arg.validated(text) assert text in unicode(excinfo)
def test_multiple_with_use_arg(): arg = Arg(multiple=True, use=lambda x: x.upper()) assert arg.validated(['foo', 'bar']) == ['FOO', 'BAR']
def test_convert_and_use_params(): arg = Arg(int, use=lambda x: x + 1) assert arg.validated('41') == 42