예제 #1
0
def test_iterating_response():
    obj = {'hi': 'people'}
    secondobj = {'bye': 'friends'}
    wsgiapp = RegistryUsingIteratorApp(regobj, obj)
    wsgiapp = RegistryManager(wsgiapp)
    wsgiapp = RegistryMiddleMan(wsgiapp, regobj, secondobj, 0)
    wsgiapp = RegistryManager(wsgiapp)
    app = TestApp(wsgiapp)
    res = app.get('/')
    assert 'Hello world' in res
    assert 'The variable is' in res
    assert "{'hi': 'people'}" in res
    assert "InsertValue at depth 0 is {'bye': 'friends'}" in res
    assert "AppendValue at depth 0 is {'bye': 'friends'}" in res
예제 #2
0
def make_app(controller_klass=None, environ=None, config_options=None, with_errors=False):
    """Creates a `TestApp` instance."""
    if controller_klass is None:
        controller_klass = TGController

    tg.config['renderers'] = default_config['renderers']
    tg.config['rendering_engines_options'] = default_config['rendering_engines_options']

    config = default_config.copy()
    config['application_wrappers'] = [
        I18NApplicationWrapper,
        IdentityApplicationWrapper,
        CacheApplicationWrapper,
        SessionApplicationWrapper
    ]

    if with_errors:
        config['errorpage.enabled'] = True
        config['errorpage.status_codes'] = [403, 404]
        config['application_wrappers'].append(ErrorPageApplicationWrapper)

    config['session.enabled'] = True
    config['session.data_dir'] = session_dir
    config['cache.enabled'] = True
    config['cache.cache_dir'] = cache_dir

    if config_options is not None:
        config.update(config_options)

    app = TGApp(config=config)
    app.controller_classes['root'] = ControllerWrap(controller_klass)

    app = FakeRoutes(app)
    app = RegistryManager(app)
    return TestApp(app)
예제 #3
0
파일: test_authz.py 프로젝트: wukele/tg2
def make_app(controller_klass, environ={}, with_errors=False):
    """Creates a ``TestApp`` instance."""
    # The basic middleware:
    app = TGApp(config=default_config)
    app.controller_classes['root'] = ControllerWrap(controller_klass)

    app = FakeRoutes(app)
    
    if with_errors:
        app = ErrorHandler(app, {}, debug=False)
        app = StatusCodeRedirect(app, [403, 404, 500])
    app = RegistryManager(app)
    app = SessionMiddleware(app, {}, data_dir=session_dir)
    app = CacheMiddleware(app, {}, data_dir=os.path.join(data_dir, 'cache'))

    # Setting repoze.who up:
    from repoze.who.plugins.auth_tkt import AuthTktCookiePlugin
    cookie = AuthTktCookiePlugin('secret', 'authtkt')
    identifiers = [('cookie', cookie)]

    app = setup_auth(app, TGAuthMetadata(),
                     identifiers=identifiers, skip_authentication=True,
                     authenticators=[], challengers=[])

    return TestApp(app)
예제 #4
0
def test_solo_registry():
    obj = {'hi': 'people'}
    wsgiapp = RegistryUsingApp(regobj, obj)
    wsgiapp = RegistryManager(wsgiapp)
    app = TestApp(wsgiapp)
    res = app.get('/')
    assert 'Hello world' in res
    assert 'The variable is' in res
    assert "{'hi': 'people'}" in res
예제 #5
0
def test_really_deep_registry():
    keylist = [
        'fred', 'wilma', 'barney', 'homer', 'marge', 'bart', 'lisa', 'maggie'
    ]
    valuelist = range(0, len(keylist))
    obj = {'hi': 'people'}
    wsgiapp = RegistryUsingApp(regobj, obj)
    wsgiapp = RegistryManager(wsgiapp)
    for depth in valuelist:
        newobj = {keylist[depth]: depth}
        wsgiapp = RegistryMiddleMan(wsgiapp, regobj, newobj, depth)
        wsgiapp = RegistryManager(wsgiapp)
    app = TestApp(wsgiapp)
    res = app.get('/')
    assert 'Hello world' in res
    assert 'The variable is' in res
    assert "{'hi': 'people'}" in res
    for depth in valuelist:
        assert "InsertValue at depth %s is {'%s': %s}" %\
               (depth, keylist[depth], depth) in res
    for depth in valuelist:
        assert "AppendValue at depth %s is {'%s': %s}" %\
               (depth, keylist[depth], depth) in res
예제 #6
0
def test_registry_preserved_when_forcefuly_preserved():
    def app(environ, start_response):
        environ['paste.registry'].register(regobj, {'hi': 'people'})
        environ['paste.registry'].preserve(force=True)
        return ['HI']

    app_with_rm = RegistryManager(app,
                                  streaming=False,
                                  preserve_exceptions=False)
    environ = {}

    app_with_rm(environ, None)

    # check the object are preserved as force=True was used
    assert regobj._object_stack()
예제 #7
0
def test_registry_not_preserved_when_disabled():
    def app(environ, start_response):
        environ['paste.registry'].register(regobj, {'hi': 'people'})
        environ['paste.registry'].preserve()
        return ['HI']

    app_with_rm = RegistryManager(app,
                                  streaming=False,
                                  preserve_exceptions=False)
    environ = {}

    app_with_rm(environ, None)

    # check the object are not preserved as preserve_exceptions is False
    assert not regobj._object_stack()
예제 #8
0
def make_app(controller_klass=None, environ=None):
    """Creates a `TestApp` instance."""
    if controller_klass is None:
        controller_klass = TGController

    tg.config['renderers'] = default_config['renderers']
    app = TGApp(config=default_config)
    app.controller_classes['root'] = ControllerWrap(controller_klass)

    app = FakeRoutes(app)

    app = RegistryManager(app)
    app = beaker.middleware.SessionMiddleware(app, {}, data_dir=session_dir)
    app = CacheMiddleware(app, {}, data_dir=os.path.join(data_dir, 'cache'))
    return TestApp(app)
예제 #9
0
def test_registry_streaming():
    def app(environ, start_response):
        environ['paste.registry'].register(regobj, {'hi': 'people'})
        for i in range(10):
            yield str(i)

    rm = RegistryManager(app, streaming=True)

    environ = {}

    res = []
    for x in rm(environ, None):
        res.append(int(x))
        assert len(regobj._object_stack())

    assert len(res) == 10
    assert not (regobj._object_stack())
예제 #10
0
def test_registry_streaming_exception():
    def app(environ, start_response):
        environ['paste.registry'].register(regobj, {'hi': 'people'})
        for i in range(10):
            if i == 5:
                raise SystemError('Woah!')
            else:
                yield str(i)

    rm = RegistryManager(app, streaming=True, preserve_exceptions=True)
    environ = {}
    try:
        for x in rm(environ, None):
            assert len(regobj._object_stack())
    except:
        #check the object got preserved due to exception
        assert regobj._object_stack()
        regobj._pop_object()
        raise
예제 #11
0
def test_stacked_object_twice():
    d = {'hi': 'people'}

    def app(environ, start_response):
        environ['paste.registry'].register(regobj, d)
        environ['paste.registry'].register(regobj, d)
        for i in range(3):
            yield str(i)

    rm = RegistryManager(app, streaming=True)

    environ = {}
    resp = rm(environ, None)
    for idx, x in enumerate(resp, 1):
        objproxy = list(environ['paste.registry'].reglist[-1].values())[0][0]
        if idx == 1:
            objproxy._pop_object()
        elif idx == 2:
            # Trying to pop again should fail,
            # because as we pushed twice the same object
            # there is actually only on on the stack
            try:
                objproxy._pop_object()
            except AssertionError as e:
                assert str(
                    e) == 'No object has been registered for this thread'
            else:
                assert False, 'Should have failed'

            # Won't proceed further, as exhausting the iterator
            # will lead to a crash due to cleanup of the registry.
            break

    assert idx == 2

    try:
        next(resp)
    except:
        # Looping again will crash because we already popped
        # The registered object and cleanup will fail.
        pass
예제 #12
0
파일: middleware.py 프로젝트: 00mjk/allura
def _make_core_app(root, global_conf, full_stack=True, **app_conf):
    """
    Set allura up with the settings found in the PasteDeploy configuration
    file used.

    :param root: The controller module containing the TG root
    :param global_conf: The global settings for allura (those
        defined under the ``[DEFAULT]`` section).
    :type global_conf: dict
    :param full_stack: Should the whole TG2 stack be set up?
    :type full_stack: str or bool
    :return: The allura application with all the relevant middleware
        loaded.

    This is the PasteDeploy factory for the allura application.

    ``app_conf`` contains all the application-specific settings (those defined
    under ``[app:main]``.


    """
    # Run all the initialization code here
    mimetypes.init([pkg_resources.resource_filename('allura', 'etc/mime.types')] + mimetypes.knownfiles)

    # Configure MongoDB
    ming.configure(**app_conf)

    # Configure ActivityStream
    if asbool(app_conf.get('activitystream.recording.enabled', False)):
        activitystream.configure(**h.convert_bools(app_conf, prefix='activitystream.'))

    # Configure EW variable provider
    ew.render.TemplateEngine.register_variable_provider(get_tg_vars)

    # Set FormEncode language to english, as we don't support any other locales
    formencode.api.set_stdtranslation(domain='FormEncode', languages=['en'])

    # Create base app
    base_config = ForgeConfig(root)
    load_environment = base_config.make_load_environment()

    # Code adapted from tg.configuration, replacing the following lines:
    #     make_base_app = base_config.setup_tg_wsgi_app(load_environment)
    #     app = make_base_app(global_conf, full_stack=True, **app_conf)

    # Configure the TG environment
    load_environment(global_conf, app_conf)

    app = tg.TGApp()

    for mw_ep in h.iter_entry_points('allura.middleware'):
        Middleware = mw_ep.load()
        if getattr(Middleware, 'when', 'inner') == 'inner':
            app = Middleware(app, config)

    # Required for sessions
    app = SessionMiddleware(app, config, data_serializer=BeakerPickleSerializerWithLatin1())
    # Handle "Remember me" functionality
    app = RememberLoginMiddleware(app, config)
    # Redirect 401 to the login page
    app = LoginRedirectMiddleware(app)
    # Add instrumentation
    app = AlluraTimerMiddleware(app, app_conf)
    # Clear cookies when the CSRF field isn't posted
    if not app_conf.get('disable_csrf_protection'):
        app = CSRFMiddleware(app, '_session_id')
    if asbool(config.get('cors.enabled', False)):
        # Handle CORS requests
        allowed_methods = aslist(config.get('cors.methods'))
        allowed_headers = aslist(config.get('cors.headers'))
        cache_duration = asint(config.get('cors.cache_duration', 0))
        app = CORSMiddleware(app, allowed_methods, allowed_headers, cache_duration)
    # Setup the allura SOPs
    app = allura_globals_middleware(app)
    # Ensure http and https used per config
    if config.get('override_root') != 'task':
        app = SSLMiddleware(app, app_conf.get('no_redirect.pattern'),
                            app_conf.get('force_ssl.pattern'),
                            app_conf.get('force_ssl.logged_in'))
    # Setup resource manager, widget context SOP
    app = ew.WidgetMiddleware(
        app,
        compress=True,
        use_cache=not asbool(global_conf['debug']),
        script_name=app_conf.get('ew.script_name', '/_ew_resources/'),
        url_base=app_conf.get('ew.url_base', '/_ew_resources/'),
        extra_headers=ast.literal_eval(app_conf.get('ew.extra_headers', '[]')),
        cache_max_age=asint(app_conf.get('ew.cache_header_seconds', 60*60*24*365)),

        # settings to pass through to jinja Environment for EW core widgets
        # these are for the easywidgets' own [easy_widgets.engines] entry point
        # (the Allura [easy_widgets.engines] entry point is named "jinja" (not jinja2) but it doesn't need
        #  any settings since it is a class that uses the same jinja env as the rest of allura)
        **{
            'jinja2.auto_reload': asbool(config['auto_reload_templates']),
            'jinja2.bytecode_cache': AlluraJinjaRenderer._setup_bytecode_cache(),
            'jinja2.cache_size': asint(config.get('jinja_cache_size', -1)),
        }
    )
    # Handle static files (by tool)
    app = StaticFilesMiddleware(app, app_conf.get('static.script_name'))
    # Handle setup and flushing of Ming ORM sessions
    app = MingMiddleware(app)
    # Set up the registry for stacked object proxies (SOPs).
    #    streaming=true ensures they won't be cleaned up till
    #    the WSGI application's iterator is exhausted
    app = RegistryManager(app, streaming=True)

    # "task" wsgi would get a 2nd request to /error/document if we used this middleware
    if config.get('override_root') not in ('task', 'basetest_project_root'):
        if asbool(config['debug']):
            # Converts exceptions to HTTP errors, shows traceback in debug mode
            # don't use TG footer with extra CSS & images that take time to load
            tg.error.footer_html = '<!-- %s %s -->'
            app = tg.error.ErrorHandler(app, global_conf, **config['tg.errorware'])
        else:
            app = ErrorMiddleware(app, config, **config['tg.errorware'])

        app = SetRequestHostFromConfig(app, config)

        # Redirect some status codes to /error/document
        if asbool(config['debug']):
            app = StatusCodeRedirect(app, base_config.handle_status_codes)
        else:
            app = StatusCodeRedirect(
                app, base_config.handle_status_codes + [500])

    for mw_ep in h.iter_entry_points('allura.middleware'):
        Middleware = mw_ep.load()
        if getattr(Middleware, 'when', 'inner') == 'outer':
            app = Middleware(app, config)

    return app