Ejemplo n.º 1
0
    def test_new_text_format(self):
        """Verify that our view is able to send new text format to Genshi."""

        # make sure we have asked for new format in the config
        new_syntax = config.get("genshi.new_text_syntax", False)
        config.update({"genshi.new_text_syntax": True})
        # we need to reload the engines for the config changes to take effect
        view.load_engines()

        # load our expected result in memory
        expected_result = 'Dear Florent Aide\nYour items:\n  * Apples\n  * Bananas\n  * Cherries\n\n'

        info = dict(
            name=u"Florent Aide",
            itemlist=[u'Apples', u'Bananas', u'Cherries']
        )
        template = "genshi-text:turbogears.tests.genshi_new_text_format"
        headers = {}
        val = view.render(info, template, headers=headers, format="text")
        config.update({"genshi.new_text_syntax": new_syntax})

        print "Got this:"
        print "*" * 35
        print "%r" % val
        print "*" * 35
        print "Expected that:"
        print "*" * 35
        print "%r" % expected_result
        print "*" * 35
        assert val == expected_result
Ejemplo n.º 2
0
    def test_remote_form_factory(self):
        from turbogears.view import load_engines
        load_engines()
       
        # WidgetsList object
        widget_list_object = self.widget_factory.get_widgetlist_object()
        #print widget_list_object
        remote_form = RemoteFormFactory(widget_list_object).get_remote_form()

        #it is a key,value dict
        widget_list=self.widget_factory.get_widgetlist()
        #print widget_list
        all_fields = [getattr(field,"name") for field in remote_form.fields]
        #print all_fields
        #will check if the remote form object hass all the names in it
        for argument_name in widget_list.items():
            argument_name in all_fields 
Ejemplo n.º 3
0
    def test_remote_form_factory(self):
        from turbogears.view import load_engines
        load_engines()
      
        schema_factory = WidgetSchemaFactory(self.get_test_default_args())
        schema_validator=schema_factory.get_ready_schema()
      
        # WidgetsList object
        widget_list_object = self.widget_factory.get_widgetlist_object()
        #print widget_list_object
        remote_form = RemoteFormFactory(widget_list_object,schema_validator).get_remote_form()

        #it is a key,value dict
        widget_list=self.widget_factory.get_widgetlist()
        #print widget_list
        all_fields = [getattr(field,"name") for field in remote_form.fields]
        #print all_fields
        #will check if the remote form object hass all the names in it
        for argument_name in widget_list.items():
            argument_name in all_fields 
Ejemplo n.º 4
0
    def test_default_output_encoding(self):
        """Test we can set Genshi default encoding and headers are set correctly."""

        info = dict(someval=u"Español")
        template = "genshi:turbogears.tests.simple"
        headers = {}
        # default encoding is utf-8
        val = view.render(info, template, headers=headers)
        assert headers.get('Content-Type') == 'text/html; charset=utf-8'
        # encoding can be changed and will be added to existing content type
        try:
            genshi_encoding = config.get('genshi.default_encoding', "utf-8")
            config.update({'genshi.default_encoding': 'iso-8859-1'})
            # we need to reload the engines for the config change to take effect
            view.load_engines()
            headers['Content-Type'] = 'text/html'
            val = view.render(info, template, headers=headers)
            assert headers.get('Content-Type') == 'text/html; charset=iso-8859-1'
            self.assertRaises(UnicodeDecodeError, val.decode, 'utf-8')
            assert u"Paging all Español" in val.decode('iso-8859-1')
        finally:
            config.update({'genshi.default_encoding': genshi_encoding})
Ejemplo n.º 5
0
def startTurboGears():
    """Handles TurboGears tasks when the CherryPy server starts.

    This adds the "tg_js" configuration to make MochiKit accessible.
    It also turns on stdlib logging when in development mode.
    """
    config.update({"/tg_static":
            {
            "static_filter.on": True,
            "static_filter.dir":
                os.path.abspath(pkg_resources.resource_filename(__name__, "static")),
            'log_debug_info_filter.on' : False,
            }
        })
    config.update({"/tg_js" :
            {
            "static_filter.on" : True,
            "static_filter.dir" :
                os.path.abspath(pkg_resources.resource_filename(__name__, "static/js")),
            'log_debug_info_filter.on' : False,
            }
        })
    cherrypy.config.environments['development']['log_debug_info_filter.on'] = False
    
    if config.get("decoding_filter.on", path="/") is None:
        config.update({"/": {
            "decoding_filter.on" : True,
            "decoding_filter.encoding" : config.get(
                                        "kid.encoding", "utf8")
        }})
        
    view.load_engines()
    view.loadBaseTemplates()
    global webpath
    webpath = config.get("server.webpath", "")

    if hasattr(cherrypy, "root") and cherrypy.root:
        if not hasattr(cherrypy.root, "_cp_filters"):
            cherrypy.root._cp_filters= []
        morefilters = [EndTransactionsFilter(),
                       NestedVariablesFilter()]
        if webpath:
            morefilters.insert(0, VirtualPathFilter())
        cherrypy.root._cp_filters.extend(morefilters)

    if webpath.startswith("/"):
        webpath = webpath[1:]
    if webpath and not webpath.endswith("/"):
        webpath = webpath + "/"
    isdev = config.get('server.environment') == 'development'
    if not config.get("tg.new_style_logging"):
        if config.get('server.log_to_screen'):
            setuplog = logging.getLogger()
            setuplog.setLevel(logging.DEBUG)
            fmt = logging.Formatter("%(asctime)s %(name)s "
                                    "%(levelname)s %(message)s")
            handler = logging.StreamHandler(sys.stdout)
            handler.setLevel(logging.DEBUG)
            handler.setFormatter(fmt)
            setuplog.addHandler(handler)
        
        logfile = config.get("server.log_file")
        if logfile:
            setuplog = logging.getLogger("turbogears.access")
            setuplog.propagate = 0
            fmt = logging.Formatter("%(message)s")
            handler = logging.FileHandler(logfile)
            handler.setLevel(logging.INFO)
            handler.setFormatter(fmt)
            setuplog.addHandler(handler)

    bonjoursetting = config.get("tg.bonjour", None)
    if bonjoursetting or isdev:
        start_bonjour(bonjoursetting)
    
    if config.get("sqlalchemy.dburi"):
        database.bind_meta_data()

    # Start all TurboGears extensions
    extensions= pkg_resources.iter_entry_points( "turbogears.extensions" )
    for entrypoint in extensions:
        ext= entrypoint.load()
        if hasattr(ext, "start_extension"):
            ext.start_extension()
    
    for item in call_on_startup:
        item()
        
    if config.get("tg.scheduler", False):
        scheduler._start_scheduler()
        log.info("Scheduler started")
Ejemplo n.º 6
0
def setup_module():
    global oldrequest
    oldrequest = cherrypy.request
    cherrypy.request = Request()
    if not view.engines:
        view.load_engines()
Ejemplo n.º 7
0
    def setUp(self):
        """Reload the template engines before each run."""

        print "Loading all template engines..."
        view.load_engines()
Ejemplo n.º 8
0
def startTurboGears():
    """Handles TurboGears tasks when the CherryPy server starts.

    This adds the "tg_js" configuration to make MochiKit accessible.
    It also turns on stdlib logging when in development mode.

    """
    # Set up old-style logging
    cherrypy.config.environments['development'][
        'log_debug_info_filter.on'] = False

    if not config.get('tg.new_style_logging'):
        if config.get('server.log_to_screen'):
            setuplog = logging.getLogger()
            setuplog.setLevel(logging.DEBUG)
            fmt = logging.Formatter(
                "%(asctime)s %(name)s %(levelname)s %(message)s")
            handler = logging.StreamHandler(sys.stdout)
            handler.setLevel(logging.DEBUG)
            handler.setFormatter(fmt)
            setuplog.addHandler(handler)

        logfile = config.get('server.log_file')
        if logfile:
            setuplog = logging.getLogger('turbogears.access')
            setuplog.propagate = 0
            fmt = logging.Formatter("%(message)s")
            handler = logging.FileHandler(logfile)
            handler.setLevel(logging.INFO)
            handler.setFormatter(fmt)
            setuplog.addHandler(handler)

    # Add static filters
    resource_filename = pkg_resources.resource_filename
    config.update({'/tg_static': {
            'static_filter.on': True,
            'static_filter.dir':
                os.path.abspath(resource_filename(__name__, 'static')),
            'log_debug_info_filter.on': False,
        }})
    config.update({'/tg_js': {
            'static_filter.on': True,
            'static_filter.dir':
                os.path.abspath(resource_filename(__name__, 'static/js')),
            'log_debug_info_filter.on': False,
        }})
    mochikit_version = config.get(
        'tg.mochikit_version', config.get('tg_mochikit.version', '1.3'))
    mochikit_suffix = '_'.join(mochikit_version.split('.', 2)[:2])
    mochikit_file = os.path.abspath(resource_filename(
        __name__, 'static/js/MochiKit_%s.js' % mochikit_suffix))
    if os.path.exists(mochikit_file):
        for path in ('/tg_static/js/MochiKit.js', '/tg_js/MochiKit.js',
                '/tg_widgets/turbogears/js/MochiKit.js'):
            config.update({path: {
                'static_filter.on': True,
                'static_filter.file': mochikit_file,
            }})
    else:
        log.warning("MochiKit version %s not available" % mochikit_version)
    # Add decoding filter
    if config.get('decoding_filter.on', path='/') is None:
        config.update({'/': {
            'decoding_filter.on': True,
            'decoding_filter.encoding': config.get('kid.encoding', 'utf8')
        }})

    # Initialize template engines and load base templates
    view.load_engines()
    view.loadBaseTemplates()

    # Add request filters
    global webpath
    webpath = config.get('server.webpath') or ''

    if getattr(cherrypy, 'root', None):
        if not hasattr(cherrypy.root, '_cp_filters'):
            cherrypy.root._cp_filters = []
        cherrypy.root._cp_filters.extend([VirtualPathFilter(webpath),
            EndTransactionsFilter(), NestedVariablesFilter()])

    webpath = webpath.lstrip('/')
    if webpath and not webpath.endswith('/'):
        webpath += '/'

    # Register server with Bonjour framework
    bonjoursetting = config.get('tg.bonjour', None)
    if bonjoursetting or config.get('server.environment') == 'development':
        start_bonjour(bonjoursetting)

    # Bind metadata for SQLAlchemy
    if config.get("sqlalchemy.dburi"):
        database.get_engine()

    # Start all TurboGears extensions
    extensions = pkg_resources.iter_entry_points('turbogears.extensions')
    for entrypoint in extensions:
        ext = entrypoint.load()
        if hasattr(ext, 'start_extension'):
            ext.start_extension()

    # Call registered startup functions
    for item in call_on_startup:
        item()

    # Start the scheduler
    if config.get('tg.scheduler', False):
        scheduler._start_scheduler()
        log.info('Scheduler started')
Ejemplo n.º 9
0
def setup_module():
    global oldrequest
    oldrequest = cherrypy.request
    cherrypy.request = Request()
    if not view.engines:
        view.load_engines()
Ejemplo n.º 10
0
def startTurboGears():
    """Handles TurboGears tasks when the CherryPy server starts.

    This performs the following initialization tasks (in given order):

    * Turns off CherryPy's logging filter when in development mode
    * If logging is not already set up, turns on old-style stdlib logging.
    * Adds a static filter for TurboGears's static files (URL '/tg_static').
    * Adds a static filter for TurboGears's JavaScript files (URL '/tg_js').
    * Loads the template engines and the base templates.
    * Adds the CherryPy request filters to the root controller.
    * Adds the decoding filter to the root URL ('/') if enabled in the
      configuration.
    * Registers the server with the Bonjour framework, if available.
    * Calls 'turbogears.database.bind_metadata' when using SQLAlchemy.
    * Loads all turbogears.extensions entry points and calls their
      'start_extension' method.
    * Calls the callables registered in 'turbogears.call_on_startup'.
    * Starts the TurboGears scheduler.

    """
    global webpath
    conf = config.get
    rfn = pkg_resources.resource_filename

    cherrypy.config.environments['development'][
        'log_debug_info_filter.on'] = False

    # XXX: obsolete --> to be removed
    # Set up old-style logging
    if not conf('tg.new_style_logging', False):
        if conf('server.log_to_screen'):
            setuplog = logging.getLogger()
            setuplog.setLevel(logging.DEBUG)
            fmt = logging.Formatter(
                "%(asctime)s %(name)s %(levelname)s %(message)s")
            handler = logging.StreamHandler(sys.stdout)
            handler.setLevel(logging.DEBUG)
            handler.setFormatter(fmt)
            setuplog.addHandler(handler)

        logfile = conf('server.log_file')
        if logfile:
            setuplog = logging.getLogger('turbogears.access')
            setuplog.propagate = 0
            fmt = logging.Formatter("%(message)s")
            handler = logging.FileHandler(logfile)
            handler.setLevel(logging.INFO)
            handler.setFormatter(fmt)
            setuplog.addHandler(handler)

    # Add static filters
    config.update({'/tg_static': {
        'static_filter.on': True,
        'static_filter.dir': abspath(rfn(__name__, 'static')),
        'log_debug_info_filter.on': False,
    }})
    config.update({'/tg_js': {
        'static_filter.on': True,
        'static_filter.dir': abspath(rfn(__name__, 'static/js')),
        'log_debug_info_filter.on': False,
    }})
    # Add decoding filter
    if conf('decoding_filter.on', path='/') is None:
        config.update({'/': {
            'decoding_filter.on': True,
            'decoding_filter.encoding': conf('kid.encoding', 'utf8')
        }})

    # Initialize template engines and load base templates
    view.load_engines()
    view.loadBaseTemplates()

    # Add request filters
    webpath = conf('server.webpath') or ''

    if getattr(cherrypy, 'root', None):
        if not hasattr(cherrypy.root, '_cp_filters'):
            cherrypy.root._cp_filters = []
        extra_filters = [
            VirtualPathFilter(webpath),
            EndTransactionsFilter(),
            NestedVariablesFilter(),
            SafeMultipartFilter()
        ]
        # Do not add filters twice which are already present
        for cp_filter in cherrypy.root._cp_filters[:]:
            for candidate in extra_filters:
                if candidate.__class__ == cp_filter.__class__:
                    extra_filters.remove(candidate)
                    break
        cherrypy.root._cp_filters.extend(extra_filters)

    # Monkey patch CherryPy Decoding filter: injects our replacement filter
    # MonkeyDecodingFilter into the CherryPy filter chain
    decoding_filter = MonkeyDecodingFilter()
    for index, active_filter in enumerate(
            cherrypy.filters._filterhooks.get('before_main', [])):
        if active_filter.im_class == \
                cherrypy.filters.decodingfilter.DecodingFilter:
            cherrypy.filters._filterhooks['before_main'].pop(index)
            if conf('decoding_filter.on', False, path='/'):
                log.info("Request decoding filter activated.")
                cherrypy.filters._filterhooks['before_main'].insert(
                        index, decoding_filter.before_main)


    webpath = webpath.lstrip('/')
    if webpath and not webpath.endswith('/'):
        webpath += '/'

    # Register server with Bonjour framework
    bonjoursetting = conf('tg.bonjour', None)
    if bonjoursetting or conf('server.environment') == 'development':
        start_bonjour(bonjoursetting)

    # Bind metadata for SQLAlchemy
    if conf('sqlalchemy.dburi'):
        database.bind_metadata()

    # Start all TurboGears extensions
    extensions = pkg_resources.iter_entry_points('turbogears.extensions')
    for entrypoint in extensions:
        # We try to load the extension and run its 'start_extension'
        # method ,if present. If either fails, we simply log the exception and
        # continue, because a) when the autoreloader is active, unhandled
        # exceptions in the startup phase will not stop the server and
        # b) faulty extensions (which may be from a different package)
        # should not crash the server.
        try:
            ext = entrypoint.load()
        except Exception, e:
            log.exception("Error loading TurboGears extension plugin '%s': %s",
                entrypoint, e)
            continue
        if hasattr(ext, 'start_extension'):
            try:
                ext.start_extension()
            except Exception, e:
                log.exception("Error starting TurboGears extension '%s': %s",
                    entrypoint, e)
Ejemplo n.º 11
0
def setup_module():
    if not view.engines:
        view.load_engines()
Ejemplo n.º 12
0
def setup_module():
    if not view.engines:
        view.load_engines()
Ejemplo n.º 13
0
 def setUp(self):
     if not view.engines:
         view.load_engines()