Exemplo n.º 1
0
def test_ashes():
    ashes_render = AshesRenderFactory(_TMPL_DIR)
    tmpl = 'basic_template.html'
    app = Application([('/', hello_world_ctx, tmpl),
                       ('/<name>/', hello_world_ctx, tmpl),
                       ('/beta/<name>/', complex_context, tmpl)],
                      render_factory=ashes_render)

    c = app.get_local_client()
    resp = c.get('/')
    assert resp.status_code == 200
    assert b'world' in resp.data

    resp = c.get('/beta/Rajkumar/')
    assert resp.status_code, 200
    assert b'Rajkumar' in resp.data

    # test rebind

    # no loss of binding on applications with no render factory
    wrap_app = Application([('/', app)])
    assert wrap_app.routes[0].render_factory is ashes_render
    c = wrap_app.get_local_client()
    resp = c.get('/')
    assert resp.status_code == 200
    assert b'<html>' in resp.data
    assert b'world' in resp.data

    # test bind new but not old
    ashes_render2 = AshesRenderFactory(_TMPL_DIR)
    wrap_app2 = Application([('/test', hello_world_ctx, tmpl), ('/', app)],
                            render_factory=ashes_render2)
    assert wrap_app2.routes[0].render_factory is ashes_render2
    assert wrap_app2.routes[1].render_factory is ashes_render
Exemplo n.º 2
0
def test_debug_raises():
    app_nodebug = Application([('/', lambda: 1/0)], debug=False)
    client = app_nodebug.get_local_client()
    assert client.get('/').status_code == 500

    err_handler = ErrorHandler(reraise_uncaught=True)
    app_debug = Application([('/', lambda: 1/0)], error_handler=err_handler)
    client = app_debug.get_local_client()

    with raises(ZeroDivisionError):
        client.get('/')
    return
Exemplo n.º 3
0
def test_debug_raises():
    app_nodebug = Application([('/', lambda: 1/0)], debug=False)
    client = app_nodebug.get_local_client()
    assert client.get('/').status_code == 500

    err_handler = ErrorHandler(reraise_uncaught=True)
    app_debug = Application([('/', lambda: 1/0)], error_handler=err_handler)
    client = app_debug.get_local_client()

    with raises(ZeroDivisionError):
        client.get('/')
    return
Exemplo n.º 4
0
def test_default_render():
    app = Application([('/', hello_world_ctx, render_basic),
                       ('/<name>/', hello_world_ctx, render_basic),
                       ('/text/<name>/', hello_world_str, render_basic),
                       ('/html/<name>/', hello_world_html, render_basic),
                       ('/beta/<name>/', complex_context, render_basic)])

    assert callable(app.routes[0]._execute)
    assert callable(app.routes[0].render)
    c = app.get_local_client()

    resp = c.get('/')  # test simple json with endpoint default
    assert resp.status_code == 200
    resp_data = json.loads(resp.get_data(True))
    assert resp_data['name'] == 'world'

    resp = c.get('/Kurt/')  # test simple json with url param
    assert resp.status_code == 200
    resp_data = json.loads(resp.get_data(True))
    assert resp_data['name'] == 'Kurt'

    resp = c.get('/beta/Rajkumar/')  # test fancy json
    assert resp.status_code == 200
    resp_data = json.loads(resp.get_data(True))
    assert resp_data['name'] == 'Rajkumar'
    assert resp_data['date']
    assert len(resp_data) > 4

    resp = c.get('/text/Noam/')  # test text
    assert resp.status_code == 200
    assert resp.data == b'Hello, Noam!'

    resp = c.get('/html/Asia/')  # test basic html
    assert resp.status_code == 200
    assert 'text/html' in resp.headers['Content-Type']
Exemplo n.º 5
0
def test_json_render(render_json=None):
    if render_json is None:
        render_json = JSONRender(dev_mode=True)
    app = Application([('/', hello_world_ctx, render_json),
                       ('/<name>/', hello_world_ctx, render_json),
                       ('/beta/<name>/', complex_context, render_json)])

    assert callable(app.routes[0]._execute)
    assert callable(app.routes[0].render)
    c = app.get_local_client()

    resp = c.get('/')
    assert resp.status_code == 200
    resp_data = json.loads(resp.get_data(True))
    assert resp_data['name'] == 'world'

    resp = c.get('/Kurt/')
    assert resp.status_code == 200
    resp_data = json.loads(resp.get_data(True))
    assert resp_data['name'] == 'Kurt'

    resp = c.get('/beta/Rajkumar/')
    assert resp.status_code == 200
    resp_data = json.loads(resp.get_data(True))
    assert resp_data['name'] == 'Rajkumar'
    assert resp_data['date']
    assert len(resp_data) > 4
Exemplo n.º 6
0
def test_ctx_proc_nonctx():
    add_name = ContextProcessor(defaults={'name': 'Kurt'})
    app = Application([('/', hello_world_str, render_basic)],
                      middlewares=[add_name])
    c = app.get_local_client()
    resp = c.get('/')
    assert resp.data == b'Hello, world!'
Exemplo n.º 7
0
def test_custom_table_render():
    def hello_world_ctx(name=None):
        """
        This docstring will be visible in the rendered response.

        Links like https://example.com and www.example.com will be linkified automatically.
        """
        if name is None:
            name = 'world'
        greeting = 'Hello, %s!' % name
        return {'name': name, 'greeting': greeting}

    class BoldHTMLTable(Table):
        def get_cell_html(self, value):
            std_html = super(BoldHTMLTable, self).get_cell_html(value)
            return '<b>' + std_html + '</b>'

    custom_tr = TabularRender(table_type=BoldHTMLTable)
    custom_render = BasicRender(tabular_render=custom_tr)
    app = Application([('/', hello_world_ctx, custom_render)])
    c = app.get_local_client()

    resp = c.get('/?format=html')
    assert resp.status_code == 200
    resp_data = resp.get_data(True)
    assert '<b>' in resp_data
    assert '<a href="https://example.com">' in resp_data
Exemplo n.º 8
0
def test_big_mw_stack():
    from clastic.middleware import (client_cache,
                                    compress,
                                    context,
                                    cookie,
                                    form,
                                    profile,
                                    stats,
                                    url)
    middlewares = [client_cache.HTTPCacheMiddleware(),
                   compress.GzipMiddleware(),
                   context.ContextProcessor(),
                   context.SimpleContextProcessor(),
                   cookie.SignedCookieMiddleware(),
                   form.PostDataMiddleware({'lol': str}),
                   profile.SimpleProfileMiddleware(),
                   stats.StatsMiddleware(),
                   url.ScriptRootMiddleware(),
                   url.GetParamMiddleware({})]
    [repr(mw) for mw in middlewares]
    app = Application([('/', hello_world)],
                      middlewares=middlewares)
    cl = app.get_local_client()
    resp = cl.get('/')
    assert resp.status_code == 200
Exemplo n.º 9
0
def test_http_method_routes():
    ep = lambda _route: repr(_route.methods)
    routes = [
        GET('/get', ep, render_basic),
        POST('/post', ep, render_basic),
        PUT('/put', ep, render_basic),
        DELETE('/delete', ep, render_basic)
    ]
    app = Application(routes)
    client = app.get_local_client()
    methods = ('get', 'post', 'put', 'delete')
    status_map = {}
    for correct_method in methods:
        for attempted_method in methods:
            req_func = getattr(client, attempted_method)
            resp = req_func('/' + correct_method)
            status_code = resp.status_code
            try:
                status_map[status_code] += 1
            except KeyError:
                status_map[status_code] = 1

            if status_code == 200:
                resp_data = resp.data
                # lololol yay eval()
                route_methods = eval(resp_data) - set(['HEAD'])
                assert set([correct_method.upper()]) == route_methods
    assert status_map[200] == len(routes)
    assert status_map.get(405) == len(routes) * (len(methods) - 1)
    return
Exemplo n.º 10
0
def test_custom_table_render():
    def hello_world_ctx(name=None):
        """
        This docstring will be visible in the rendered response.

        Links like https://example.com and www.example.com will be linkified automatically.
        """
        if name is None:
            name = 'world'
        greeting = 'Hello, %s!' % name
        return {'name': name,
                'greeting': greeting}

    class BoldHTMLTable(Table):
        def get_cell_html(self, value):
            std_html = super(BoldHTMLTable, self).get_cell_html(value)
            return '<b>' + std_html + '</b>'

    custom_tr = TabularRender(table_type=BoldHTMLTable)
    custom_render = BasicRender(tabular_render=custom_tr)
    app = Application([('/', hello_world_ctx, custom_render)])
    c = app.get_local_client()

    resp = c.get('/?format=html')
    assert resp.status_code == 200
    resp_data = resp.get_data(True)
    assert '<b>' in resp_data
    assert '<a href="https://example.com">' in resp_data
Exemplo n.º 11
0
def test_error_render_count():
    class AccumErrorHandler(ErrorHandler):
        def render_error(self, _error, request, error_list, **kwargs):
            if 'reraise' in request.path:
                raise _error
            if 'badgateway' in request.path:
                _error = BadGateway()
            error_list.append(_error)
            return _error

    rt = Route('/<number:int>/<option?>', odd_endpoint, render_basic)
    error_list = []
    rsrc = {'error_list': error_list}
    app = Application([rt], rsrc, error_handler=AccumErrorHandler())
    cl = app.get_local_client()

    err_resp = cl.get('/39')
    assert err_resp.status_code == 200
    err_resp = cl.get('/2')
    assert err_resp.status_code == 500
    assert len(error_list) == 1

    # reraising means the error will be handled by the default
    # handler, so no length change should occur
    err_resp = cl.get('/4/reraise')
    assert err_resp.status_code == 500
    assert len(error_list) == 1

    err_resp = cl.get('/6/badgateway')
    assert err_resp.status_code == 502
    assert len(error_list) == 2
Exemplo n.º 12
0
def test_error_render_count():

    class AccumErrorHandler(ErrorHandler):
        def render_error(self, _error, request, error_list, **kwargs):
            if 'reraise' in request.path:
                raise _error
            if 'badgateway' in request.path:
                _error = BadGateway()
            error_list.append(_error)
            return _error

    rt = Route('/<number:int>/<option?>', odd_endpoint, render_basic)
    error_list = []
    rsrc = {'error_list': error_list}
    app = Application([rt], rsrc, error_handler=AccumErrorHandler())
    cl = app.get_local_client()

    err_resp = cl.get('/39')
    assert err_resp.status_code == 200
    err_resp = cl.get('/2')
    assert err_resp.status_code == 500
    assert len(error_list) == 1

    # reraising means the error will be handled by the default
    # handler, so no length change should occur
    err_resp = cl.get('/4/reraise')
    assert err_resp.status_code == 500
    assert len(error_list) == 1

    err_resp = cl.get('/6/badgateway')
    #if err_resp.status_code != 502:
    #    import pdb;pdb.set_trace()
    assert err_resp.status_code == 502
    assert len(error_list) == 2
Exemplo n.º 13
0
def test_nonbreaking_exc():
    app = Application([('/', lambda: NotFound(is_breaking=False)),
                       ('/', lambda: 'so hot in here', render_basic)])
    client = app.get_local_client()
    resp = client.get('/')
    assert resp.status_code == 200
    assert resp.data == b'so hot in here'
Exemplo n.º 14
0
def test_direct_no_render():
    render_raises_mw = RenderRaisesMiddleware()
    app = Application([('/', hello_world)],
                      middlewares=[render_raises_mw])
    c = app.get_local_client()
    resp = c.get('/')
    assert resp.data == b'Hello, world!'
Exemplo n.º 15
0
def test_nonbreaking_exc():
    app = Application([('/', lambda: NotFound(is_breaking=False)),
                       ('/', lambda: 'so hot in here', render_basic)])
    client = app.get_local_client()
    resp = client.get('/')
    assert resp.status_code == 200
    assert resp.data == b'so hot in here'
Exemplo n.º 16
0
def test_json_render(render_json=None):
    if render_json is None:
        render_json = JSONRender(dev_mode=True)
    app = Application([('/', hello_world_ctx, render_json),
                       ('/<name>/', hello_world_ctx, render_json),
                       ('/beta/<name>/', complex_context, render_json)])

    assert callable(app.routes[0]._execute)
    assert callable(app.routes[0]._render)
    c = app.get_local_client()

    resp = c.get('/')
    assert resp.status_code == 200
    resp_data = json.loads(resp.get_data(True))
    assert resp_data['name'] == 'world'

    resp = c.get('/Kurt/')
    assert resp.status_code == 200
    resp_data = json.loads(resp.get_data(True))
    assert resp_data['name'] == 'Kurt'

    resp = c.get('/beta/Rajkumar/')
    assert resp.status_code == 200
    resp_data = json.loads(resp.get_data(True))
    assert resp_data['name'] == 'Rajkumar'
    assert resp_data['date']
    assert len(resp_data) > 4
Exemplo n.º 17
0
def test_default_render():
    app = Application([('/', hello_world_ctx, render_basic),
                       ('/<name>/', hello_world_ctx, render_basic),
                       ('/text/<name>/', hello_world_str, render_basic),
                       ('/html/<name>/', hello_world_html, render_basic),
                       ('/beta/<name>/', complex_context, render_basic)])

    assert callable(app.routes[0]._execute)
    assert callable(app.routes[0]._render)
    c = app.get_local_client()

    resp = c.get('/')  # test simple json with endpoint default
    assert resp.status_code == 200
    resp_data = json.loads(resp.get_data(True))
    assert resp_data['name'] == 'world'

    resp = c.get('/Kurt/')  # test simple json with url param
    assert resp.status_code == 200
    resp_data = json.loads(resp.get_data(True))
    assert resp_data['name'] == 'Kurt'

    resp = c.get('/beta/Rajkumar/')  # test fancy json
    assert resp.status_code == 200
    resp_data = json.loads(resp.get_data(True))
    assert resp_data['name'] == 'Rajkumar'
    assert resp_data['date']
    assert len(resp_data) > 4

    resp = c.get('/text/Noam/')  # test text
    assert resp.status_code == 200
    assert resp.data == b'Hello, Noam!'

    resp = c.get('/html/Asia/')  # test basic html
    assert resp.status_code == 200
    assert 'text/html' in resp.headers['Content-Type']
Exemplo n.º 18
0
def test_ctx_proc_empty():
    add_name = ContextProcessor()
    app = Application([('/', hello_world_ctx, render_json)],
                      middlewares=[add_name])
    c = app.get_local_client()
    resp = c.get('/')
    resp_data = json.loads(resp.get_data(True))
    assert resp_data['name'] == 'world'  # does overwrite
Exemplo n.º 19
0
def test_meta_basic():
    app = Application([('/meta', MetaApplication()),
                       ('/<name?>', cookie_hello_world, render_basic)],
                      middlewares=[SignedCookieMiddleware()])
    cl = app.get_local_client()

    assert cl.get('/').status_code == 200
    assert cl.get('/meta/').status_code == 200
Exemplo n.º 20
0
def test_get_param_mw():
    get_name_mw = GetParamMiddleware(['name', 'date'])
    app = Application([('/', hello_world)], middlewares=[get_name_mw])
    c = app.get_local_client()
    resp = c.get('/')
    assert resp.data == b'Hello, world!'
    resp = c.get('/?name=Kurt')
    assert resp.data == b'Hello, Kurt!'
Exemplo n.º 21
0
def test_basic_static_route():
    static_app = Application([StaticFileRoute('/source_code',
                                              _CUR_DIR + '/test_static.py')])

    c = static_app.get_local_client()
    resp = c.get('/source_code')
    assert resp.mimetype in ('text/x-python', 'text/plain')  # text/plain on appveyor/windows for some reason
    assert resp.status_code == 200
Exemplo n.º 22
0
def test_meta_basic():
    app = Application([('/meta', MetaApplication()),
                       ('/<name?>', cookie_hello_world, render_basic)],
                      middlewares=[SignedCookieMiddleware()])
    cl = app.get_local_client()

    assert cl.get('/').status_code == 200
    assert cl.get('/meta/').status_code == 200
Exemplo n.º 23
0
def test_req_provides():
    req_provides = RequestProvidesName('Rajkumar')
    app = Application([('/', hello_world)], middlewares=[req_provides])
    c = app.get_local_client()
    resp = c.get('/')
    assert resp.data == b'Hello, Rajkumar!'
    resp = c.get('/?name=Kurt')
    assert resp.data == b'Hello, Kurt!'
Exemplo n.º 24
0
def test_basic_static_route():
    static_app = Application([StaticFileRoute('/source_code',
                                              _CUR_DIR + '/test_static.py')])

    c = static_app.get_local_client()
    resp = c.get('/source_code')
    assert resp.mimetype in ('text/x-python', 'text/plain')  # text/plain on appveyor/windows for some reason
    assert resp.status_code == 200
Exemplo n.º 25
0
def test_redirector():
    redirect_other = Redirector('/other')
    app = Application([('/', redirect_other)])
    c = app.get_local_client()
    resp = c.get('/')
    assert resp.status_code == 301
    assert resp.headers['Location'] == 'http://localhost/other'

    repr(redirect_other)
Exemplo n.º 26
0
def test_simple_ctx_proc():
    add_name_lang = SimpleContextProcessor(name='Kurt', language='en')
    app = Application([('/', hello_world_ctx, render_json)],
                      middlewares=[add_name_lang])
    c = app.get_local_client()
    resp = c.get('/')
    resp_data = json.loads(resp.get_data(True))
    assert resp_data['name'] == 'world'  # does not overwrite
    assert resp_data['language'] == 'en'
Exemplo n.º 27
0
def test_get_param_mw():
    get_name_mw = GetParamMiddleware(['name', 'date'])
    app = Application([('/', hello_world)],
                      middlewares=[get_name_mw])
    c = app.get_local_client()
    resp = c.get('/')
    assert resp.data == b'Hello, world!'
    resp = c.get('/?name=Kurt')
    assert resp.data == b'Hello, Kurt!'
Exemplo n.º 28
0
def test_req_provides():
    req_provides = RequestProvidesName('Rajkumar')
    app = Application([('/', hello_world)],
                      middlewares=[req_provides])
    c = app.get_local_client()
    resp = c.get('/')
    assert resp.data == b'Hello, Rajkumar!'
    resp = c.get('/?name=Kurt')
    assert resp.data == b'Hello, Kurt!'
Exemplo n.º 29
0
def test_broken_decorated():
    req_provides_blank = RequestProvidesName()
    app = Application([('/', hello_world_no)],
                      middlewares=[req_provides_blank])
    c = app.get_local_client()
    resp = c.get('/')
    assert resp.data == b'Hello, world!'
    resp = c.get('/?name=Kurt')
    assert resp.data != b'Hello, Kurt!'
Exemplo n.º 30
0
def test_cookie_mw():
    cookie_mw = SignedCookieMiddleware(expiry=NEVER)
    _ = repr(cookie_mw)  # coverage, lol
    app = Application([('/', cookie_hello_world, render_basic),
                       ('/<name>/', cookie_hello_world, render_basic)],
                      middlewares=[cookie_mw])
    ic = app.get_local_client()
    resp = ic.get('/')
    assert resp.status_code == 200
    assert resp.data == b'Hello, world!'
    resp = ic.get('/Kurt/')
    assert resp.data == b'Hello, Kurt!'
    resp = ic.get('/')
    assert resp.data == b'Hello, Kurt!'

    ic2 = app.get_local_client()
    resp = ic2.get('/')
    assert resp.data == b'Hello, world!'
Exemplo n.º 31
0
def test_redirector():
    redirect_other = Redirector('/other')
    app = Application([('/', redirect_other)])
    c = app.get_local_client()
    resp = c.get('/')
    assert resp.status_code == 301
    assert resp.headers['Location'] == 'http://localhost/other'

    repr(redirect_other)
Exemplo n.º 32
0
def test_cookie_expire():
    cookie_mw = SignedCookieMiddleware(expiry=0.1)
    app = Application([('/', cookie_hello_world, render_basic),
                       ('/<name>/', cookie_hello_world, render_basic)],
                      middlewares=[cookie_mw])
    ic = app.get_local_client()
    resp = ic.get('/')
    assert resp.status_code == 200
    assert resp.data == b'Hello, world!'
    resp = ic.get('/Kurt/')
    assert resp.data == b'Hello, Kurt!'
    time.sleep(0.11)
    resp = ic.get('/')
    assert resp.data == b'Hello, world!'

    ic2 = app.get_local_client()
    resp = ic2.get('/')
    assert resp.data == b'Hello, world!'
Exemplo n.º 33
0
def test_chameleon_broken_template():
    chameleon_render = ChameleonRenderFactory(_TMPL_DIR)
    tmpl = 'broken_template_1.pt'
    app = Application([('/', hello_world_ctx, tmpl)],
                      render_factory=chameleon_render)
    c = app.get_local_client()
    resp = c.get('/')
    assert resp.status_code == 500
    assert len(resp.data) > 1024  # a longish response
Exemplo n.º 34
0
def test_nondebug_server_errors():
    app = Application([('/', _raiser, render_basic)], debug=False)
    cl = app.get_local_client()
    resps = []
    resps.append(cl.get('/', headers={'Accept': 'text/plain'}))
    resps.append(cl.get('/', headers={'Accept': 'text/html'}))
    resps.append(cl.get('/', headers={'Accept': 'application/json'}))
    resps.append(cl.get('/', headers={'Accept': 'application/xml'}))

    assert all(['RuntimeError' in r.get_data(True) for r in resps])
Exemplo n.º 35
0
def test_nondebug_server_errors():
    app = Application([('/', _raiser, render_basic)], debug=False)
    cl = app.get_local_client()
    resps = []
    resps.append(cl.get('/', headers={'Accept': 'text/plain'}))
    resps.append(cl.get('/', headers={'Accept': 'text/html'}))
    resps.append(cl.get('/', headers={'Accept': 'application/json'}))
    resps.append(cl.get('/', headers={'Accept': 'application/xml'}))

    assert all(['RuntimeError' in r.get_data(True) for r in resps])
Exemplo n.º 36
0
def test_serve():
    cookie_mw = SignedCookieMiddleware()
    app = Application([('/', cookie_hello_world, render_basic),
                       ('/<name>/', cookie_hello_world, render_basic)],
                      middlewares=[cookie_mw])

    assert app.serve(_jk_just_testing=True, static_path=_CUR_DIR)
    cl = app.get_local_client()

    assert cl.get('/').status_code == 200
    assert cl.get('/static/test_serve.py').status_code == 200
Exemplo n.º 37
0
def test_reroute_wsgi():
    # simulate home page served by one app, and all else by another
    other_app = Application([('/other', lambda: 'okay', render_basic)])
    main_app = Application([('/', lambda: 'hooray', render_basic),
                            ('/<x*str>', RerouteWSGI(other_app))])
    cl = main_app.get_local_client()
    resp = cl.get('/')
    assert resp.get_data(as_text=True) == 'hooray'

    resp = cl.get('/other/')
    assert resp.get_data(as_text=True) == 'okay'
Exemplo n.º 38
0
def test_resource_redaction():
    app = Application(routes=[('/meta', MetaApplication())],
                      resources={'a_secret': 'vsecret', 'ok': 'bokay'})

    cl = app.get_local_client()
    resp = cl.get('/meta/')
    assert resp.status_code == 200

    content = resp.get_data(as_text=True)
    assert 'bokay' in content
    assert 'vsecret' not in content
Exemplo n.º 39
0
def test_broken_error_render():
    class BrokenErrorHandler(ErrorHandler):
        def render_error(self, **kwargs):
            1 / 0

    rt = Route('/<number:int>', odd_endpoint, render_basic)
    app = Application([rt], error_handler=BrokenErrorHandler())
    cl = app.get_local_client()
    err_resp = cl.get('/2')
    assert err_resp.status_code == 500
    assert b'not in my house' in err_resp.data
Exemplo n.º 40
0
def test_broken_error_render():
    class BrokenErrorHandler(ErrorHandler):
        def render_error(self, **kwargs):
            1/0

    rt = Route('/<number:int>', odd_endpoint, render_basic)
    app = Application([rt], error_handler=BrokenErrorHandler())
    cl = app.get_local_client()
    err_resp = cl.get('/2')
    assert err_resp.status_code == 500
    assert b'not in my house' in err_resp.data
Exemplo n.º 41
0
def test_nondebug_notfound_errors():
    app = Application([('/', _raiser, render_basic)], debug=True)
    cl = app.get_local_client()
    nf_url = '/nf'

    resps = []
    resps.append(cl.get(nf_url, headers={'Accept': 'text/plain'}))
    resps.append(cl.get(nf_url, headers={'Accept': 'text/html'}))
    resps.append(cl.get(nf_url, headers={'Accept': 'application/xml'}))
    resps.append(cl.get(nf_url, headers={'Accept': 'application/json'}))

    assert all(['not found' in r.get_data(True).lower() for r in resps])
Exemplo n.º 42
0
def test_create_route_order_incr():
    "tests route order when routes are added incrementally"
    routes = [('/api/<api_path+>', api, render_basic),
              ('/<one>/<two>', two_segments, render_basic),
              ('/<one>/<two>/<three>', three_segments, render_basic)]
    app = Application()
    client = app.get_local_client()
    for r in routes:
        app.add(r)
        assert client.get('/api/a').data == b'api: a'
        assert client.get('/api/a/b/').data == b'api: a/b'
    return
Exemplo n.º 43
0
def test_nondebug_notfound_errors():
    app = Application([('/', _raiser, render_basic)], debug=True)
    cl = app.get_local_client()
    nf_url = '/nf'

    resps = []
    resps.append(cl.get(nf_url, headers={'Accept': 'text/plain'}))
    resps.append(cl.get(nf_url, headers={'Accept': 'text/html'}))
    resps.append(cl.get(nf_url, headers={'Accept': 'application/xml'}))
    resps.append(cl.get(nf_url, headers={'Accept': 'application/json'}))

    assert all(['not found' in r.get_data(True).lower() for r in resps])
Exemplo n.º 44
0
def test_create_route_order_incr():
    "tests route order when routes are added incrementally"
    routes = [('/api/<api_path+>', api, render_basic),
              ('/<one>/<two>', two_segments, render_basic),
              ('/<one>/<two>/<three>', three_segments, render_basic)]
    app = Application()
    client = app.get_local_client()
    for r in routes:
        app.add(r)
        assert client.get('/api/a/b').data == b'api: a/b'
        assert app.routes[-1].get_info()['url_pattern'] == r[0]
    return
Exemplo n.º 45
0
def test_profile_mw():
    from clastic.middleware import profile

    app = Application([('/<name?>', hello_world)], middlewares=[profile.SimpleProfileMiddleware()])
    cl = app.get_local_client()
    resp = cl.get('/')
    assert resp.status_code == 200

    resp = cl.get('/?_prof=true')
    assert resp.status_code == 200
    resp_data = resp.get_data(True)
    assert 'function calls in 0.00' in resp_data  # e.g., 46 function calls in 0.000 seconds but that's variable/flaky
Exemplo n.º 46
0
def test_gzip_mw():
    from clastic.middleware import compress

    app = Application([('/<name>', hello_world)], middlewares=[compress.GzipMiddleware()])
    cl = app.get_local_client()
    resp = cl.get('/' + 'a' * 2000)
    assert resp.status_code == 200
    assert len(resp.get_data()) > 2000

    resp = cl.get('/' + 'a' * 2000, headers={'Accept-Encoding': 'gzip'})
    assert resp.status_code == 200
    assert len(resp.get_data()) < 200
Exemplo n.º 47
0
def test_gzip_mw():
    from clastic.middleware import compress

    app = Application([('/<name>', hello_world)],
                      middlewares=[compress.GzipMiddleware()])
    cl = app.get_local_client()
    resp = cl.get('/' + 'a' * 2000)
    assert resp.status_code == 200
    assert len(resp.get_data()) > 2000

    resp = cl.get('/' + 'a' * 2000, headers={'Accept-Encoding': 'gzip'})
    assert resp.status_code == 200
    assert len(resp.get_data()) < 200
Exemplo n.º 48
0
def test_profile_mw():
    from clastic.middleware import profile

    app = Application([('/<name?>', hello_world)],
                      middlewares=[profile.SimpleProfileMiddleware()])
    cl = app.get_local_client()
    resp = cl.get('/')
    assert resp.status_code == 200

    resp = cl.get('/?_prof=true')
    assert resp.status_code == 200
    resp_data = resp.get_data(True)
    assert 'function calls in 0.00' in resp_data  # e.g., 46 function calls in 0.000 seconds but that's variable/flaky
Exemplo n.º 49
0
def test_slashing_behaviors():
    routes = [('/', NO_OP),
              ('/goof/spoof/', NO_OP)]
    app_strict = Application(routes, slash_mode=S_STRICT)
    app_redirect = Application(routes, slash_mode=S_REDIRECT)
    app_rewrite = Application(routes, slash_mode=S_REWRITE)

    cl_strict = app_strict.get_local_client()
    cl_redirect = app_redirect.get_local_client()
    cl_rewrite = app_rewrite.get_local_client()

    assert cl_strict.get('/').status_code == 200
    assert cl_rewrite.get('/').status_code == 200
    assert cl_redirect.get('/').status_code == 200

    assert cl_strict.get('/goof//spoof//').status_code == 404
    assert cl_rewrite.get('/goof//spoof//').status_code == 200
    assert cl_redirect.get('/goof//spoof//').status_code == 302
    assert cl_redirect.get('/goof//spoof//', follow_redirects=True).status_code == 200

    assert cl_strict.get('/dne/dne//').status_code == 404
    assert cl_rewrite.get('/dne/dne//').status_code == 404
    assert cl_redirect.get('/dne/dne//').status_code == 404
Exemplo n.º 50
0
def test_ctx_proc_req():
    req_provides_name = RequestProvidesName()
    add_name_lang = ContextProcessor(['name'], {'language': 'en'})
    app = Application([('/', hello_world_ctx, render_json)],
                      middlewares=[req_provides_name, add_name_lang])
    c = app.get_local_client()
    resp = c.get('/')
    resp_data = json.loads(resp.get_data(True))
    assert resp_data['name'] == 'world'  # does not overwrite
    assert resp_data['language'] == 'en'

    resp = c.get('/?name=Alex')
    resp_data = json.loads(resp.get_data(True))
    assert resp_data['name'] == 'Alex'  # still does not overwrite
Exemplo n.º 51
0
def test_create_route_order_list():
    "tests route order when routes are added as a list"
    routes = [('/api/<api_path+>', api, render_basic),
              ('/<one>/<two>', two_segments, render_basic),
              ('/<one>/<two>/<three>', three_segments, render_basic)]
    app = Application(routes)
    client = app.get_local_client()
    assert client.get('/api/a').data == b'api: a'
    assert client.get('/api/a/b').data == b'api: a/b'

    for i, rt in enumerate(app.routes):
        assert rt.pattern == routes[i][0]

    return
Exemplo n.º 52
0
def test_debug_server_errors():
    app = Application([GET('/', _raiser, render_basic)], debug=True)
    cl = app.get_local_client()

    resps = []
    resps.append(cl.get('/', headers={'Accept': 'text/plain'}))
    resps.append(cl.get('/', headers={'Accept': 'text/html'}))
    json_resp = cl.get('/', headers={'Accept': 'application/json'})
    resps.append(json_resp)
    resps.append(cl.get('/', headers={'Accept': 'application/xml'}))

    assert all(['RuntimeError' in r.get_data(True) for r in resps])
    json_data = json.loads(json_resp.get_data(True))
    assert json_data['clastic_version'] == __version__
Exemplo n.º 53
0
def test_chameleon_mixed():
    chameleon_render = ChameleonRenderFactory(_TMPL_DIR)
    tmpl = 'basic_template.pt'
    app = Application([('/', hello_world_ctx, tmpl),
                       ('/json/', hello_world_ctx, render_basic)],
                      render_factory=chameleon_render)

    c = app.get_local_client()
    resp = c.get('/')
    assert resp.status_code == 200
    assert b'clasty' in resp.data

    resp = c.get('/json/')
    assert resp.status_code == 200
Exemplo n.º 54
0
def test_chameleon():
    chameleon_render = ChameleonRenderFactory(_TMPL_DIR)
    tmpl = 'basic_template.pt'
    app = Application([('/', hello_world_ctx, tmpl),
                       ('/<name>/', hello_world_ctx, tmpl),
                       ('/beta/<name>/', complex_context, tmpl)],
                      render_factory=chameleon_render)

    c = app.get_local_client()
    resp = c.get('/')
    assert resp.status_code == 200
    assert b'clasty' in resp.data

    resp = c.get('/beta/Rajkumar/')
    assert resp.status_code == 200
    assert b'clasty' in resp.data
Exemplo n.º 55
0
def test_app_error_render():

    rt = Route('/<number:int>', odd_endpoint, render_basic)
    assert rt._render_error is None

    app = Application([rt])
    # assert rt._render_error is render_error_basic

    cl = app.get_local_client()
    assert cl.get('/1').status_code == 200

    err_resp = cl.get('/2')
    assert err_resp.status_code == 500
    assert b'not in my house' in err_resp.data

    err_resp = cl.get('/non-int')
    assert err_resp.status_code == 404
Exemplo n.º 56
0
def test_jsonp_render(render_json=None):
    if render_json is None:
        render_json = JSONPRender(qp_name='callback', dev_mode=True)
    app = Application([('/', hello_world_ctx, render_json),
                       ('/<name>/', hello_world_ctx, render_json),
                       ('/beta/<name>/', complex_context, render_json)])

    c = app.get_local_client()

    resp = c.get('/?callback=test_callback')
    assert resp.status_code == 200
    assert resp.data.startswith(b'test_callback')
    assert b'world' in resp.data

    resp = c.get('/?callback=test_callback')
    assert resp.status_code == 200
    assert resp.data.startswith(b'test_callback')
    assert b'world' in resp.data
Exemplo n.º 57
0
def test_basic_static_serve():
    static_app = StaticApplication(_CUR_DIR)
    app = Application([('/static/', static_app)])

    c = app.get_local_client()
    resp = c.get('/static/test_static.py')
    assert resp.mimetype in ('text/x-python', 'text/plain')  # text/plain on appveyor/windows for some reason
    resp = c.get('/static/does_not_exist.txt')
    assert resp.status_code == 404
    resp = c.get('/static/../core.py')
    assert resp.status_code == 403
    resp = c.get('/static/_ashes_tmpls/basic_template.html')
    assert resp.status_code == 200
    resp = c.get('/static/_ashes_tmpls/../../core.py')
    assert resp.status_code == 403

    # check that we don't navigate to root
    resp = c.get('/static//etc/hosts')
    if os.path.exists('/etc/hosts'):
        assert resp.status_code == 403
    else:
        assert resp.status_code == 404  # mostly windows
Exemplo n.º 58
0
def test_render_raises():
    render_raises_mw = RenderRaisesMiddleware()
    app = Application([('/', hello_world_ctx)],
                      middlewares=[render_raises_mw])
    resp = app.get_local_client().get('/')
    assert resp.status_code == 500