Exemplo n.º 1
0
 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'}
Exemplo n.º 2
0
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)
Exemplo n.º 3
0
 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)
Exemplo n.º 4
0
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}
Exemplo n.º 5
0
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)
Exemplo n.º 6
0
 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)
Exemplo n.º 7
0
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)
Exemplo n.º 8
0
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))
Exemplo n.º 9
0
    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}
Exemplo n.º 10
0
    def test_extra_arguments_are_excluded(self):
        arg = Arg({
            'foo': Arg(),
        })

        in_data = {'foo': 42, 'bar': 24}

        assert arg.validated('', in_data) == {'foo': 42}
Exemplo n.º 11
0
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}
Exemplo n.º 12
0
    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)
Exemplo n.º 13
0
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))
Exemplo n.º 14
0
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'))
Exemplo n.º 15
0
 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
Exemplo n.º 16
0
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
Exemplo n.º 17
0
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
Exemplo n.º 18
0
    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
Exemplo n.º 19
0
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': '******'}
Exemplo n.º 20
0
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
Exemplo n.º 21
0
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'])
Exemplo n.º 22
0
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}
Exemplo n.º 23
0
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}
Exemplo n.º 24
0
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)
Exemplo n.º 25
0
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
Exemplo n.º 26
0
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'}
Exemplo n.º 27
0
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)
Exemplo n.º 28
0
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
Exemplo n.º 29
0
 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
Exemplo n.º 30
0
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
Exemplo n.º 31
0
def test_convert_and_use_params():
    arg = Arg(float, use=lambda val: val + 1)
    assert arg.validated(41) == 42.0
Exemplo n.º 32
0
def test_use_param():
    arg = Arg(use=lambda x: x.upper())
    assert arg.validated('foo') == 'FOO'
Exemplo n.º 33
0
def test_conversion_to_str():
    arg = Arg(str)
    assert arg.validated(42) == '42'
Exemplo n.º 34
0
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)
Exemplo n.º 35
0
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)
Exemplo n.º 36
0
def test_validated_with_bad_type():
    arg = Arg(type_=int)
    assert arg.validated(42) == 42
    with pytest.raises(ValidationError):
        arg.validated('nonint')
Exemplo n.º 37
0
def test_validated_with_conversion():
    arg = Arg(validate=lambda x: x == 42, type_=int)
    assert arg.validated('42') == 42
Exemplo n.º 38
0
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)
Exemplo n.º 39
0
def test_validated():
    arg = Arg(validate=lambda x: x == 42)
    assert arg.validated(42) == 42
    with pytest.raises(ValidationError):
        arg.validated(32)
Exemplo n.º 40
0
def test_multiple_with_type_arg():
    arg = Arg(int, multiple=True)
    assert arg.validated(['1', 2, 3.0]) == [1, 2, 3]
Exemplo n.º 41
0
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)
Exemplo n.º 42
0
def test_validate_can_be_none():
    arg = Arg(validate=None)
    assert arg.validated(41) == 41
Exemplo n.º 43
0
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)
Exemplo n.º 44
0
def test_multiple_with_use_arg():
    arg = Arg(multiple=True, use=lambda x: x.upper())
    assert arg.validated(['foo', 'bar']) == ['FOO', 'BAR']
Exemplo n.º 45
0
def test_convert_and_use_params():
    arg = Arg(int, use=lambda x: x + 1)
    assert arg.validated('41') == 42