def test_load_template_from_string(self): plugin = MarkupTemplateEnginePlugin() tmpl = plugin.load_template(None, template_string="""<p> $message </p>""") self.assertEqual(None, tmpl.filename) assert isinstance(tmpl, MarkupTemplate)
def test_helper_functions(self): plugin = MarkupTemplateEnginePlugin() tmpl = plugin.load_template(PACKAGE + '.templates.functions') output = plugin.render({'snippet': '<b>Foo</b>'}, template=tmpl) self.assertEqual("""<div> False bar <b>Foo</b> <b>Foo</b> </div>""", output)
def test_helper_functions(self): plugin = MarkupTemplateEnginePlugin() tmpl = plugin.load_template(PACKAGE + '.templates.functions') output = plugin.render({'snippet': u'<b>Foo</b>'}, template=tmpl) self.assertEqual("""<div> False bar <b>Foo</b> <b>Foo</b> </div>""", output)
def setup_tw_middleware(app, config): # Set up the TW middleware, as per errors and instructions at: # http://groups.google.com/group/toscawidgets-discuss/browse_thread/thread/c06950b8d1f62db9 # http://toscawidgets.org/documentation/ToscaWidgets/install/pylons_app.html def enable_i18n_for_template(template): template.filters.insert(0, Translator(ugettext)) def filename_suffix_adder(inner_loader, suffix): def _add_suffix(filename): return inner_loader(filename + suffix) return _add_suffix # Ensure that the toscawidgets template loader includes the search paths # from our main template loader. tw_engine_options = {"genshi.loader_callback": enable_i18n_for_template} tw_engines = EngineManager(extra_vars_func=None, options=tw_engine_options) tw_engines["genshi"] = MarkupTemplateEnginePlugin() tw_engines["genshi"].loader = config["pylons.app_globals"].genshi_loader # Disable the built-in package name template resolution. tw_engines["genshi"].use_package_naming = False # Rebuild package name template resolution using mostly standard Genshi # load functions. With our customizations to the TemplateLoader, the # absolute paths that the builtin resolution produces are erroneously # treated as being relative to the search path. # Search the tw templates dir using the pkg_resources API. # Expected input: 'input_field.html' tw_loader = loader.package("tw.forms", "templates") # Include the .html extension automatically. # Expected input: 'input_field' tw_loader = filename_suffix_adder(tw_loader, ".html") # Apply this loader only when the filename starts with tw.forms.templates. # This prefix is stripped off when calling the above loader. # Expected input: 'tw.forms.templates.input_field' tw_loader = loader.prefixed(**{"tw.forms.templates.": tw_loader}) # Add this path to our global loader tw_engines["genshi"].loader.search_path.append(tw_loader) app = tw.api.make_middleware( app, { "toscawidgets.framework": "pylons", "toscawidgets.framework.default_view": "genshi", "toscawidgets.framework.translator": lazy_ugettext, "toscawidgets.framework.engines": tw_engines, }, ) return app
def test_render(self): plugin = MarkupTemplateEnginePlugin() tmpl = plugin.load_template(PACKAGE + '.templates.test') output = plugin.render({'message': 'Hello'}, template=tmpl) self.assertEqual("""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html lang="en"> <head> <title>Test</title> </head> <body> <h1>Test</h1> <p>Hello</p> </body> </html>""", output)
def test_render_fragment_with_doctype(self): plugin = MarkupTemplateEnginePlugin(options={ 'genshi.default_doctype': 'html-strict', }) tmpl = plugin.load_template(PACKAGE + '.templates.test_no_doctype') output = plugin.render({'message': 'Hello'}, template=tmpl, fragment=True) self.assertEqual("""<html lang="en"> <head> <title>Test</title> </head> <body> <h1>Test</h1> <p>Hello</p> </body> </html>""", output)
def test_render_with_doctype(self): plugin = MarkupTemplateEnginePlugin(options={ 'genshi.default_doctype': 'html-strict', }) tmpl = plugin.load_template(PACKAGE + '.templates.test') output = plugin.render({'message': 'Hello'}, template=tmpl) self.assertEqual("""<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <title>Test</title> </head> <body> <h1>Test</h1> <p>Hello</p> </body> </html>""", output)
def setup_tw_middleware(app, config): def filename_suffix_adder(inner_loader, suffix): def _add_suffix(filename): return inner_loader(filename + suffix) return _add_suffix # Ensure that the toscawidgets template loader includes the search paths # from our main template loader. tw_engines = EngineManager(extra_vars_func=None) tw_engines["genshi"] = MarkupTemplateEnginePlugin() tw_engines["genshi"].loader = config["pylons.app_globals"].genshi_loader # Disable the built-in package name template resolution. tw_engines["genshi"].use_package_naming = False # Rebuild package name template resolution using mostly standard Genshi # load functions. With our customizations to the TemplateLoader, the # absolute paths that the builtin resolution produces are erroneously # treated as being relative to the search path. # Search the tw templates dir using the pkg_resources API. # Expected input: 'input_field.html' tw_loader = loader.package("tw.forms", "templates") # Include the .html extension automatically. # Expected input: 'input_field' tw_loader = filename_suffix_adder(tw_loader, ".html") # Apply this loader only when the filename starts with tw.forms.templates. # This prefix is stripped off when calling the above loader. # Expected input: 'tw.forms.templates.input_field' tw_loader = loader.prefixed(**{"tw.forms.templates.": tw_loader}) # Add this path to our global loader tw_engines["genshi"].loader.search_path.append(tw_loader) app = tw.api.make_middleware( app, { "toscawidgets.framework": "pylons", "toscawidgets.framework.default_view": "genshi", "toscawidgets.framework.engines": tw_engines, }, ) return app
def test_init_no_options(self): plugin = MarkupTemplateEnginePlugin() self.assertEqual('utf-8', plugin.default_encoding) self.assertEqual('html', plugin.default_format) self.assertEqual(None, plugin.default_doctype) self.assertEqual([], plugin.loader.search_path) self.assertEqual(True, plugin.loader.auto_reload) self.assertEqual(25, plugin.loader._cache.capacity)
def test_init_with_output_options(self): plugin = MarkupTemplateEnginePlugin(options={ 'genshi.default_encoding': 'iso-8859-15', 'genshi.default_format': 'xhtml', 'genshi.default_doctype': 'xhtml-strict', }) self.assertEqual('iso-8859-15', plugin.default_encoding) self.assertEqual('xhtml', plugin.default_format) self.assertEqual(DocType.XHTML, plugin.default_doctype)
def setup_tw_middleware(app, config): def filename_suffix_adder(inner_loader, suffix): def _add_suffix(filename): return inner_loader(filename + suffix) return _add_suffix # Ensure that the toscawidgets template loader includes the search paths # from our main template loader. tw_engines = EngineManager(extra_vars_func=None) tw_engines['genshi'] = MarkupTemplateEnginePlugin() tw_engines['genshi'].loader = config['pylons.app_globals'].genshi_loader # Disable the built-in package name template resolution. tw_engines['genshi'].use_package_naming = False # Rebuild package name template resolution using mostly standard Genshi # load functions. With our customizations to the TemplateLoader, the # absolute paths that the builtin resolution produces are erroneously # treated as being relative to the search path. # Search the tw templates dir using the pkg_resources API. # Expected input: 'input_field.html' tw_loader = loader.package('tw.forms', 'templates') # Include the .html extension automatically. # Expected input: 'input_field' tw_loader = filename_suffix_adder(tw_loader, '.html') # Apply this loader only when the filename starts with tw.forms.templates. # This prefix is stripped off when calling the above loader. # Expected input: 'tw.forms.templates.input_field' tw_loader = loader.prefixed(**{'tw.forms.templates.': tw_loader}) # Add this path to our global loader tw_engines['genshi'].loader.search_path.append(tw_loader) app = tw.api.make_middleware( app, { 'toscawidgets.framework': 'pylons', 'toscawidgets.framework.default_view': 'genshi', 'toscawidgets.framework.engines': tw_engines, }) return app
def test_init_with_loader_options(self): plugin = MarkupTemplateEnginePlugin(options={ 'genshi.auto_reload': 'off', 'genshi.max_cache_size': '100', 'genshi.search_path': '/usr/share/tmpl:/usr/local/share/tmpl', }) self.assertEqual(['/usr/share/tmpl', '/usr/local/share/tmpl'], plugin.loader.search_path) self.assertEqual(False, plugin.loader.auto_reload) self.assertEqual(100, plugin.loader._cache.capacity)
class WSGITrac: """Callable class. Initi with path=/path/to/trac/env""" def __init__(self, path, secure=False, parent=False): self.path = path self.secure = secure self.parent = parent self.template = MarkupTemplateEnginePlugin() def __call__(self, environ, start_response): https = environ.get("HTTPS", "off") if self.secure and https != 'on': return redirect_https(environ, start_response) if self.parent: project = path_info_pop(environ) if project: environ['trac.env_path'] = os.path.join(self.path, project) return dispatch_request(environ, start_response) else: return self._send_index(environ, start_response) else: environ['trac.env_path'] = self.path return dispatch_request(environ, start_response) def _send_index(self, environ, start_response): projects = [] for env_name in os.listdir(self.path): env_path = os.path.join(self.path, env_name) try: env = open_environment(env_path) env_perm = PermissionCache( PermissionSystem(env).get_user_permissions( environ.get("REMOTE_USER", "anonymous"))) if env_perm.has_permission('WIKI_VIEW'): projects.append({ 'name': env.project_name, 'description': env.project_description, # XXX: get rid of the double / in the beginning 'href': construct_url(environ, path_info="/" + env_name), }) except Exception: pass projects.sort(lambda x, y: cmp(x['name'].lower(), y['name'].lower())) start_response("200 OK", [('content-type', 'text/html')]) return self.template.render({"projects": projects}, format='xhtml', template="wsgiplugin.index")
class WSGITrac: """Callable class. Initi with path=/path/to/trac/env""" def __init__(self, path, secure=False, parent=False): self.path = path self.secure = secure self.parent = parent self.template = MarkupTemplateEnginePlugin() def __call__(self, environ, start_response): https = environ.get("HTTPS", "off") if self.secure and https != 'on': return redirect_https(environ, start_response) if self.parent: project = path_info_pop(environ) if project: if not os.path.isdir('{0}/{1}'.format(self.path, project)): start_response("404 Not Found", [('content-type', 'text/html')]) return self.template.render({'message': 'Trac name {0} does\'t exist.'.format(project)}, format='xhtml', template="wsgiplugin.notfound") environ['trac.env_path'] = os.path.join(self.path, project) try: return dispatch_request(environ, start_response) except HTTPForbidden: if environ.get('REMOTE_USER'): #We have SOMETHING set in REMOTE_USER - so Forbidden start_response("200 OK", [('content-type', 'text/html')]) return self.template.render({}, format='xhtml', template="wsgiplugin.unauthorized") else: url = '/login_form?came_from=%s' % construct_url(environ) start_response("302 Temporary Redirect", [('Location', url)]) return [] except HTTPNotFound, e: start_response("404 Not Found", [('content-type', 'text/html')]) return self.template.render({'message': e}, format='xhtml', template="wsgiplugin.notfound") else: return self._send_index(environ, start_response) else:
class WSGITrac: """Callable class. Initi with path=/path/to/trac/env""" def __init__(self, path, secure=False, parent=False): self.path = path self.secure = secure self.parent = parent self.template = MarkupTemplateEnginePlugin() def __call__(self, environ, start_response): https = environ.get("HTTPS", "off") if self.secure and https != 'on': return redirect_https(environ, start_response) if self.parent: project = path_info_pop(environ) if project: environ['trac.env_path'] = os.path.join(self.path, project) return dispatch_request(environ, start_response) else: return self._send_index(environ, start_response) else: environ['trac.env_path'] = self.path return dispatch_request(environ, start_response) def _send_index(self, environ, start_response): projects = [] for env_name in os.listdir(self.path): env_path = os.path.join(self.path, env_name) try: env = open_environment(env_path) env_perm = PermissionCache(PermissionSystem(env).get_user_permissions(environ.get("REMOTE_USER", "anonymous"))) if env_perm.has_permission('WIKI_VIEW'): projects.append({ 'name': env.project_name, 'description': env.project_description, # XXX: get rid of the double / in the beginning 'href': construct_url(environ, path_info="/"+env_name), }) except Exception: pass projects.sort(lambda x, y: cmp(x['name'].lower(), y['name'].lower())) start_response("200 OK", [('content-type', 'text/html')]) return self.template.render({"projects":projects}, format='xhtml', template = "wsgiplugin.index")
def create_tw_engine_manager(app_globals): def filename_suffix_adder(inner_loader, suffix): def _add_suffix(filename): return inner_loader(filename + suffix) return _add_suffix # Ensure that the toscawidgets template loader includes the search paths # from our main template loader. tw_engines = EngineManager(extra_vars_func=None) tw_engines['genshi'] = MarkupTemplateEnginePlugin() tw_engines['genshi'].loader = app_globals.genshi_loader # Disable the built-in package name template resolution. tw_engines['genshi'].use_package_naming = False # Rebuild package name template resolution using mostly standard Genshi # load functions. With our customizations to the TemplateLoader, the # absolute paths that the builtin resolution produces are erroneously # treated as being relative to the search path. # Search the tw templates dir using the pkg_resources API. # Expected input: 'input_field.html' tw_loader = loader.package('tw.forms', 'templates') # Include the .html extension automatically. # Expected input: 'input_field' tw_loader = filename_suffix_adder(tw_loader, '.html') # Apply this loader only when the filename starts with tw.forms.templates. # This prefix is stripped off when calling the above loader. # Expected input: 'tw.forms.templates.input_field' tw_loader = loader.prefixed(**{'tw.forms.templates.': tw_loader}) # Add this path to our global loader tw_engines['genshi'].loader.search_path.append(tw_loader) return tw_engines
def test_load_template_from_file(self): plugin = MarkupTemplateEnginePlugin() tmpl = plugin.load_template(PACKAGE + '.templates.test') self.assertEqual('test.html', os.path.basename(tmpl.filename)) assert isinstance(tmpl, MarkupTemplate)
def __init__(self, path, secure=False, parent=False): self.path = path self.secure = secure self.parent = parent self.template = MarkupTemplateEnginePlugin()
def test_transform_without_load(self): plugin = MarkupTemplateEnginePlugin() stream = plugin.transform({'message': 'Hello'}, PACKAGE + '.templates.test') assert isinstance(stream, Stream)
def __init__(self, extra_vars_func=None, options=None): default_doctype = options.pop('genshi.default_doctype', None) MarkupTemplateEnginePlugin.__init__(self, extra_vars_func, options) self.default_doctype = default_doctype