Esempio n. 1
0
    def test_disconnect_hooks_multiple_listener(self):
        hook1_has_been_called = []
        def hook1_listener():
            hook1_has_been_called.append(True)

        hook2_has_been_called = []
        def hook2_listener():
            hook2_has_been_called.append(True)

        class RootController(TGController):
            @expose()
            def test(self):
                tg.hooks.notify('custom_hook', controller=RootController.test)
                return 'HI!'

        conf = AppConfig(minimal=True, root_controller=RootController())
        tg.hooks.register('custom_hook', hook1_listener)
        tg.hooks.register('custom_hook', hook2_listener)
        conf.package = PackageWithModel()
        app = conf.make_wsgi_app()
        app = TestApp(app)

        app.get('/test')
        app.get('/test')
        tg.hooks.disconnect('custom_hook', hook2_listener)
        app.get('/test')

        # Disconnecting an unregistered hook should do nothing.
        tg.hooks.disconnect('unregistered', hook1_listener)

        assert len(hook1_has_been_called) == 3, hook1_has_been_called
        assert len(hook2_has_been_called) == 2, hook2_has_been_called
Esempio n. 2
0
def make_app(controller_klass=None, environ=None, config_options=None, with_errors=False,
             make_app=True):
    """Creates a `TestApp` instance."""
    if controller_klass is None:
        controller_klass = TGController

    conf = AppConfig(root_controller=ControllerWrap(controller_klass),
                     **default_config)

    # Just let exceptions crash.
    conf['trace_errors.enable'] = False

    if with_errors:
        conf['errorpage.enabled'] = True
        conf['errorpage.status_codes'] = [403, 404]
    else:
        conf['errorpage.enabled'] = False

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

    if config_options is not None:
        for k, v in config_options.items():
            conf[k] = v

    if make_app:
        return TestApp(conf.make_wsgi_app())
    else:
        return conf
Esempio n. 3
0
def configure_app():
    app_cfg = AppConfig(minimal=True)
    app_cfg.renderers = ['genshi']
    app_cfg.default_renderer = 'genshi'
    app_cfg.use_dotted_templatenames = True
    app_cfg.package = FakeAppPackage()
    app_cfg.use_toscawidgets2 = True
    app_cfg['tw2.enabled'] = True
    app_cfg.sa_auth.authmetadata = TestAuthMetadata()
    app_cfg['beaker.session.secret'] = 'SECRET'
    app_cfg.auth_backend = 'sqlalchemy'
    app_cfg.sa_auth.cookie_secret = 'SECRET'
    app_cfg.package.model = FakeSQLAModel()
    app_cfg.use_sqlalchemy = True
    app_cfg['sqlalchemy.url'] = 'sqlite://'
    app_cfg.use_transaction_manager = True
    app_cfg['tm.enabled'] = True
    app_cfg.model = app_cfg.package.model
    app_cfg.DBSession = app_cfg.package.model.DBSession

    plug(app_cfg,
         'calendarevents',
         event_types=[FakeEventType()],
         global_models=False,
         plug_bootstrap=False,
         form_instance=calendar_form)

    # This is to reset @cached_properties so they get reconfigured for new backend

    return app_cfg
Esempio n. 4
0
    def test_config_hooks_through_app_config(self):
        class RootController(TGController):
            @expose()
            def test(self):
                return 'HI!'

        visited_hooks = []
        def before_config_hook(app):
            visited_hooks.append('before_config')
            return app
        def after_config_hook(app):
            visited_hooks.append('after_config')
            return app
        def configure_new_app_hook(app):
            assert isinstance(app, TGApp)
            visited_hooks.append('configure_new_app')

        conf = AppConfig(minimal=True, root_controller=RootController())
        conf.register_hook('before_config', before_config_hook)
        conf.register_hook('after_config', after_config_hook)
        conf.register_hook('configure_new_app', configure_new_app_hook)
        app = conf.make_wsgi_app()
        app = TestApp(app)

        assert 'HI!' in app.get('/test')
        assert 'before_config' in visited_hooks
        assert 'after_config' in visited_hooks
        assert 'configure_new_app' in visited_hooks
Esempio n. 5
0
    def test_test_context_broken_app(self):
        from webtest import TestApp
        from tg import AppConfig, config
        from tg.request_local import context

        app = TestApp(
            AppConfig(minimal=True, root_controller=None).make_wsgi_app())

        try:
            with test_context(app):
                raise RuntimeError('This is an error')
        except RuntimeError:
            pass
        else:
            assert False, 'Should have raised RuntimeError...'

        with test_context(app):
            config._pop_object()
        # Check that context got cleaned up even though config caused an exception
        assert not context._object_stack()

        with test_context(app):
            context._pop_object()
        # Check that config got cleaned up even though context caused an exception
        assert not config._object_stack()
Esempio n. 6
0
    def test_startup_hook_with_exception(self):
        def func():
            raise Exception

        tg.hooks.register('startup', func)
        conf = AppConfig(minimal=True)
        app = conf.make_wsgi_app()
Esempio n. 7
0
def test_render_default():
    conf = AppConfig(minimal=True)
    conf.default_renderer = 'json'
    app = conf.make_wsgi_app()

    res = tg.render_template({'value': 'value'})
    assert 'value": "value' in res
Esempio n. 8
0
 def setup(self):
     conf = AppConfig(minimal=True)
     conf.use_dotted_templatenames = True
     conf.renderers.append('mako')
     conf.package = FakePackage()
     self.conf = conf
     self.app = conf.make_wsgi_app()
Esempio n. 9
0
    def test_dedicated_controller_wrapper_after_milestone_reached(self):
        conf = AppConfig(minimal=True)

        def f():
            pass

        milestones.environment_loaded.reach()
        conf.register_controller_wrapper(None, controller=f)
Esempio n. 10
0
 def setup(self):
     conf = AppConfig(minimal=True)
     conf.use_dotted_templatenames = True
     conf.renderers.append('kajiki')
     conf.package = FakePackage()
     self.conf = conf
     self.app = TestApp(conf.make_wsgi_app())
     self.render = tg.config['render_functions']['kajiki']
Esempio n. 11
0
    def setup(self):
        class RootController(TGController):
            @expose()
            def test(self):
                return str(bool(EqualsTwo()))

        conf = AppConfig(minimal=True, root_controller=RootController())
        app = conf.make_wsgi_app()
        self.app = TestApp(app)
Esempio n. 12
0
    def test_startup_hook(self):
        executed = []
        def func():
            executed.append(True)

        tg.hooks.register('startup', func)
        conf = AppConfig(minimal=True)
        app = conf.make_wsgi_app()
        assert True in executed, executed
Esempio n. 13
0
 def setup(self):
     conf = AppConfig(minimal=True, root_controller=i18nRootController())
     conf['paths']['root'] = 'tests'
     conf['i18n.enabled'] = True
     conf['session.enabled'] = True
     conf['i18n.lang'] = 'kr'
     conf['beaker.session.key'] = 'tg_test_session'
     conf['beaker.session.secret'] = 'this-is-some-secret'
     conf.renderers = ['json']
     conf.default_renderer = 'json'
     conf.package = _FakePackage()
     app = conf.make_wsgi_app()
     self.app = TestApp(app)
Esempio n. 14
0
def configure_app(using, create_form=True):
    # Simulate starting configuration process from scratch
    milestones._reset_all()

    app_cfg = AppConfig(minimal=True)
    app_cfg.renderers = ['kajiki']
    app_cfg.default_renderer = 'kajiki'
    app_cfg.use_dotted_templatenames = True
    app_cfg.package = FakeAppPackage()
    app_cfg.use_toscawidgets2 = True
    app_cfg['tw2.enabled'] = True
    app_cfg.sa_auth.authmetadata = TestAuthMetadata()
    app_cfg['beaker.session.secret'] = app_cfg['session.secret'] = 'SECRET'
    app_cfg['mail.debugmailer'] = 'dummy'

    if using == 'sqlalchemy':
        app_cfg.auth_backend = 'sqlalchemy'
        app_cfg.package.model = FakeSQLAModel()
        app_cfg.use_sqlalchemy = True
        app_cfg['sqlalchemy.url'] = 'sqlite://'
        app_cfg.use_transaction_manager = True
        app_cfg['tm.enabled'] = True
    elif using == 'ming':
        app_cfg.auth_backend = 'ming'
        app_cfg.package.model = FakeMingModel()
        app_cfg.use_ming = True
        app_cfg['ming.url'] = 'mim:///testresetpassword'
    else:
        raise ValueError('Unsupported backend')

    # Reset the Sprox provider on every change of configuration.
    from resetpassword import model as resetpassword_model
    resetpassword_model.provider._provider = None

    app_cfg.model = app_cfg.package.model
    app_cfg.DBSession = app_cfg.package.model.DBSession

    # CUSTOM resetpassword options
    app_cfg['resetpassword.email_sender'] = '*****@*****.**'

    plug(app_cfg, 'tgext.mailer', plug_bootstrap=True, debugmailer='dummy')
    plug(
        app_cfg,
        'resetpassword',
        plug_bootstrap=False,
        reset_password_form_instance=resetpassword_form
        if create_form else None,
        new_password_form_instance=newpassword_form if create_form else None,
    )

    return app_cfg
Esempio n. 15
0
def test_jinja_lookup_nonexisting_template():
    conf = AppConfig(minimal=True)
    conf.use_dotted_templatenames = True
    conf.renderers.append('jinja')
    conf.package = FakePackage()
    app = conf.make_wsgi_app()

    from jinja2 import TemplateNotFound
    try:
        render_jinja = tg.config['render_functions']['jinja']
        render_jinja('tg.this_template_does_not_exists',
                     {'app_globals': tg.config['tg.app_globals']})
        assert False
    except TemplateNotFound:
        pass
Esempio n. 16
0
def run_api():
    global userconfig
    try:
        port = userconfig['Web']['apiport']
    except KeyError:
        port = '9380'
    global httpd
    config = AppConfig(minimal=True, root_controller=APIRootController())
    config['helpers'] = webhelpers2
    config.renderers = ['kajiki']
    config.serve_static = False
    application = config.make_wsgi_app()

    print("Serving APIs on port " + port + "...")
    httpd = make_server('', int(port), application, 3)
    httpd.serve_forever()
Esempio n. 17
0
def configure_app(using):
    # Simulate starting configuration process from scratch
    milestones._reset_all()

    app_cfg = AppConfig(minimal=True)
    app_cfg.renderers = ['kajiki']
    app_cfg.default_renderer = 'kajiki'
    app_cfg.use_dotted_templatenames = True
    app_cfg.package = FakeAppPackage()
    app_cfg.use_toscawidgets2 = True
    app_cfg['tw2.enabled'] = True
    app_cfg.sa_auth.authmetadata = TestAuthMetadata()
    app_cfg['beaker.session.secret'] = app_cfg['session.secret'] = 'SECRET'
    app_cfg.auth_backend = 'ming'
    app_cfg['mail.debugmailer'] = "dummy"

    if using == 'sqlalchemy':
        app_cfg.package.model = FakeSQLAModel()
        app_cfg.use_sqlalchemy = True
        app_cfg['sqlalchemy.url'] = 'sqlite://'
        app_cfg.use_transaction_manager = True
        app_cfg['tm.enabled'] = True
        app_cfg.SQLASession = app_cfg.package.model.DBSession
    elif using == 'ming':
        app_cfg.package.model = FakeMingModel()
        app_cfg.use_ming = True
        app_cfg['ming.url'] = 'mim:///mailtemapltes'
        app_cfg.MingSession = app_cfg.package.model.DBSession
    else:
        raise ValueError('Unsupported backend')

    app_cfg.model = app_cfg.package.model
    app_cfg.DBSession = app_cfg.package.model.DBSession

    # Guarantee that the same form is used between multiple
    # configurations of TGApps. Otherwise the validated
    # form would be different from the displayed one.

    plug(app_cfg, 'tgext.mailer', plug_bootstrap=True, debugmailer='dummy')
    plug(app_cfg,
         'tgext.asyncjob',
         plug_bootstrap=True,
         app_globals=app_cfg['app_globals'])
    # it is important that tgext.mailer and tgext.asyncjob are plugged
    # before mailtemplates or not plugged at all as mailtemplates plugs them
    plug(app_cfg, 'mailtemplates', plug_bootstrap=True, default_language='EN')
    return app_cfg
Esempio n. 18
0
def testWebServer():
    print("Hosting server")

    config = AppConfig(minimal=True, root_controller=RootController())

    application = config.make_wsgi_app()

    httpd = make_server('', 62433, application)

    thr = threading.Thread(target=httpd.serve_forever)
    thr.start()

    print("Running test")
    page = request.urlopen('http://127.0.0.1:62433/')
    if page.read().decode() != "Hello World":
        raise RuntimeError("Server did not correctly host 'Hello World' page.")
    httpd.shutdown()
Esempio n. 19
0
def run():
    global userconfig
    try:
        port = userconfig['Web']['porttoserve']
    except AttributeError:
        port = '9375'
    global httpd
    config = AppConfig(minimal=True, root_controller=RootController())
    config['helpers'] = webhelpers2
    config.renderers = ['kajiki']
    config.serve_static = True
    config.paths['static_files'] = 'web/public'
    application = config.make_wsgi_app()

    print("Serving on port " + port + "...")
    httpd = make_server('', int(port), application, 3)
    httpd.serve_forever()
Esempio n. 20
0
def configure_app(using):
    # Simulate starting configuration process from scratch
    milestones._reset_all()

    app_cfg = AppConfig(minimal=True)
    app_cfg.renderers = ['kajiki']
    app_cfg.default_renderer = 'kajiki'
    app_cfg.use_dotted_templatenames = True
    app_cfg.package = FakeAppPackage()
    app_cfg.use_toscawidgets2 = True
    app_cfg.sa_auth.authmetadata = TestAuthMetadata()
    app_cfg['beaker.session.secret'] = app_cfg['session.secret'] = 'SECRET'
    app_cfg.auth_backend = 'ming'
    app_cfg['mail.debugmailer'] = 'dummy'

    if using == 'sqlalchemy':
        app_cfg.package.model = FakeSQLAModel()
        app_cfg.use_sqlalchemy = True
        app_cfg['sqlalchemy.url'] = 'sqlite://'
        app_cfg.use_transaction_manager = True
    elif using == 'ming':
        app_cfg.package.model = FakeMingModel()
        app_cfg.use_ming = True
        app_cfg['ming.url'] = 'mim:///testregistration'
    else:
        raise ValueError('Unsupported backend')

    app_cfg.model = app_cfg.package.model
    app_cfg.DBSession = app_cfg.package.model.DBSession

    # CUSTOM registration options
    app_cfg['registration.email_sender'] = '*****@*****.**'

    from registration.lib import send_email, get_form

    # Guarantee that the same form is used between multiple
    # configurations of TGApps. Otherwise the validated
    # form would be different from the displayed one.
    plug_args = {}
    if '_pluggable_registration_config' in config:
        plug_args['form_instance'] = get_form()

    plug(app_cfg, 'tgext.mailer', plug_bootstrap=True, debugmailer='dummy')
    plug(app_cfg, 'registration', plug_bootstrap=False, **plug_args)
    return app_cfg
Esempio n. 21
0
    def setUp(self):
        self.root_controller = self.controller_factory()
        conf = AppConfig(minimal=True, root_controller=self.root_controller)
        conf.package = FakePackage()
        conf.model = conf.package.model
        conf.use_dotted_templatenames = True
        conf.renderers = ['json', 'jinja', 'mako']
        conf.default_renderer = 'jinja'
        conf.use_sqlalchemy = True
        conf.paths = {'controllers': 'tests', 'templates': ['tests']}
        conf.disable_request_extensions = False
        conf.prefer_toscawidgets2 = True
        conf.use_transaction_manager = True
        conf['sqlalchemy.url'] = 'sqlite:///:memory:'

        self.app = TestApp(conf.make_wsgi_app())

        metadata.create_all()
Esempio n. 22
0
def start_server():
    """ start webserver """

    catalog_engine = create_engine(SQLITE_DATA_TARGET)
    login_engine = create_engine(LOGIN_DATA_TARGET)
    config = AppConfig(minimal=True,
                       root_controller=RootController(catalog_engine,
                                                      login_engine))
    config.sa_auth.charset = 'utf-8'
    config.renderers = ['kajiki']
    config.default_renderer = 'kajiki'
    config.serve_static = True
    config.paths['static_files'] = 'public'
    config.paths['controllers'] = 'controllers'

    application = config.make_wsgi_app()
    print "Serving on port 8080..."
    httpd = make_server('', 8080, application)
    httpd.serve_forever()
Esempio n. 23
0
def configure_app(using):
    # Simulate starting configuration process from scratch
    milestones._reset_all()

    app_cfg = AppConfig(minimal=True)
    app_cfg.renderers = ['kajiki']
    app_cfg.default_renderer = 'kajiki'
    app_cfg.use_dotted_templatenames = True
    app_cfg.package = FakeAppPackage()
    app_cfg.use_toscawidgets2 = True
    app_cfg['beaker.session.secret'] = app_cfg['session.secret'] = 'SECRET'
    app_cfg['mail.debugmailer'] = "dummy"

    if using == 'sqlalchemy':
        app_cfg.auth_backend = 'sqlalchemy'
        app_cfg.package.model = FakeSQLAModel()
        app_cfg.use_sqlalchemy = True
        app_cfg['sqlalchemy.url'] = 'sqlite://'
        app_cfg.use_transaction_manager = True
        app_cfg.SQLASession = app_cfg.package.model.DBSession
    elif using == 'ming':
        app_cfg.auth_backend = 'ming'
        app_cfg.package.model = FakeMingModel()
        app_cfg.use_ming = True
        app_cfg['ming.url'] = 'mim:///userprofile'
        app_cfg.MingSession = app_cfg.package.model.DBSession
    else:
        raise ValueError('Unsupported backend')

    app_cfg.model = app_cfg.package.model
    app_cfg.DBSession = app_cfg.package.model.DBSession
    app_cfg.sa_auth.authmetadata = TestAuthMetadata()

    # Guarantee that the same form is used between multiple
    # configurations of TGApps. Otherwise the validated
    # form would be different from the displayed one.

    app_cfg['userprofile.email_sender'] = '[email protected]'

    plug(app_cfg, 'userprofile', plug_bootstrap=True)
    return app_cfg
Esempio n. 24
0
    def test_controller_hooks_with_value(self):
        # Reset milestone so that registered hooks
        milestones._reset_all()

        class RootController(TGController):
            @expose()
            def test(self):
                return tg.hooks.notify_with_value('test_hook', 'BO',
                                                  controller=RootController.test)

        def value_hook(value):
            return value*2

        tg.hooks.register('test_hook', value_hook, controller=RootController.test)

        conf = AppConfig(minimal=True, root_controller=RootController())
        app = conf.make_wsgi_app()
        app = TestApp(app)

        resp = app.get('/test')
        assert 'BOBO' in resp, resp
Esempio n. 25
0
    def test_disconnect_hooks(self):
        hook1_has_been_called = []
        def hook1_listener():
            hook1_has_been_called.append(True)

        class RootController(TGController):
            @expose()
            def test(self):
                tg.hooks.notify('custom_hook')
                return 'HI!'

        conf = AppConfig(minimal=True, root_controller=RootController())
        tg.hooks.register('custom_hook', hook1_listener)
        conf.package = PackageWithModel()
        app = conf.make_wsgi_app()
        app = TestApp(app)

        app.get('/test')
        app.get('/test')
        tg.hooks.disconnect('custom_hook', hook1_listener)
        app.get('/test')

        assert len(hook1_has_been_called) == 2, hook1_has_been_called
Esempio n. 26
0
        output += "  Imagem:<br>"
        #output+="  <input type=\"text\" name=\"imagem\"><br>"
        output += "  <input type=\"file\" name=\"file1\"><br>"
        output += "  <input type=\"submit\" value=\"Submit\">"
        output += " </form> "

        return output

    @expose()
    def conteiner(self, numero=None):
        DBSession.add(Conteiner(numero=numero or ''))
        DBSession.commit()
        return "OK"


config = AppConfig(minimal=True, root_controller=RootController())

config.renderers = ['kajiki']
config.serve_static = True
config.paths['static_files'] = 'img'
config['use_sqlalchemy'] = True
config['sqlalchemy.url'] = 'sqlite:///devdata.db'
from tg.util import Bunch
from sqlalchemy.orm import scoped_session, sessionmaker

DBSession = scoped_session(sessionmaker(autoflush=True, autocommit=False))


def init_model(engine):
    DBSession.configure(bind=engine)
    DeclarativeBase.metadata.create_all(
Esempio n. 27
0
def make_appcfg_for_controller(root_controller):
    config = AppConfig(minimal=True, root_controller=root_controller)
    config['helpers'] = Bunch()
    config['app_globals'] = AppGlobals
    return config
Esempio n. 28
0
 def setup_class(cls):
     config = AppConfig(minimal=True, root_controller=RootController())
     cls.wsgi_app = config.make_wsgi_app()
Esempio n. 29
0
 def setup_class(cls):
     config = AppConfig(minimal=True, root_controller=RootController())
     config.paths['static_files'] = PATH_TO_STORAGE
     cls.wsgi_app = config.make_wsgi_app()
Esempio n. 30
0
def test_render_missing_renderer():
    conf = AppConfig(minimal=True)
    app = conf.make_wsgi_app()

    tg.render_template({}, 'gensh')