PKZ8ð6¤v9½A½Akid/__init__.py# -*- coding: utf-8 -*- """Pythonic, XML Templating Kid is a simple, Python-based template language for generating and transforming XML vocabularies. Kid was spawned as a result of a kinky love triangle between XSLT, TAL, and PHP. We believe many of the best features of these languages live on in Kid with much of the limitations and complexity stamped out (well, eventually :). """ __revision__ = "$Rev: 492 $" __date__ = "$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $" from kid import release __version__ = release.version __author__ = release.author __email__ = release.email __copyright__ = release.copyright __license__ = release.license import sys, os assert sys.hexversion >= 0x02030000, "Kid templates need Python 2.3 or later" from kid.util import xml_sniff, QuickTextReader from kid.namespace import Namespace from kid.codewriter import KID_XMLNS, raise_template_error from kid.compiler import KID_EXT from kid.element import Element, SubElement, Comment, \ ProcessingInstruction, Fragment from kid.parser import ElementStream, XML, document, _coalesce from kid.filter import transform_filter from kid.serialization import Serializer, PlainSerializer, \ XMLSerializer, HTMLSerializer, XHTMLSerializer from kid.format import Format, output_formats import kid.template_util as template_util __all__ = ['KID_XMLNS', 'BaseTemplate', 'Template', 'enable_import', 'import_template', 'load_template', 'Element', 'SubElement', 'XML', 'document', 'Namespace', 'Serializer', 'XMLSerializer', 'HTMLSerializer', 'XHTMLSerializer', 'output_methods', 'Format', 'output_formats', 'filter', 'format', 'namespace', 'serialization', 'util'] assume_encoding = sys.getdefaultencoding() def enable_import(ext=None, path=None): """Enable the kid module loader and import hooks. This function must be called before importing kid templates if templates are not pre-compiled. """ import kid.importer kid.importer.install(ext, path) def disable_import(path=None): """Disable the kid module loader and import hooks again.""" import kid.importer kid.importer.uninstall(path) # Turn on import hooks if KID_IMPORT variables are set if os.environ.get('KID_IMPORT'): enable_import(os.environ.get('KID_IMPORT_EXT')) if os.environ.get('KID_IMPORT_PATH'): enable_import(os.environ.get('KID_IMPORT_EXT'), os.environ['KID_IMPORT_PATH']) def import_template(name, encoding=None): """Import template by name. This is identical to calling `enable_import` followed by an import statement. For example, importing a template named foo using the normal import mechanism looks like this:: import kid kid.enable_import() import foo This function can be used to achieve the same result as follows:: import kid foo = kid.import_template('foo') This is sometimes useful when the name of the template is available only as a string. """ enable_import() mod = __import__(name) components = name.split('.') for comp in components[1:]: mod = getattr(mod, comp) if encoding: mod.encoding = encoding return mod def load_template(file, name='', cache=True, encoding=None, ns={}, entity_map=None, exec_module=None): """Bypass import machinery and load a template module directly. This can be used as an alternative to accessing templates using the native python import mechanisms. file Can be a filename, a kid template string, or an open file object. name Optionally specifies the module name to use for this template. This is a hack to enable relative imports in templates. cache Whether to look for a byte-compiled version of the template. If no byte-compiled version is found, an attempt is made to dump a byte-compiled version after compiling. This argument is ignored if file is not a filename. entity_map Entity map to be used when parsing the template. exec_module If you want full control over how the template module is executed, you can provide this callable that will be called with the template module and the code to be executed as parameters, after the code has been compiled and the module has been created. """ if isinstance(file, basestring): if xml_sniff(file): fo = QuickTextReader(file) filename = '' else: fo = None filename = file else: fo = file filename = '' import kid.importer as importer if filename != '': abs_filename = path.find(filename) if not abs_filename: raise template_util.TemplateNotFound( "%s (in %s)" % (filename, ', '.join(path.paths))) filename = abs_filename name = importer.get_template_name(name, filename) if sys.modules.has_key(name): return sys.modules.get(name) import kid.compiler as compiler if filename == '': code = compiler.compile(fo, filename, encoding, entity_map) else: template = compiler.KidFile(filename, force=False, encoding=encoding, entity_map=entity_map) code = template.compile(dump_code=cache, dump_source=os.environ.get('KID_OUTPUT_PY')) mod = importer._create_module(code, name, filename, store=cache, ns=ns, exec_module=exec_module) return mod # create some default serializers... output_methods = { 'xml': XMLSerializer(decl=True), 'wml': XMLSerializer(decl=True, doctype='wml'), 'xhtml-strict': XHTMLSerializer(decl=False, doctype='xhtml-strict'), 'xhtml': XHTMLSerializer(decl=False, doctype='xhtml'), 'xhtml-frameset': XHTMLSerializer(decl=False, doctype='xhtml-frameset'), 'html-strict': HTMLSerializer(doctype='html-strict'), 'html': HTMLSerializer(doctype='html'), 'html-frameset': HTMLSerializer(doctype='html-frameset'), 'html-quirks': HTMLSerializer(doctype='html-quirks'), 'html-frameset-quirks': HTMLSerializer(doctype='html-frameset-quirks'), 'HTML-strict': HTMLSerializer(doctype='html-strict', transpose=True), 'HTML': HTMLSerializer(doctype='html', transpose=True), 'HTML-frameset': HTMLSerializer(doctype='html-frameset', transpose=True), 'HTML-quirks': HTMLSerializer(doctype='html-quirks', transpose=True), 'HTML-frameset-quirks': HTMLSerializer(doctype='html-frameset-quirks', transpose=True), 'plain': PlainSerializer()} def Template(file=None, source=None, name=None, encoding=None, **kw): """Get a Template class quickly given a module name, file, or string. This is a convenience function for getting a template in a variety of ways. One and only one of the arguments name or file must be specified. file:string The template module is loaded by calling ``load_template(file, name='', cache=True)`` name:string The kid import hook is enabled and the template module is located using the normal Python import mechanisms. source:string string containing the templates source. Once the template module is obtained, a new instance of the module's Template class is created with the keyword arguments passed to this function. """ if name: mod = import_template(name, encoding=encoding) elif file is not None: mod = load_template(file, name=name, encoding=encoding) elif source is not None: mod = load_template(QuickTextReader(source), name=name or hex(id(source)), encoding=encoding) else: raise template_util.TemplateError( "Must specify one of name, file, or source.") try: mod.Template.module = mod except Exception: raise template_util.TemplateImportError( "Template could not be initialized.") return mod.Template(**kw) class BaseTemplate(object): """Base class for compiled Templates. All kid template modules expose a class named ``Template`` that extends from this class making the methods defined here available on all Template subclasses. This class should not be instantiated directly. """ # the serializer to use when writing output serializer = output_methods['xml'] def __init__(self, *args, **kw): """ Initialize a template with instance attributes specified by keyword arguments. Keyword arguments are available to the template using self.var notation. """ for k in kw: # check that reserved keywords such as 'content' are not used if hasattr(BaseTemplate, k): raise template_util.TemplateAttrsError( "Keyword argument %r is a reserved name." % k) self.__dict__.update(kw) self._filters = [transform_filter] self._layout_classes = [] def write(self, file, encoding=None, fragment=False, output=None, format=None): """ Execute template and write output to file. file:file A filename or a file like object (must support write()). encoding:string The output encoding. Default: utf-8. fragment:bool Controls whether prologue information (such as declaration and DOCTYPE should be written). Set to True when generating fragments meant to be inserted into existing XML documents. output:string,`Serializer` A string specifying an output method ('xml', 'html', 'xhtml') or a Serializer object. """ serializer = self._get_serializer(output) try: return serializer.write(self, file, encoding, fragment, format) except Exception: raise_template_error(module=self.__module__) def serialize(self, encoding=None, fragment=False, output=None, format=None): """ Execute a template and return a single string. encoding The output encoding. Default: utf-8. fragment Controls whether prologue information (such as declaration and DOCTYPE should be written). Set to True when generating fragments meant to be inserted into existing XML documents. output A string specifying an output method ('xml', 'html', 'xhtml') or a Serializer object. This is a convienence method, roughly equivalent to:: ''.join([x for x in obj.generate(encoding, fragment, output)] """ serializer = self._get_serializer(output) try: return serializer.serialize(self, encoding, fragment, format) except Exception: raise_template_error(module=self.__module__) def generate(self, encoding=None, fragment=False, output=None, format=None): """ Execute template and generate serialized output incrementally. This method returns an iterator that yields an encoded string for each iteration. The iteration ends when the template is done executing. encoding The output encoding. Default: utf-8. fragment Controls whether prologue information (such as declaration and DOCTYPE should be written). Set to True when generating fragments meant to be inserted into existing XML documents. output A string specifying an output method ('xml', 'html', 'xhtml') or a Serializer object. """ serializer = self._get_serializer(output) try: return serializer.generate(self, encoding, fragment, format) except Exception: raise_template_error(module=self.__module__) def __iter__(self): return iter(self.transform()) def __str__(self): return self.serialize() def __unicode__(self): return unicode(self.serialize(encoding='utf-16'), 'utf-16') def initialize(self): pass def pull(self): """Returns an iterator over the items in this template.""" # create stream and apply filters self.initialize() stream = ElementStream(_coalesce(self.content(), self._get_assume_encoding())) return stream def _pull(self): """Generate events for this template. Compiled templates implement this method. """ return [] def content(self): from inspect import getmro visited = self._layout_classes mro = list(getmro(self.__class__)) mro.reverse() for c in mro: if c.__dict__.has_key('layout') and c not in visited: visited.insert(0, c) return c.__dict__['layout'](self) return self._pull() def transform(self, stream=None, filters=[]): """ Execute the template and apply any match transformations. If stream is specified, it must be one of the following: Element A kid.Element. ElementStream An `pull.ElementStream` instance or other iterator that yields stream events. string A file or URL unless the string starts with '<' in which case it is considered an XML document and processed as if it had been an Element. By default, the `pull` method is called to obtain the stream. """ if stream is None: stream = self.pull() elif isinstance(stream, basestring): if xml_sniff(stream): stream = XML(stream, fragment=False) else: stream = document(stream) elif hasattr(stream, 'tag'): stream = ElementStream(stream) else: stream = ElementStream.ensure(stream) for f in filters + self._filters: stream = f(stream, self) return stream def _get_match_templates(self): # XXX: use inspect instead of accessing __mro__ directly try: rslt = self._match_templates_cached except AttributeError: rslt = [] mro = self.__class__.__mro__ for C in mro: try: templates = C._match_templates except AttributeError: continue rslt += templates self._match_templates_cached = rslt return rslt def _get_serializer(self, serializer): if serializer is None: return self.serializer elif isinstance(serializer, basestring): return output_methods[serializer] else: return serializer def _get_assume_encoding(self): global assume_encoding if hasattr(self, "assume_encoding"): return self.assume_encoding else: return assume_encoding def defined(self, name): return hasattr(self, name) def value_of(self, name, default=None): return getattr(self, name, default) class TemplatePath(object): """Finding templates on a list of paths.""" def __init__(self, paths=None): """Initialize with path list.""" if isinstance(paths, basestring): paths = paths.split(os.pathsep) elif paths is None: paths = [] paths.append(os.getcwd()) self.paths = [] for path in paths: self.append(path) def _cleanse_path(self, path): """Normalize path.""" return os.path.abspath(os.path.normpath(os.path.expanduser(path))) def insert(self, path, pos=0): """Insert path to list if not already there.""" path = self._cleanse_path(path) if path not in self.paths: self.paths.insert(pos, path) def append(self, path): """Append path to list if not already there.""" path = self._cleanse_path(path) if path not in self.paths: self.paths.append(path) def remove(self, path): """Remove path from list.""" path = self._cleanse_path(path) self.paths = [p for p in self.paths if p != path] def find(self, path, rel=None): """Find file relative to path list and rel.""" path = os.path.normpath(path) if rel: rel = [os.path.dirname(rel)] else: rel = [] for p in self.paths + rel: p = os.path.join(p, path) if os.path.exists(p): return p if not p.endswith(KID_EXT): p += KID_EXT if os.path.exists(p): return p path = TemplatePath() PKY8ð6• ~¥_ _ kid/compile.py#!/usr/bin/env python # -*- coding: utf-8 -*- # This module provides the "kidc" command """Usage: kidc [OPTIONS] [file...] Compile kid templates into Python byte-code (.pyc) files. OPTIONS: -f, --force Force compilation even if .pyc file already exists. -s, --source Generate .py source files along with .pyc files. This is sometimes useful for debugging. -d, --strip-dest-dir Strips the supplied path from the beginning of source filenames stored for error messages in the generated .pyc files The file list may have files and/or directories. If a directory is specified, all .kid files found in the directory and any sub-directories are compiled. """ __revision__ = "$Rev: 492 $" __date__ = "$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " import sys from os.path import isdir from getopt import getopt, GetoptError as gerror try: from os import EX_OK, EX_DATAERR, EX_USAGE except ImportError: EX_OK, EX_DATAERR, EX_USAGE = 0, 1, 2 import kid.compiler def main(): # get options try: opts, args = getopt(sys.argv[1:], 'fshd=', ['force', 'source', 'help', 'strip-dest-dir=']) except gerror, e: sys.stderr.write(str(e) + '\n') sys.stdout.write(__doc__) sys.exit(EX_USAGE) force = source = False strip_dest_dir = None for o, a in opts: if o in ('-f', '--force'): force = True elif o in ('-s', '--source'): source = True elif o in ('-h', '--help'): sys.stdout.write(__doc__) sys.exit(EX_OK) elif o in ('-d', '--strip-dest-dir'): strip_dest_dir = a files = args if not files: sys.stderr.write('kidc: No kid template specified.\n') sys.stderr.write(" Try 'kidc --help' for usage information.\n") sys.exit(EX_USAGE) # a quick function for printing results def print_result(res): stat, filename = res if stat == True: msg = 'compile: %s\n' % filename elif stat == False: msg = 'fresh: %s\n' % filename else: msg = 'error: %s (%s)\n' % (filename, stat) sys.stderr.write(msg) # run through files and compile err = False for f in files: if isdir(f): for res in kid.compiler.compile_dir(f, force=force, source=source, strip_dest_dir=strip_dest_dir): if res[0] not in (True, False): err = True print_result(res) else: try: stat = kid.compiler.compile_file(f, force=force, source=source, strip_dest_dir=strip_dest_dir) except Exception, e: stat, err = e, True print_result((stat, f)) # exit with error status if one compilation failed sys.exit(err and EX_DATAERR or EX_OK) if __name__ == '__main__': main() PKZ8ð6× \zzkid/compiler.py# -*- coding: utf-8 -*- """Kid Compiler Compile XML to Python byte-code. """ __revision__ = "$Rev: 492 $" __date__ = "$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " import os import os.path import imp import stat import struct import marshal import kid from kid.codewriter import raise_template_error __all__ = ['KID_EXT', 'compile', 'compile_file', 'compile_dir'] # kid filename extension KID_EXT = ".kid" def actualize(code, dict=None): """Run code with variables in dict, updating the dict.""" if dict is None: dict = {} exec code in dict return dict _py_compile = compile def py_compile(code, filename='', kind='exec'): """The Python built-in compile function with safeguard.""" if type(code) == unicode: # unicode strings may not have a PEP 0263 encoding declaration if code.startswith('# -*- coding: '): # we want the line numbering to match with the source file, # so we only remove the magic word in the comment line: code = '# -*-' + code[13:] return _py_compile(code, filename, 'exec') def compile(source, filename='', encoding=None, entity_map=None): """Compiles Kid XML source to a Python code object. source -- A file like object - must support read. filename -- An optional filename that is used """ # XXX all kinds of work to do here catching syntax errors and # adjusting line numbers... py = kid.codewriter.parse(source, encoding, filename, entity_map) return py_compile(py, filename) _timestamp = lambda filename : os.stat(filename)[stat.ST_MTIME] class KidFile(object): magic = imp.get_magic() def __init__(self, kid_file, force=False, encoding=None, strip_dest_dir=None, entity_map=None): self.kid_file = kid_file self.py_file = os.path.splitext(kid_file)[0] + '.py' self.strip_dest_dir = strip_dest_dir self.pyc_file = self.py_file + 'c' self.encoding = encoding self.entity_map = entity_map fp = None if force: stale = True else: stale = False try: fp = open(self.pyc_file, "rb") except IOError: stale = True else: if fp.read(4) != self.magic: stale = True else: mtime = struct.unpack(' 0 and name != os.curdir and name != os.pardir \ and os.path.isdir(fullname) and not os.path.islink(fullname): for res in compile_dir(fullname, maxlevels - 1, force, source, encoding, strip_dest_dir, entity_map): yield res PKZ8ð6Ô+G«!! kid/pull.py# -*- coding: utf-8 -*- """Pull-style interface for ElementTree. The kid.pull module has been deprecated in favor of kid.parser. """ __revision__ = "$Rev: 429 $" __date__ = "$Date: 2006-10-26 15:24:33 +0200 (Do, 26 Okt 2006) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " import warnings warnings.warn("kid.pull has been superseded by kid.parser", DeprecationWarning) from kid.parser import *PKZ8ð6¶ ˜Í Í kid/filter.py# -*- coding: utf-8 -*- """Kid tranformations""" __revision__ = "$Rev: 492 $" __date__ = "$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " from kid.parser import ElementStream, START, XML_DECL, document, _coalesce from kid.namespace import Namespace from kid.template_util import generate_content __all__ = ['transform_filter'] def transform_filter(stream, template): templates = template._get_match_templates() def apply_func(item): return transform_filter(generate_content(item), template) stream = ElementStream.ensure(stream) return ElementStream(apply_matches(stream, template, templates, apply_func)) def apply_matches(stream, template, templates, apply_func): for ev, item in stream: if ev == START: matched = False for i in range(0, len(templates)): match, call = templates[i] if match(item): item = stream.expand() newstream = _coalesce(call(template, item, apply_func), template._get_assume_encoding()) if len(templates) < 2: for ev, item in newstream: yield ev, item else: for ev, item in apply_matches( ElementStream(newstream), template, templates[:i] + templates[i+1:], apply_func): yield ev, item matched = True break if matched: continue yield ev, item # XXX haven't tested this yet.. def xinclude_filter(stream, template): xi = Namespace('http://www.w3.org/2001/XInclude') include = xi.include fallback = xi.fallback for ev, item in stream: if ev == START and item.tag == include: item = item.expand() href = item.get('href') try: doc = document(href, template._get_assume_encoding()) except: fallback_elm = item.find(fallback) for ev, item in ElementStream(fallback_elm).strip(1): yield ev, item else: for ev, item in doc: if ev != XML_DECL: yield ev PKZ8ð6_ñ›1RRkid/importer.py# -*- coding: utf-8 -*- """Kid Import Hooks. When installed, these hooks allow importing .kid files as if they were Python modules. Notes: We use new import hooks instead of the old ihooks module, because ihooks is incompatible with Python eggs. We allow importing from one or more specified paths for Kid templates, or importing from sys.path. In the latter case, we use an importer on meta_path because importers on path_hook do not fall back to the built-in import in Python >= 2.5 (this worked in Python 2.3 and 2.4). """ __revision__ = "$Rev: 492 $" __date__ = "$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com); Christoph Zwerschke (cito@online.de)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko; 2006 Christoph Zwerschke" __license__ = "MIT " import sys import time import new from os import environ, extsep, pathsep from os.path import exists, join as joinpath, isdir from kid import __version__ from kid.codewriter import raise_template_error from kid.compiler import KidFile, KID_EXT from kid.template_util import TemplateImportError __all__ = ['install', 'uninstall', 'import_template', 'get_template_name'] def install(ext=None, path=None): """Install importer for Kid templates. ext can be one or more extensions as list or comma separated string path can be one or more paths as list or pathsep separated string """ if ext: if isinstance(ext, basestring): exts = ext.split(',') else: exts = list(ext) for ext in exts: if not ext.startswith(extsep): raise Exception, "Illegal exception: " + ext if KID_EXT in exts: exts.remove(KID_EXT) else: exts = [] exts.insert(0, KID_EXT) if path: # install path hook if isinstance(path, basestring): paths = path.split(pathsep) else: paths = list(path) # Install special Kid template paths, because since Python 2.5, # path hooks do not fall back to the built-in import any more. ext = ','.join(exts) kidpaths = [] syspath = sys.path for path in paths: kidpath = 'kid::%s::' % path syspath = [path for path in syspath if not path.startswith(kidpath)] kidpaths.append(kidpath + ext) sys.path = kidpaths + syspath if kidpaths: if not KidImporter in sys.path_hooks: sys.path_hooks.insert(0, KidImporter) else: # install meta hook for all sys paths for importer in sys.meta_path: if isinstance(importer, KidImporter): importer.exts = exts break else: importer = KidImporter(ext=exts) sys.meta_path.insert(0, importer) def uninstall(path=None): """Uninstall importer for Kid templates. path can be one or more paths as list or pathsep separated string """ if path: # uninstall path hook if isinstance(path, basestring): paths = path.split(pathsep) else: paths = list(path) syspath = [] remove_hook = True for path in sys.path: p = path.split(':') if len(p) >= 5 and \ p[0] == 'kid' and not p[1] and not p[-2]: if ':'.join(p[2:-2]) in paths: continue remove_hook = False syspath.append(path) sys.path = syspath if remove_hook: if KidImporter in sys.path_hooks: sys.path_hooks = [hook for hook in sys.path_hooks if hook != KidImporter] sys.path_importer_cache.clear() else: # uninstall meta hook for all sys paths sys.meta_path = [importer for importer in sys.meta_path if not isinstance(importer, KidImporter)] def import_template(name, filename, force=False): if not force and name and sys.modules.has_key(name): return sys.modules[name] template = KidFile(filename) code = template.compile(dump_source=environ.get('KID_OUTPUT_PY')) module = _create_module(code, name, filename) return module def get_template_name(name, filename): if name: return name else: return 'kid.util.template_%x' % (hash(filename) + sys.maxint + 1) def _create_module(code, name, filename, store=True, ns={}, exec_module=None): for recompiled in range(2): name = get_template_name(name, filename) mod = new.module(name) mod.__file__ = filename mod.__ctime__ = time.time() mod.__dict__.update(ns) try: if exec_module: exec_module(mod, code) else: exec code in mod.__dict__ except Exception: if store: sys.modules[name] = mod raise_template_error(module=name, filename=filename) if getattr(mod, 'kid_version', None) == __version__: break # the module has been compiled against an old Kid version, # recompile to ensure compatibility and best performance if recompiled: # already tried recompiling, to no avail raise TemplateImportError('Cannot recompile template file' ' %r for Kid version %s' % (filename, __version__)) template = KidFile(filename) template.stale = True template._python = template._code = None code = template.compile(dump_source=environ.get('KID_OUTPUT_PY')) if store: sys.modules[name] = mod return mod class KidImporter(object): """Importer for Kid templates via sys.path_hooks or sys.meta_path.""" def __init__(self, path=None, ext=None): if path: # initialized via sys.path_hooks # check for special path format: # path = kid::/path/to/templates::.ext1,.ext2 p = path.split(':') if len(p) >= 5 and \ p[0] == 'kid' and not p[1] and not p[-2]: path = ':'.join(p[2:-2]) exts = p[-1].split(',') if exts: for ext in exts: if not ext.startswith(extsep): break else: if isdir(path): self.path = path self.exts = exts return raise ImportError else: # initialize for use via sys.meta_path if ext: if isinstance(ext, basestring): exts = ext.split(',') else: exts = list(ext) for ext in exts: if not ext.startswith(extsep): raise ImportError else: raise ImportError self.path = None self.exts = exts def find_module(self, fullname, path=None): name = fullname.split('.')[-1] if self.path: if path: raise ImportError else: paths = [self.path] else: paths = sys.path if path: paths = path + paths for path in paths: if isdir(path): path = joinpath(path, name) for ext in self.exts: if exists(path + ext): self.filename = path + ext return self return None def load_module(self, fullname): return import_template(fullname, self.filename, force=True) PKZ8ð6C®ækid/namespace.py# -*- coding: utf-8 -*- """Namespace handling.""" __revision__ = "$Rev: 492 $" __date__ = "$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " __all__ = ['Namespace', 'xml', 'xhtml', 'atom', 'rdf', 'rss', 'nons'] namespaces = {} class Namespace(object): def __init__(self, uri, prefix=None): self.uri = uri self.prefix = prefix if prefix: namespaces[uri] = prefix def qname(self, name): if self.prefix: return '%s:%s' % (self.prefix, name) else: return name def clarkname(self, name): if self.uri: return '{%s}%s' % (self.uri, name) else: return name __getattr__ = clarkname __getitem__ = clarkname def __str__(self): return self.uri def __unicode__(self): return unicode(self.uri) def __repr__(self): return 'Namespace(%r, %r)' % (self.uri, self.prefix) def __equals__(self, other): if isinstance(other, basestring): return self.uri == other elif isinstance(other, Namespace): return self.uri == other.uri else: return False xml = Namespace('http://www.w3.org/XML/1998/namespace', 'xml') xhtml = Namespace('http://www.w3.org/1999/xhtml', 'html') atom = Namespace('http://purl.org/atom/ns#', 'atom') rdf = Namespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'rdf') rss = Namespace('http://purl.org/rss/1.0/', 'rss') nons = Namespace(None, None) PKZ8ð6¹²Ïuukid/codewriter.py# -*- coding: utf-8 -*- """KidWriter Write Python source code from XML. """ __revision__ = "$Rev: 496 $" __date__ = "$Date: 2007-07-15 18:14:35 -0400 (Sun, 15 Jul 2007) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " import sys, re from os.path import splitext from traceback import extract_tb, format_exception_only from kid import __version__, Namespace from kid.parser import document, START, END, TEXT, XML_DECL, DOCTYPE, LOCATION from kid.element import namespaces, Comment, ProcessingInstruction __all__ = ['KID_XMLNS', 'KID_PREFIX', 'kidns', 'raise_template_error'] # the Kid XML namespace KID_XMLNS = "http://purl.org/kid/ns#" KID_PREFIX = 'py' kidns = Namespace(KID_XMLNS) QNAME_FOR = kidns['for'] QNAME_IF = kidns['if'] QNAME_DEF = kidns['def'] QNAME_SLOT = kidns['slot'] QNAME_CONTENT = kidns['content'] QNAME_REPLACE = kidns['replace'] QNAME_MATCH = kidns['match'] QNAME_STRIP = kidns['strip'] QNAME_ATTRIBUTES = kidns['attrs'] QNAME_EXTENDS = kidns['extends'] QNAME_LAYOUT = kidns['layout'] # deprectaed QNAME_OMIT = kidns['omit'] QNAME_REPEAT = kidns['repeat'] # the Kid processing instruction name KID_PI = 'python' KID_ALT_PI = 'py' KID_OLD_PI = 'kid' def parse(source, encoding=None, filename=None, entity_map=None): doc = document(source, encoding=encoding, filename=filename, entity_map=entity_map) return KidWriter(doc, encoding, filename).parse() def parse_file(filename, encoding=None, entity_map=None): """Parse the file specified. filename -- the name of a file. fp -- an optional file like object to read from. If not specified, filename is opened. """ source = open(filename, 'rb') try: return parse(source, encoding, filename, entity_map) finally: source.close() def error_location(filename, encoding=None, entity_map=None, lineno=None): if lineno: try: source = open(filename, 'rb') try: doc = document(source, encoding=encoding, filename=filename, entity_map=entity_map, debug=True) writer = KidWriter(doc, encoding, filename, lineno) return writer.parse() finally: source.close() except Exception: pass def TemplateExceptionError(error, add_message): """Get exception with additional error message.""" Error = error.__class__ class TemplateExceptionError(Error): def __init__(self): for arg in dir(error): if not arg.startswith('_'): setattr(self, arg, getattr(error, arg)) def __str__(self): return str(error) + '\n' + add_message TemplateExceptionError.__name__ = Error.__name__ TemplateExceptionError.__module__ = Error.__module__ return TemplateExceptionError() def raise_template_error(module=None, filename=None, encoding=None): """Raise template error along with additional context information. If the module containing the erroneous code has been compiled from a Kid template, try to compile that template with additional debug information, and display the location in the Kid template file corresponding to the erroneous code. """ if module and not (filename and encoding): if module in sys.modules: mod = sys.modules[module] if hasattr(mod, 'encoding'): encoding = mod.encoding if hasattr(mod, 'kid_file'): filename = mod.kid_file if not filename or filename == '': raise if not encoding: encoding = 'utf-8' py_file = splitext(filename)[0] + '.py' exc_type, exc_value = sys.exc_info()[:2] if exc_type == SyntaxError: tb = [(py_file, exc_value.lineno)] else: tb = extract_tb(sys.exc_info()[2]) tb.reverse() for t in tb: if py_file != t[0] or not t[1]: continue location = error_location(filename, encoding, lineno=t[1]) if not location: continue (start_line, start_col), (end_line, end_col) = location if start_line > end_line: continue s = [] if not end_col and end_line > start_line: end_line -= 1 end_col = -1 if start_line == end_line: s.append('on line %d' % start_line) if start_col == end_col: s.append(', column %d' % start_col) elif start_col: if end_col > start_col: s.append(' between columns %d and %d' % (start_col, end_col)) else: s.append(' after column %d' % start_col) elif end_col > 0: s.append(' before column %d' % end_col) else: s.append('between line %d' % start_line) if start_col: s.append(', column %d' % start_col) s.append(' and line %d' % end_line) if end_col > 0: s.append(', column %d' % end_col) if s: s = ''.join(s) try: start_line -= 1 end_line -= 1 error_line, error_text = [], [] for line, text in enumerate(open(filename)): if line < start_line: continue text = text.rstrip() if text: if line == start_line and start_col: if text[:start_col].rstrip(): text = text[start_col:].lstrip() if text: text = '... ' + text if line == end_line and end_col > 0: if text[end_col:].lstrip(): if end_col > 75: end_col = 75 text = text[:end_col].rstrip() if text: text += ' ...' else: text = text[:end_col].rstrip() if len(text) > 79: text = text[:75].rstrip() + ' ...' if text: if len(error_line) < 3: error_line.append(line) error_text.append(text) else: error_line[2] = line error_text[2] = text if line >= end_line: break if not error_line: raise LookupError, 'error line not found' if len(error_line) == 2: if error_line[1] - error_line[0] > 1: error_text.insert(1, '...') elif len(error_line) == 3: if error_line[2] - error_line[0] > 2: error_text[1] = '...' s = [s + ':'] + error_text except Exception, e: s = [s, '(cannot acquire source text: %s)' % str(e)] s.insert(0, 'Error location in template file %r' % filename) break else: s = ['Error in code generated from template file %r' % filename] s = ''.join(format_exception_only(exc_type, exc_value)[:-1]) + '\n'.join(s) if isinstance(exc_type, str): exc_type += '\n' + s else: exc_value = TemplateExceptionError(exc_value, s) exc_type = exc_value.__class__ raise exc_type, exc_value, sys.exc_info()[2] class KidWriter(object): def __init__(self, stream, encoding=None, filename=None, lineno=None): self.stream = stream self.encoding = encoding or 'utf-8' self.filename = filename self.depth = 0 self.lineno = lineno self.location = None self.locations = [] self.module_code = self.codegen() self.class_code = self.codegen() self.expand_code = self.codegen(level=1) self.end_module_code = self.codegen() self.module_defs = [] self.inst_defs = [] def codegen(self, code=None, level=0, tab='\t'): if self.lineno: return LocationGenerator(code, self.getloc) else: return CodeGenerator(code, level, tab) def getloc(self): return self.location def parse(self): self.begin() self.proc_stream(self.module_code) self.end() parts = [] parts += self.module_code.code for c in self.module_defs: parts += c.code parts += self.class_code.code parts += self.expand_code.code for c in self.inst_defs: parts += c.code parts += self.end_module_code.code if self.lineno: lineno = self.lineno - 1 if not 0 <= lineno < len(parts): return None pos = parts[lineno] if not pos: return None pos, is_start = pos if not 0 <= pos < len(self.locations): return None start_loc = self.locations[pos] pos += is_start and 1 or -1 if 0 <= pos < len(self.locations): end_loc = self.locations[pos] else: end_line = start_loc[0] if is_start: end_line += 1 end_loc = (end_line, 0) if not is_start: start_loc, end_loc = end_loc, start_loc return start_loc, end_loc return '\n'.join(parts) def begin(self): code = self.module_code # Start with PEP 0263 encoding declaration code.line('# -*- coding: %s -*-' % self.encoding, '# Kid template module', # version against which the file has been compiled 'kid_version = %r' % __version__, # source from which the file has been compiled 'kid_file = %r' % self.filename, # imports 'import kid', 'from kid.template_util import *', 'import kid.template_util as template_util', '_def_names = []', # default variables (can be overridden by template) 'encoding = "%s"' % self.encoding, 'doctype = None', 'omit_namespaces = [kid.KID_XMLNS]', 'layout_params = {}', # module methods 'def pull(**kw): return Template(**kw).pull()', "def generate(encoding=encoding, fragment=False," " output=None, format=None, **kw):" " return Template(**kw).generate(encoding=encoding," " fragment=fragment, output=output, format=format)", "def serialize(encoding=encoding, fragment=False," " output=None, format=None, **kw):" " return Template(**kw).serialize(encoding=encoding," " fragment=fragment, output=output, format=format)", "def write(file, encoding=encoding, fragment=False," " output=None, format=None, **kw):" " return Template(**kw).write(file, encoding=encoding," " fragment=fragment, output=output, format=format)", 'def initialize(template): pass', 'BaseTemplate = kid.BaseTemplate') # expand code code = self.expand_code code.start_block('def initialize(self):') code.line('rslt = initialize(self)', 'if rslt != 0: super(Template, self).initialize()') code.end_block() code.start_block('def _pull(self):') # XXX hack: nasty kluge for making kwargs locals code.line("exec template_util.get_locals(self, locals())", 'current, ancestors = None, []', 'if doctype: yield DOCTYPE, doctype') code = self.end_module_code code.line('') def end(self): self.expand_code.end_block() def proc_stream(self, code): for ev, item in self.stream: if ev == START: if item.tag == Comment: text = item.text.strip() if text.startswith('!'): continue # swallow comment if code is self.module_code: line = self.expand_code.line else: line = code.line if text.startswith('[') or text.startswith('', 'exec') # if it works, line does not start new block except SyntaxError: # unexpected EOF while parsing? try: # try to compile the whole block block = '\n'.join(lines) + '\n' compile(block, '', 'exec') # if it works, line does not start new block except IndentationError: # expected an indented block? # so try to add some indentation: lines2 = lines[:1] + [tab + line for line in lines[1:]] block = '\n'.join(lines2) + '\n' # try again to compile the whole block: compile(block, '', 'exec') lines = lines2 # if it works, keep the indentation except: pass # leave it as it is except: pass # leave it as it is return lines PKZ8ð6²Æü9 < < kid/parser.py# -*- coding: utf-8 -*- """Pull-style interface for ElementTree.""" __revision__ = "$Rev: 492 $" __date__ = "$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " import htmlentitydefs from xml.parsers import expat from kid.element import Element, Comment, ProcessingInstruction from kid.util import open_resource, QuickTextReader, get_expat_error __all__ = ['ElementStream', 'XML', 'document', 'Parser', 'ExpatParser', 'START', 'END', 'TEXT', 'COMMENT', 'PI', 'XML_DECL', 'DOCTYPE', 'LOCATION'] # This is the default entity map: default_entity_map = {} default_external_dtd = [] for k, v in htmlentitydefs.name2codepoint.items(): default_entity_map[k] = unichr(v) default_external_dtd.append('' % (k, v)) default_external_dtd = '\n'.join(default_external_dtd) class InvalidStreamState(Exception): def __init__(self, msg="Invalid stream state."): Exception.__init__(self, msg) def XML(text, fragment=True, encoding=None, xmlns=None, entity_map=None): """Convert XML string into an ElementStream.""" if text.startswith('%s' % (xmlns, text) else: text = '%s' % text if isinstance(text, unicode): encoding = 'utf-16' text = text.encode(encoding) p = Parser(QuickTextReader(text), encoding, entity_map) return ElementStream(_coalesce(p, encoding=encoding)).strip() else: if isinstance(text, unicode): encoding = 'utf-16' text = text.encode(encoding) p = Parser(QuickTextReader(text), encoding, entity_map) return ElementStream(_coalesce(p, encoding=encoding)) def document(file, encoding=None, filename=None, entity_map=None, debug=False): """Convert XML document into an Element stream.""" if not hasattr(file, 'read'): if filename is None: filename = file file = open_resource(file, 'rb') else: if filename is None: filename = '' p = Parser(file, encoding, entity_map, debug) p._filename = filename return ElementStream(_coalesce(p, encoding=encoding)) class ElementStream(object): """Provides a pull/streaming interface to ElementTree. Instances of this class are iterable. Most methods of the class act on the Element that is currently being visited. """ def __init__(self, stream, current=None): """Create an ElementStream. stream - an iterator that returns ElementStream events. current - If an Element is provided in this parameter than it is yielded as the first element in the stream. """ if hasattr(stream, 'tag') and hasattr(stream, 'attrib'): stream = self._pull(stream, tail=True) self.current = None self._iter = self._track(iter(stream), current) def __iter__(self): return self._iter def expand(self): """Expand the current item in the stream as an Element. In the case where there is no current element and no single root element, this will return a list of Elements. """ current = self.current if current is None: current = [] stack = [current] this, last = current, None for ev, item in self._iter: if ev == START: current, last = item, None stack[-1].append(current) stack.append(current) elif ev == END: last = stack.pop() assert last is item if not stack: break elif ev == TEXT: if last is not None: last.tail = item elif not isinstance(current, list): current.text = item if isinstance(this, list) and len(this) == 1: this = this[0] return this def strip(self, levels=1): """Return new ElementStream with first element level(s) stripped.""" def strip(depth): for ev, item in self._iter: if ev == END: depth -= 1 if depth == 0: break elif depth < 0: raise InvalidStreamState() if depth >= levels: yield ev, item if ev == START: depth += 1 depth = self.current is not None and 1 or 0 return ElementStream(strip(depth)) def eat(self): """Eat the current element and all decendant items.""" depth = self.current is not None and 1 or 0 for ev, item in self._iter: if ev == START: depth += 1 elif ev == END: depth -= 1 if depth == 0: break return self def _pull(self, elem, tail=False): """Make a stream from an Element.""" orig = elem elem = Element(orig.tag, dict(orig.attrib)) ## XXX: find a better way if elem.tag in (Comment, ProcessingInstruction): elem.text = orig.text orig.text = None yield START, elem if orig.text: yield TEXT, orig.text for child in orig.getchildren(): for event in self._pull(child, tail=True): yield event yield END, elem if tail and orig.tail: yield TEXT, orig.tail def _track(self, stream, current=None): """Track current item in stream.""" if current is not None: self.current = current yield START, current for p in stream: ev, item = p if ev == START: self.current = item elif ev == END: self.current = None yield ev, item def ensure(cls, stream, current=None): """Ensure the stream is an ElementStream.""" if isinstance(stream, cls): return stream else: return cls(stream, current) ensure = classmethod(ensure) def to_unicode(value, encoding): if isinstance(value, unicode): return value if hasattr(value, '__unicode__'): return unicode(value) if not isinstance(value, str): value = str(value) return unicode(value, encoding) def _coalesce(stream, encoding): """Coalesces TEXT events and namespace events. Fold multiple sequential TEXT events into a single event. The 'encoding' attribute is for the source strings. """ textbuf = [] namespaces = [] last_ev = None stack = [None] for ev, item in stream: if ev == TEXT: textbuf.append(item) last_ev = TEXT continue if last_ev == TEXT: text = u"" for value in textbuf: text += to_unicode(value, encoding) textbuf = [] if text: yield TEXT, text if ev == START: attrib = item.attrib for prefix, uri in namespaces: if prefix: attrib['xmlns:%s' % prefix] = uri else: attrib['xmlns'] = uri namespaces = [] current = item stack.append(item) elif ev == END: current = stack.pop() elif ev == START_NS: prefix, uri = item namespaces.append((prefix, uri)) continue elif ev == END_NS: continue yield ev, item if last_ev == TEXT: text = u"" for value in textbuf: text += to_unicode(value, encoding) if text: yield TEXT, text # Common Events START = 1 END = 2 TEXT = 3 DOCTYPE = 4 XML_DECL = 5 # These events aren't used after initial parsing START_NS = 10 END_NS = 11 PI = 12 COMMENT = 13 # This is for forwarding the location in the XML document LOCATION = 20 def Parser(source, encoding=None, entity_map=None, debug=False): return ExpatParser(source, encoding, entity_map, debug) # Most of the following copied from ElementTree.XMLTreeBuilder. # Differences from ElementTree implementation: # # * Specialized for generator based processing. Elements are built # using a iterator approach instead of the TreeBuilder approach. # # * Support for DOCTYPE, Comment, and Processing Instruction nodes. class ExpatParser(object): def __init__(self, source, encoding=None, entity_map=None, debug=False): if hasattr(source, 'read'): filename = '' else: filename = source source = open(source, 'rb') self._filename = filename self._source = source self._encoding = encoding self._parser = parser = expat.ParserCreate(encoding, "}") self._queue = [] try: self._parser.CurrentLineNumber except AttributeError: # Expat in Python < 2.4 does not provide the location, # silently switch off the debug mode in this case debug = False if debug: self.push = self._push_location else: self.push = self._push self.debug = debug # callbacks parser.DefaultHandler = self._default parser.StartElementHandler = self._start parser.EndElementHandler = self._end parser.CharacterDataHandler = self._data parser.ProcessingInstructionHandler = self._pi parser.CommentHandler = self._comment parser.StartNamespaceDeclHandler = self._start_ns parser.EndNamespaceDeclHandler = self._end_ns parser.XmlDeclHandler = self._xmldecl_handler parser.StartDoctypeDeclHandler = self._doctype_handler # attributes # (these should all become customizable at some point) parser.buffer_text = True parser.ordered_attributes = False parser.specified_attributes = True self._doctype = None if entity_map: self.entity = entity_map else: self.entity = default_entity_map self.external_dtd = default_external_dtd # setup entity handling parser.SetParamEntityParsing(expat.XML_PARAM_ENTITY_PARSING_ALWAYS) parser.ExternalEntityRefHandler = self._buildForeign parser.UseForeignDTD() def _buildForeign(self, context, base, systemId, publicId): import StringIO parseableFile = StringIO.StringIO(default_external_dtd) original_parser = self._parser self._parser = self._parser.ExternalEntityParserCreate(context) self._parser.ParseFile(parseableFile) self._parser = original_parser return True def _push(self, ev, stuff): self._queue.append((ev, stuff)) def _push_location(self, ev, stuff): self._push(LOCATION, (self._parser.CurrentLineNumber, self._parser.CurrentColumnNumber)) self._push(ev, stuff) def _expat_stream(self): bufsize = 4 * 1024 # 4K feed = self.feed read = self._source.read more = True while more: while more and not self._queue: data = read(bufsize) if data == '': self.close() more = False else: feed(data) for item in self._queue: yield item self._queue = [] def __iter__(self): clarknames = {} def clarkname(key): try: name = clarknames[key] except KeyError: if "}" in key: name = "{" + key else: name = key clarknames[key] = name return name stack = [] current = None for ev, stuff in self._expat_stream(): if ev == TEXT: yield TEXT, stuff elif ev == START: tag, attrib = stuff tag = clarkname(tag) attrib = dict([(clarkname(key), value) for key, value in attrib.items()]) parent = current current = Element(tag, attrib) stack.append(current) yield START, current elif ev == END: current = stack.pop() assert clarkname(stuff) == current.tag parent = len(stack) and stack[-1] or None yield END, current elif ev == COMMENT: current = Comment(stuff) yield START, current yield END, current elif ev == PI: current = ProcessingInstruction(*stuff) yield START, current yield END, current else: yield ev, stuff def feed(self, data, isfinal=False): try: self._parser.Parse(data, isfinal) except expat.ExpatError, e: e.filename = self._filename e.source = self._source try: e = 'Error parsing XML%s:\n%s%s' % ( e.filename and e.filename != '' and (' file %r' % e.filename) or '', get_expat_error(e), str(e)) except Exception: pass raise expat.ExpatError(e) def close(self): if hasattr(self, '_parser'): try: self.feed('', True) # end of data finally: del self._parser # get rid of circular references def _start(self, tag, attrib): self.push(START, (tag, attrib)) def _data(self, text): self.push(TEXT, text) def _end(self, tag): self.push(END, tag) def _default(self, text): if text.startswith('&'): # deal with undefined entities try: self.push(TEXT, self.entity[text[1:-1]]) except KeyError: raise expat.error("undefined entity %s: line %d, column %d" % (text, self._parser.ErrorLineNumber, self._parser.ErrorColumnNumber)) else: # XXX not sure what should happen here. # This gets: \n at the end of documents?, " import sys from os.path import dirname, abspath from getopt import getopt, GetoptError as gerror try: from os import EX_OK, EX_DATAERR, EX_USAGE except ImportError: EX_OK, EX_DATAERR, EX_USAGE = 0, 1, 2 import kid def main(): # get options try: opts, args = getopt(sys.argv[1:], 'e:o:s:hV', ['encoding=', 'output=', 'server=', 'help', 'version']) except gerror, e: sys.stderr.write(str(e) + '\n') sys.stdout.write(__doc__) sys.exit(EX_USAGE) enc = 'utf-8' outfile = server = None for o, a in opts: if o in ('-e', '--encoding'): enc = a elif o in ('-o', '--output'): outfile = a elif o in ('-s', '--server'): server = a elif o in ('-h', '--help'): sys.stdout.write(__doc__) sys.exit(EX_OK) elif o in ('-V', '--version'): from kid import __version__ sys.stdout.write('Kid %s\n' % __version__) sys.exit(EX_OK) if server is None: if args: # get template file f = args.pop(0) sys.argv = [f] if f != '-': # make sure template dir is on sys.path path = abspath(dirname(f)) if not path in sys.path: sys.path.insert(0, path) else: f = sys.stdin.read() # get arguments for the template file kw = {} while args: a = args.pop(0).split('=', 1) if len(a) > 1: kw[a[0]] = a[1] else: sys.argv.append(a[0]) # do not run as __main__ module sys.modules['__kid_main__'] = sys.modules['__main__'] __name__ = '__kid_main__' del sys.modules['__main__'] # load kid template as __main__ module module = kid.load_template(f, name='__main__', cache=False) # execute the template and write output if not outfile: outfile = sys.stdout module.write(outfile, encoding=enc, **kw) else: sys.stderr.write('kid: No template file specified.\n') sys.stderr.write(" Try 'kid --help' for usage information.\n") sys.exit(EX_USAGE) else: if len(args) < 2: if outfile: stderr = file(outfile, 'a', 1) sys.stderr = stderr sys.stdout.write('Starting HTTP server ...\n') if args: # get base directory basedir = args.pop(0) from os import chdir chdir(basedir) from os import getcwd basedir = getcwd() sys.stdout.write('Base directory: %s\n' % basedir) if outfile: sys.stdout.write('Server log: %s\n' % outfile) if server == '-': server = 'localhost' sys.argv[1:] = [server] from kid.server import main main() if outfile: sys.stderr = sys.__stderr__ stderr.close() else: sys.stderr.write('kid: Server does not need additional arguments.\n') sys.stderr.write(" Try 'kid --help' for usage information.\n") sys.exit(EX_USAGE) if __name__ == '__main__': main() PKZ8ð6@ƒ(Oÿ€ÿ€kid/serialization.py# -*- coding: utf-8 -*- """Infoset serialization formats (XML, XHTML, HTML, etc)""" __revision__ = "$Rev: 492 $" __date__ = "$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " import htmlentitydefs try: set except NameError: # fallback for Python 2.3 from sets import Set as set from kid.element import Element, Comment, ProcessingInstruction, \ Fragment, QName, namespaces, encode_entity, raise_serialization_error import kid.namespace as namespace from kid.parser import START, END, TEXT, COMMENT, PI, _coalesce from kid.format import Format, output_formats __all__ = ['doctypes', 'Serializer', 'XMLSerializer', 'HTMLSerializer'] # bring in well known namespaces xml_uri = namespace.xml.uri xhtml_uri = namespace.xhtml.uri # This is the default entity map: default_entity_map = {} for k, v in htmlentitydefs.codepoint2name.items(): default_entity_map[unichr(k)] = "&%s;" % v # Some common doctypes. # You can pass doctype strings from here or doctype tuples to Serializers. doctypes = { 'wml': ('wml', "-//WAPFORUM//DTD WML 1.1//EN", "http://www.wapforum.org/DTD/wml_1.1.xml"), 'xhtml-strict': ('html', "-//W3C//DTD XHTML 1.0 Strict//EN", "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"), 'xhtml': ('html', "-//W3C//DTD XHTML 1.0 Transitional//EN", "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"), 'xhtml-frameset': ('html', "-//W3C//DTD XHTML 1.0 Frameset//EN", "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"), 'html-strict': ('HTML', "-//W3C//DTD HTML 4.01//EN", "http://www.w3.org/TR/html4/strict.dtd"), 'html': ('HTML', "-//W3C//DTD HTML 4.01 Transitional//EN", "http://www.w3.org/TR/html4/loose.dtd"), 'html-frameset': ('HTML', "-//W3C//DTD HTML 4.01 Frameset//EN", "http://www.w3.org/TR/html4/frameset.dtd"), 'html-quirks': ('HTML', '-//W3C//DTD HTML 4.01 Transitional//EN'), 'html-frameset-quirks': ('HTML', "-//W3C//DTD HTML 4.01 Frameset//EN") } class Serializer(object): namespaces = namespace.namespaces src_encoding = encoding = 'utf-8' format = output_formats['default'] formatted = False inline = False def __init__(self, encoding=None, src_encoding=None, formatted=None, inline=None, format=None): """Initialize Serializer. You can change the following parameters: encoding: the output encoding src_encoding: the source encoding formatted: whether all tags should be considered formatted inline: whether all tags should be considered inline format: format to be applied (string or instance of Format) """ if encoding is not None: self.encoding = encoding if src_encoding is not None: self.src_encoding = src_encoding if formatted is not None: self.formatted = formatted if inline is not None: self.inline = inline if format is not None: self.format = format self.format = self._get_format(format) def _get_format(self, format): if format is None: return self.format elif isinstance(format, basestring): return output_formats[format] else: return format def is_formatted(self, tagname): return self.formatted def is_inline(self, tagname): return self.inline def serialize(self, stream, encoding=None, fragment=False, format=None): try: text = ''.join(self.generate(stream, encoding, fragment, format)) except TypeError: # workaround for bug 905389 in Python < 2.5 text = ''.join(tuple( self.generate(stream, encoding, fragment, format))) if not fragment: text = Format.strip(text) return text def write(self, stream, file, encoding=None, fragment=False, format=None): needs_closed = False if not hasattr(file, 'write'): needs_closed = True file = open(file, 'wb') try: write = file.write for text in self.generate(stream, encoding, fragment, format): write(text) finally: # only close a file if it was opened locally if needs_closed: file.close() def generate(self, stream, encoding=None, fragment=False, format=None): pass def apply_filters(self, stream, format=None): stream = _coalesce(stream, self.src_encoding) if format: stream = self.format_stream(stream, format) return stream def format_stream(self, stream, format): """Apply format to stream. Note that this method is unaware of the serialization of the tags and does only take into account the text inside the stream. So the results may sometimes differ from what you expect when formatting the complete serialized output. """ filter_text = format.filter indent, wrap = format.indent, format.wrap if indent is not None: indent_lines = format.indent_lines lstrip_blanks = format.lstrip_blanks rstrip_blanks = format.rstrip_blanks lstrip_lines = format.lstrip_lines min_level, max_level = format.min_level, format.max_level indent_level = [] new_line = False if wrap is not None: wrap_lines = format.wrap_lines indent_width, new_offset = format.indent_width, format.new_offset offset = 0 formatted = 0 text = last_char = '' for ev, item in stream: if ev == TEXT: text += item else: if ev in (START, END): tag = item.tag if not formatted: text = filter_text(text, last_char) if indent is None: if wrap is not None: text = wrap_lines(text, wrap, offset) else: level = len(indent_level) if max_level and level > max_level: level = max_level if min_level: level -= min_level if level < 0: level = 0 if wrap is not None: text = wrap_lines(text, wrap, offset, indent_width(level*indent)) if '\n' in text and indent_level: indent_level[-1] = True if new_line: if lstrip_blanks(text)[:1] != '\n': text = '\n' + lstrip_blanks(text) offset = 0 new_line = False if tag == Comment or not self.is_inline(tag): if ev == START: if indent_level: if rstrip_blanks(text)[-1:] != '\n': text = rstrip_blanks(text) + '\n' text = indent_lines(text, level*indent) indent_level[-1] = True elif text: text = lstrip_lines(text) if tag != Comment \ and not self.is_formatted(tag): indent_level.append(False) else: if indent_level: if indent_level.pop(): if rstrip_blanks(text)[-1:] == '\n': text = rstrip_blanks(text)[:-1] text = indent_lines(text, level*indent) text = rstrip_blanks(text) + '\n' level = len(indent_level) if max_level and level > max_level: level = max_level if min_level: level -= min_level if level < 0: level = 0 text += level*indent elif text: text = lstrip_lines(text) new_line = True elif text: text = indent_lines(text, level*indent) if tag == Comment or self.is_formatted(tag): if ev == START: formatted += 1 elif formatted: formatted -= 1 new_line = True yield TEXT, text if wrap is not None: offset = new_offset(text, offset) last_char = text[-1:] text = '' yield ev, item if text: if not formatted: text = filter_text(text, last_char) if wrap is not None: text = wrap_lines(text, wrap, offset) if indent is None: if wrap is not None: text = wrap_lines(text, wrap, offset) else: level = len(indent_level) if max_level and level > max_level: level = max_level if min_level: level -= min_level if level < 0: level = 0 if wrap is not None: text = wrap_lines(text, wrap, offset, indent_width(level*indent)) if rstrip_blanks(text)[-1:] == '\n': text = text[:-1] text = indent_lines(text, level*indent) yield TEXT, text class XMLSerializer(Serializer): decl = True doctype = None entity_map = None def __init__(self, encoding=None, decl=None, doctype=None, entity_map=None, namespaces=None, formatted=None, inline=None, format=None): """Initialize XMLSerializer. You can change the following parameters: encoding: the output encoding decl: add xml declaration at the beginning (True/False) doctype: add doctype (None, string, tuple) entity_map: use named entities for output (True/False or mapping) namespaces: mapping of namespaces formatted: whether all tags should be considered formatted inline: whether all tags should be considered inline format: format to be applied (string or instance of Format) """ Serializer.__init__(self, encoding=encoding, format=format, formatted=formatted, inline=inline) if decl is not None: self.decl = decl if doctype is not None: self.doctype = doctype if entity_map is not None: self.entity_map = entity_map if namespaces is not None: self.namespaces = namespaces def can_be_empty_element(self, item_name): return True def generate(self, stream, encoding=None, fragment=False, format=None): """Serializes an event stream to bytes of the specified encoding. This function yields an encoded string over and over until the stream is exhausted. """ decl = self.decl doctype = self.doctype encoding = encoding or self.encoding or 'utf-8' entity_map = self.entity_map format = self._get_format(format) if format: if format.decl is not None: decl = format.decl if format.doctype is not None: doctype = format.doctype if format.entity_map is not None: entity_map = format.entity_map if entity_map == True: # if True, use default HTML entity map entity_map = default_entity_map elif entity_map == False: entity_map = None if isinstance(doctype, basestring): # allow doctype strings doctype = doctypes[self.doctype] escape_cdata = XMLSerializer.escape_cdata escape_attrib = XMLSerializer.escape_attrib lastev = None stream = iter(stream) names = NamespaceStack(self.namespaces) if not fragment: if decl: yield '\n' % encoding if doctype is not None: yield serialize_doctype(doctype) + '\n' text = None for ev, item in self.apply_filters(stream, format): if ev in (START, END) and item.tag == Fragment: continue elif ev == TEXT: if text is not None: text = u''.join([text, item]) else: text = item continue if lastev == START: if ev == END and (not text or not (Format.strip(text) or self.is_formatted(item.tag))) \ and self.can_be_empty_element(item.tag): yield ' />' lastev = END text = None names.pop() continue yield ">" if text: yield escape_cdata(text, encoding, entity_map) text = None if ev == START: if item.tag == Comment: yield "" % item.text.encode(encoding) lastev = COMMENT continue elif item.tag == ProcessingInstruction: yield "" % item.text.encode(encoding) lastev = PI continue else: current_names = names.current names.push(namespaces(item, remove=True)) qname = names.qname(item.tag, default=True) yield "<" + qname.encode(encoding) for k, v in item.attrib.items(): k = names.qname(k, default=False).encode(encoding) v = escape_attrib(v, encoding) yield ' %s="%s"' % (k, v) for prefix, uri in names.current.items(): if prefix not in current_names \ or current_names[prefix] != uri: v = escape_attrib(uri, encoding) if prefix: k = 'xmlns:' + prefix.encode(encoding) else: k = 'xmlns' yield ' %s="%s"' % (k, v) elif ev == END and item.tag not in ( Comment, ProcessingInstruction): qname = names.qname(item.tag, default=True) yield "" % qname.encode(encoding) names.pop() lastev = ev if fragment and text: yield escape_cdata(text, encoding, entity_map) return def escape_cdata(text, encoding=None, entity_map=None): """Escape character data.""" try: if encoding: try: text = text.encode(encoding) except UnicodeError: return encode_entity(text, entities=entity_map) text = text.replace("&", "&") text = text.replace("<", "<") except (TypeError, AttributeError): raise_serialization_error(text) return text escape_cdata = staticmethod(escape_cdata) def escape_attrib(text, encoding=None, entity_map=None): """Escape attribute value.""" try: if encoding: try: text = text.encode(encoding) except UnicodeError: return encode_entity(text, entities=entity_map) text = text.replace("&", "&") text = text.replace("<", "<") text = text.replace("\"", """) except (TypeError, AttributeError): raise_serialization_error(text) return text escape_attrib = staticmethod(escape_attrib) class HTMLBased(object): """Mixin class for HTML based serializers.""" inject_type = None empty_elements = set([ 'area', 'base', 'basefont', 'br', 'col', 'frame', 'hr', 'img', 'input', 'isindex', 'link', 'meta', 'param']) formatted_elements = set([ 'code', 'kbd', 'math', 'pre', 'script', 'textarea']) inline_elements = set(['a', 'abbr', 'acronym', 'b', 'basefont', 'bdo', 'big', 'br', 'cite', 'code', 'dfn', 'em', 'font', 'i', 'img', 'input', 'kbd', 'label', 'q', 's', 'samp', 'select', 'small', 'span', 'strike', 'strong', 'sub', 'sup', 'textarea', 'tt', 'u', 'var']) def can_be_empty_element(self, tag): return self.tagname(tag) in self.empty_elements def is_formatted(self, tag): return self.tagname(tag) in self.formatted_elements def is_inline(self, tag): return self.tagname(tag) in self.inline_elements def is_escape(self, tag): return self.tagname(tag) not in self.noescape_elements def inject_meta_content_type(self, stream, encoding): """Injects a meta tag for the content-type.""" return self.inject_meta_tags(stream, [{'http-equiv': 'content-type', 'content': 'text/html; charset=%s' % encoding}]) def inject_meta_tags(self, stream, taglist): """Injects meta tags at the start of the head section. If meta tags already exist at that position, they are kept. Expects a list of meta-tag attributes with content keys. The attribute names and values must be given in lower case. """ done = False meta_tag = None for ev, item in stream: if not done: if ev in (START, END): tag = self.tagname(item.tag) if meta_tag: if item.tag == meta_tag: if ev == START: for attributes in taglist: for attrib, value in item.items(): attrib = attrib.lower() if attrib == 'content': continue if attrib not in attributes: break value = value.lower() if attributes[attrib] != value: break else: # that meta tag exists already attributes['content'] = None break else: for attributes in taglist: if attributes['content'] is None: continue meta_item = Element(meta_tag, **attributes) yield START, meta_item yield END, meta_item yield TEXT, '\n' done = True elif tag == 'head' and ev == START: meta_tag = item.tag[:-4] + 'meta' yield ev, item class HTMLSerializer(HTMLBased, Serializer): doctype = doctypes['html'] transpose = False inject_type = True entity_map = None noescape_elements = set([ 'script', 'style']) boolean_attributes = set( ['selected', 'checked', 'compact', 'declare', 'defer', 'disabled', 'ismap', 'multiple', 'nohref', 'noresize', 'noshade', 'nowrap']) def __init__(self, encoding='utf-8', doctype=None, transpose=False, inject_type=None, entity_map=None, format=None): """Initialize HTMLSerializer. You can change the following parameters: encoding: the output encoding doctype: add doctype (None, string, tuple) transpose: alter tag names (None, True/False, callable) inject_type: inject content type (True/False) entity_map: use named entities for output (True/False or mapping) format: format to be applied (string or instance of Format) """ Serializer.__init__(self, encoding=encoding, format=format) if doctype is not None: self.doctype = doctype self.transpose = transpose if inject_type is not None: self.inject_type = inject_type if entity_map is not None: self.entity_map = entity_map def tagname(tag): """Remove namespace from tag and make it lowercase.""" if isinstance(tag, basestring): if tag.startswith('{'): tag = tag.split('}', 1)[-1] tag = tag.lower() return tag tagname = staticmethod(tagname) def is_escape(self, tag): return self.tagname(tag) not in self.noescape_elements def is_boolean_attribute(self, attribute): return attribute in self.boolean_attributes def generate(self, stream, encoding=None, fragment=False, format=None): """Serializes an event stream to bytes of the specified encoding. This function yields an encoded string over and over until the stream is exhausted. """ doctype = self.doctype encoding = encoding or self.encoding or 'utf-8' entity_map = self.entity_map transpose = self.transpose inject_type = self.inject_type format = self._get_format(format) if format: if format.doctype is not None: doctype = format.doctype if format.entity_map is not None: entity_map = format.entity_map if format.transpose is not None: transpose = format.transpose if format.inject_type is not None: inject_type = format.inject_type if entity_map == True: # if True, use default HTML entity map entity_map = default_entity_map elif entity_map == False: entity_map = None if isinstance(doctype, basestring): # allow doctype strings doctype = doctypes[self.doctype] if transpose is not None: if not callable(transpose): if transpose: transpose = lambda s: s.upper() else: transpose = lambda s: s.lower() escape_cdata = HTMLSerializer.escape_cdata escape_attrib = HTMLSerializer.escape_attrib names = NamespaceStack(self.namespaces) def grok_name(tag): if tag[0] == '{': uri, localname = tag[1:].split('}', 1) else: uri, localname = None, tag if uri and uri != xhtml_uri: qname = names.qname(tag, default=False) else: qname = localname if transpose: qname = transpose(qname) return uri, localname, qname current = None stack = [current] stream = iter(stream) if not fragment and doctype is not None: yield serialize_doctype(doctype) + '\n' if inject_type and encoding: stream = self.inject_meta_content_type(stream, encoding) for ev, item in self.apply_filters(stream, format): if ev == TEXT and item: escape = self.is_escape(current) yield escape_cdata(item, encoding, entity_map, escape) elif ev == START: if item.tag == Comment: yield "" % item.text.encode(encoding) continue elif item.tag == ProcessingInstruction: yield "" % item.text.encode(encoding) continue elif item.tag == Fragment: continue else: names.push(namespaces(item, remove=True)) tag = item.tag qname = grok_name(tag)[2] # push this name on the stack so we know where we are current = qname.lower() stack.append(current) yield "<" + qname.encode(encoding) attrs = item.attrib.items() if attrs: for k, v in attrs: q = grok_name(k)[2] lq = q.lower() if lq == 'xml:lang': continue if self.is_boolean_attribute(lq): # XXX: what if v is 0, false, or no. # should we omit the attribute? yield ' %s' % q.encode(encoding) else: yield ' %s="%s"' % ( q.encode(encoding), escape_attrib(v, encoding, entity_map)) yield ">" elif ev == END and item.tag not in ( Comment, ProcessingInstruction, Fragment): current = stack.pop() if not self.can_be_empty_element(current): tag = item.tag qname = grok_name(tag)[2] yield "" % qname.encode(encoding) current = stack[-1] names.pop() def escape_cdata(text, encoding=None, entity_map=None, escape=True): """Escape character data.""" try: if encoding: try: text = text.encode(encoding) except UnicodeError: return encode_entity(text, entities=entity_map) if escape: text = text.replace("&", "&") text = text.replace("<", "<") except (TypeError, AttributeError): raise_serialization_error(text) return text escape_cdata = staticmethod(escape_cdata) def escape_attrib(text, encoding=None, entity_map=None): """Escape attribute value.""" try: if encoding: try: text = text.encode(encoding) except UnicodeError: return encode_entity(text, entities=entity_map) text = text.replace("&", "&") text = text.replace("\"", """) except (TypeError, AttributeError): raise_serialization_error(text) return text escape_attrib = staticmethod(escape_attrib) class XHTMLSerializer(HTMLBased, XMLSerializer): doctype = doctypes['xhtml'] inject_type = True def __init__(self, encoding='utf-8', decl=None, doctype=None, inject_type=None, entity_map=None, namespaces=None, format=None): """Initialize XHTMLSerializer.""" XMLSerializer.__init__(self, encoding=encoding, decl=decl, doctype=doctype, entity_map=entity_map, namespaces=namespaces, format=format) if inject_type is not None: self.inject_type = inject_type def tagname(tag): """Remove namespace from tag.""" if isinstance(tag, basestring) and tag.startswith('{%s}' % xhtml_uri): tag = tag.split('}', 1)[-1] return tag tagname = staticmethod(tagname) def generate(self, stream, encoding=None, fragment=False, format=None): encoding = encoding or self.encoding or 'utf-8' inject_type = self.inject_type format = self._get_format(format) if format: if format.inject_type is not None: inject_type = format.inject_type if inject_type and encoding: stream = self.inject_meta_content_type(stream, encoding) return XMLSerializer.generate(self, stream, encoding=encoding, fragment=fragment, format=format) class PlainSerializer(Serializer): def generate(self, stream, encoding=None, fragment=False, format=None): """Generate only the text content.""" encoding = encoding or self.encoding or 'utf-8' for ev, item in self.apply_filters(stream, format): if ev == TEXT: yield item class NamespaceStack: """Maintains a stack of namespace prefix to URI mappings.""" def __init__(self, default_map=namespace.namespaces): self.stack = [] self.default_map = default_map self.push() self.ns_count = 0 def push(self, names=None): if names is None: names = {} self.current = names self.stack.insert(0, self.current) def pop(self): names = self.stack.pop(0) if self.stack: self.current = self.stack[0] return names def resolve_prefix(self, uri, default=True): """Figure out prefix given a URI.""" if uri == xml_uri: return 'xml' # first check if the default is correct is_default = None prefix = None for names in self.stack: for p, u in names.items(): if default and is_default is None and not p: # this is the current default namespace is_default = (u == uri) if (default and is_default) or prefix: break if u == uri and p: prefix = p if is_default is not None: break if default and is_default == True: return '' elif prefix: return prefix else: return None def resolve_uri(self, prefix): """Figure out URI given a prefix.""" if prefix == 'xml': return xml_uri for names in self.stack: uri = names.get(prefix) if uri: return uri return None def qname(self, cname, default=False): if isinstance(cname, QName): cname = cname.text if cname[0] != '{': # XXX: need to make sure default namespace is "no-namespace" return cname uri, localname = cname[1:].split('}', 1) prefix = self.resolve_prefix(uri, default) if prefix is None: # see if we have it in our default map prefix = self.default_map.get(uri) if prefix is not None: self.current[prefix] = uri else: if default and not self.current.has_key(''): prefix = '' self.current[prefix] = uri else: self.ns_count += 1 # XXX : need to check for collisions here. prefix = 'ns%d' % self.ns_count self.current[prefix] = uri if prefix != '': return '%s:%s' % (prefix, localname) else: return localname def serialize_doctype(doctype): if isinstance(doctype, basestring): return doctype elif len(doctype) == 1: return '' % doctype elif len(doctype) == 2: return '' % doctype else: return '' % doctype PKZ8ð6k"-¬(¬(kid/template_util.py# -*- coding: utf-8 -*- """Utility functions used by generated kid modules.""" __revision__ = "$Rev: 492 $" __date__ = "$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " import inspect import sys from types import TypeType, ModuleType, ClassType, GeneratorType import itertools # these are for use by template code import kid from kid.parser import XML, document, ElementStream, START, END, TEXT, \ START_NS, COMMENT, PI, DOCTYPE, XML_DECL, to_unicode from kid.element import Element, SubElement, Comment, ProcessingInstruction __all__ = ['XML', 'document', 'ElementStream', 'Element', 'SubElement', 'Comment', 'ProcessingInstruction', 'START', 'END', 'TEXT', 'START_NS', 'COMMENT', 'PI', 'DOCTYPE', 'XML_DECL'] class TemplateError(Exception): pass class TemplateNotFound(TemplateError): pass class TemplateImportError(TemplateError): pass class TemplateDictError(TemplateError): pass class TemplateAttrsError(TemplateError): pass class TemplateExtendsError(TemplateError): pass class TemplateLayoutError(TemplateError): pass _local_excludes = ['generate', 'module', 'parser', 'serialize', 'transform', 'write'] def get_locals(inst, _locals=None): if _locals is None: _locals = {} ls = [] local_excludes = _local_excludes # local copy for var, value in inspect.getmembers(inst): if not var.startswith('_') and not var in local_excludes \ and var not in _locals: ls.append('%s=self.%s' % (var, var)) return ';'.join(ls) def get_base_class(thing, from_file=None, arg=None): """Get template base class for thing, raising an exception on error.""" if thing is None: return kid.BaseTemplate if isinstance(thing, TypeType): return thing elif isinstance(thing, ModuleType): try: cls = thing.Template except AttributeError: cls = None if (isinstance(cls, TypeType) and issubclass(cls, kid.BaseTemplate) and cls != kid.Template): return cls thing = repr(thing) if arg: thing = arg else: try: thing = thing.__name__ except AttributeError: thing = repr(thing) raise TemplateNotFound( '%s is a module without Template class' % thing) elif isinstance(thing, basestring): try: path = kid.path.find(thing, from_file) except Exception: path = None if not path: if arg: thing = arg raise TemplateNotFound('Template file %r not found' % thing) try: mod = kid.load_template(path) except Exception: mod = None if not mod: raise TemplateNotFound('Could not open %r' % path) try: cls = mod.Template except AttributeError: cls = None if (isinstance(cls, TypeType) and issubclass(cls, kid.BaseTemplate) and cls != kid.Template): return cls raise TemplateNotFound('%r does not contain a template class' % path) thing = repr(thing) if arg: thing = '%s (%s)' % (arg, thing) raise TemplateNotFound('%s is not a Template class' % thing) def base_class(arg, globals, locals): """Get base class for argument with graceful exception handling.""" try: from_file = globals['__file__'] thing = eval(arg, globals, locals) return get_base_class(thing, from_file, arg) except Exception, e: errors = [str(e)] # try again without evaluating the argument (forgotten quotes etc.) try: return get_base_class(arg, from_file, arg) except Exception, e: errors.append(str(e)) # reraise the original problem when we tried to evaluate the thing errors = '\n'.join(filter(bool, errors)) or arg raise TemplateNotFound, errors def base_class_extends(extends, globals, locals, all_extends=None): """Get Template base class for 'extends'.""" try: return base_class(extends, globals, locals) except Exception, e: raise TemplateExtendsError((str(e) + '\nwhile processing extends=%r' % (all_extends or extends)).lstrip()) def base_class_layout(layout, globals, locals): """Get Template base class for 'layout'.""" try: return base_class(layout, globals, locals) except Exception, e: raise TemplateLayoutError((str(e) + '\nwhile processing layout=%r' % layout).lstrip()) def make_attrib(attrib, encoding=None): """Generate unicode strings in dictionary.""" if attrib is None: return {} if encoding is None: encoding = sys.getdefaultencoding() for (k, v) in attrib.items(): if v is not None: try: v = generate_attrib(v, encoding) except TemplateAttrsError: raise TemplateAttrsError('Illegal value for attribute "%s"' % k.encode('raw_unicode_escape')) if v is None: del attrib[k] else: attrib[k] = v return attrib def generate_attrib(attrib, encoding): """Generate unicode string from attribute.""" if attrib is None: return None elif isinstance(attrib, basestring): return to_unicode(attrib, encoding) elif isinstance(attrib, ElementStream): text = [] for ev, item in attrib: if ev == TEXT: text.append(to_unicode(item, encoding)) else: raise TemplateAttrsError if text: return ''.join(text) else: return None elif hasattr(attrib, '__iter__'): # if we get any other iterable, join the strings together: text = [] for item in attrib: if item is not None: item = generate_attrib(item, encoding) if item is not None: text.append(item) if text: return ''.join(text) else: return None else: return to_unicode(attrib, encoding) def generate_content(content): """Generate ElementStream from content.""" if content is None: return [] elif isinstance(content, basestring): return [(TEXT, content)] elif isinstance(content, (ElementStream, kid.BaseTemplate)): return content elif isinstance(content, GeneratorType): return ElementStream(content) elif hasattr(content, 'tag') and hasattr(content, 'attrib'): # if we get an Element back, make it an ElementStream return ElementStream(content) elif hasattr(content, '__iter__'): # if we get any other iterable, chain the contents together: return itertools.chain(*itertools.imap(generate_content, content)) else: return [(TEXT, unicode(content))] def filter_names(names, omit_list): for ns in names.keys(): if ns in omit_list: del names[ns] return names def update_dict(a, args, globals, locals): """Update dictionary a from keyword argument string args.""" try: b = eval('%s' % args, globals, locals) if not isinstance(b, dict): b = dict(b) except Exception: try: b = eval('dict(%s)' % args, globals, locals) except SyntaxError: # TypeErrror could happen with Python versions < 2.3, because # building dictionaries from keyword arguments was not supported. # Kid requires a newer Python version, so we do not catch this. # SyntaxError can happen if one of the keyword arguments is # the same as a Python keyword (e.g. "class") or if it is # a qualified name containing a namespace prefixed with a colon. # In these cases we parse the keyword arguments manually: try: try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from tokenize import generate_tokens from token import NAME, OP depth, types, parts = 0, [], [] for token in generate_tokens(StringIO(args).readline): type_, string = token[:2] if type_ == OP: if string == '=': if depth == 0: if len(types) > 0 \ and types[-1] == NAME and parts[-1]: if len(types) > 2 \ and types[-2] == OP and parts[-2] == ':' \ and types[-3] == NAME and parts[-3]: parts[-3:] = ["'%s'" % ''.join(parts[-3:])] else: parts[-1] = "'%s'" % parts[-1] string = ':' elif string in '([{': depth += 1 elif depth > 0 and string in ')]}': depth -= 1 types.append(type_) parts.append(string) b = eval('{%s}' % ''.join(parts), globals, locals) except Exception: b = None if not isinstance(b, dict): raise for k in b.keys(): if b[k] is None: del b[k] if k in a: del a[k] a.update(b) return a def update_attrs(attrib, attrs, globals, locals): """Update attributes from attrs string args.""" try: return update_dict(attrib, attrs, globals, locals) except Exception, e: raise TemplateAttrsError((str(e) + '\nwhile processing attrs=%r' % attrs).lstrip()) def make_updated_attrib(attrib, attrs, globals, locals, encoding=None): """"Generate unicode strings in updated dictionary.""" return make_attrib(update_attrs(attrib, attrs, globals, locals), encoding) PKZ8ð6.pª‡"‡" kid/server.py# -*- coding: utf-8 -*- """Kid-savvy HTTP Server. Written by Christoph Zwerschke based on CGIHTTPServer 0.4. This module builds on SimpleHTTPServer by implementing GET and POST requests to Kid templates. In all cases, the implementation is intentionally naive -- all requests are executed by the same process and sychronously. Code to create and run the server looks like this: from kid.server import HTTPServer host, port = 'localhost', 8000 HTTPServer((host, port)).serve_forever() This serves files and kid templates from the current directory and any of its subdirectories. If you want the server to be accessible via the network, use your local host name or an empty string as the host. (Security warning: Don't do this unless you are inside a firewall.) You can also call the test() function to run the server, or run this module as a script, providing host and port as command line arguments. The Kid templates have access to the following predefined objects: FieldStorage (access to GET/POST variables) environ (CGI environment) request (the request handler object) Here is a simple Kid template you can use to test the server: Python Expression Evaluator

${FieldStorage.getvalue('expr')} = ${eval(FieldStorage.getvalue('expr'))}

Enter a Python expression:

""" __revision__ = "$Rev: 492 $" __date__ = "$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $" __author__ = "Christoph Zwerschke (cito@online.de)" __copyright__ = "Copyright 2005, Christoph Zwerschke" __license__ = "MIT " import os.path from urllib import unquote from BaseHTTPServer import HTTPServer as BaseHTTPServer from SimpleHTTPServer import SimpleHTTPRequestHandler from cgi import FieldStorage from kid import load_template __all__ = ["HTTPServer", "HTTPRequestHandler"] default_host = 'localhost' default_port = 8000 class HTTPRequestHandler(SimpleHTTPRequestHandler): """Complete HTTP server with GET, HEAD and POST commands. GET and HEAD also support running Kid templates. The POST command is *only* implemented for Kid templates.""" def do_POST(self): """Serve a POST request implemented for Kid templates.""" if self.is_kid(): self.run_kid() else: self.send_error(501, "Can only POST to Kid templates") def send_head(self): """Version of send_head that supports Kid templates.""" if self.is_kid(): return self.run_kid() else: return SimpleHTTPRequestHandler.send_head(self) def is_kid(self): """Test whether self.path corresponds to a Kid template. The default implementation tests whether the path ends with one of the strings in the list self.kid_extensions. """ path = self.path i = path.rfind('?') if i >= 0: path, query = path[:i], path[i+1:] else: query = '' for x in self.kid_extensions: if path.endswith(x): self.cgi_info = path, query return True return False kid_extensions = ['.kid', '.kid.html'] def run_kid(self): """Execute a Kid template.""" scriptname, query = self.cgi_info scriptfile = self.translate_path(scriptname) if not os.path.exists(scriptfile): self.send_error(404, "No such Kid template (%r)" % scriptname) return if not os.path.isfile(scriptfile): self.send_error(403, "Kid template is not a plain file (%r)" % scriptname) return env = {} env['SERVER_SOFTWARE'] = self.version_string() env['SERVER_NAME'] = self.server.server_name env['GATEWAY_INTERFACE'] = 'CGI/1.1' env['SERVER_PROTOCOL'] = self.protocol_version env['SERVER_PORT'] = str(self.server.server_port) env['REQUEST_METHOD'] = self.command uqpath = unquote(scriptname) env['PATH_INFO'] = uqpath env['PATH_TRANSLATED'] = self.translate_path(uqpath) env['SCRIPT_NAME'] = scriptname if query: env['QUERY_STRING'] = query host = self.address_string() if host != self.client_address[0]: env['REMOTE_HOST'] = host env['REMOTE_ADDR'] = self.client_address[0] authorization = self.headers.getheader("authorization") if authorization: authorization = authorization.split() if len(authorization) == 2: import base64, binascii env['AUTH_TYPE'] = authorization[0] if authorization[0].lower() == "basic": try: authorization = base64.decodestring(authorization[1]) except binascii.Error: pass else: authorization = authorization.split(':') if len(authorization) == 2: env['REMOTE_USER'] = authorization[0] if self.headers.typeheader is None: env['CONTENT_TYPE'] = self.headers.type else: env['CONTENT_TYPE'] = self.headers.typeheader length = self.headers.getheader('content-length') if length: env['CONTENT_LENGTH'] = length accept = [] for line in self.headers.getallmatchingheaders('accept'): if line[:1] in "\t\n\r ": accept.append(line.strip()) else: accept = accept + line[7:].split(',') env['HTTP_ACCEPT'] = ','.join(accept) ua = self.headers.getheader('user-agent') if ua: env['HTTP_USER_AGENT'] = ua co = filter(None, self.headers.getheaders('cookie')) if co: env['HTTP_COOKIE'] = ', '.join(co) self.send_response(200, "Script output follows") # Execute template in this process try: template_module = load_template(scriptfile, cache=True) template = template_module.Template( request=self, environ=env, FieldStorage=FieldStorage(self.rfile, environ=env)) s = str(template) self.send_header("Content-type", "text/html") self.send_header("Content-Length", str(len(s))) self.end_headers() self.wfile.write(s) except Exception, e: self.log_error("Kid template exception: %s", str(e)) else: self.log_message("Kid template exited OK") class HTTPServer(BaseHTTPServer): def __init__(self, server_address=None, RequestHandlerClass=HTTPRequestHandler): if server_address is None: server_address = (default_host, default_port) BaseHTTPServer.__init__(self, server_address, HTTPRequestHandler) def test(server_address=None, HandlerClass=HTTPRequestHandler, ServerClass=HTTPServer, protocol="HTTP/1.0"): """Test the HTTP request handler class.""" HandlerClass.protocol_version = protocol server = ServerClass(server_address, HandlerClass) sa = server.socket.getsockname() print "Serving HTTP on", sa[0], "port", sa[1], "..." server.serve_forever() def main(): """This runs the Kid-savvy HTTP server. Provide host and port as command line arguments. The current directory serves as the root directory. """ from sys import argv, exit if len(argv) > 3: print "Usage:", argv[0], "[host]:[port]" exit(2) if len(argv) < 2: server_address = (default_host, default_port) else: if len(argv) == 3: host = argv[1] port = argv[2] else: host = argv[1].split(':', 1) if len(host) < 2: host = host[0] if host.isdigit(): port = host host = '' else: port = None else: host, port = host if port: if port.isdigit(): port = int(port) else: print "Bad port number." exit(1) else: port = default_port server_address = (host, port) test(server_address) if __name__ == '__main__': main() PKY8ð6ð]ÝdUdU kid/format.py# -*- coding: utf-8 -*- """Infoset serialization format styles. This modules provides methods assisting the serialization module in formatting the text content of serialized infosets. The methods for "educating" and "stupefying" typographic characters have been inspired by John Gruber's "SmartyPants" project (http://daringfireball.net/projects/smartypants/, see also http://web.chad.org/projects/smartypants.py/). """ __revision__ = "$Rev: 492 $" __date__ = "$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $" __author__ = "Christoph Zwerschke (cito@online.de)" __copyright__ = "Copyright 2006, Christoph Zwerschke" __license__ = "MIT " import re __all__ = ['Format', 'output_formats'] class Format(object): """Formatting details for Serializers.""" # Default values for some parameters: wrap = 80 indent = '\t' min_level, max_level = 1, 8 tabsize = 8 apostrophe = u'\u2019' squotes = u'\u2018\u2019' dquotes = u'\u201c\u201d' dashes = u'\u2013\u2014' ellipsis = u'\u2026' # Regular expressions used by the Format class: re_whitespace = re.compile(r'[ \t\n\r]+') re_leading_blanks = re.compile(r'^[ \t]+', re.MULTILINE) re_trailing_blanks = re.compile(r'[ \t]+$', re.MULTILINE) re_duplicate_blanks = re.compile(r'[ \t]{2,}') re_duplicate_newlines = re.compile(r'\n[ \t\n\r]*\n') re_whitespace_with_newline = re.compile(r'[ \t]*\n[ \t\n\r]*') re_indentation = re.compile(r'\n[ \t]*') re_squotes = re.compile(r"'") re_dquotes = re.compile(r'"') re_sbackticks = re.compile(r"`") re_dbackticks = re.compile(r"(? width > 0: t.append('\n') offset = indent + len(word) t.append(word) for word in s: offset += len(word) + 1 if offset <= width: t.append(' ') else: t.append('\n') offset = indent + len(word) t.append(word) return ''.join(t) # Auxiliary functions for indentation and word wrapping def indent_width(indent, tabsize=tabsize): """Calculate width of indentation.""" if indent.startswith('\t'): width = len(indent) indent = indent.lstrip('\t') width -= len(indent) width *= tabsize width += len(indent) else: width = len(indent) return width indent_width = staticmethod(indent_width) def new_offset(s, offset=0): """Calculate new offset after appending a string.""" n = s.rfind('\n') if n < 0: offset += len(s) else: offset = Format.indent_width(s[n+1:]) return offset new_offset = staticmethod(new_offset) # create some predefined serialization formats... output_formats = { 'default': Format(no_empty_lines=True), 'straight': Format(), 'compact': Format(simple_whitespace=True), 'newlines': Format(simple_whitespace=True, indent=''), 'pretty': Format(simple_whitespace=True, indent='\t'), 'wrap': Format(wrap=True, indent=''), 'nice': Format(no_empty_lines=True, nice=True), 'ugly': Format(no_empty_lines=True, ugly=True), 'named': Format(no_empty_lines=True, named=True), 'compact+named': Format(simple_whitespace=True, named=True), 'newlines+named': Format(simple_whitespace=True, indent='', named=True), 'pretty+named': Format(simple_whitespace=True, indent='\t', named=True), 'wrap+named': Format(wrap=True, indent='', named=True), 'compact+nice': Format(simple_whitespace=True, nice=True), 'newlines+nice': Format(simple_whitespace=True, indent='', nice=True), 'pretty+nice': Format(simple_whitespace=True, indent='\t', nice=True), 'wrap+nice': Format(wrap=True, indent='', nice=True), 'nice+named': Format(no_empty_lines=True, nice=True, named=True), 'compact+named+nice': Format(simple_whitespace=True, nice=True, named=True), 'newlines+named+nice': Format(simple_whitespace=True, indent='', nice=True), 'pretty+named+nice': Format(simple_whitespace=True, indent='\t', nice=True, named=True), 'wrap+named+nice': Format(wrap=True, indent='', nice=True, named=True), } PKZ8ð6Eû©‡‡ kid/util.py# -*- coding: utf-8 -*- """Utility functions for Kid.""" __revision__ = "$Rev: 492 $" __date__ = "$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " from urllib import splittype class QuickTextReader(object): def __init__(self, text): self.text = text self.len = len(self.text) self.pos = 0 self.lines = None def __iter__(self): while 1: if self.lines is None: self.lines = self.text.splitlines(True) if not self.lines: break yield self.lines.pop(0) def close(self): self.text = None self.pos = self.len = 0 self.lines = None def read(self, size=None): if size is not None: try: size = int(size) except: size = None else: if not 0 <= size < self.len: size = None pos = self.pos if size is None: self.pos = self.len return self.text[pos:] else: self.pos += size if self.pos > self.len: self.pos = self.len return self.text[pos:self.pos] def seek(self, offset, whence=0): if whence: if whence == 2: self.pos = self.len - offset else: self.pos += offset else: self.pos = offset self.lines = None if self.pos < 0: self.pos = 0 elif self.pos > self.len: self.pos = self.len def tell(self): return self.pos def next(self): if not self.lineno: self.lines = self.splitlines(True) self.lineno += 1 if not self.lines: raise StopIteration return self.lines.pop(0) def xml_sniff(text): """Sniff text to see if it looks like XML. Return True if text looks like XML, otherwise return False. """ for x in text: if x in '\t\r\n ': continue elif x == '<': return True else: return False def open_resource(uri, mode='rb'): """Generic resource opener.""" scheme, rest = splittype(uri) if not scheme or (len(scheme) == 1 and rest.startswith('\\')): return open(uri, mode) else: import urllib2 return urllib2.urlopen(uri) def get_expat_error(error): """Return text showing the position of an Expat error.""" source, lineno, offset = error.source, error.lineno, error.offset if lineno < 1: lineno = 1 offset = 0 source.seek(0) nlines = 0 for line in source: lineno -= 1 nlines += 1 if not lineno: break else: offset = 0 if nlines: if nlines == 1: if line.startswith('\xef\xbb\xbf'): line = line[3:] if line: if offset < 0: offset = 0 elif offset > len(line): offset = len(line) if offset > 75: if len(line) - offset > 37: line = line[offset-38:offset+38] offset = 38 else: offset -= len(line) - 76 line = line[-76:] else: line = line[:76] if line: line = '%s\n%%%ds\n' % (line.rstrip(), offset + 1) line = line % '^' return line PKY8ð6½§¦KQQkid/element.py# -*- coding: utf-8 -*- """A partial implementation of ElementTree and some extensions.""" __revision__ = "$Rev: 492 $" __date__ = "$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " import re __all__ = ['Element', 'SubElement', 'Comment', 'ProcessingInstruction', 'Fragment', 'QName', 'namespaces', 'escape_map', 'encode_entity', 'raise_serialization_error'] class Element(object): """A class representing an XML element.""" text = None tail = None def __init__(self, tag, attrib={}, **extra): attrib = attrib.copy() attrib.update(extra) self.tag = tag self.attrib = attrib self._children = [] def __repr__(self): return "" % (self.tag, id(self)) # Methods for dealing with children - a list interface def __len__(self): return len(self._children) def __getitem__(self, index): return self._children[index] def __setitem__(self, index, element): assert isinstance(element, Element) self._children[index] = element def __delitem__(self, index): del self._children[index] def __getslice__(self, start, stop): return self._children[start:stop] def __setslice__(self, start, stop, elements): for element in elements: assert isinstance(element, Element) self._children[start:stop] = list(elements) def __delslice__(self, start, stop): del self._children[start:stop] def append(self, element): assert isinstance(element, Element) self._children.append(element) def insert(self, index, element): assert isinstance(element, Element) self._children.insert(index, element) def remove(self, element): assert isinstance(element, Element) self._children.remove(element) def getchildren(self): return self._children def clear(self): self.attrib.clear() self._children = [] self.text = self.tail = None # Methods for dealing with attributes - a dictionary like interface def get(self, key, value=None): return self.attrib.get(key, value) def set(self, key, value): self.attrib[key] = value def keys(self): return self.attrib.keys() def items(self): return self.attrib.items() def SubElement(parent, tag, attrib={}, **extra): attrib = attrib.copy() attrib.update(extra) element = Element(tag, attrib) parent.append(element) return element def Comment(text=None): """Comment element factory.""" elem = Element(Comment) elem.text = text return elem def ProcessingInstruction(target, text=None): """PI element factory.""" elem = Element(ProcessingInstruction) elem.text = target if text: elem.text += " " + text return elem def Fragment(text=''): """XML fragment factory. Fragments hold TEXT and children but do not have a tag or attributes. """ elem = Element(Fragment) elem.text = text return elem class QName: def __init__(self, text_or_uri, tag=None): if tag: text_or_uri = "{%s}%s" % (text_or_uri, tag) self.text = text_or_uri def __str__(self): return self.text def namespaces(elem, remove=False): """Get the namespace declarations for an Element. This function looks for attributes on the Element provided that have the following characteristics: * Begin with 'xmlns:' and have no namespace URI. * Are named 'xmlns' and have no namespace URI. The result is a dictionary containing namespace prefix -> URI mappings. Default namespace attributes result in a key of ''. If remove is truthful, namespace declaration attributes are removed from the passed in Element. """ names = {} for k in elem.keys(): if k.startswith('xmlns:'): names[k[6:]] = elem.get(k) if remove: del elem.attrib[k] elif k == 'xmlns': names[''] = elem.get(k) if remove: del elem.attrib[k] return names escape_map = { "&": "&", "<": "<", ">": ">", '"': """, } re_escape = re.compile(eval(r'u"[&<>\"\u0080-\uffff]+"')) def encode_entity(text, pattern=re_escape, entities=None): if entities is None: entities = escape_map # map reserved and non-ascii characters to XML entities def escape_entities(m, entities=entities): out = [] for char in m.group(): text = entities.get(char) if text is None: text = "&#%d;" % ord(char) out.append(text) return ''.join(out) try: return pattern.sub(escape_entities, text).encode('ascii') except TypeError: raise_serialization_error(text) def raise_serialization_error(text): raise TypeError( "cannot serialize %r (type %s)" % (text, type(text).__name__) ) PKY8ð6zœûÙÙkid/options.py# -*- coding: utf-8 -*- """Configuration API.""" import release __revision__ = "$Rev: 492 $" __date__ = "$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $" __author__ = "David Stanek " __copyright__ = "Copyright 2006, David Stanek" __license__ = release.license __all__ = ['Options'] _prefix = "kid:" class Options(object): def __init__(self, options={}, **extra): self._options = {} for name, value in options.items(): self.set(name, value) for name, value in extra.items(): self.set(name, value) def isset(self, name): """Returns True if a option exists or False if it doesn't. name: the option to check """ return self._options.has_key(self.__prefix(name)) def get(self, name, default=None): """Get the value of an option. name: the option to retrieve default: returned for non-existing properties, defaults to None """ return self._options.get(self.__prefix(name), default) def set(self, name, value): """Set the value of an option. name: the option to set value: the value to be set for the option Returns the value passed in. """ self._options[self.__prefix(name)] = value return value def remove(self, name): """Remove an option.""" if self.isset(name): del self._options[self.__prefix(name)] def __getitem__(self, name): if not self.isset(name): raise KeyError, "no option %s" % name return self.get(name) def __setitem__(self, name, value): self.set(name, value) def __delitem__(self, name): if not self.isset(name): raise KeyError, "no option %s" % name self.remove(name) def __prefix(self, name): """Add the prefix if it does not already exist.""" if not name.startswith(_prefix): name = _prefix + name return name PKÆ=ð6àß'äòUòUkid/__init__.pyc;ò \P›Fc@sîdZdZdZdklZeiZeiZei Z ei Z ei ZdkZdkZeidjp td‚dklZlZdklZd klZlZd klZd klZlZl Z l!Z!l"Z"d k#l$Z$l%Z%l&Z&l'Z'd k(l)Z)dk*l+Z+l,Z,l-Z-l.Z.l/Z/dk0l1Z1l2Z2dk3i4Z4ddddddddddddddddd d!d"d#d$d%d&gZ5ei6ƒa7e8e8d'„Z9e8d(„Z:ei;i<d)ƒoe9ei;i<d*ƒƒnei;i<d+ƒo$e9ei;i<d*ƒei;d+ƒne8d,„Z=d-e>e8he8e8d.„Z?hd/e-d0e>ƒ<d1e-d0e>d2d1ƒ<d3e/d0e@d2d3ƒ<d4e/d0e@d2d4ƒ<d5e/d0e@d2d5ƒ<d6e.d2d6ƒ<d7e.d2d7ƒ<d8e.d2d8ƒ<d9e.d2d9ƒ<d:e.d2d:ƒ<d;e.d2d6d<e>ƒ<d=e.d2d7d<e>ƒ<d>e.d2d8d<e>ƒ<d?e.d2d9d<e>ƒ<d@e.d2d:d<e>ƒ<dAe,ƒs s KID_IMPORTsKID_IMPORT_EXTsKID_IMPORT_PATHcCsbtƒt|ƒ}|idƒ}x!|dD]}t||ƒ}q-W|o ||_n|SdS(sþImport template by name. This is identical to calling `enable_import` followed by an import statement. For example, importing a template named foo using the normal import mechanism looks like this:: import kid kid.enable_import() import foo This function can be used to achieve the same result as follows:: import kid foo = kid.import_template('foo') This is sometimes useful when the name of the template is available only as a string. s.iN( s enable_imports __import__snamesmodssplits componentsscompsgetattrsencoding(snamesencodings componentsscompsmod((s*build/bdist.linux-i686/egg/kid/__init__.pysimport_templateLs   sc Cs”t|tƒo3t|ƒot|ƒ}d} qOt}|} n |}d} dki } | djoƒt i | ƒ} | o)t id| dit iƒfƒ‚n| } | i|| ƒ}tii|ƒotii|ƒSqëndki}| djo|i|| ||ƒ}nF|i| dtd|d|ƒ} | id|d t!i"id ƒƒ}| i#||| d |d |d |ƒ} | SdS(sôBypass import machinery and load a template module directly. This can be used as an alternative to accessing templates using the native python import mechanisms. file Can be a filename, a kid template string, or an open file object. name Optionally specifies the module name to use for this template. This is a hack to enable relative imports in templates. cache Whether to look for a byte-compiled version of the template. If no byte-compiled version is found, an attempt is made to dump a byte-compiled version after compiling. This argument is ignored if file is not a filename. entity_map Entity map to be used when parsing the template. exec_module If you want full control over how the template module is executed, you can provide this callable that will be called with the template module and the code to be executed as parameters, after the code has been compiled and the module has been created. sNs %s (in %s)s, sforcesencodings entity_maps dump_codes dump_sources KID_OUTPUT_PYsstoresnss exec_module('s isinstancesfiles basestrings xml_sniffsQuickTextReadersfosfilenamesNones kid.importersimporterspathsfinds abs_filenames template_utilsTemplateNotFoundsjoinspathssget_template_namesnamessyssmodulesshas_keysgets kid.compilerscompilerscompilesencodings entity_mapscodesKidFilesFalsestemplatescachesossenvirons_create_modulesnss exec_modulesmod(sfilesnamescachesencodingsnss entity_maps exec_modulescodesfosmodsfilenamesimporterstemplates abs_filenamescompiler((s*build/bdist.linux-i686/egg/kid/__init__.pys load_templateis8      )   sxmlsdeclswmlsdoctypes xhtml-strictsxhtmlsxhtml-framesets html-strictshtmls html-framesets html-quirksshtml-frameset-quirkss HTML-stricts transposesHTMLs HTML-framesets HTML-quirkssHTML-frameset-quirkssplaincKsÝ|ot|d|ƒ}n{|tj ot|d|d|ƒ}nR|tj o5tt|ƒd|pt t |ƒƒd|ƒ}nt i dƒ‚y||i _Wn"tj ot idƒ‚nX|i |SdS(sºGet a Template class quickly given a module name, file, or string. This is a convenience function for getting a template in a variety of ways. One and only one of the arguments name or file must be specified. file:string The template module is loaded by calling ``load_template(file, name='', cache=True)`` name:string The kid import hook is enabled and the template module is located using the normal Python import mechanisms. source:string string containing the templates source. Once the template module is obtained, a new instance of the module's Template class is created with the keyword arguments passed to this function. sencodingsnames*Must specify one of name, file, or source.s"Template could not be initialized.N(snamesimport_templatesencodingsmodsfilesNones load_templatessourcesQuickTextReadershexsids template_utils TemplateErrorsTemplatesmodules ExceptionsTemplateImportErrorskw(sfilessourcesnamesencodingskwsmod((s*build/bdist.linux-i686/egg/kid/__init__.pysTemplate¸s   )cBsÞtZdZedZd„Zeeeed„Zeeeed„Z eeeed„Z d„Z d„Z d„Z d „Zd „Zd „Zd „Zegd „Zd„Zd„Zd„Zd„Zed„ZRS(sBase class for compiled Templates. All kid template modules expose a class named ``Template`` that extends from this class making the methods defined here available on all Template subclasses. This class should not be instantiated directly. sxmlcOsax5|D]-}tt|ƒotid|ƒ‚qqW|ii|ƒt g|_ g|_ dS(s Initialize a template with instance attributes specified by keyword arguments. Keyword arguments are available to the template using self.var notation. s'Keyword argument %r is a reserved name.N( skwskshasattrs BaseTemplates template_utilsTemplateAttrsErrorsselfs__dict__supdatestransform_filters_filterss_layout_classes(sselfsargsskwsk((s*build/bdist.linux-i686/egg/kid/__init__.pys__init__ës cCsV|i|ƒ}y|i|||||ƒSWn#t j ot d|i ƒnXdS(s_ Execute template and write output to file. file:file A filename or a file like object (must support write()). encoding:string The output encoding. Default: utf-8. fragment:bool Controls whether prologue information (such as declaration and DOCTYPE should be written). Set to True when generating fragments meant to be inserted into existing XML documents. output:string,`Serializer` A string specifying an output method ('xml', 'html', 'xhtml') or a Serializer object. smoduleN( sselfs_get_serializersoutputs serializerswritesfilesencodingsfragmentsformats Exceptionsraise_template_errors __module__(sselfsfilesencodingsfragmentsoutputsformats serializer((s*build/bdist.linux-i686/egg/kid/__init__.pyswriteüs cCsS|i|ƒ}y|i||||ƒSWn#tj ot d|i ƒnXdS(sw Execute a template and return a single string. encoding The output encoding. Default: utf-8. fragment Controls whether prologue information (such as declaration and DOCTYPE should be written). Set to True when generating fragments meant to be inserted into existing XML documents. output A string specifying an output method ('xml', 'html', 'xhtml') or a Serializer object. This is a convienence method, roughly equivalent to:: ''.join([x for x in obj.generate(encoding, fragment, output)] smoduleN( sselfs_get_serializersoutputs serializers serializesencodingsfragmentsformats Exceptionsraise_template_errors __module__(sselfsencodingsfragmentsoutputsformats serializer((s*build/bdist.linux-i686/egg/kid/__init__.pys serializes cCsS|i|ƒ}y|i||||ƒSWn#tj ot d|i ƒnXdS(s¡ Execute template and generate serialized output incrementally. This method returns an iterator that yields an encoded string for each iteration. The iteration ends when the template is done executing. encoding The output encoding. Default: utf-8. fragment Controls whether prologue information (such as declaration and DOCTYPE should be written). Set to True when generating fragments meant to be inserted into existing XML documents. output A string specifying an output method ('xml', 'html', 'xhtml') or a Serializer object. smoduleN( sselfs_get_serializersoutputs serializersgeneratesencodingsfragmentsformats Exceptionsraise_template_errors __module__(sselfsencodingsfragmentsoutputsformats serializer((s*build/bdist.linux-i686/egg/kid/__init__.pysgenerate/s cCst|iƒƒSdS(N(sitersselfs transform(sself((s*build/bdist.linux-i686/egg/kid/__init__.pys__iter__IscCs|iƒSdS(N(sselfs serialize(sself((s*build/bdist.linux-i686/egg/kid/__init__.pys__str__LscCst|iddƒdƒSdS(Nsencodingsutf-16(sunicodesselfs serialize(sself((s*build/bdist.linux-i686/egg/kid/__init__.pys __unicode__OscCsdS(N((sself((s*build/bdist.linux-i686/egg/kid/__init__.pys initializeRscCs3|iƒtt|iƒ|iƒƒƒ}|SdS(s4Returns an iterator over the items in this template.N(sselfs initializes ElementStreams _coalescescontents_get_assume_encodingsstream(sselfsstream((s*build/bdist.linux-i686/egg/kid/__init__.pyspullUs  cCsgSdS(s^Generate events for this template. Compiled templates implement this method. N((sself((s*build/bdist.linux-i686/egg/kid/__init__.pys_pull]scCs™dkl}|i}t||iƒƒ}|iƒxS|D]K}|i i dƒo ||jo%|i d|ƒ|i d|ƒSq<q<W|i ƒSdS(N(sgetmroslayouti(sinspectsgetmrosselfs_layout_classessvisitedslists __class__smrosreversescs__dict__shas_keysinserts_pull(sselfscsmrosvisitedsgetmro((s*build/bdist.linux-i686/egg/kid/__init__.pyscontentds    cCs¾|tjo|iƒ}nst|tƒo3t|ƒot|dtƒ}qt |ƒ}n0t |dƒot |ƒ}nt i |ƒ}x$||iD]}|||ƒ}qW|SdS(s. Execute the template and apply any match transformations. If stream is specified, it must be one of the following: Element A kid.Element. ElementStream An `pull.ElementStream` instance or other iterator that yields stream events. string A file or URL unless the string starts with '<' in which case it is considered an XML document and processed as if it had been an Element. By default, the `pull` method is called to obtain the stream. sfragmentstagN(sstreamsNonesselfspulls isinstances basestrings xml_sniffsXMLsFalsesdocumentshasattrs ElementStreamsensuresfilterss_filterssf(sselfsstreamsfilterssf((s*build/bdist.linux-i686/egg/kid/__init__.pys transformos  cCs‡y |i}Wnotj ocg}|ii}x>|D]6}y |i}Wntj o q7nX||7}q7W||_nX|SdS(N( sselfs_match_templates_cachedsrsltsAttributeErrors __class__s__mro__smrosCs_match_templatess templates(sselfs templatessCsmrosrslt((s*build/bdist.linux-i686/egg/kid/__init__.pys_get_match_templatess   cCs<|tjo |iSn!t|tƒo t|Sn|SdS(N(s serializersNonesselfs isinstances basestringsoutput_methods(sselfs serializer((s*build/bdist.linux-i686/egg/kid/__init__.pys_get_serializer s    cCs#t|dƒo |iSntSdS(Nsassume_encoding(shasattrsselfsassume_encoding(sself((s*build/bdist.linux-i686/egg/kid/__init__.pys_get_assume_encoding¨s cCst||ƒSdS(N(shasattrsselfsname(sselfsname((s*build/bdist.linux-i686/egg/kid/__init__.pysdefined°scCst|||ƒSdS(N(sgetattrsselfsnamesdefault(sselfsnamesdefault((s*build/bdist.linux-i686/egg/kid/__init__.pysvalue_of³s(s__name__s __module__s__doc__soutput_methodss serializers__init__sNonesFalseswrites serializesgenerates__iter__s__str__s __unicode__s initializespulls_pullscontents transforms_get_match_templatess_get_serializers_get_assume_encodingsdefinedsvalue_of(((s*build/bdist.linux-i686/egg/kid/__init__.pys BaseTemplateÝs&          !    s TemplatePathcBsMtZdZed„Zd„Zdd„Zd„Zd„Zed„Z RS(s%Finding templates on a list of paths.cCs{t|tƒo|itiƒ}n|tjo g}n|itiƒƒg|_x|D]}|i|ƒq`WdS(sInitialize with path list.N( s isinstancespathss basestringssplitsosspathsepsNonesappendsgetcwdsselfspath(sselfspathsspath((s*build/bdist.linux-i686/egg/kid/__init__.pys__init__ºs   cCs,tiitiitii|ƒƒƒSdS(sNormalize path.N(sosspathsabspathsnormpaths expanduser(sselfspath((s*build/bdist.linux-i686/egg/kid/__init__.pys _cleanse_pathÅsicCs:|i|ƒ}||ijo|ii||ƒndS(s)Insert path to list if not already there.N(sselfs _cleanse_pathspathspathssinsertspos(sselfspathspos((s*build/bdist.linux-i686/egg/kid/__init__.pysinsertÉscCs7|i|ƒ}||ijo|ii|ƒndS(s)Append path to list if not already there.N(sselfs _cleanse_pathspathspathssappend(sselfspath((s*build/bdist.linux-i686/egg/kid/__init__.pysappendÏscCsQ|i|ƒ}gi}|iD]!}||jo||ƒq q ~|_dS(sRemove path from list.N(sselfs _cleanse_pathspathsappends_[1]spathssp(sselfspaths_[1]sp((s*build/bdist.linux-i686/egg/kid/__init__.pysremoveÕscCs¾tii|ƒ}|otii|ƒg}ng}x|i|D]p}tii||ƒ}tii |ƒo|Sn|i t ƒ o)|t 7}tii |ƒo|Sq¶qFqFWdS(s(Find file relative to path list and rel.N( sosspathsnormpathsrelsdirnamesselfspathsspsjoinsexistssendswithsKID_EXT(sselfspathsrelsp((s*build/bdist.linux-i686/egg/kid/__init__.pysfindÚs ( s__name__s __module__s__doc__sNones__init__s _cleanse_pathsinsertsappendsremovesfind(((s*build/bdist.linux-i686/egg/kid/__init__.pys TemplatePath·s     (Gs__doc__s __revision__s__date__skidsreleasesversions __version__sauthors __author__semails __email__s copyrights __copyright__slicenses __license__ssyssoss hexversionsAssertionErrorskid.utils xml_sniffsQuickTextReaders kid.namespaces Namespaceskid.codewriters KID_XMLNSsraise_template_errors kid.compilersKID_EXTs kid.elementsElements SubElementsCommentsProcessingInstructionsFragments kid.parsers ElementStreamsXMLsdocuments _coalesces kid.filterstransform_filterskid.serializations SerializersPlainSerializers XMLSerializersHTMLSerializersXHTMLSerializers kid.formatsFormatsoutput_formatsskid.template_utils template_utils__all__sgetdefaultencodingsassume_encodingsNones enable_importsdisable_importsenvironsgetsimport_templatesTrues load_templatesFalsesoutput_methodssTemplatesobjects BaseTemplates TemplatePathspath(,sraise_template_errorsXHTMLSerializers load_templates Namespaces __email__s ElementStreamsTemplatesPlainSerializerstransform_filters XMLSerializersQuickTextReaders _coalesces __revision__s__all__sFormatsFragmentsHTMLSerializersKID_EXTs template_utils xml_sniffsdisable_importsXMLsoutput_methodss __license__s enable_imports __author__ssysspathsElementsdocuments Serializers BaseTemplatesComments __copyright__s __version__sProcessingInstructions KID_XMLNSsoutput_formatss__date__s SubElementsimport_templatesreleasesoss TemplatePath((s*build/bdist.linux-i686/egg/kid/__init__.pys? sJ        % % K   <ÿW%Ú4PKÆ=ð6ZŒi¦ÊÊkid/compile.pyc;ò [P›Fc@sÆdZdZdZdZdZdZdkZdklZdk l Z l Z yd k l Z lZlZWn+ej od d d f\Z ZZnXdkZd „Zedjo eƒndS(s}Usage: kidc [OPTIONS] [file...] Compile kid templates into Python byte-code (.pyc) files. OPTIONS: -f, --force Force compilation even if .pyc file already exists. -s, --source Generate .py source files along with .pyc files. This is sometimes useful for debugging. -d, --strip-dest-dir Strips the supplied path from the beginning of source filenames stored for error messages in the generated .pyc files The file list may have files and/or directories. If a directory is specified, all .kid files found in the directory and any sub-directories are compiled. s $Rev: 492 $s5$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $s!Ryan Tomayko (rtomayko@gmail.com)s!Copyright 2004-2005, Ryan Tomaykos8MIT N(sisdir(sgetopts GetoptError(sEX_OKs EX_DATAERRsEX_USAGEiiic Cs{y/ttiddddddgƒ\} }WnLtj o@}tiit |ƒdƒti it ƒti t ƒnXt}}t}xŸ| D]—\} }| dd fjo t}q•| d d fjo t}q•| d d fjo!ti it ƒti tƒq•| ddfjo |}q•q•W|}| o1tiidƒtiidƒti t ƒnd„}t} xÛ|D]Ó} t| ƒo^x½tii| d|d|d|ƒD]1}|dttfjo t} n||ƒq½Wq…y(tii | d|d|d|ƒ} Wn't"j o}|tf\} } nX|| | fƒq…Wti | ot#ptƒdS(Nisfshd=sforcessourceshelpsstrip-dest-dir=s s-fs--forces-ss--sources-hs--helps-ds--strip-dest-dirs!kidc: No kid template specified. s/ Try 'kidc --help' for usage information. cCsf|\}}|tjod|}n,|tjod|}nd||f}tii|ƒdS(Ns compile: %s s fresh: %s serror: %s (%s) ( sressstatsfilenamesTruesmsgsFalsessyssstderrswrite(sressstatsfilenamesmsg((s)build/bdist.linux-i686/egg/kid/compile.pys print_resultGs   sstrip_dest_diri($sgetoptssyssargvsoptssargssgerrorsesstderrswritesstrsstdouts__doc__sexitsEX_USAGEsFalsesforcessourcesNonesstrip_dest_dirsosasTruesEX_OKsfiless print_resultserrsfsisdirskidscompilers compile_dirsress compile_filesstats Exceptions EX_DATAERR(sforcesstrip_dest_dirs print_resultsresssourcesfilessargssesasstatserrsfsosopts((s)build/bdist.linux-i686/egg/kid/compile.pysmain*sV "       s__main__(s__doc__s __revision__s__date__s __author__s __copyright__s __license__ssyssos.pathsisdirsgetopts GetoptErrorsgerrorsossEX_OKs EX_DATAERRsEX_USAGEs ImportErrors kid.compilerskidsmains__name__(sisdirssyss __copyright__s __revision__s __license__s EX_DATAERRsgerrors __author__s__date__smainsEX_OKsgetoptsEX_USAGEskid((s)build/bdist.linux-i686/egg/kid/compile.pys?s     ; PKÆ=ð6(6†ì%ì%kid/compiler.pyc;ò \P›Fc@s#dZdZdZdZdZdZdkZdkZdkZdk Z dk Z dk Z dk Z dk lZdd d d gZd Zed „ZeZddd„Zdeed„Zd„Zdefd„ƒYZd„Zd„Zeeeeed„Zdeeeeed„ZdS(s0Kid Compiler Compile XML to Python byte-code. s $Rev: 492 $s5$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $s!Ryan Tomayko (rtomayko@gmail.com)s!Copyright 2004-2005, Ryan Tomaykos8MIT N(sraise_template_errorsKID_EXTscompiles compile_files compile_dirs.kidcBs'|ejo h}n||U|SdS(s3Run code with variables in dict, updating the dict.N(sdictsNonescode(scodesdict((s*build/bdist.linux-i686/egg/kid/compiler.pys actualizes   ssexeccCsMt|ƒtjo&|idƒod|d}q9nt||dƒSdS(s4The Python built-in compile function with safeguard.s# -*- coding: s# -*-i sexecN(stypescodesunicodes startswiths _py_compilesfilename(scodesfilenameskind((s*build/bdist.linux-i686/egg/kid/compiler.pys py_compile&s cCs,tii||||ƒ}t||ƒSdS(s¡Compiles Kid XML source to a Python code object. source -- A file like object - must support read. filename -- An optional filename that is used N( skids codewritersparsessourcesencodingsfilenames entity_mapspys py_compile(ssourcesfilenamesencodings entity_mapspy((s*build/bdist.linux-i686/egg/kid/compiler.pyscompile0scCsti|ƒtiS(N(sossstatsfilenamesST_MTIME(sfilename((s*build/bdist.linux-i686/egg/kid/compiler.pys=ssKidFilecBsztZeiƒZeeeed„Zeed„Z d„Z e e ƒZ d„Z e e ƒZ ed„Z ed„ZRS(Nc Cs:||_tii|ƒdd|_||_|id|_||_||_ t }|o t }n«t}yt|idƒ}Wntj o t }ntX|idƒ|ijo t }nPtid|idƒƒd}t|ƒ} | t jp || jo t }n||_||_t |_t |_dS(Nis.pyscsrbisNs*kid.pull has been superseded by kid.parser(s*( s__doc__s __revision__s__date__s __author__s __copyright__s __license__swarningsswarnsDeprecationWarnings kid.parser(s __copyright__s __revision__s __license__swarningss __author__s__date__((s&build/bdist.linux-i686/egg/kid/pull.pys?s PKÆ=ð6àSƆРРkid/filter.pyc;ò ]P›Fc@s‹dZdZdZdZdZdZdklZlZl Z l Z l Z dk l Z dklZd gZd „Zd „Zd „Zd S(sKid tranformationss $Rev: 492 $s5$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $s!Ryan Tomayko (rtomayko@gmail.com)s!Copyright 2004-2005, Ryan Tomaykos8MIT (s ElementStreamsSTARTsXML_DECLsdocuments _coalesce(s Namespace(sgenerate_contentstransform_filtercsDˆiƒ}‡d†}ti|ƒ}tt|ˆ||ƒƒSdS(Ncstt|ƒˆƒSdS(N(stransform_filtersgenerate_contentsitemstemplate(sitem(stemplate(s(build/bdist.linux-i686/egg/kid/filter.pys apply_funcs(stemplates_get_match_templatess templatess apply_funcs ElementStreamsensuresstreams apply_matches(sstreamstemplates templatess apply_func((stemplates(build/bdist.linux-i686/egg/kid/filter.pystransform_filters  c cs=x6|D].\}}|tjo t} xðtdt|ƒƒD]Ù}||\} }| |ƒo¶|i ƒ}t ||||ƒ|iƒƒ}t|ƒdjo%xh|D]\}}||fVq¦WnGxCtt|ƒ||| ||d|ƒD]\}}||fVqðWt} Pq<q<W| oqq+n||fVqWdS(Niii(sstreamsevsitemsSTARTsFalsesmatchedsrangeslens templatessismatchscallsexpands _coalescestemplates apply_funcs_get_assume_encodings newstreams apply_matchess ElementStreamsTrue( sstreamstemplates templatess apply_funcsisitems newstreamscallsevsmatchsmatched((s(build/bdist.linux-i686/egg/kid/filter.pys apply_matchess0        c cstdƒ}|i} |i}xÞ|D]Ö\}}|tjo |i| jo­|i ƒ}|i dƒ}yt ||iƒƒ}WnF|i|ƒ}x]t|ƒidƒD]\}}||fVq­WqûXx-|D]!\}}|tjo|VqÒqÒWq%q%WdS(Nshttp://www.w3.org/2001/XIncludeshrefi(s NamespacesxisincludesfallbacksstreamsevsitemsSTARTstagsexpandsgetshrefsdocumentstemplates_get_assume_encodingsdocsfinds fallback_elms ElementStreamsstripsXML_DECL( sstreamstemplates fallback_elmsxisevsdocsitemshrefsfallbacksinclude((s(build/bdist.linux-i686/egg/kid/filter.pysxinclude_filter2s&        N(s__doc__s __revision__s__date__s __author__s __copyright__s __license__s kid.parsers ElementStreamsSTARTsXML_DECLsdocuments _coalesces kid.namespaces Namespaceskid.template_utilsgenerate_contents__all__stransform_filters apply_matchessxinclude_filter(s __copyright__s __revision__s__all__s __license__sgenerate_contentsxinclude_filters Namespaces __author__s__date__sSTARTs apply_matchess ElementStreamsXML_DECLstransform_filtersdocuments _coalesce((s(build/bdist.linux-i686/egg/kid/filter.pys?s%     PKÆ=ð6ÇDìì$"$"kid/importer.pyc;ò \P›Fc@sdZdZdZdZdZdZdkZdkZdkZdk l Z l Z l Z dk lZlZlZd klZd klZd klZlZd klZd dddgZeed„Zed„Zed„Z d„Z!e"hed„Z#de$fd„ƒYZ%dS(sóKid Import Hooks. When installed, these hooks allow importing .kid files as if they were Python modules. Notes: We use new import hooks instead of the old ihooks module, because ihooks is incompatible with Python eggs. We allow importing from one or more specified paths for Kid templates, or importing from sys.path. In the latter case, we use an importer on meta_path because importers on path_hook do not fall back to the built-in import in Python >= 2.5 (this worked in Python 2.3 and 2.4). s $Rev: 492 $s5$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $sGRyan Tomayko (rtomayko@gmail.com); Christoph Zwerschke (cito@online.de)s;Copyright 2004-2005, Ryan Tomayko; 2006 Christoph Zwerschkes8MIT N(senvironsextsepspathsep(sexistssjoinsisdir(s __version__(sraise_template_error(sKidFilesKID_EXT(sTemplateImportErrorsinstalls uninstallsimport_templatesget_template_namec Csù|o„t|tƒo|idƒ}n t|ƒ}x0|D](}|itƒ otd|‚q=q=Wt |jo|i t ƒq‘ng}|i dt ƒ|oùt|tƒo|it ƒ}n t|ƒ}di|ƒ}g}ti }xe|D]]}d|}gi}|D]%}|i|ƒ o||ƒqq~}|i||ƒqüW||t_ |o,ttij otii dtƒqqõnUxQtiD]$}t|tƒo||_Pq«q«Wtd|ƒ}tii d|ƒdS(s¸Install importer for Kid templates. ext can be one or more extensions as list or comma separated string path can be one or more paths as list or pathsep separated string s,sIllegal exception: is kid::%s::sextN(sexts isinstances basestringssplitsextsslists startswithsextseps ExceptionsKID_EXTsremovesinsertspathspathsepspathssjoinskidpathsssysssyspathskidpathsappends_[1]s KidImporters path_hookss meta_pathsimporter( sextspathsimporterspathssextsssyspathskidpathss_[1]skidpath((s*build/bdist.linux-i686/egg/kid/importer.pysinstall&sH     <    cCs™|oLt|tƒo|itƒ}n t|ƒ}g}t}x—t iD]Œ}|idƒ}t |ƒdjo&|ddjo|d o |d o.di |dd!ƒ|joqLnt}n|i|ƒqLW|t _|octt ijoOgi}t iD]!}|tjo||ƒq q ~t _t iiƒqOq•nCgi}t iD]%}t|tƒ o||ƒqdqd~t _dS( srUninstall importer for Kid templates. path can be one or more paths as list or pathsep separated string s:iiskidiiþÿÿÿiN(spaths isinstances basestringssplitspathsepspathsslistssyspathsTrues remove_hookssysspslensjoinsFalsesappends KidImporters path_hookss_[1]shookspath_importer_cachesclears meta_pathsimporter(spathspathsssyspathspsimporters_[1]s remove_hookshook((s*build/bdist.linux-i686/egg/kid/importer.pys uninstallVs*  <  >cCsr| o|otii|ƒoti|Snt|ƒ}|idt i dƒƒ}t |||ƒ}|SdS(Ns dump_sources KID_OUTPUT_PY(sforcesnamessyssmodulesshas_keysKidFilesfilenamestemplatescompilesenvironsgetscodes_create_modulesmodule(snamesfilenamesforcescodesmodulestemplate((s*build/bdist.linux-i686/egg/kid/importer.pysimport_templateus " cCs,|o|Sndt|ƒtidSdS(Nskid.util.template_%xi(snameshashsfilenamessyssmaxint(snamesfilename((s*build/bdist.linux-i686/egg/kid/importer.pysget_template_name}sc BsdxAedƒD]3}e||ƒ}ei|ƒ}||_e i ƒ|_ |i i |ƒy'|o|||ƒn ||i UWn>ej o2|o|ei|s NamespacesxmlsxhtmlsatomsrdfsrsssnonscBsVtZed„Zd„Zd„ZeZeZd„Zd„Z d„Z d„Z RS(NcCs+||_||_|o|t|d.e6fd/„ƒYZ?d0„Z@d1d2„ZAdS(3s/KidWriter Write Python source code from XML. s $Rev: 496 $s5$Date: 2007-07-15 18:14:35 -0400 (Sun, 15 Jul 2007) $s!Ryan Tomayko (rtomayko@gmail.com)s!Copyright 2004-2005, Ryan Tomaykos8MIT N(ssplitext(s extract_tbsformat_exception_only(s __version__s Namespace(sdocumentsSTARTsENDsTEXTsXML_DECLsDOCTYPEsLOCATION(s namespacessCommentsProcessingInstructions KID_XMLNSs KID_PREFIXskidnssraise_template_errorshttp://purl.org/kid/ns#spysforsifsdefsslotscontentsreplacesmatchsstripsattrssextendsslayoutsomitsrepeatspythonskidcCs8t|d|d|d|ƒ}t|||ƒiƒSdS(Nsencodingsfilenames entity_map(sdocumentssourcesencodingsfilenames entity_mapsdocs KidWritersparse(ssourcesencodingsfilenames entity_mapsdoc((s,build/bdist.linux-i686/egg/kid/codewriter.pysparse3s cCs8t|dƒ}zt||||ƒSWd|iƒXdS(sµParse the file specified. filename -- the name of a file. fp -- an optional file like object to read from. If not specified, filename is opened. srbN(sopensfilenamessourcesparsesencodings entity_mapsclose(sfilenamesencodings entity_mapssource((s,build/bdist.linux-i686/egg/kid/codewriter.pys parse_file8s c Cs|o‚yht|dƒ}zGt|d|d|d|dtƒ}t ||||ƒ}|i ƒSWd|i ƒXWq‰t j oq‰XndS(Nsrbsencodingsfilenames entity_mapsdebug(slinenosopensfilenamessourcesdocumentsencodings entity_mapsTruesdocs KidWriterswritersparsescloses Exception(sfilenamesencodings entity_mapslinenoswriterssourcesdoc((s,build/bdist.linux-i686/egg/kid/codewriter.pyserror_locationFs csHˆi}d|f‡‡d†ƒY}|i|_|i|_|ƒSdS(s,Get exception with additional error message.sTemplateExceptionErrorcs#tZ‡d†Z‡‡d†ZRS(NcsIxBtˆƒD]4}|idƒ ot||tˆ|ƒƒq q WdS(Ns_(sdirserrorsargs startswithssetattrsselfsgetattr(sselfsarg(serror(s,build/bdist.linux-i686/egg/kid/codewriter.pys__init__Xs cstˆƒdˆSdS(Ns (sstrserrors add_message(sself(s add_messageserror(s,build/bdist.linux-i686/egg/kid/codewriter.pys__str__\s(s__name__s __module__s__init__s__str__((serrors add_message(s,build/bdist.linux-i686/egg/kid/codewriter.pysTemplateExceptionErrorWs N(serrors __class__sErrorsTemplateExceptionErrors__name__s __module__(serrors add_messagesErrorsTemplateExceptionError((serrors add_messages,build/bdist.linux-i686/egg/kid/codewriter.pysTemplateExceptionErrorTs    cCs7|o |o| o_|tijoKti|}t|dƒo |i}nt|dƒo |i}qqqun| p |djo‚n| o d}nt|ƒdd}ti ƒd \}} |t jo|| ifg} n!tti ƒdƒ} | iƒx§| D]’}||djp |d oqnt||d |dƒ}| oqn|\\}} \}} ||joqng}| o ||jo|d8}d } n||jo|id |ƒ| | jo|id | ƒqÎ| o=| | jo|id | | fƒqj|id| ƒqÎ| djo|id| ƒqÎna|id|ƒ| o|id | ƒn|id|ƒ| djo|id | ƒn|oÔdi|ƒ}y~|d8}|d8}ggf\}}x©tt|ƒƒD]•\} }| |joq n|i"ƒ}|oP| |jo| o>|| i"ƒo)|| i#ƒ}|od|}q¡q¥n| |jo | djoe|| i#ƒo@| djo d} n|| i"ƒ}|o|d7}q q$|| i"ƒ}nt$|ƒdjo|d i"ƒd}n|oIt$|ƒdjo|i| ƒ|i|ƒqŸ| |d<||dsutf-8is.pyiislinenoiÿÿÿÿs on line %ds , column %ds between columns %d and %ds after column %ds before column %dsbetween line %ds and line %dss... iKs ...iOiserror line not founds...s:s (cannot acquire source text: %s)s"Error location in template file %rs-Error in code generated from template file %rs N(.smodulesfilenamesencodingssyssmodulessmodshasattrskid_filessplitextspy_filesexc_infosexc_types exc_values SyntaxErrorslinenostbs extract_tbsreversestserror_locationslocations start_lines start_colsend_linesend_colsssappendsjoins error_lines error_texts enumeratesopenslinestextsrstripslstripslens LookupErrorsinserts Exceptionsesstrsformat_exception_onlys isinstancesTemplateExceptionErrors __class__(smodulesfilenamesencodings start_linesexc_types error_lineslocationstextspy_filestbs exc_valuesend_cols start_colslinesmodsesssend_linests error_text((s,build/bdist.linux-i686/egg/kid/codewriter.pysraise_template_errorbsÎ                           ) s KidWritercBsªtZeeed„Zeddd„Zd„Zd„Zd„Zd„Zd „Z d „Z d „Z d „Z d „Z d„Zd„Zd„Zd„Zd„ZRS(NcCsž||_|pd|_||_d|_||_t|_g|_|i ƒ|_ |i ƒ|_ |i ddƒ|_ |i ƒ|_ g|_g|_dS(Nsutf-8isleveli(sstreamsselfsencodingsfilenamesdepthslinenosNoneslocations locationsscodegens module_codes class_codes expand_codesend_module_codes module_defss inst_defs(sselfsstreamsencodingsfilenameslineno((s,build/bdist.linux-i686/egg/kid/codewriter.pys__init__Ûs       is cCs2|iot||iƒSnt|||ƒSdS(N(sselfslinenosLocationGeneratorscodesgetlocs CodeGeneratorslevelstab(sselfscodeslevelstab((s,build/bdist.linux-i686/egg/kid/codewriter.pyscodegenês cCs |iSdS(N(sselfslocation(sself((s,build/bdist.linux-i686/egg/kid/codewriter.pysgetlocðsc Cs |iƒ|i|iƒ|iƒg}||ii7}x|iD]}||i7}qDW||i i7}||i i7}x|i D]}||i7}q…W||i i7}|i oD|i d}d|jot|ƒjn otSn||}| otSn|\}}d|jot|iƒjn otSn|i|}||odpd7}d|jot|iƒjno|i|}n,|d}|o|d7}n|df}| o||f\}}n||fSndi|ƒSdS(Niiiÿÿÿÿs (sselfsbegins proc_streams module_codesendspartsscodes module_defsscs class_codes expand_codes inst_defssend_module_codeslinenoslensNonespossis_starts locationss start_locsend_locsend_linesjoin( sselfs start_locscsposspartssend_lineslinenosend_locsis_start((s,build/bdist.linux-i686/egg/kid/codewriter.pysparseósH      %  ( '  cCsÌ|i}|id|iddtd|iddddd |id d d d dddddƒ|i}|idƒ|iddƒ|i ƒ|idƒ|idddƒ|i }|idƒdS(Ns# -*- coding: %s -*-s# Kid template moduleskid_version = %rs kid_file = %rs import kidsfrom kid.template_util import *s)import kid.template_util as template_utils_def_names = []sencoding = "%s"sdoctype = Nones!omit_namespaces = [kid.KID_XMLNS]slayout_params = {}s,def pull(**kw): return Template(**kw).pull()s³def generate(encoding=encoding, fragment=False, output=None, format=None, **kw): return Template(**kw).generate(encoding=encoding, fragment=fragment, output=output, format=format)sµdef serialize(encoding=encoding, fragment=False, output=None, format=None, **kw): return Template(**kw).serialize(encoding=encoding, fragment=fragment, output=output, format=format)s¹def write(file, encoding=encoding, fragment=False, output=None, format=None, **kw): return Template(**kw).write(file, encoding=encoding, fragment=fragment, output=output, format=format)sdef initialize(template): passsBaseTemplate = kid.BaseTemplatesdef initialize(self):srslt = initialize(self)s0if rslt != 0: super(Template, self).initialize()sdef _pull(self):s-exec template_util.get_locals(self, locals())scurrent, ancestors = None, []s"if doctype: yield DOCTYPE, doctypes( sselfs module_codescodeslinesencodings __version__sfilenames expand_codes start_blocks end_blocksend_module_code(sselfscode((s,build/bdist.linux-i686/egg/kid/codewriter.pysbegins<          cCs|iiƒdS(N(sselfs expand_codes end_block(sself((s,build/bdist.linux-i686/egg/kid/codewriter.pysendIsc Cs x|iD]ù\}}|tjo¦|itjoà|iiƒ}|i dƒoq n||i jo|i i } n |i } |i dƒp|i dƒp |idƒo=t|iƒ}t|tƒod|}qþt|ƒ}nt|iƒ}| d|dƒn˜|itjo·d|iiƒjo|iidd ƒ\} } n|id f\} } | tttfjo| o|i| ƒqÖqª|io|p|i } | i d | | fdƒ~ nÑt}||i jo|i t!ƒ}|tj o|i"t!=t#|ƒ}ng} |i t%ƒ}|tj o}|i"t%=t#|ƒ}xV|id ƒD]E} | i'd t(| ƒd ƒ|i d| d| iƒ|fƒqnW|i)ƒn| i'dƒ|i*}|i+ddi,| ƒƒ|i dƒ|i }n|i-||i"|ƒ|tj ox|}|i/dd ƒ}|i+dƒ|i ddddddd|dddd ƒ |i)ƒ|i0i'|ƒ|}n|i1ot2|i1d |diƒggi}|dD]}||iƒƒq"~}t}x|dD]„}|djoq|iƒ}|ddjoPt |ƒt |ƒ}|tjp ||jo|}|djoPqÏqÓq×qSqSW|tj p |djoEgi}|dD]"}||| iƒ||ƒq~|d)n|do|dddj oÛyt |dddƒWq6t j oªy'di|ƒd}t |ddƒWq2tj og|d gi}|dD]}|||ƒqÕ~}di|ƒd}t |ddƒ|}q2q2Xq6q6Xn|SdS( s)Adjust the indentation of a Python block.iiss#ssexecs N(slinessstripsappends_[1]slinesrstripsNonesindslstripssslensiscompiles SyntaxErrorsjoinsblocksIndentationErrorstabslines2( slinesstabsislines2s_[1]sssindslinesblock((s,build/bdist.linux-i686/egg/kid/codewriter.pys_adjust_python_blockís@B    E!7 (Bs__doc__s __revision__s__date__s __author__s __copyright__s __license__ssyssresos.pathssplitexts tracebacks extract_tbsformat_exception_onlyskids __version__s Namespaces kid.parsersdocumentsSTARTsENDsTEXTsXML_DECLsDOCTYPEsLOCATIONs kid.elements namespacessCommentsProcessingInstructions__all__s KID_XMLNSs KID_PREFIXskidnss QNAME_FORsQNAME_IFs QNAME_DEFs QNAME_SLOTs QNAME_CONTENTs QNAME_REPLACEs QNAME_MATCHs QNAME_STRIPsQNAME_ATTRIBUTESs QNAME_EXTENDSs QNAME_LAYOUTs QNAME_OMITs QNAME_REPEATsKID_PIs KID_ALT_PIs KID_OLD_PIsNonesparses parse_fileserror_locationsTemplateExceptionErrorsraise_template_errorsobjects KidWriterslists SubExpressionscompilesDOTALLs _sub_exprs interpolates CodeGeneratorsLocationGenerators _ascii_encodes_adjust_python_block(7s QNAME_STRIPsraise_template_errors SubExpressionssplitexts NamespacesDOCTYPEs KID_PREFIXsparses QNAME_DEFs QNAME_REPEATs QNAME_LAYOUTsXML_DECLskidnssTemplateExceptionErrors QNAME_OMITs QNAME_SLOTs __revision__s__all__s KidWriters QNAME_REPLACEsformat_exception_onlysQNAME_ATTRIBUTESsres extract_tbsLOCATIONsTEXTs parse_files QNAME_FORs __version__sKID_PIsENDs _sub_exprs __license__sLocationGeneratorserror_locations QNAME_EXTENDSs interpolates __author__ssyssSTARTs _ascii_encodes namespacessQNAME_IFs QNAME_CONTENTsComments __copyright__sdocuments KID_XMLNSsProcessingInstructions CodeGenerators QNAME_MATCHs__date__s KID_ALT_PIs KID_OLD_PIs_adjust_python_block((s,build/bdist.linux-i686/egg/kid/codewriter.pys?s\ 1               wÿ—   $,! PKÆ=ð6Ü‚§XiMiMkid/parser.pyc;ò \P›Fc @sËdZdZdZdZdZdZdkZdklZdk l Z l Z l Z d k lZlZlZd d d d dddddddddg ZhZgZxDeiiƒD]3\ZZeeƒeeN(sexpat(sElementsCommentsProcessingInstruction(s open_resourcesQuickTextReadersget_expat_errors ElementStreamsXMLsdocumentsParsers ExpatParsersSTARTsENDsTEXTsCOMMENTsPIsXML_DECLsDOCTYPEsLOCATIONss sInvalidStreamStatecBstZdd„ZRS(NsInvalid stream state.cCsti||ƒdS(N(s Exceptions__init__sselfsmsg(sselfsmsg((s(build/bdist.linux-i686/egg/kid/parser.pys__init__s(s__name__s __module__s__init__(((s(build/bdist.linux-i686/egg/kid/parser.pysInvalidStreamStatescCs|idƒp |idƒo t}n|o†|od||f}n d|}t|tƒod}|i|ƒ}nt t |ƒ||ƒ}t t|d|ƒƒiƒSnXt|tƒod}|i|ƒ}nt t |ƒ||ƒ}t t|d|ƒƒSdS(s)Convert XML string into an ElementStream.s%ss %ssutf-16sencodingN(stexts startswithsFalsesfragmentsxmlnss isinstancesunicodesencodingsencodesParsersQuickTextReaders entity_mapsps ElementStreams _coalescesstrip(stextsfragmentsencodingsxmlnss entity_mapsp((s(build/bdist.linux-i686/egg/kid/parser.pysXML#s"    cCsŠt|dƒ o*|tjo |}nt|dƒ}n|tjo d}nt||||ƒ}||_ t t |d|ƒƒSdS(s,Convert XML document into an Element stream.sreadsrbssencodingN( shasattrsfilesfilenamesNones open_resourcesParsersencodings entity_mapsdebugsps _filenames ElementStreams _coalesce(sfilesencodingsfilenames entity_mapsdebugsp((s(build/bdist.linux-i686/egg/kid/parser.pysdocument:s     cBsqtZdZed„Zd„Zd„Zdd„Zd„Ze d„Z ed„Z ed „Z e e ƒZ RS( s¶Provides a pull/streaming interface to ElementTree. Instances of this class are iterable. Most methods of the class act on the Element that is currently being visited. cCsat|dƒo t|dƒo|i|dtƒ}nt|_|it|ƒ|ƒ|_ dS(sêCreate an ElementStream. stream - an iterator that returns ElementStream events. current - If an Element is provided in this parameter than it is yielded as the first element in the stream. stagsattribstailN( shasattrsstreamsselfs_pullsTruesNonescurrents_tracksiters_iter(sselfsstreamscurrent((s(build/bdist.linux-i686/egg/kid/parser.pys__init__Ps   cCs |iSdS(N(sselfs_iter(sself((s(build/bdist.linux-i686/egg/kid/parser.pys__iter__]scCsV|i}|tjo g}n|g}|tf\}}xß|iD]Ô\}}|t jo4|tf\}}|di |ƒ|i |ƒqE|t jo1|i ƒ}||jpt ‚| oPqqE|tjo<|tj o ||_qt|tƒ o ||_qqEqEWt|tƒot|ƒdjo|d}n|SdS(s¾Expand the current item in the stream as an Element. In the case where there is no current element and no single root element, this will return a list of Elements. iÿÿÿÿiiN(sselfscurrentsNonesstacksthisslasts_itersevsitemsSTARTsappendsENDspopsAssertionErrorsTEXTstails isinstancesliststextslen(sselfslaststhisscurrentsitemsevsstack((s(build/bdist.linux-i686/egg/kid/parser.pysexpand`s2            #ics@‡‡d†}ˆitj odpd}t||ƒƒSdS(s>Return new ElementStream with first element level(s) stripped.c#s›x”ˆiD]‰\}}|tjo:|d8}|djoPq]|djo tƒ‚q]n|ˆjo||fVn|tjo|d7}q q WdS(Nii( sselfs_itersevsitemsENDsdepthsInvalidStreamStateslevelssSTART(sdepthsitemsev(sselfslevels(s(build/bdist.linux-i686/egg/kid/parser.pysstrips       iiN(sstripsselfscurrentsNonesdepths ElementStream(sselfslevelssdepthsstrip((sselfslevelss(build/bdist.linux-i686/egg/kid/parser.pysstrips cCs‡|itj odpd}x_|iD]T\}}|tjo|d7}q'|tjo |d8}|djoPq{q'q'W|SdS(s0Eat the current element and all decendant items.iiN( sselfscurrentsNonesdepths_itersevsitemsSTARTsEND(sselfsitemsdepthsev((s(build/bdist.linux-i686/egg/kid/parser.pyseats      ccsà|}t|it|iƒƒ}|ittfjo|i|_t |_nt |fV|iot |ifVnx8|i ƒD]*}x!|i|dtƒD] }|VqžWq‚Wt|fV|o|iot |ifVndS(sMake a stream from an Element.stailN(selemsorigsElementstagsdictsattribsCommentsProcessingInstructionstextsNonesSTARTsTEXTs getchildrenschildsselfs_pullsTrueseventsENDstail(sselfselemstailschildseventsorig((s(build/bdist.linux-i686/egg/kid/parser.pys_pullœs"       ccsƒ|tj o||_t|fVnxX|D]P}|\}}|tjo ||_n|tjo t|_n||fVq+WdS(sTrack current item in stream.N( scurrentsNonesselfsSTARTsstreamspsevsitemsEND(sselfsstreamscurrentspsitemsev((s(build/bdist.linux-i686/egg/kid/parser.pys_track®s       cCs)t||ƒo|Sn|||ƒSdS(s&Ensure the stream is an ElementStream.N(s isinstancesstreamsclsscurrent(sclssstreamscurrent((s(build/bdist.linux-i686/egg/kid/parser.pysensure»s(s__name__s __module__s__doc__sNones__init__s__iter__sexpandsstripseatsFalses_pulls_tracksensures classmethod(((s(build/bdist.linux-i686/egg/kid/parser.pys ElementStreamHs      cCsht|tƒo|Snt|dƒot|ƒSnt|tƒ ot|ƒ}nt||ƒSdS(Ns __unicode__(s isinstancesvaluesunicodeshasattrsstrsencoding(svaluesencoding((s(build/bdist.linux-i686/egg/kid/parser.pys to_unicodeÄsccsÞg}g}t} tg} xl|D]d\} }| tjo|i |ƒt} q"n| tjoId} x!|D]}| t ||ƒ7} qoWg}| ot| fVq«n| tjo`|i} x7|D]/\}}|o|| d|srbs}(9shasattrssourcesfilenamesopensselfs _filenames_sourcesencodings _encodingsexpats ParserCreates_parsersparsers_queuesCurrentLineNumbersAttributeErrorsFalsesdebugs_push_locationspushs_pushs_defaultsDefaultHandlers_startsStartElementHandlers_endsEndElementHandlers_datasCharacterDataHandlers_pisProcessingInstructionHandlers_commentsCommentHandlers _start_nssStartNamespaceDeclHandlers_end_nssEndNamespaceDeclHandlers_xmldecl_handlersXmlDeclHandlers_doctype_handlersStartDoctypeDeclHandlersTrues buffer_textsordered_attributessspecified_attributessNones_doctypes entity_mapsentitysdefault_entity_mapsdefault_external_dtds external_dtdsSetParamEntityParsingsXML_PARAM_ENTITY_PARSING_ALWAYSs _buildForeignsExternalEntityRefHandlers UseForeignDTD(sselfssourcesencodings entity_mapsdebugsparsersfilename((s(build/bdist.linux-i686/egg/kid/parser.pys__init__#sL                          cCsWdk}|itƒ}|i}|ii|ƒ|_|ii|ƒ||_t SdS(N( sStringIOsdefault_external_dtds parseableFilesselfs_parsersoriginal_parsersExternalEntityParserCreatescontexts ParseFilesTrue(sselfscontextsbasessystemIdspublicIdsoriginal_parsersStringIOs parseableFile((s(build/bdist.linux-i686/egg/kid/parser.pys _buildForeignWs   cCs|ii||fƒdS(N(sselfs_queuesappendsevsstuff(sselfsevsstuff((s(build/bdist.linux-i686/egg/kid/parser.pys_push`scCs6|it|ii|iifƒ|i||ƒdS(N(sselfs_pushsLOCATIONs_parsersCurrentLineNumbersCurrentColumnNumbersevsstuff(sselfsevsstuff((s(build/bdist.linux-i686/egg/kid/parser.pys_push_locationcs"ccsªdd}|i}|ii}t}x~|ovxN|o|i o;||ƒ}|djo|i ƒt }q2||ƒq2Wx|iD] }|VqŠWg|_q(WdS(Niis( sbufsizesselfsfeeds_sourcesreadsTruesmores_queuesdatasclosesFalsesitem(sselfsfeedsreadsdatasitemsbufsizesmore((s(build/bdist.linux-i686/egg/kid/parser.pys _expat_streamhs"        c #sÂh‰‡d†}g}t}x|iƒD]\}} |t jot | fVq+|t jo| \}} ||ƒ}t gi} | iƒD]"\}} | ||ƒ| fƒqŽ~ ƒ} |}t|| ƒ}|i|ƒt |fVq+|tjoU|iƒ}|| ƒ|i jpt‚t|ƒo|dpt}t|fVq+|tjo$t| ƒ}t |fVt|fVq+|tjo$t| Œ}t |fVt|fVq+|| fVq+WdS(NcsWyˆ|}Wn>tj o2d|jod|}n|}|ˆ|s file %rs(sselfs_parsersParsesdatasisfinalsexpats ExpatErrorses _filenamesfilenames_sourcessourcesget_expat_errorsstrs Exception(sselfsdatasisfinalse((s(build/bdist.linux-i686/egg/kid/parser.pysfeed¥s  KcCs6t|dƒo"z|idtƒWd|`XndS(Ns_parsers(shasattrsselfsfeedsTrues_parser(sself((s(build/bdist.linux-i686/egg/kid/parser.pysclose´s cCs|it||fƒdS(N(sselfspushsSTARTstagsattrib(sselfstagsattrib((s(build/bdist.linux-i686/egg/kid/parser.pys_start»scCs|it|ƒdS(N(sselfspushsTEXTstext(sselfstext((s(build/bdist.linux-i686/egg/kid/parser.pys_data¾scCs|it|ƒdS(N(sselfspushsENDstag(sselfstag((s(build/bdist.linux-i686/egg/kid/parser.pys_endÁscCsx|idƒody"|it|i|dd!ƒWqttj o/tid||i i |i i fƒ‚qtXndS(Ns&iiÿÿÿÿs'undefined entity %s: line %d, column %d( stexts startswithsselfspushsTEXTsentitysKeyErrorsexpatserrors_parsersErrorLineNumbersErrorColumnNumber(sselfstext((s(build/bdist.linux-i686/egg/kid/parser.pys_defaultÄs "1cCs|it||fƒdS(N(sselfspushsPIstargetsdata(sselfstargetsdata((s(build/bdist.linux-i686/egg/kid/parser.pys_piÒscCs|it|ƒdS(N(sselfspushsCOMMENTstext(sselfstext((s(build/bdist.linux-i686/egg/kid/parser.pys_commentÕscCs!|it|pd|fƒdS(Ns(sselfspushsSTART_NSsprefixsuri(sselfsprefixsuri((s(build/bdist.linux-i686/egg/kid/parser.pys _start_nsØscCs|it|pdƒdS(Ns(sselfspushsEND_NSsprefix(sselfsprefix((s(build/bdist.linux-i686/egg/kid/parser.pys_end_nsÛscCs|it|||fƒdS(N(sselfspushsXML_DECLsversionsencodings standalone(sselfsversionsencodings standalone((s(build/bdist.linux-i686/egg/kid/parser.pys_xmldecl_handlerÞscCs|it|||fƒdS(N(sselfspushsDOCTYPEsnamespubidssysid(sselfsnamessysidspubidshas_internal_subset((s(build/bdist.linux-i686/egg/kid/parser.pys_doctype_handlerás(s__name__s __module__sNonesFalses__init__s _buildForeigns_pushs_push_locations _expat_streams__iter__sfeedscloses_starts_datas_ends_defaults_pis_comments _start_nss_end_nss_xmldecl_handlers_doctype_handler(((s(build/bdist.linux-i686/egg/kid/parser.pys ExpatParser!s$4    ,           (2s__doc__s __revision__s__date__s __author__s __copyright__s __license__shtmlentitydefss xml.parserssexpats kid.elementsElementsCommentsProcessingInstructionskid.utils open_resourcesQuickTextReadersget_expat_errors__all__sdefault_entity_mapsdefault_external_dtdsname2codepointsitemssksvsunichrsappendsjoins ExceptionsInvalidStreamStatesTruesNonesXMLsFalsesdocumentsobjects ElementStreams to_unicodes _coalescesSTARTsENDsTEXTsDOCTYPEsXML_DECLsSTART_NSsEND_NSsPIsCOMMENTsLOCATIONsParsers ExpatParser($s to_unicodesTEXTsexpatsDOCTYPEs ElementStreamsXML_DECLsQuickTextReaders _coalescesCOMMENTs __revision__s__all__sSTART_NSsget_expat_errorsLOCATIONsdocumentsInvalidStreamStatesXMLsENDs __license__shtmlentitydefssdefault_external_dtds __author__sSTARTs ExpatParsersdefault_entity_mapsElementsComments __copyright__sPIsEND_NSsProcessingInstructionsksParsers__date__svs open_resource((s(build/bdist.linux-i686/egg/kid/parser.pys?sF  - | 4 PKÆ=ð6§Ï11kid/release.pyc;ò óR›Fc@sSdZdZdZdZdZdZdZdZdiei ƒd ƒi ƒZ d S( scPythonic, XML Templating Kid is a simple, Python-based template language for generating and transforming XML vocabularies. Kid was spawned as a result of a kinky love triangle between XSLT, TAL, and PHP. We believe many of the best features of these languages live on in Kid with much of the limitations and complexity stamped out (well, eventually :). s $Rev: 497 $s5$Date: 2007-07-16 14:48:50 -0400 (Mon, 16 Jul 2007) $s0.9.6s Ryan Tomaykosrtomayko@gmail.comsSCopyright 2004-2006, Ryan Tomayko, David Stanek, Christoph Zwerschke, Daniel MillersMITs iN( s__doc__s __revision__s__date__sversionsauthorsemails copyrightslicensesjoins splitlinessstripslong_description(s __revision__slicenses copyrightsauthorslong_descriptions__date__sversionsemail((s)build/bdist.linux-i686/egg/kid/release.pys? sPKÆ=ð6#TÎ×ÎÎ kid/run.pyc;ò \P›Fc@sÌdZdZdZdZdZdZdkZdklZl Z dk l Z l Z yd k lZlZlZWn+ej od d d f\ZZZnXdkZd „Zedjo eƒndS(s÷Usage: kid [options] file [args] Expand a Kid template file. OPTIONS: -e enc, --encoding=enc Specify the output character encoding. Default: utf-8 -o outfile, --output=outfile Specify the output file. Default: standard output -s host:port, --server=host:port Specify the server address if you want to start the HTTP server. Instead of the Kid template, you can specify a base directory. -h, --help Print this help message and exit. -V, --version Print the Kid version number and exit. file: filename of the Kid template to be processed or "-" for reading the template from stdin. args: key=value or other arguments passed to the template. s $Rev: 492 $s5$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $s!Ryan Tomayko (rtomayko@gmail.com)s!Copyright 2004-2005, Ryan Tomaykos8MIT N(sdirnamesabspath(sgetopts GetoptError(sEX_OKs EX_DATAERRsEX_USAGEiiicCsay2ttidddddddgƒ\}}WnLtj o@} tiit | ƒdƒti it ƒti t ƒnXd }t} }xä|D]Ü\}} |d d fjo | }q˜|d d fjo | } q˜|ddfjo | }q˜|ddfjo!ti it ƒti tƒq˜|ddfjo2dkl}ti id|ƒti tƒq˜q˜W|tjoˆ|oP|idƒ}|gt_|djo>tt|ƒƒ} | tij otiid| ƒqntiiƒ}h}xd|o\|idƒi ddƒ} t!| ƒdjo| d|| dN(sSet(sElementsCommentsProcessingInstructionsFragmentsQNames namespacess encode_entitysraise_serialization_error(sSTARTsENDsTEXTsCOMMENTsPIs _coalesce(sFormatsoutput_formatssdoctypess Serializers XMLSerializersHTMLSerializers&%s;swmls-//WAPFORUM//DTD WML 1.1//ENs'http://www.wapforum.org/DTD/wml_1.1.xmls xhtml-strictshtmls -//W3C//DTD XHTML 1.0 Strict//ENs1http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtdsxhtmls&-//W3C//DTD XHTML 1.0 Transitional//ENs7http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtdsxhtml-framesets"-//W3C//DTD XHTML 1.0 Frameset//ENs3http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtds html-strictsHTMLs-//W3C//DTD HTML 4.01//ENs%http://www.w3.org/TR/html4/strict.dtds&-//W3C//DTD HTML 4.01 Transitional//ENs$http://www.w3.org/TR/html4/loose.dtds html-framesets"-//W3C//DTD HTML 4.01 Frameset//ENs'http://www.w3.org/TR/html4/frameset.dtds html-quirksshtml-frameset-quirkscBs¯tZeiZdZZedZeZ eZ e e e e e d„Z d„Z d„Zd„Ze ee d„Ze ee d„Ze ee d „Ze d „Zd „ZRS( Nsutf-8sdefaultcCs˜|tj o ||_n|tj o ||_n|tj o ||_n|tj o ||_n|tj o ||_n|i|ƒ|_dS(sgInitialize Serializer. You can change the following parameters: encoding: the output encoding src_encoding: the source encoding formatted: whether all tags should be considered formatted inline: whether all tags should be considered inline format: format to be applied (string or instance of Format) N(sencodingsNonesselfs src_encodings formattedsinlinesformats _get_format(sselfsencodings src_encodings formattedsinlinesformat((s/build/bdist.linux-i686/egg/kid/serialization.pys__init__As           cCs<|tjo |iSn!t|tƒo t|Sn|SdS(N(sformatsNonesselfs isinstances basestringsoutput_formats(sselfsformat((s/build/bdist.linux-i686/egg/kid/serialization.pys _get_formatZs    cCs |iSdS(N(sselfs formatted(sselfstagname((s/build/bdist.linux-i686/egg/kid/serialization.pys is_formattedbscCs |iSdS(N(sselfsinline(sselfstagname((s/build/bdist.linux-i686/egg/kid/serialization.pys is_inlineescCs…y%di|i||||ƒƒ}Wn:tj o.dit |i||||ƒƒƒ}nX| ot i |ƒ}n|SdS(Ns( sjoinsselfsgeneratesstreamsencodingsfragmentsformatstexts TypeErrorstuplesFormatsstrip(sselfsstreamsencodingsfragmentsformatstext((s/build/bdist.linux-i686/egg/kid/serialization.pys serializehs%,c Cs‡t}t|dƒ ot}t|dƒ}nz:|i}x*|i||||ƒD]}||ƒqUWWd|o|iƒnXdS(Nswriteswb(sFalses needs_closedshasattrsfilesTruesopenswritesselfsgeneratesstreamsencodingsfragmentsformatstextsclose( sselfsstreamsfilesencodingsfragmentsformatswrites needs_closedstext((s/build/bdist.linux-i686/egg/kid/serialization.pyswritess cCsdS(N((sselfsstreamsencodingsfragmentsformat((s/build/bdist.linux-i686/egg/kid/serialization.pysgenerate‚scCs7t||iƒ}|o|i||ƒ}n|SdS(N(s _coalescesstreamsselfs src_encodingsformats format_stream(sselfsstreamsformat((s/build/bdist.linux-i686/egg/kid/serialization.pys apply_filters†sccs|i}|i|if\}}|tj oL|i} |i}|i} |i } |i |i f\}}g}t }n|tj o+|i}|i|if\}}d}nd} d}} xø|D]ð\}}|tjo||7}qÉ|ttfjo¬|i}| o||| ƒ}|tjo'|tj o||||ƒ}qqt|ƒ}|o ||jo |}n|o%||8}|djo d}q­n|tj o#|||||||ƒƒ}nd|jo|ot|d| o(||| ƒ}|tj o||||ƒ}n|tjo'|tj o||||ƒ}qðqôt|ƒ}|o ||jo |}n|o%||8}|djo d}qˆn|tj o#|||||||ƒƒ}n| |ƒddjo|d }n| |||ƒ}nt|fVndS(s)Apply format to stream. Note that this method is unaware of the serialization of the tags and does only take into account the text inside the stream. So the results may sometimes differ from what you expect when formatting the complete serialized output. iss iÿÿÿÿiN(&sformatsfilters filter_textsindentswrapsNones indent_liness lstrip_blankss rstrip_blankss lstrip_liness min_levels max_levels indent_levelsFalsesnew_lines wrap_liness indent_widths new_offsetsoffsets formattedstexts last_charsstreamsevsitemsTEXTsSTARTsENDstagslenslevelsTruesCommentsselfs is_inlines is_formattedsappendspop(sselfsstreamsformatstexts filter_texts lstrip_blanksstagswrapsevs last_chars lstrip_liness rstrip_blankss formatteds indent_liness indent_widths wrap_liness max_levelsoffsetsindentsnew_lines min_levels indent_levelslevelsitems new_offset((s/build/bdist.linux-i686/egg/kid/serialization.pys format_streamŒsÜ                                               (s__name__s __module__s namespaces namespacess src_encodingsencodingsoutput_formatssformatsFalses formattedsinlinesNones__init__s _get_formats is_formatteds is_inlines serializeswritesgenerates apply_filterss format_stream(((s/build/bdist.linux-i686/egg/kid/serialization.pys Serializer9s        c BsŒtZeZeZeZeeeeeeeed„Zd„Zee ed„Z eed„Z e e ƒZ eed„Z e e ƒZ RS(Nc Cs‘ti|d|d|d|d|ƒ|tj o ||_n|tj o ||_ n|tj o ||_ n|tj o ||_ ndS(s'Initialize XMLSerializer. You can change the following parameters: encoding: the output encoding decl: add xml declaration at the beginning (True/False) doctype: add doctype (None, string, tuple) entity_map: use named entities for output (True/False or mapping) namespaces: mapping of namespaces formatted: whether all tags should be considered formatted inline: whether all tags should be considered inline format: format to be applied (string or instance of Format) sencodingsformats formattedsinlineN( s Serializers__init__sselfsencodingsformats formattedsinlinesdeclsNonesdoctypes entity_maps namespaces( sselfsencodingsdeclsdoctypes entity_maps namespacess formattedsinlinesformat((s/build/bdist.linux-i686/egg/kid/serialization.pys__init__s       cCstSdS(N(sTrue(sselfs item_name((s/build/bdist.linux-i686/egg/kid/serialization.pyscan_be_empty_element*sccs¿|i}|i}|p|ipd}|i}|i|ƒ}|o[|itj o |i}n|itj o |i}n|itj o |i}q£n|tjo t }n|t jo t}nt |t ƒot |i}nti} ti}t}t|ƒ}t|iƒ} | o6|o d|Vn|tj ot|ƒdVqcnt}x)|i||ƒD]\} }| ttfjo |it joq|nA| t!jo3|tj odi"||gƒ}q||}q|n|tjou| tjo<| p!t#i$|ƒp|i%|iƒ o|i&|iƒo!dVt}t}| i'ƒq|ndVn|o| |||ƒVt}n| tjo|it(jo!d|ii)|ƒVt*}q|q‹|it+jo!d|ii)|ƒVt,}q|q‹| i-} | i/t|d tƒƒ| i0|id tƒ}d |i)|ƒVxX|i1i2ƒD]G\}}| i0|d t ƒi)|ƒ}|||ƒ}d ||fVq_WxÞ| i-i2ƒD]o\} }| | jp| | |joE|||ƒ}| od | i)|ƒ}nd}d ||fVqºqºWn[| tjo|it(t+fjo7| i0|id tƒ}d|i)|ƒV| i'ƒn| }q|W|o|o| |||ƒVndSdS(s­Serializes an event stream to bytes of the specified encoding. This function yields an encoded string over and over until the stream is exhausted. sutf-8s$ s us />s>s ssremovesdefaultsN(7sselfsdeclsdoctypesencodings entity_maps _get_formatsformatsNonesTruesdefault_entity_mapsFalses isinstances basestringsdoctypess XMLSerializers escape_cdatas escape_attribslastevsitersstreamsNamespaceStacks namespacessnamessfragmentsserialize_doctypestexts apply_filterssevsitemsSTARTsENDstagsFragmentsTEXTsjoinsFormatsstrips is_formattedscan_be_empty_elementspopsCommentsencodesCOMMENTsProcessingInstructionsPIscurrents current_namesspushsqnamesattribsitemssksvsprefixsuri(sselfsstreamsencodingsfragmentsformatsdeclstextsqnamesurisprefixs current_namessnamessevs escape_cdatasksdoctypesitemsvslastevs entity_maps escape_attrib((s/build/bdist.linux-i686/egg/kid/serialization.pysgenerate-s¨               #   L      # cCsšyl|o=y|i|ƒ}WqGtj ot|d|ƒSqGXn|iddƒ}|iddƒ}Wn#ttfj ot |ƒnX|SdS(sEscape character data.sentitiess&s&sVscCs |iƒS(N(ssslower(ss((s/build/bdist.linux-i686/egg/kid/serialization.pysXscsž|ddjo |diddƒ\}}nt|f\}}|o |tjoˆi|dtƒ}n|}ˆoˆ|ƒ}n|||fSdS(Nis{is}sdefault( stagssplitsuris localnamesNones xhtml_urisnamessqnamesFalses transpose(stagsqnamesuris localname(s transposesnames(s/build/bdist.linux-i686/egg/kid/serialization.pys grok_name^s s s ssremoveissiÿÿÿÿN(:sselfsdoctypesencodings entity_maps transposes inject_types _get_formatsformatsNonesTruesdefault_entity_mapsFalses isinstances basestringsdoctypesscallablesHTMLSerializers escape_cdatas escape_attribsNamespaceStacks namespacessnamess grok_namescurrentsstacksitersstreamsfragmentsserialize_doctypesinject_meta_content_types apply_filterssevsitemsTEXTs is_escapesescapesSTARTstagsCommentstextsencodesProcessingInstructionsFragmentspushsqnameslowersappendsattribsitemssattrssksvsqslqsis_boolean_attributesENDspopscan_be_empty_element(sselfsstreamsencodingsfragmentsformatsqnamestags escape_attribsescapesevs escape_cdatasstackscurrentsattrsslqs grok_names transposes inject_typesksdoctypesqsitemsvs entity_mapsnames((s transposesnamess/build/bdist.linux-i686/egg/kid/serialization.pysgenerate4sœ                          +&   cCs¥yw|o=y|i|ƒ}WqGtj ot|d|ƒSqGXn|o(|iddƒ}|iddƒ}nWn#tt fj ot |ƒnX|SdS(sEscape character data.sentitiess&s&sq>Wq+W|o |t jodSn|o|SntSdS(sFigure out prefix given a URI.sxmlsN( surisxml_urisNones is_defaultsprefixsselfsstacksnamessitemsspsusdefaultsTrue(sselfsurisdefaults is_defaultspsprefixsusnames((s/build/bdist.linux-i686/egg/kid/serialization.pysresolve_prefixs,      cCsO|djotSnx/|iD]$}|i|ƒ}|o|SqqWtSdS(sFigure out URI given a prefix.sxmlN(sprefixsxml_urisselfsstacksnamessgetsurisNone(sselfsprefixsurisnames((s/build/bdist.linux-i686/egg/kid/serialization.pys resolve_uri s   cCs't|tƒo |i}n|ddjo|Sn|diddƒ\}}|i||ƒ}|t jo|i i |ƒ}|t j o||i|iss(s isinstancesdoctypes basestringslen(sdoctype((s/build/bdist.linux-i686/egg/kid/serialization.pysserialize_doctypeFs  (6s__doc__s __revision__s__date__s __author__s __copyright__s __license__shtmlentitydefsssets NameErrorssetssSets kid.elementsElementsCommentsProcessingInstructionsFragmentsQNames namespacess encode_entitysraise_serialization_errors kid.namespaces namespaces kid.parsersSTARTsENDsTEXTsCOMMENTsPIs _coalesces kid.formatsFormatsoutput_formatss__all__sxmlsurisxml_urisxhtmls xhtml_urisdefault_entity_mapscodepoint2namesitemssksvsunichrsdoctypessobjects Serializers XMLSerializers HTMLBasedsHTMLSerializersXHTMLSerializersPlainSerializersNamespaceStacksserialize_doctype('s xhtml_urissetsXHTMLSerializers encode_entitysTEXTsraise_serialization_errorsPlainSerializers XMLSerializers _coalescesCOMMENTs __revision__s__all__sFormatsFragments namespacesHTMLSerializersPIsENDsdoctypess __license__sNamespaceStacksserialize_doctypesxml_urishtmlentitydefss __author__sSTARTs namespacessdefault_entity_mapsElements SerializersComments __copyright__sProcessingInstructionsoutput_formatssksQNames__date__s HTMLBasedsv((s/build/bdist.linux-i686/egg/kid/serialization.pys?s< 7 +   ¢ÏªNÄ# TPKÆ=ð6Ê[ßch3h3kid/template_util.pyc;ò \P›Fc@s<dZdZdZdZdZdZdkZdkZdkl Z l Z l Z l Z dk Z dkZdklZlZlZlZlZlZlZlZlZlZlZlZd klZlZlZl Z d d d d dddddddddddgZ!de"fd„ƒYZ#de#fd„ƒYZ$de#fd„ƒYZ%de#fd „ƒYZ&d!e#fd"„ƒYZ'd#e#fd$„ƒYZ(d%e#fd&„ƒYZ)d'd(d)d*d+d,gZ*e+d-„Z,e+e+d.„Z-d/„Z.e+d0„Z/d1„Z0e+d2„Z1d3„Z2d4„Z3d5„Z4d6„Z5d7„Z6e+d8„Z7dS(9s0Utility functions used by generated kid modules.s $Rev: 492 $s5$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $s!Ryan Tomayko (rtomayko@gmail.com)s!Copyright 2004-2005, Ryan Tomaykos8MIT N(sTypeTypes ModuleTypes ClassTypes GeneratorType( sXMLsdocuments ElementStreamsSTARTsENDsTEXTsSTART_NSsCOMMENTsPIsDOCTYPEsXML_DECLs to_unicode(sElements SubElementsCommentsProcessingInstructionsXMLsdocuments ElementStreamsElements SubElementsCommentsProcessingInstructionsSTARTsENDsTEXTsSTART_NSsCOMMENTsPIsDOCTYPEsXML_DECLs TemplateErrorcBstZRS(N(s__name__s __module__(((s/build/bdist.linux-i686/egg/kid/template_util.pys TemplateErrorssTemplateNotFoundcBstZRS(N(s__name__s __module__(((s/build/bdist.linux-i686/egg/kid/template_util.pysTemplateNotFoundssTemplateImportErrorcBstZRS(N(s__name__s __module__(((s/build/bdist.linux-i686/egg/kid/template_util.pysTemplateImportErrorssTemplateDictErrorcBstZRS(N(s__name__s __module__(((s/build/bdist.linux-i686/egg/kid/template_util.pysTemplateDictErrorssTemplateAttrsErrorcBstZRS(N(s__name__s __module__(((s/build/bdist.linux-i686/egg/kid/template_util.pysTemplateAttrsError ssTemplateExtendsErrorcBstZRS(N(s__name__s __module__(((s/build/bdist.linux-i686/egg/kid/template_util.pysTemplateExtendsError!ssTemplateLayoutErrorcBstZRS(N(s__name__s __module__(((s/build/bdist.linux-i686/egg/kid/template_util.pysTemplateLayoutError"ssgeneratesmodulesparsers serializes transformswritecCs›|tjo h}ng}t}xdti|ƒD]S\}}|i dƒ o||j o ||jo|i d||fƒq3q3Wdi |ƒSdS(Ns_s %s=self.%ss;( s_localssNoneslss_local_excludesslocal_excludessinspects getmemberssinstsvarsvalues startswithsappendsjoin(sinsts_localsslocal_excludessvalueslssvar((s/build/bdist.linux-i686/egg/kid/template_util.pys get_locals&s   ,cCst|tjo tiSnt|tƒo|Sn t|tƒoÄy |i}Wnt j o t}nXt|tƒo t |tiƒo |tijo|Snt |ƒ}|o |}n0y |i }Wnt j ot |ƒ}nXtd|ƒ‚n6t|tƒo%ytii||ƒ}Wntj o t}nX| o%|o |}ntd|ƒ‚nyti|ƒ}Wntj o t}nX| otd|ƒ‚ny |i}Wnt j o t}nXt|tƒo t |tiƒo |tijo|Sntd|ƒ‚nt |ƒ}|od||f}ntd|ƒ‚dS(sAGet template base class for thing, raising an exception on error.s%%s is a module without Template classsTemplate file %r not foundsCould not open %rs$%r does not contain a template classs%s (%s)s%s is not a Template classN(sthingsNoneskids BaseTemplates isinstancesTypeTypes ModuleTypesTemplatesclssAttributeErrors issubclasssreprsargs__name__sTemplateNotFounds basestringspathsfinds from_files Exceptions load_templatesmod(sthings from_filesargsmodsclsspath((s/build/bdist.linux-i686/egg/kid/template_util.pysget_base_class1s\    3        3 cCsÂy0|d}t|||ƒ}t|||ƒSWn‹tj o}t |ƒg}yt|||ƒSWn(tj o}|i t |ƒƒnXdi t t|ƒƒp|}t|‚nXdS(s=Get base class for argument with graceful exception handling.s__file__s N(sglobalss from_filesevalsargslocalssthingsget_base_classs ExceptionsesstrserrorssappendsjoinsfiltersboolsTemplateNotFound(sargsglobalsslocalss from_fileserrorssesthing((s/build/bdist.linux-i686/egg/kid/template_util.pys base_classgs cCsWyt|||ƒSWn<tj o0}tt|ƒd|p|i ƒƒ‚nXdS(s&Get Template base class for 'extends'.s while processing extends=%rN( s base_classsextendssglobalsslocalss ExceptionsesTemplateExtendsErrorsstrs all_extendsslstrip(sextendssglobalsslocalss all_extendsse((s/build/bdist.linux-i686/egg/kid/template_util.pysbase_class_extendsxs cCsPyt|||ƒSWn5tj o)}tt|ƒd|iƒƒ‚nXdS(s%Get Template base class for 'layout'.s while processing layout=%rN( s base_classslayoutsglobalsslocalss ExceptionsesTemplateLayoutErrorsstrslstrip(slayoutsglobalsslocalsse((s/build/bdist.linux-i686/egg/kid/template_util.pysbase_class_layouts cCsÌ|tjohSn|tjotiƒ}nx|iƒD]\}}|tj oFyt||ƒ}Wqžt j o t d|i dƒƒ‚qžXn|tjo ||=q?||| Python Expression Evaluator

${FieldStorage.getvalue('expr')} = ${eval(FieldStorage.getvalue('expr'))}

Enter a Python expression:

s $Rev: 492 $s5$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $s$Christoph Zwerschke (cito@online.de)s#Copyright 2005, Christoph Zwerschkes8MIT N(sunquote(s HTTPServer(sSimpleHTTPRequestHandler(s FieldStorage(s load_templates HTTPServersHTTPRequestHandlers localhosti@cBs>tZdZd„Zd„Zd„ZddgZd„ZRS(s©Complete HTTP server with GET, HEAD and POST commands. GET and HEAD also support running Kid templates. The POST command is *only* implemented for Kid templates.cCs/|iƒo|iƒn|iddƒdS(s3Serve a POST request implemented for Kid templates.iõsCan only POST to Kid templatesN(sselfsis_kidsrun_kids send_error(sself((s(build/bdist.linux-i686/egg/kid/server.pysdo_POSTPs cCs,|iƒo|iƒSnti|ƒSdS(s1Version of send_head that supports Kid templates.N(sselfsis_kidsrun_kidsSimpleHTTPRequestHandlers send_head(sself((s(build/bdist.linux-i686/egg/kid/server.pys send_headWs cCs|i}|idƒ}|djo"|| ||df\}}nd}x8|iD]-}|i|ƒo||f|_t SqWqWWt SdS(sÀTest whether self.path corresponds to a Kid template. The default implementation tests whether the path ends with one of the strings in the list self.kid_extensions. s?iisN( sselfspathsrfindsisqueryskid_extensionssxsendswithscgi_infosTruesFalse(sselfsisquerysxspath((s(build/bdist.linux-i686/egg/kid/server.pysis_kid^s  "  s.kids .kid.htmlc Cs[|i\}}|i|ƒ}tii|ƒ o|i dd|ƒdSntii |ƒ o|i dd|ƒdSnh} |i ƒ| d<|i i| dNsFormatsoutput_formatscBs†tZdZdZdZddf\ZZdZdZdZ dZ dZ d Z e id ƒZe id e iƒZe id e iƒZe id ƒZe idƒZe idƒZe idƒZe idƒZe idƒZe idƒZe idƒZe idƒZe ide iƒZe ide iƒZe ide iƒZe ide iƒZ e idƒZ!e idƒZ"e ide iƒZ#e idƒZ$d„Z%d„Z&e'e'd „Z(d!„Z)d"„Z*e+e*ƒZ*d#„Z,e+e,ƒZ,d$„Z-e+e-ƒZ-d%„Z.e+e.ƒZ.d&„Z/e+e/ƒZ/d'„Z0e+e0ƒZ0d(„Z1e2e1ƒZ1d)„Z3e2e3ƒZ3d*„Z4e2e4ƒZ4d+„Z5e2e5ƒZ5d,„Z6e2e6ƒZ6d-„Z7e2e7ƒZ7d.„Z8e2e8ƒZ8d/„Z9e2e9ƒZ9d0„Z:d1„Z;d2„Z<d3„Z=e'e'd4„Z>e'e'd5„Z?e'd6„Z@e'd7d7d8„ZAed9„ZBe+eBƒZBd7d:„ZCe+eCƒZCRS(;s#Formatting details for Serializers.iPs iiu’u‘’u“â€u–—u…s [ \t\n\r]+s^[ \t]+s[ \t]+$s [ \t]{2,}s\n[ \t\n\r]*\ns[ \t]*\n[ \t\n\r]*s\n[ \t]*s's"s`s(?|tt |ƒjo$|ddfjot pt }nWnt j onX|t j o|||(s splittypesQuickTextReadercBs;tZd„Zd„Zd„Zed„Zdd„ZRS(NcCs1||_t|iƒ|_d|_t|_dS(Ni(stextsselfslenspossNoneslines(sselfstext((s&build/bdist.linux-i686/egg/kid/util.pys__init__s  ccs\xUnoM|itjo|iitƒ|_n|i oPn|iidƒVq WdS(Nii(sselfslinessNonestexts splitlinessTruespop(sself((s&build/bdist.linux-i686/egg/kid/util.pys__iter__s cCs&t|_d|_|_t|_dS(Ni(sNonesselfstextsposslenslines(sself((s&build/bdist.linux-i686/egg/kid/util.pyscloses cCsÕ|tj oPyt|ƒ}Wn t}q]Xd|jo |ijn o t}q]n|i}|tjo|i|_|i|SnD|i|7_|i|ijo|i|_n|i||i!SdS(Ni(ssizesNonesintsselfslensposstext(sselfssizespos((s&build/bdist.linux-i686/egg/kid/util.pysread$s  "   icCs£|o4|djo|i||_qM|i|7_n||_t|_|idjo d|_n$|i|ijo|i|_nd„}d„}dS(NiicCs |iSdS(N(sselfspos(sself((s&build/bdist.linux-i686/egg/kid/util.pystellEscCsY|i o|itƒ|_n|id7_|i o t‚n|iidƒSdS(Nii(sselfslinenos splitlinessTruesliness StopIterationspop(sself((s&build/bdist.linux-i686/egg/kid/util.pysnextHs    ( swhencesselfslensoffsetspossNoneslinesstellsnext(sselfsoffsetswhencesnextstell((s&build/bdist.linux-i686/egg/kid/util.pysseek7s     (s__name__s __module__s__init__s__iter__sclosesNonesreadsseek(((s&build/bdist.linux-i686/egg/kid/util.pysQuickTextReaders     cCsBx;|D]3}|djoqq|djotSqtSqWdS(snSniff text to see if it looks like XML. Return True if text looks like XML, otherwise return False. s sNsElements SubElementsCommentsProcessingInstructionsFragmentsQNames namespacess escape_maps encode_entitysraise_serialization_errorcBsÂtZdZeZeZhd„Zd„Zd„Zd„Z d„Z d„Z d„Z d„Z d „Zd „Zd „Zd „Zd „Zd„Zed„Zd„Zd„Zd„ZRS(s$A class representing an XML element.cKs8|iƒ}|i|ƒ||_||_g|_dS(N(sattribscopysupdatesextrastagsselfs _children(sselfstagsattribsextra((s)build/bdist.linux-i686/egg/kid/element.pys__init__s     cCsd|it|ƒfSdS(Ns(sselfstagsid(sself((s)build/bdist.linux-i686/egg/kid/element.pys__repr__scCst|iƒSdS(N(slensselfs _children(sself((s)build/bdist.linux-i686/egg/kid/element.pys__len__$scCs|i|SdS(N(sselfs _childrensindex(sselfsindex((s)build/bdist.linux-i686/egg/kid/element.pys __getitem__'scCs(t|tƒpt‚||i| URI mappings. Default namespace attributes result in a key of ''. If remove is truthful, namespace declaration attributes are removed from the passed in Element. sxmlns:isxmlnssN(snamesselemskeyssks startswithsgetsremovesattrib(selemsremovesksnames((s)build/bdist.linux-i686/egg/kid/element.pys namespaces†s  s&s&ss>s"s"su"[&<>\"\u0080-\uffff]+"cCsd|tjo t}n|d„}y|i||ƒidƒSWntj ot |ƒnXdS(NcCskg}xQ|iƒD]C}|i|ƒ}|tjodt|ƒ}n|i |ƒqWdi |ƒSdS(Ns&#%d;s( soutsmsgroupscharsentitiessgetstextsNonesordsappendsjoin(smsentitiesstextscharsout((s)build/bdist.linux-i686/egg/kid/element.pysescape_entities¯s  sascii( sentitiessNones escape_mapsescape_entitiesspatternssubstextsencodes TypeErrorsraise_serialization_error(stextspatternsentitiessescape_entities((s)build/bdist.linux-i686/egg/kid/element.pys encode_entity«s   cCs#td|t|ƒifƒ‚dS(Nscannot serialize %r (type %s)(s TypeErrorstextstypes__name__(stext((s)build/bdist.linux-i686/egg/kid/element.pysraise_serialization_error¼s(s__doc__s __revision__s__date__s __author__s __copyright__s __license__sres__all__sobjectsElements SubElementsNonesCommentsProcessingInstructionsFragmentsQNamesFalses namespacess escape_mapscompilesevals re_escapes encode_entitysraise_serialization_error(s re_escapesraise_serialization_errors encode_entitys __revision__s__all__sFragmentsres escape_maps __license__s __author__s namespacessElementsComments __copyright__sProcessingInstructionsQNames__date__s SubElement((s)build/bdist.linux-i686/egg/kid/element.pys?s$ $L     *PKÆ=ð6%LÜÝkid/options.pyc;ò [P›Fc@sYdZdkZdZdZdZdZeiZdgZdZ de fd„ƒYZ dS( sConfiguration API.Ns $Rev: 492 $s5$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $s"David Stanek sCopyright 2006, David StaneksOptionsskid:cBs_tZhd„Zd„Zed„Zd„Zd„Zd„Zd„Z d„Z d „Z RS( NcKsgh|_x*|iƒD]\}}|i||ƒqWx*|iƒD]\}}|i||ƒqCWdS(N(sselfs_optionssoptionssitemssnamesvaluessetsextra(sselfsoptionssextrasvaluesname((s)build/bdist.linux-i686/egg/kid/options.pys__init__s   cCs|ii|i|ƒƒSdS(scReturns True if a option exists or False if it doesn't. name: the option to check N(sselfs_optionsshas_keys_Options__prefixsname(sselfsname((s)build/bdist.linux-i686/egg/kid/options.pysissetscCs |ii|i|ƒ|ƒSdS(s’Get the value of an option. name: the option to retrieve default: returned for non-existing properties, defaults to None N(sselfs_optionssgets_Options__prefixsnamesdefault(sselfsnamesdefault((s)build/bdist.linux-i686/egg/kid/options.pysget!scCs||i|i|ƒ<|SdS(sœSet the value of an option. name: the option to set value: the value to be set for the option Returns the value passed in. N(svaluesselfs_optionss_Options__prefixsname(sselfsnamesvalue((s)build/bdist.linux-i686/egg/kid/options.pysset)scCs+|i|ƒo|i|i|ƒ=ndS(sRemove an option.N(sselfsissetsnames_optionss_Options__prefix(sselfsname((s)build/bdist.linux-i686/egg/kid/options.pysremove3scCs3|i|ƒ otd|‚n|i|ƒSdS(Ns no option %s(sselfsissetsnamesKeyErrorsget(sselfsname((s)build/bdist.linux-i686/egg/kid/options.pys __getitem__8scCs|i||ƒdS(N(sselfssetsnamesvalue(sselfsnamesvalue((s)build/bdist.linux-i686/egg/kid/options.pys __setitem__=scCs3|i|ƒ otd|‚n|i|ƒdS(Ns no option %s(sselfsissetsnamesKeyErrorsremove(sselfsname((s)build/bdist.linux-i686/egg/kid/options.pys __delitem__@scCs'|itƒ ot|}n|SdS(s,Add the prefix if it does not already exist.N(snames startswiths_prefix(sselfsname((s)build/bdist.linux-i686/egg/kid/options.pys__prefixEs( s__name__s __module__s__init__sissetsNonesgetssetsremoves __getitem__s __setitem__s __delitem__s_Options__prefix(((s)build/bdist.linux-i686/egg/kid/options.pysOptionss       ( s__doc__sreleases __revision__s__date__s __author__s __copyright__slicenses __license__s__all__s_prefixsobjectsOptions( s __copyright__s __revision__s__all__s __license__s_prefixs __author__s__date__sreleasesOptions((s)build/bdist.linux-i686/egg/kid/options.pys?s   PKY8ð6)’ø*ââkid/test/test_comment.py"""Unit Tests for the XML comments.""" __revision__ = "$Rev: 455 $" __author__ = "David Stanek " __copyright__ = "Copyright 2005, David Stanek" import kid from kid.serialization import serialize_doctype, doctypes def test_comments_inside(): """Comments inside the root element.""" t = kid.Template('') assert (t.serialize(output='HTML') == serialize_doctype(doctypes['html']) + '\n') def test_comments_outside(): """Comments outside the root element (ticket #134).""" t = kid.Template('') assert (t.serialize(output='HTML') == serialize_doctype(doctypes['html']) + '\n') def test_comments_and_python(): """Comments and PI outside the root element evaluated inside.""" t = kid.Template('' '$x') assert (t.serialize(output='HTML') == serialize_doctype(doctypes['html']) + '\n42') def test_nested_comments(): """Nested comments.""" t = kid.Template('
' '

') assert (t.serialize(output='HTML') == serialize_doctype(doctypes['html']) + '\n
' '

') def test_comment_removal(): """Comments that start with '!' should not be output.""" t = kid.Template('') assert t.serialize(output='HTML') == \ serialize_doctype(doctypes['html']) + '\n' assert t.serialize(output='xhtml') == \ serialize_doctype(doctypes['xhtml']) + '\n' assert t.serialize(output='xml') == \ '\n' t = kid.Template('') assert t.serialize(output='HTML') == \ serialize_doctype(doctypes['html']) + '\n' assert t.serialize(output='xhtml') == \ serialize_doctype(doctypes['xhtml']) + '\n' assert t.serialize(output='xml') == \ '\n' def test_comment_interpolation(): """Comments starting with '[' or '' % (b, c, d) if c.startswith('!'): after_comment = '' elif c == '[' or c == '' % (b, c, d) else: after_comment = before_comment before = '%s' % before_comment t = kid.Template(before, before='after') for output in ('HTML', 'xhtml', 'xml'): if output == 'HTML': after = '%s' % after_comment elif output == 'xhtml' or after_comment: after = '%s' % after_comment else: after = '' if output == 'xml': after = '\n' + after else: doctype = serialize_doctype(doctypes[output.lower()]) after = doctype + '\n' + after assert t.serialize(output=output) == after def test_comment_for_loop(): """Commenting out section with py:for and substitution (ticket #149).""" xml = """ """ t = kid.Template(xml, mylist = ['peaches', 'cream']) assert """ """ in t.serialize(output='html') def test_comment_style_sheet(): """Allow variable substitution in style sheet (ticket #124).""" xml = """ """ t = kid.Template(xml, section="support") assert "#menu a#support" in t.serialize(output='html') PKY8ð6ÄÙ“â((kid/test/__init__.py# -*- coding: utf-8 -*- """Kid test package.""" __revision__ = "$Rev: 492 $" __date__ = "$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " import sys import os import glob from os.path import abspath, basename, dirname, join as joinpath from kid.test.util import dot __all__ = ['dot', 'run_suite', 'template_package', 'output_dir', 'template_dir'] _mydir = abspath(joinpath(dirname(__file__), '..', '..')) template_dir = joinpath(_mydir, 'test') output_dir = template_dir template_package = 'test.' test_modules = [basename(f)[:-3] for f in glob.glob(joinpath(_mydir, 'kid', 'test', 'test*.py'))] additional_tests = 0 basic_tests = 0 def run_suite(args): stop_first = '-x' in args from kid.test.util import run_suite tests = ['kid.test.%s' % m for m in test_modules] run_suite(tests, stop_first) if __name__ == '__main__': run_suite(sys.argv[1:]) PKY8ð6Ü}·A¬¬kid/test/test_compiler.py# -*- coding: utf-8 -*- """Kid package tests.""" __revision__ = "$Rev: 492 $" __date__ = "$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " import sys from os.path import join as joinpath, exists import kid import kid.compiler import kid.test.test_kid check_xml_file = kid.test.test_kid.check_xml_file def setup_module(module): kid.test.test_kid.setup_module(module) def teardown_module(module): kid.test.test_kid.teardown_module(module) def assert_template_interface(t): assert hasattr(t, 'pull') assert hasattr(t, 'generate') assert hasattr(t, 'write') assert hasattr(t, 'serialize') def test_import_hook(): kid.enable_import() import test.test_if assert_template_interface(test.test_if) assert sys.modules.has_key('test.test_if') kid.disable_import() def test_pyc_generation(): # if this exists, the test is worthless. make sure this test runs before # anything else import test_content from kid.test import template_dir kid.enable_import() assert not exists(joinpath(template_dir, 'test_content.pyc')) import test.test_content assert exists(joinpath(template_dir, 'test_content.pyc')) assert sys.modules.has_key('test.test_content') def test_import_and_expand(): from kid.test import output_dir kid.enable_import() import test.context as c C = c.Template out = joinpath(output_dir, 'context.out') t = C(foo=10, bar='bla bla') it = t.pull() for e in it: pass t.write(out) check_xml_file(out) PKY8ð6B°+üë ë kid/test/test_kid_lang.py __revision__ = "$Rev: 421 $" __author__ = "David Stanek " __copyright__ = "Copyright 2005, David Stanek" import kid def test_strip_no_expr(): """A py:strip without an expression will strip that element.""" source = """ stuff """ data = kid.Template(source=source).serialize() assert "wrapper" not in data assert "present" in data def test_strip_with_boolean_expression__or(): """Test for the bug that was reported in ticket #97.""" source_template = """ content content """ t = kid.Template(source=source_template % (True, True)) assert "" not in t.serialize() t = kid.Template(source=source_template % (True, False)) assert "" not in t.serialize() t = kid.Template(source=source_template % (False, True)) assert "" not in t.serialize() t = kid.Template(source=source_template % (False, False)) assert t.serialize().count("") == 2 def test_strip_with_boolean_expression__eq(): source = """ """ data = kid.Template(source=source).serialize() assert " you will never see this """ data = kid.Template(source=source).serialize() assert "wrapper" not in data assert "x" in data def test_replace_with_strip(): """py:strip as ignored if py:replace exists in the same element.""" source = """ content """ data = kid.Template(source=source).serialize() assert "wrapper" not in data assert "x" in data def test_attr(): source = """ """ data = kid.Template(source=source).serialize() assert data.count('') == 4 def test_attr_with_strip(): source = """ """ data = kid.Template(source=source).serialize() print data assert 'a="1"' in data assert 'b="2"' in data PKY8ð6…I/9l#l#kid/test/test_kid.py"""kid package tests.""" __revision__ = "$Rev: 455 $" __date__ = "$Date: 2006-12-21 01:42:34 -0500 (Thu, 21 Dec 2006) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " import os import sys from os.path import exists, join as joinpath, splitext from glob import glob import kid, kid.test from kid.test import template_package, output_dir, template_dir try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree keep_files = [] def cleanup(): for f in glob(joinpath(output_dir, '*.out')): try: os.unlink(f) except OSError: pass for f in glob(joinpath(template_dir, '*.pyc')): try: os.unlink(f) except OSError: pass for f in glob(joinpath(template_dir, '*.py')): if exists(splitext(f)[0] + '.kid') and not f in keep_files: try: os.unlink(f) except OSError: pass def setup_module(module): cleanup() def teardown_module(module): if not os.environ.get('KID_NOCLEANUP'): cleanup() def assert_template_interface(t): assert hasattr(t, 'pull') assert hasattr(t, 'generate') assert hasattr(t, 'write') assert hasattr(t, 'serialize') def test_import_and_expand(): try: del sys.modules['test.context'] except KeyError: pass kid.disable_import() try: import test.context as c except ImportError: c = None assert c is None kid.enable_import() import test.context as c kid.disable_import() C = c.Template out = joinpath(output_dir, 'context.out') t = C(foo=10, bar='bla bla') it = t.pull() for e in it: pass t.write(out) check_xml_file(out) def test_import_template_func(): assert not sys.modules.has_key(template_package + 'test_def') t = kid.import_template(template_package + 'test_def') assert_template_interface(t) assert sys.modules.has_key(template_package + 'test_def') def test_load_template_func(): t = kid.load_template(joinpath(template_dir, 'test_if.kid'), name='', cache=False) assert_template_interface(t) t2 = kid.load_template(joinpath(template_dir, 'test_if.kid'), name=template_package + 'test_if', cache=True) assert not t is t2 t3 = kid.load_template(joinpath(template_dir, 'test_if.kid'), name=template_package + 'test_if', cache=True) assert t3 is t2 def test_load_template_func_with_ns(): t = kid.load_template(joinpath(template_dir, 'templates.kid'), name='', cache=False) s = """ """ t2 = kid.load_template(s, cache=False, ns={'t': t}) xml = t2.serialize() assert "This is a test" in xml def test_load_template_with_exec_module(): s = """ Hello, World!""" t= kid.load_template(s) assert t.Mickey == 'Mouse' assert not hasattr(t, 'Donald') def exec_module(mod, code): exec code in mod.__dict__ mod.Donald = 'Duck' t = kid.load_template(s, exec_module=exec_module) assert t.Mickey == 'Mouse' assert t.Donald == 'Duck' def test_template_func(): t = kid.Template(name=template_package + 'test_if') assert_template_interface(t) assert isinstance(t, kid.BaseTemplate) def test_generate_func(): def run_test(o): for s in o.generate(encoding='ascii'): assert s is not None and len(s) > 0 run_test(kid.Template(name=template_package + 'test_if')) run_test(kid.load_template(joinpath(template_dir, 'test_if.kid'))) def test_write_func(): class FO: def write(self, text): pass kid.Template(name=template_package+'test_if').write(file=FO()) m = kid.load_template(joinpath(template_dir, 'test_if.kid')) m.write(file=FO()) def test_serialize_func(): def run_test(o): out = o.serialize(encoding='utf-8') assert out is not None and len(out) > 0 out = o.serialize(encoding='ascii') assert out is not None and len(out) > 0 run_test(kid.Template(name=template_package + 'test_if')) run_test(kid.load_template(joinpath(template_dir, 'test_if.kid'))) def test_short_form(): # check that the serializer is outputting short-form elements when # no character data is present text = """ """ template = kid.Template(file=text) #mod.Template() actual = template.serialize().strip() assert actual == text, '%r != %r' % (actual, text) def test_XML_func_fragment(): text = u"""some plain "text" with & entities.""" t = kid.Template(source="

${XML(text)}

", text=text) rslt = t.serialize(fragment=True) assert rslt == '''

some plain "text" with & entities.

''' # another one text = """something

something else

""" t = kid.Template(source="

${XML(text)}

", text=text) actual = t.serialize(fragment=True) expected = '''

something

something else

''' assert actual == expected, '%r != %r' % (actual, expected) def test_XML_ns_fragment(): text = """something

something else

""" t = kid.Template(source='

${XML(text, xmlns="foo")}

', text=text) actual = t.serialize(fragment=True) expected = '''

something

something else

''' assert actual == expected, '%r != %r' % (actual, expected) def test_XML_func_unicode(): s = u"""asdf \u2015 qwer""" t = kid.Template(source="""

${XML(s)}

""", s=s) print repr(t.serialize()) def test_dont_modify_trees(): t = kid.Template(source="$xml") t.xml = ElementTree.fromstring("somenestedelements") expected = "somenestedelements" assert t.serialize(fragment=True) == expected print ElementTree.dump(t.xml) assert t.serialize(fragment=True) == expected def test_comments(): t = kid.Template(source="") rslt = t.serialize(fragment=True) assert rslt == "" def test_kid_files(test='*'): test_files = glob(joinpath(template_dir, 'test_%s.kid' % test)) for f in test_files: out = f[0:-4] + '.out' try: template = kid.Template(file=f, cache=True) template.assume_encoding = "utf-8" template.write(out) check_xml_file(out) except Exception: print '\nTemplate: %s' % f try: kid.compiler.compile_file(f, source=True, force=True, encoding="utf-8") except: print "Corresponding source module could not be created." else: keep_files.append(splitext(f)[0] + '.py') print "The correspoding source module has been created." raise def check_xml_file(filename): dot = kid.test.dot doc = ElementTree.parse(filename).getroot() assert doc.tag == 'testdoc' for t in doc.findall('test'): attempt = t.find('attempt') expect = t.find('expect') if expect.get('type') == 'text': doc = ElementTree.XML(expect.text) expect.append(doc) expect.text = '' try: diff_elm(attempt, expect, diff_this=False) except AssertionError: raise else: dot() kid.test.additional_tests += 1 def diff_elm(elm1, elm2, diff_this=True): for e in [elm1, elm2]: e.tail = e.tail and e.tail.strip() or None e.text = e.text and e.text.strip() or None if diff_this: assert elm1.tag == elm2.tag assert elm1.attrib == elm2.attrib assert elm1.tail == elm2.tail expected = elm2.text actual = elm1.text assert actual == expected, '%r != %r' % (actual, expected) ch1 = elm1.getchildren() ch2 = elm2.getchildren() assert len(ch1) == len(ch2) for elm1, elm2 in zip(ch1, ch2): diff_elm(elm1, elm2) def test_string_templates(): """Test for collisions in templates created with a string (ticket #70).""" t1 = kid.Template(source="") t2 = kid.Template(source="") assert str(t1) == '\n' assert str(t2) == '\n' def test_reserved_names(): """Check for reserved keyword arguments (ticket #181).""" from kid.template_util import TemplateAttrsError try: t = kid.Template('
', content=None) except TemplateAttrsError, e: e = str(e) else: e = 'reserved name was not detected' assert repr('content') in e assert 'reserved name' in e PKY8ð6.ÑiFiFkid/test/test_serialization.py# -*- coding: utf-8 -*- """kid.serialization tests.""" __revision__ = "$Rev: 492 $" __date__ = "$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " import kid from kid.namespace import xhtml from kid.serialization import serialize_doctype, doctypes xhtml_namespace = str(xhtml) def test_serialize_doctype(): sd = serialize_doctype assert (sd(doctypes['xhtml-strict']) == '') assert (sd(doctypes['html-quirks']) == '') assert sd('a') == 'a' assert sd(('a',)) == '' assert sd(('a', 'b')) == '' assert sd(('a', 'b', 'c')) == '' def test_html_output_method(): t = kid.Template('

Test


') for output in 'html', 'html-strict': rslt = t.serialize(output=output) expected = serialize_doctype(doctypes[output]) + \ '\n

Test


' assert rslt == expected def test_HTML_output_method(): t = kid.Template('

Test


') for output in 'HTML', 'HTML-strict': rslt = t.serialize(output=output) expected = serialize_doctype(doctypes[output.lower()]) + \ '\n

Test


' assert rslt == expected def test_xhtml_output_method(): t = kid.Template('' '

test


') for output in 'xhtml', 'xhtml-strict': rslt = t.serialize(output=output) expected = serialize_doctype(doctypes[output]) \ + '\n' \ + '

test

' \ + '
' assert rslt == expected def test_html_strict_output_method(): t = kid.Template('

test


') rslt = t.serialize(output='HTML-strict') expected = serialize_doctype(doctypes['html-strict']) + \ '\n

test


' assert rslt == expected def test_html_quirks_output_method(): t = kid.Template('

test


') rslt = t.serialize(output='HTML-quirks') expected = serialize_doctype(doctypes['html-quirks']) + \ '\n

test


' assert rslt == expected def test_xml_output_method(): t = kid.Template('

test


') rslt = t.serialize(output='xml') expected = '\n' + \ '

test


' assert rslt == expected from kid.serialization import HTMLSerializer, XMLSerializer, XHTMLSerializer serializer = HTMLSerializer() serializer.doctype = None serializer.inject_type = False def HTMLTemplate(text, **kw): t = kid.Template(text, **kw) t.serializer = serializer return t def test_html_transpose(): t = kid.Template('') t.serializer = HTMLSerializer() rslt = t.serialize() assert rslt.endswith('') t.serializer = HTMLSerializer(transpose=False) rslt = t.serialize() assert rslt.endswith('') t.serializer = HTMLSerializer(transpose=True) rslt = t.serialize() assert rslt.endswith('') t.serializer = HTMLSerializer(transpose=None) rslt = t.serialize() assert rslt.endswith('') def transpose(s): return s.capitalize() t.serializer = HTMLSerializer(transpose=transpose) rslt = t.serialize() assert rslt.endswith('') def test_html_empty_elements(): close_tags = 'div p pre span script textarea'.split() noclose_tags = 'br hr img input link meta'.split() for tag in close_tags + noclose_tags: xml = '<%s/>' % tag t = HTMLTemplate(xml) rslt = t.serialize() if tag in noclose_tags: html = '<%s>' % tag else: html = '<%s>' % (tag, tag) html = xml.replace('<%s/>' % tag, html) assert rslt == html def test_xhtml_empty_elements(): noempty_tags = 'div p pre textarea'.split() empty_tags = 'br hr img input'.split() for namespace in ('', ' xmlns="%s"' % xhtml_namespace): for tag in noempty_tags + empty_tags: xml = '<%s/>' % (namespace, tag) t = kid.Template(xml) rslt = t.serialize(output='xhtml') if tag in empty_tags: xhtml = '<%s />' % tag else: xhtml = '<%s>' % (tag, tag) xhtml = xml.replace('<%s/>' % tag, xhtml) xhtml = serialize_doctype(doctypes['xhtml']) + '\n' + xhtml assert rslt == xhtml def test_html_noescape_elements(): t = HTMLTemplate("") expected = '' rslt = t.serialize() assert rslt == expected def test_html_boolean_attributes(): t = HTMLTemplate('' '' % xhtml_namespace) expected = '' rslt = t.serialize() assert rslt == expected def test_doctype_and_injection(): serializer = HTMLSerializer(encoding='utf-8', transpose=True) serializer.doctype = doctypes['html-strict'] serializer.inject_type = True source = "" t = kid.Template(source) t.serializer = serializer from kid.format import Format format=Format(no_empty_lines=True) rslt = t.serialize(format=format) rslt = rslt.replace('\n', '') expected = ('' '' '' '') assert rslt == expected serializer = HTMLSerializer(encoding='ascii', transpose=False) serializer.doctype = None serializer.inject_type = True source = ('' '' '' '' 'Content' '

Hello, World!

') t = kid.Template(source) t.serializer = serializer rslt = t.serialize() expected = source.replace('/>', '>') assert rslt == expected source = source.replace('content-type', 'garbage-type') t = kid.Template(source) t.serializer = serializer rslt = t.serialize() rslt = rslt.replace('\n', '') expected = source.replace('/>', '>').replace('', '<meta content="text/html; charset=ascii"' ' http-equiv="content-type"><title>') assert rslt == expected def test_output_methods(): xml = '<html xmlns="%s"><h1 />Hello<br />World</html>' % xhtml_namespace t = kid.Template(xml) assert len(kid.output_methods) >= 15 for output in kid.output_methods: s = t.serialize(output=output) if 'html' in output.lower(): # html or xhtml assert s.startswith('<!DOCTYPE ') assert s.lower().startswith('<!doctype html public "') if output.startswith('xhtml'): assert 'DOCTYPE html PUBLIC' in s assert ' "-//W3C//DTD XHTML 1.0' in s else: assert 'DOCTYPE HTML PUBLIC' in s assert ' "-//W3C//DTD HTML 4.01' in s assert '//EN"' in s if 'strict' in output: assert 'transitional' not in s.lower() assert 'frameset' not in s.lower() assert 'loose' not in s.lower() else: assert 'strict' not in s.lower() if 'frameset' in output: assert 'transitional' not in s.lower() assert ' Frameset' in s else: assert 'frameset' not in s.lower() assert ' Transitional' in s if 'quirks' in output: assert 'http://' not in s assert 'dtd' not in s else: assert '"http://www.w3.org/TR/' in s assert '.dtd"' in s if output.startswith('xhtml'): if 'strict' in output: assert '/xhtml1/DTD/xhtml1-strict.dtd"' in s elif 'frameset' in output: assert '/xhtml1/DTD/xhtml1-frameset.dtd"' in s else: assert '/xhtml1/DTD/xhtml1-transitional.dtd"' in s else: if 'strict' in output: assert '/html4/strict.dtd"' in s elif 'frameset' in output: assert '/html4/frameset.dtd"' in s else: assert '/html4/loose.dtd"' in s r = xml r = r.replace('<h1 />', '<h1></h1>') if not output.startswith('x'): r = r.replace('<br />', '<br>') r = r.replace(' xmlns="%s"' % xhtml_namespace, '') if output.lower() != output: r = r.upper() r = r.replace('HELLO', 'Hello').replace('WORLD', 'World') r = '\n' + r assert s.endswith(r) elif output.endswith('ml'): # xml or wml assert s.startswith('<?xml version="1.0" encoding="utf-8"?>\n') assert s.endswith(xml) else: assert output == 'plain' assert s == 'HelloWorld' def test_strip_lang(): serializer = HTMLSerializer(transpose=True) serializer.doctype = doctypes['html-strict'] t = kid.Template("<html xml:lang='en' lang='en' />") t.serializer = serializer expected = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"' \ ' "http://www.w3.org/TR/html4/strict.dtd">\n' \ '<HTML LANG="en"></HTML>' rslt = t.serialize() assert rslt == expected import string def test_transpose_lower(): serializer = HTMLSerializer() serializer.doctype = None serializer.inject_type = False serializer.transpose = string.lower t = kid.Template("<HTML><HEAD /></HTML>") t.serializer = serializer expected = '<html><head></head></html>' rslt = t.serialize() assert rslt == expected def test_transpose_off(): serializer = HTMLSerializer() serializer.doctype = None serializer.inject_type = False serializer.transpose = None t = kid.Template("<HTML><HEAD /></HTML>") t.serializer = serializer expected = '<HTML><HEAD></HEAD></HTML>' rslt = t.serialize() assert rslt == expected def test_whitespace(): """Only real XML whitespace should be stripped away.""" # These chars are whitespace in XML and Python: for char in '\x09\x0a\x0d\x20': # HT, LF, CR, SP t = kid.Template('<p>%s</p>' % char) rslt = t.serialize(encoding='latin-1') assert rslt.endswith('<p />') rslt = kid.Template('<p> </p>').serialize(output='xhtml') assert rslt.endswith('<p> </p>') # These chars are considered whitespace in Python, but not in XML: from xml.parsers.expat import ExpatError for char in '\x0b\x0c\xa0': # VT, FF, NBSP try: t = kid.Template('<p>%s</p>' % char) rslt = t.serialize(encoding='latin-1') except ExpatError, e: e = str(e) if 'not well-formed' in e and 'invalid token' in e: rslt = '<p>%s</p>' % char else: rslt = 'XML Error' assert rslt.endswith('<p>%s</p>' % char) rslt = kid.Template('<p> </p>').serialize( output='xhtml', encoding='latin-1') assert rslt.endswith('<p>\xa0</p>') t = kid.Template('<p> </p>') rslt = t.serialize(output='xhtml', encoding='latin-1') assert rslt.endswith('<p>\xa0</p>') def test_whitespace2(): """Keep nonbreakable space inside paragraph (ticket #140).""" rslt = kid.Template("""\ <?python def nbsp1(): return XML("nbsp") def nbsp2(): return XML(" ") def nbsp3(): return XML(" ") def nbsp4(): return u'\u00a0' ?> <div xmlns:py="http://purl.org/kid/ns#"> <h1>ticket #140</h1> <span py:content="nbsp1()"/> <span py:content="nbsp2()"/> <span py:content="nbsp3()"/> <span py:content="nbsp4()"/> </div>""").serialize(encoding='latin-1') rslt = rslt.replace(' ', '').replace('\n', '') assert rslt.endswith('<div><h1>ticket#140</h1><span>nbsp</span>' + 3*'<span>\xa0</span>' + '</div>') def test_comment_whitespace(): """Comments should not add an additional newline (ticket #107).""" expected = '<?xml version="1.0" encoding="utf-8"?>\n<html>\n' \ '<!-- a comment -->\n<element />\n</html>' assert kid.Template(expected).serialize(output='xml') == expected expected = serialize_doctype(doctypes['html']) + '\n<HTML>\n' \ '<!-- a comment -->\n<ELEMENT>\n</ELEMENT>\n</HTML>' assert kid.Template(expected).serialize(output='HTML') == expected expected = serialize_doctype(doctypes['xhtml']) + '\n<html>\n' \ '<!-- a comment -->\n<element>\n</element>\n</html>' assert kid.Template(expected).serialize(output='xhtml') == expected def test_empty_lines(): """Handling of empty lines in templates. Empty lines between elements should be removed. We assume that balanced_blocks is enabled for both HTML and XHTML templates. Inline elements in template should remain so. Other elements should be indented. """ t = kid.Template(""" <html> <script>some lines and more lines</script><body> <a href="/"><img src="pic.jpg"/></a> </body> </html>""") expected = serialize_doctype( doctypes['html']) + """\n<HTML> <SCRIPT>some lines and more lines</SCRIPT><BODY> <A HREF="/"><IMG SRC="pic.jpg"></A> </BODY> </HTML>""" assert t.serialize(output='HTML') == expected expected = serialize_doctype( doctypes['xhtml']) + """\n<html> <script>some lines and more lines</script><body> <a href="/"><img src="pic.jpg" /></a> </body> </html>""" assert t.serialize(output='xhtml') == expected def test_extra_indentation(): """Check that no extra indentation is inserted (ticket #131).""" html = """<div> <a href="/"><img src="pic.jpg"/></a> </div>""" assert HTMLTemplate(html).serialize() == html.replace('/>', '>') def test_textarea_indentation(): """Check for extra indentation to textarea (ticket #83).""" widgetsrc = """ <textarea xmlns:py="http://purl.org/kid/ns#" py:content="value" /> """ template = """ <div xmlns:py="http://purl.org/kid/ns#"> ${widget} </div> """ t = kid.Template(widgetsrc, value='') tmpl = kid.Template(template, widget=t.transform()) rslt = tmpl.serialize(output='xhtml', fragment=True) expected = """<div> <textarea></textarea> </div>""" assert rslt == expected template = """ <div xmlns:py="http://purl.org/kid/ns#">${widget}</div> """ t = kid.Template(widgetsrc, value='') tmpl = kid.Template(template, widget=t.transform()) rslt = tmpl.serialize(output='xhtml', fragment=True) expected = """<div><textarea></textarea></div>""" assert rslt == expected template = """ <div xmlns:py="http://purl.org/kid/ns#"> ${widget}</div> """ assert rslt == expected def test_br_namespace_issues(): """Check problem with handling of br in XHTML (ticket #83).""" widgetsrc = '<div><br/></div>' template = """<div xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://purl.org/kid/ns#"> ${widget}<br/> </div>""" t = kid.Template(widgetsrc, value='') tmpl = kid.Template(template, widget=t.transform()) rslt = tmpl.serialize(output='xhtml', fragment=True) expected = """<div xmlns="http://www.w3.org/1999/xhtml"> <div><br /></div><br /> </div>""" assert rslt == expected def test_nbsp(): """Check that   is rendered correctly.""" xml = '<p>Dr. Snuggles</p>' t = kid.Template(xml) for s in (XMLSerializer, HTMLSerializer, XHTMLSerializer): output = s() r = t.serialize(output=output, encoding='ascii') assert r.endswith(xml.replace(' ', ' ')) output = s(entity_map=True) r = t.serialize(output=output, encoding='ascii') assert r.endswith(xml) output = s(entity_map = {u'\xa0': ' Mooney '}) r = t.serialize(output=output, encoding='ascii') assert r.endswith(xml.replace(' ', ' Mooney ')) def test_no_repeated_namespaces(): """Check that namespaces are not repeated (ticket #144).""" div1 = """ <div xmlns="http://www.w3.org/1999/xhtml"/>""" div2 = """ <div xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://purl.org/kid/ns#" py:content="div1"/>""" t = kid.Template(div2, div1=kid.Template(div1).transform()) s = t.serialize(output='xhtml', fragment=True) assert s == '<div xmlns="http://www.w3.org/1999/xhtml"><div></div></div>' PK�����Y8ð6i\g��g�����kid/test/test_layout.py"""Unit Tests for layout templates.""" __revision__ = "$Rev: 421 $" __author__ = "Daniel Miller <millerdev@nwsdb.com>" __copyright__ = "Copyright 2006, David Stanek" import kid def test_layout_error(): from kid.template_util import TemplateLayoutError try: kid.Template(""" <html xmlns:py="http://purl.org/kid/ns#" py:layout="no_layout" /> """).serialize() except TemplateLayoutError, e: e = str(e) except Exception: e = 'wrong error' except: e = 'silent' assert "'no_layout'" in e assert 'not defined' in e assert 'while processing layout=' in e def test_dynamic_layout(): layout = kid.Template(""" <html xmlns:py="http://purl.org/kid/ns#"> ${body_content()} </html> """) child = kid.Template(""" <html py:layout="dynamic_layout" xmlns:py="http://purl.org/kid/ns#"> <body py:def="body_content()">body content</body> </html> """, dynamic_layout=type(layout)) output = child.serialize() assert output.find("body content") > -1, \ "body_content function was not executed" def test_match_locals(): layout = kid.Template(""" <?python test_var = "WRONG VALUE" ?> <html xmlns:py="http://purl.org/kid/ns#"> <body> <?python assert "test_var" in locals(), \ "test_var is not defined in layout locals" assert test_var == "test value", \ "test_var has wrong value: %r" % test_var ?> <div /> </body> </html> """) child = kid.Template(""" <?python layout_params["test_var"] = "WRONG VALUE" ?> <html py:layout="layout" xmlns:py="http://purl.org/kid/ns#"> <content py:match="item.tag == 'div'" py:strip="True"> <?python assert "test_var" in locals(), \ "test_var is not defined in py:match locals" assert test_var == "test value", \ "test_var has wrong value in py:match: %r" % test_var ?> test_var=${test_var} </content> </html> """, layout=type(layout), test_var="test value") output = child.serialize() assert output.find("test_var=test value") > -1, \ "match template was not executed" def test_def_locals(): layout = kid.Template(""" <?python test_var = "WRONG VALUE" ?> <html xmlns:py="http://purl.org/kid/ns#"> <body> <?python assert "test_var" in locals(), \ "test_var is not defined in layout locals" assert test_var == "test value", \ "test_var has wrong value: %r" % test_var ?> ${child_content()} </body> </html> """) child = kid.Template(""" <?python layout_params["test_var"] = "WRONG VALUE" ?> <html py:layout="layout" xmlns:py="http://purl.org/kid/ns#"> <content py:def="child_content()" py:strip="True"> <?python assert "test_var" in locals(), \ "test_var is not defined in py:def locals" assert test_var == "test value", \ "test_var has wrong value in py:def: %r" % test_var ?> test_var=${test_var} </content> </html> """, layout=type(layout), test_var="test value") output = child.serialize() assert output.find("test_var=test value") > -1, \ "child_content function was not executed" PK�����Y8ð6írø�������kid/test/test_match.py"""Unit Tests for the template matching.""" __revision__ = "$Rev: 455 $" __author__ = "David Stanek <dstanek@dstanek.com>" __copyright__ = "Copyright 2005, David Stanek" from os.path import join as joinpath from tempfile import mkdtemp from shutil import rmtree import kid def setup_module(module): global tmpdir tmpdir = mkdtemp(prefix='kid_test_match_') kid.path.insert(tmpdir) def teardown_module(module): kid.path.remove(tmpdir) rmtree(tmpdir) def test_match0(): open(joinpath(tmpdir, "match0_base.kid"), 'w').write("""\ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://purl.org/kid/ns#"> <head py:match="item.tag=='{http://www.w3.org/1999/xhtml}head'"> <meta content="text/html; charset=UTF-8" http-equiv="content-type" py:replace="''" /> <title py:replace="''">Your title goes here

""") open(joinpath(tmpdir, "match0_page.kid"), 'w').write("""\ Welcome to TurboGears

My Main page with bold text

""") html = kid.Template(file="match0_page.kid").serialize() assert 'Welcome to TurboGears' in html assert 'BOLD' in html def test_match1(): open(joinpath(tmpdir, "match1_base.kid"), 'w').write("""\ Some title here
Real content would go here.
""") open(joinpath(tmpdir, "match1_page.kid"), 'w').write("""\

This is a test link, or an e-mail address.

""") html = kid.Template(file="match1_page.kid").serialize() assert '' in html assert '' \ 'test link' in html assert '' \ 'e-mail address' in html assert '' in html assert '
Real content would go here.
' not in html def test_match_2(): """Test for a know bad case in the apply_matches function (ticket # 142).""" open(joinpath(tmpdir, "match2_master.kid"), 'w').write("""\
""") open(joinpath(tmpdir, "match2_userform.kid"), 'w').write("""\
""") extends = ('master', 'userform') for i in range(2): file = "match2_%s_%s.kid" % extends open(joinpath(tmpdir, file), 'w').write("""\ """ % extends) t = kid.Template(file=file) t.action = file html = t.serialize() assert 'THIS IS THE TAG' in html # text from main template assert 'MASTER MATCH' in html # text from master template assert 'seasources:userform' not in html # text from userform template extends = list(extends) extends.reverse() extends = tuple(extends) def test_match_3(): """Check for an issue with additional blank lines (ticket #131).""" template = """\ one

hello world!

two """ t = kid.Template(source=template) rslt = t.serialize(output="html") expect = """ one two """ print rslt print expect assert rslt.endswith(expect) PKY8ð6´|¼00kid/test/test_namespace.py# -*- coding: utf-8 -*- """kid.namespace tests.""" __revision__ = "$Rev: 492 $" __date__ = "$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " from kid.namespace import Namespace from kid.serialization import NamespaceStack def test_namespace_module(): ns = Namespace(uri='urn:test', prefix='test') assert ns.name == '{urn:test}name' assert ns['name'] == '{urn:test}name' assert ns.qname('name') == 'test:name' ns = Namespace(uri=None) assert ns.name == 'name' assert ns['name'] == 'name' assert ns.qname('name') == 'name' def test_namespace_stack(): stack = NamespaceStack() namespaces = [ {'': 'urn:default/namespace'}, {'test0': 'urn:test_namespace_0', 'test1': 'urn:test_namespace_1',}, {'test3': 'urn:test_namespace_3', }, {'': 'urn:new/default/namespace',}, {'test0': 'urn:inner/test0',}, {'inner_test3': 'urn:test_namespace_3',}, ] for ns in namespaces: stack.push(ns) ru = stack.resolve_uri assert ru('inner_test3') == 'urn:test_namespace_3' assert ru('test0') == 'urn:inner/test0' rp = stack.resolve_prefix assert rp('urn:default/namespace', default=True) == None assert rp('urn:default/namespace', default=False) == None assert rp('urn:new/default/namespace', default=True) == '' assert rp('urn:new/default/namespace', default=False) == None assert rp('urn:test_namespace_3', default=True) == 'test3' assert rp('urn:test_namespace_3', default=False) == 'test3' for x in range(len(namespaces)-1, -1, -1): ns = stack.pop() print ns, namespaces[x] assert ns == namespaces[x] PKY8ð6üc§Tkid/test/test_parser.py# -*- coding: utf-8 -*- """kid.parser tests""" __revision__ = "$Rev: 492 $" __date__ = "$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " from kid import Element, load_template, Template from kid.parser import ElementStream, XML def test_xml_type(): doc = XML("hello world", fragment=False) assert type(doc) is ElementStream doc = XML("hello world", fragment=True) assert type(doc) is ElementStream def test_expand(): doc = XML("world", fragment=False) assert type(doc) is ElementStream doc = doc.expand() assert type(doc) == type(Element('doc')) assert doc.tag == 'doc' assert doc[0].tag == 'hello' assert doc[0].text == 'world' def test_strip(): xml = """ The Title

Header 1

Header 1.1

Header 1.2

Header 1.2.1

Header 1.2.2

Hello, World!

Header 1.2.3

Header 1.3

""" xml_stream = XML(xml, fragment=False) assert type(xml_stream) is ElementStream xml_stream_stripped = xml_stream.strip(levels=6) assert type(xml_stream_stripped) is ElementStream from kid import XMLSerializer serializer = XMLSerializer(decl=False) xml_stripped = serializer.serialize(xml_stream_stripped, fragment=True) assert xml_stripped == 'Hello, World!' def test_xml_with_entity_map(): xml = ' ' assert list(XML(xml))[0][1] == u'\xa0' xml = '&codswallop;' try: e = list(XML(xml)) except Exception, e: e = str(e) assert 'undefined entity &codswallop;' in e xml = ' , &codswallop;!' entity_map = {'nbsp': u'Hello', 'codswallop': u'World'} assert list(XML(xml, entity_map=entity_map))[0][1] == u'Hello, World!' def test_load_template_with_entity_map(): xml = ' ' s = load_template(xml).serialize(encoding='ascii') assert s.endswith(' ') xml = '&codswallop;' try: e = load_template(xml).serialize(encoding='ascii') except Exception, e: e = str(e) assert 'undefined entity &codswallop;' in e xml = ' , &codswallop;!' entity_map = {'nbsp': u'Hello', 'codswallop': u'World'} s = load_template(xml, entity_map=entity_map).serialize(encoding='ascii') assert s.endswith('Hello, World!') def test_encoding(): s = ('\n' '' '\xb5\xb9\xe8\xbb\xbe\xfd\xe1\xed') r = load_template(s).serialize(encoding='utf-8') s = s.decode('iso-8859-2').replace('iso-8859-2', 'utf-8') r = r.decode('utf-8') assert r == s def test_expand_fragments(): """Testcase for expanding XML fragments (ticket #145).""" template = """
""" t = Template("""\

Hello World #$i

""") s = t.serialize(fragment=True) expected = """

Hello World #0

Hello World #1

Hello World #2

""" assert s == expected stream = ElementStream(t.transform()).expand() t2 = Template(source=template, stream=stream) s2 = t2.serialize(fragment=True) assert s2 == s t = Template("""\

Hello World #$i

""") s = t.serialize(fragment=True) expected = """

Hello World #0

Hello World #1

Hello World #2

""" assert s == expected stream = ElementStream(t.transform()).expand() t2 = Template(source=template, stream=stream) s2 = t2.serialize(fragment=True) assert s2 == s t = Template("""\

Hello World

""") s = t.serialize(fragment=True) expected = """

Hello World

""" assert s == expected stream = ElementStream(t.transform()).expand() t2 = Template(source=template, stream=stream) s2 = t2.serialize(fragment=True) assert s2 == s t = Template("""\

Hello World

""") s = t.serialize(fragment=True).strip() expected = """

Hello World

""" assert s == expected stream = ElementStream(t.transform()).expand() t2 = Template(source=template, stream=stream) s2 = t2.serialize(fragment=True).strip() assert s2 == s PKY8ð6°; Þÿÿkid/test/test_codewriter.py# -*- coding: utf-8 -*- """kid.codewriter tests.""" __revision__ = "$Rev: 492 $" __date__ = "$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " def test_interpolate_expr(): from kid.codewriter import interpolate tests = [ ('foo ${bar} baz', ["'foo '", "bar", "' baz'"]), ('foo $bar baz', ["'foo '", "bar", "' baz'"]), ('foo $${bar} baz', 'foo ${bar} baz'), ('foo $$bar baz', 'foo $bar baz'), ('${foo} bar baz', ["foo", "' bar baz'"]), ('$foo bar baz', ["foo", "' bar baz'"]), ('foo bar ${baz}', ["'foo bar '", "baz"]), ('foo bar $baz', ["'foo bar '", "baz"]), ('foo $${bar}${baz}', ["'foo ${bar}'", "baz"]), ('foo $$bar$baz', ["'foo $bar'", "baz"]), ('${foo} bar ${baz}', ["foo", "' bar '", "baz"]), ('$foo bar $baz', ["foo", "' bar '", "baz"]), ('${foo}$${bar}${baz}', ["foo", "'${bar}'", "baz"]), ('$foo$$bar$baz', ["foo", "'$bar'", "baz"]), ('foo $object.attr bar', ["'foo '", "object.attr", "' bar'"]), ('$ foo ${bar baz}', ["'$ foo '", 'bar baz']), ('foo$ ${bar.baz}', ["'foo$ '", 'bar.baz']), ('$foo $100 $bar', ["foo", "' $100 '", "bar"]), ('$foo $$100 $bar', ["foo", "' $100 '", "bar"]), ('$$foo', '$foo'), ('', '')] for test, expect in tests: actual = interpolate(test) assert actual == expect def test_interpolate_object(): from kid.codewriter import interpolate expr = interpolate("foo ${bar} baz") assert repr(expr) == "['foo ', bar, ' baz']" # test for ticket #79 assert repr(interpolate('$foo')) == '[foo]' def test_adjust_block(): from test.blocks import blocks from kid.codewriter import _adjust_python_block for test, expect in blocks: rslt = list(_adjust_python_block(test.splitlines())) rslt = '\n'.join(rslt) assert expect == rslt def test_exec_hack(): """Guido may break this some day...""" exec('x = 10') assert x == 10 PKY8ð6b¥¾æÏÏkid/test/test_scope.py"""Unit Tests for Python scope.""" __revision__ = "$Rev: 421 $" __author__ = "David Stanek " __copyright__ = "Copyright 2005, David Stanek" from os.path import join as joinpath from tempfile import mkdtemp from shutil import rmtree import kid def setup_module(module): global tmpdir tmpdir = mkdtemp(prefix='kid_test_scope_') kid.path.insert(tmpdir) def teardown_module(module): kid.path.remove(tmpdir) rmtree(tmpdir) def test_scope_1(): """Test for scoping issue reported in ticket #101. Parameters passed into the Template constructor override the parameters of functions created with py:def. """ open(joinpath(tmpdir, "scope.kid"), 'w').write("""\ """) s = kid.Template(file="scope.kid", bar=1).serialize() assert "0" in s PKY8ð6ÊE©™ôô'kid/test/test_serialization_escaping.py# -*- coding: utf-8 -*- """Tests exercising text escaping.""" __revision__ = "$Rev: 492 $" __date__ = "$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $" __author__ = "David Stanek " __copyright__ = "Copyright 2006, David Stanek" __license__ = "MIT " from kid.serialization import XMLSerializer, XHTMLSerializer, HTMLSerializer XML = XMLSerializer XHTML = XHTMLSerializer HTML = HTMLSerializer TEST_CHARS = ('<', '>', '"', "'", '&',) TEST_STRINGS = ('str', 'k\204se') TEST_COMBO = ('str<"&">str', "k\204se<'&'>k\204se") def escape_functions(): """Generator producing escape functions.""" for serializer in (HTMLSerializer, XMLSerializer, XHTMLSerializer): for escape in (serializer.escape_cdata, serializer.escape_attrib): yield serializer, escape def do_escape(func, test_chars, result_chars, encoding=None): for x, char in enumerate(test_chars): assert func(char, encoding) == result_chars[x] def test_escape(): expected = { XML.escape_cdata: ('<', '>', '"', "'", '&',), XML.escape_attrib: ('<', '>', '"', "'", '&',), XHTML.escape_cdata: ('<', '>', '"', "'", '&',), XHTML.escape_attrib: ('<', '>', '"', "'", '&',), HTML.escape_cdata: ('<', '>', '"', "'", '&',), HTML.escape_attrib: ('<', '>', '"', "'", '&',), } for serializer, escape in escape_functions(): do_escape(escape, TEST_CHARS, expected[escape]) def test_escape_encoding(): """Test the encoding part of the escaping functions.""" ascii_expected = ('str', 'k\204se') utf8_expected = ('str', 'k„se') for serializer, escape in escape_functions(): do_escape(escape, TEST_STRINGS, ascii_expected) do_escape(escape, TEST_STRINGS, utf8_expected, 'utf-8') def test_escape_encoding_combo(): ascii_expected = { XML.escape_cdata: ('str<"&">str', "k\204se<'&'>k\204se"), XML.escape_attrib: ('str<"&">str', "k\204se<'&'>k\204se"), XHTML.escape_cdata: ('str<"&">str', "k\204se<'&'>k\204se"), XHTML.escape_attrib: ('str<"&">str', "k\204se<'&'>k\204se"), HTML.escape_cdata: ('str<"&">str', "k\204se<'&'>k\204se"), HTML.escape_attrib: ('str<"&">str', "k\204se<'&'>k\204se"), } utf8_expected = { XML.escape_cdata: ('str<"&"str', "1k„se<'&'>k„se"), XML.escape_attrib: ('str<"&">str', "k„se<'&'>k„se"), XHTML.escape_cdata: ('str<"&">str', "k„se<'&'>k„se"), XHTML.escape_attrib: ('str<"&">str', "k„se<'&'>k„se"), HTML.escape_cdata: ('str<"&">str', "k„se<'&'>k„se"), HTML.escape_attrib: ('str<"&">str', "k„se<'&'>k„se"), } for serializer, escape in escape_functions(): do_escape(escape, TEST_COMBO, ascii_expected[escape]) do_escape(escape, TEST_COMBO, utf8_expected[escape], 'utf-8') def test_escaping_int(): for serializer, escape in escape_functions(): try: assert escape(1) except TypeError, e: assert str(e) == 'cannot serialize 1 (type int)' def test_escaping_nbsp(): for serializer, escape in escape_functions(): assert escape('\xa0', 'ascii') == ' ' assert escape('\xa0', 'ascii', {'\xa0': 'bingo'}) == 'bingo' PKY8ð62—”2”2kid/test/test_error.py"""Unit Tests for error reporting.""" __revision__ = "$Rev: 496 $" __author__ = "Christoph Zwerschke " __copyright__ = "Copyright 2006, Christoph Zwerschke" import sys from os.path import join as joinpath from tempfile import mkdtemp from shutil import rmtree import kid from kid.test.util import raises # Error tracking is only fully supported in Python 2.4 # because we need the CurrentLineNumber attribute of Expat python24 = sys.version_info[:2] >= (2, 4) def setup_module(module): global tmpdir tmpdir = mkdtemp(prefix='kid_test_error_') kid.path.insert(tmpdir) def teardown_module(module): kid.path.remove(tmpdir) rmtree(tmpdir) class KidFileWriter: test_number = 0 def __init__(self): KidFileWriter.test_number += 1 self.file_number = 0 def name(self): return 'test_error_%d_%d' % (self.test_number, self.file_number) def filename(self, full=False): filename = '%s.kid' % self.name() if full: filename = joinpath(tmpdir, filename) return filename def write(self, xml): self.file_number += 1 open(self.filename(True), 'w').write(xml) def test_xml_error(): """Check that erroneous XML is reported.""" from xml.parsers.expat import ExpatError page = """\

title

oops

That's all, folks.

""" kid.Template(page) page = page.replace('', '') e = str(raises(ExpatError, kid.Template, source=page)) assert 'Error parsing XML' in e assert 'mismatched tag: line 3, column 24' in e assert page.splitlines()[2] in e # erroneous line assert "\n%25s\n" % "^" in e # offset pointer assert 'html' not in e assert 'title' not in e assert 'folks' not in e page = """\

title

""" t = kid.Template(source=page, xml="

ok

") from xml.parsers.expat import ExpatError content = """\

start

this &is wrong

end

""" t = kid.Template(source=page, xml=content) e = str(raises(ExpatError, t.serialize)) assert 'Error parsing XML' in e assert 'not well-formed (invalid token): line 2, column 16' in e assert content.splitlines()[1] in e assert "\n%17s\n" % "^" in e assert 'html' not in e assert 'start' not in e assert 'end' not in e def test_xml_long_line(): """Check intelligent truncating of long XML error lines.""" from xml.parsers.expat import ExpatError page = 'x' + 9999*'x' e = str(raises(ExpatError, kid.Template, page)) assert 'Error parsing XML' in e assert 'mismatched tag: line 1, column 6' in e assert ('\nx' + 68*'x') in e assert "\n%7s\n" % "^" in e page = '' + 9999*'x' + '' e = str(raises(ExpatError, kid.Template, page)) assert 'Error parsing XML' in e assert 'mismatched tag: line 1, column 10004' in e assert ('\n' + 72*'x' + '') in e assert "\n%75s\n" % "^" in e page = '' + 9999*'x' + '' + 9999*'x' e = str(raises(ExpatError, kid.Template, page)) assert 'Error parsing XML' in e assert 'mismatched tag: line 1, column 10004' in e assert ('\n' + 36*'x' + '' + 36*'x') in e assert "\n%39s\n" % "^" in e def test_xml_filename_error(): """Check that erroneous XML filename is reported.""" f = KidFileWriter() f.write("This is XML") t = kid.Template(file=f.filename()) f.write("This is not XML") from xml.parsers.expat import ExpatError e = str(raises(ExpatError, kid.Template, file=f.filename())) assert 'Error parsing XML' in e assert f.filename() in e assert 'This is not XML' in e assert 'syntax error: line 1, column 0' in e assert '\n^\n' in e def test_layout_error(): """Check that erroneous py:layout expressions are reported.""" page = '' # because py:layout is dynamic, the template can be created # but the error should show up when we try to serialize the template t = kid.Template(source=page) from kid.template_util import TemplateLayoutError e = str(raises(TemplateLayoutError, t.serialize)) assert 'not defined' in e assert 'while processing layout=' in e assert 'no_layout' in e def test_extends_error(): """Check that erroneous py:extends expressions are reported.""" page = '' # because py:extends is not dynamic, the template cannot be created from kid.template_util import TemplateExtendsError e = str(raises(TemplateExtendsError, kid.Template, source=page)) assert 'not defined' in e assert 'while processing extends=' in e assert 'no_extends' in e def test_attr_error(): """Check that erroneous py:attrs expressions are reported.""" page = """\

""" t = kid.Template(source=page % "abc=123, def=789") s = t.serialize() assert 'abc="123"' in s and 'def="789"' in s from kid.template_util import TemplateAttrsError t = kid.Template(source=page % "abc=123, 456=789") e = str(raises(TemplateAttrsError, t.serialize)) assert 'invalid' in e assert 'while processing attrs=' in e assert 'abc=123, 456=789' in e t = kid.Template(source=page % "{'mickey':'mouse'}") s = t.serialize() assert 'mickey="mouse"' in s t = kid.Template(source=page % "mickey mouse") e = str(raises(TemplateAttrsError, t.serialize)) assert 'while processing attrs=' in e assert 'mickey mouse' in e t = kid.Template(source=page % "{mickey:mouse}") e = str(raises(TemplateAttrsError, t.serialize)) assert 'not defined' in e assert 'mickey' in e and 'mouse' in e def test_tracking_1(): """Check error tracking when compiling a Kid template.""" from kid.compiler import compile_file f = KidFileWriter() xml = """ compilation fails the expression ${1/0} can be compiled the expression ${1//0} can be compiled the expression ${1///0} cannot be compiled the expression ${1+1} can be compiled """ for call in (compile_file, kid.load_template, kid.Template): f.write(xml) e = str(raises(SyntaxError, call, file=f.filename(call == compile_file))) assert 'invalid syntax (%s.py, line ' % f.name() in e assert ' 1///0' in e and ' ^\n' in e assert '1/0' not in e and '1//0' not in e and '1+1' not in e assert 'can be compiled' not in e if python24: assert 'Error location in template file ' in e assert f.filename() in e assert 'on line 5 between columns 8 and 54:' in e assert 'the expression ${1///0} cannot be compiled' in e assert 'xml>' not in e and 'title>' not in e assert 'p1>' not in e and 'p2>' not in e and 'p4>' not in e assert 'compilation fails' not in e xml = """ compilation fails """ for call in (compile_file, kid.load_template, kid.Template): f.write(xml) e = str(raises(SyntaxError, call, file=f.filename(call == compile_file))) assert 'invalid syntax (%s.py, line ' % f.name() in e assert 'oops = 1///0' in e and ' ^\n' in e assert 'ok =' not in e assert '1/0' not in e and '1//0' not in e and '1+1' not in e if python24: assert 'Error location in template file ' in e assert f.filename() in e assert 'between line 10, column 8 and line 13, column 8:' in e assert ' oops = 1///0' in e assert 'xml>' not in e and 'title>' not in e assert 'compilation fails' not in e def test_tracking_2(): """Check error tracking when importing a Kid template.""" from kid.compiler import compile_file f = KidFileWriter() xml = """ import fails """ f.write(xml) try: e = compile_file(file=f.filename(True)) except Exception: e = None assert e == True, 'This file cannot be compiled properly.' for call in (kid.load_template, kid.Template): f.write(xml) e = str(raises(ZeroDivisionError, call, file=f.filename())) assert 'integer division or modulo by zero' in e if python24: assert 'Error location in template file ' in e assert f.filename() in e assert 'between line 4, column 8 and line 5, column 8:' in e assert '' in e assert 'xml>' not in e and 'title>' not in e assert 'import fails' not in e def test_tracking_3(): """Check error tracking when executing a Kid template.""" f = KidFileWriter() xml = """ execution fails the expression ${1/2} can be evaluated the expression ${1/0} cannot be evaluated """ f.write(xml) t = kid.Template(file=f.filename()) def execute_template_method(t, n): if n == 1: import StringIO output = StringIO.StringIO() t.write(file=output) ret = output.getvalue() output.close() elif n == 2: ret = list(t.generate()) else: ret = t.serialize() return ret for n in range(3): e = str(raises(ZeroDivisionError, execute_template_method, t, n)) assert 'integer division or modulo by zero' in e if python24 and n < 2: assert 'Error location in template file ' in e assert f.filename() in e assert 'on line 4 between columns 8 and 53:' in e assert 'the expression ${1/0} cannot be evaluated' in e assert 'xml>' not in e and 'title>' not in e assert 'execution fails' not in e xml = """ execution fails """ f.write(xml) t = kid.Template(file=f.filename()) e = str(raises(ZeroDivisionError, t.serialize)) assert 'integer division or modulo by zero' in e if python24: assert 'Error location in template file ' in e assert f.filename() in e assert 'between line 4, column 8 and line 5, column 8:' in e assert '' not in e and 'title>' not in e assert 'execution fails' not in e xml = """ execution fails

test1

test2

""" f.write(xml) t = kid.Template(file=f.filename()) e = str(raises(ZeroDivisionError, t.serialize)) assert 'integer division or modulo by zero' in e if python24: assert 'Error location in template file ' in e assert f.filename() in e assert 'between line 4, column 22 and line 5, column 8:' in e assert ' py:content="1/0"' in e assert '"1/2"' not in e assert 'xml>' not in e and 'title>' not in e assert 'p1>' not in e and 'h1>' not in e assert 'h2>' not in e assert 'execution fails' not in e def test_tracking_4(): """Check error tracking when compiling a Kid template.""" from kid.compiler import compile_file f = KidFileWriter() xml = """ execution fails test
""" f.write(xml) t = kid.Template(file=f.filename()) e = raises(UnicodeDecodeError, t.serialize) assert e.__class__.__name__ == UnicodeDecodeError.__name__ assert e.__class__.__module__ == UnicodeDecodeError.__module__ assert hasattr(e, 'reason') \ and e.reason == "ordinal not in range(128)" e = str(e) assert "can't decode byte 0xe4 in position 1" in e assert "ordinal not in range(128)" in e assert '\nError in code generated from template file ' in e assert f.filename() in e assert 'execution fails' not in e PKY8ð6þf£±||kid/test/util.py# -*- coding: utf-8 -*- """Utility stuff for tests.""" __revision__ = "$Rev: 492 $" __date__ = "$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " import sys import os import traceback try: from cStringIO import StringIO except ImportError: from StringIO import StringIO import kid.test class stdold: """Original sys.stderr and sys.stdout.""" out = sys.stdout err = sys.stderr def raises(ExpectedException, *args, **kwargs): """Raise AssertionError if code does not raise expected exception.""" assert args if isinstance(args[0], str): (expr,) = args assert isinstance(expr, str) frame = sys._getframe(1) loc = frame.f_locals.copy() loc.update(kwargs) try: exec expr in frame.f_globals, loc except ExpectedException, e: return e except Exception, e: pass else: e = None else: func, args = args[0], args[1:] assert callable(func) try: func(*args, **kwargs) except ExpectedException, e: return e except Exception, e: pass else: e = None expr = ["%r" % x for x in args] expr.extend(["%s=%r" % x for x in kwargs.items()]) expr = '%s(%s)' % (func.__name__, ', '.join(expr)) if e: e = 'raised %s instead of' % e.__class__ else: e = 'did not raise' raise AssertionError('%s %s %s' % (expr, e, ExpectedException)) def dot(): stdold.err.write('.') def skip(): stdold.err.write('s') def come_on_guido_this_is_just_wrong(name): mod = __import__(name) components = name.split('.') for comp in components[1:]: mod = getattr(mod, comp) return mod def get_funcs(mod): """Return a list of test functions for the given module object.""" funcs = [] for name in dir(mod): if name[:4] == 'test': attr = getattr(mod, name) if callable(attr): funcs.append(attr) return funcs def run_suite(tests, stop_first=True): """Run tests given a list of modules that export __test__ variables.""" try: os.mkdir(kid.test.output_dir) except OSError: e = sys.exc_info()[1] if int(e.errno) != 17: raise bad = [] kid.test.basic_tests = 1 test_cnt = skip_cnt = bad_cnt = 0 from time import time start = time() # run over modules... for module_name in tests: try: mod = come_on_guido_this_is_just_wrong(module_name) except ImportError, e: if 'No module named py' not in str(e): raise skip_cnt += 1 skip() continue # you don't have pylib - so i won't run these tests #if not hasattr(mod, '__tests__'): # raise '%r does not export a __tests__ variable.' % module_name if hasattr(mod, 'setup_module'): mod.setup_module(mod) try: # run each test... for test in get_funcs(mod): test_cnt += 1 sys.stdout, sys.stderr = StringIO(), StringIO() try: test() except: bad_cnt += 1 asserr = isinstance(sys.exc_info()[0], AssertionError) ftype = asserr and 'F' or 'E' buf = StringIO() traceback.print_exc(file=buf) stdold.err.write(ftype) bad.append((test, ftype, sys.exc_info(), \ (sys.stdout.getvalue(), sys.stderr.getvalue()))) if stop_first: sys.stdout, sys.stderr = stdold.out, stdold.err sys.stderr.write( '*\n\bBailing after %d tests\n\n' % test_cnt) out, err = bad[-1][3] if out: sys.stderr.write( '-- sys.stdout:\n%s\n' % out.strip()) if err: sys.stderr.write( '-- sys.stderr:\n%s\n' % err.strip()) raise else: dot() sys.stdout, sys.stderr = stdold.out, stdold.err finally: if hasattr(mod, 'teardown_module'): mod.teardown_module(mod) done = time() sys.stderr.write('\n') for test, ftype, exc_info, (out, err) in bad: sys.stderr.write('\n%s: %s\n' % ({'F': 'Failure', 'E': 'Error'}.get(ftype, 'Bad'), test.__doc__ or test.__name__)) if out: sys.stderr.write( '-- sys.stdout:\n%s\n' % out.strip()) if err: sys.stderr.write( '-- sys.stderr:\n%s\n' % err.strip()) traceback.print_exception( exc_info[0], exc_info[1], exc_info[2], 15, sys.stderr) sys.stderr.write('\nTests: %d (+%d extended) OK (%g seconds)\n' % (test_cnt, kid.test.additional_tests, done - start)) if skip_cnt: sys.stderr.write('Skipped tests (need py lib): %d\n' % skip_cnt) if bad_cnt: sys.stderr.write('Bad tests: %d\n' % bad_cnt) PKY8ð6.AöÜ% % kid/test/test_suffixes.py"""Unit Tests for the import extensions and path functionality.""" __revision__ = "$Rev: 455 $" __author__ = "David Stanek " __copyright__ = "Copyright 2005, David Stanek" import sys from os.path import join as joinpath from tempfile import mkdtemp from shutil import rmtree, copyfile import kid from kid.test.util import raises def setup_module(module): global tmpdir, tfile tmpdir = mkdtemp(prefix='kid_test_suffixes_') kid.path.insert(tmpdir) tfile = joinpath(tmpdir, 'test_suffixes0.kid') open(tfile, 'w').write("""\

my content

""") def teardown_module(module): kid.path.remove(tmpdir) rmtree(tmpdir) def test_enable_import_empty(): """By default *.kid files are imported.""" sys.path.insert(0, tmpdir) try: kid.disable_import() raises(ImportError, "import test_suffixes0") kid.enable_import() import test_suffixes0 raises(ImportError, "import test_suffixes1") kid.disable_import() finally: sys.path.remove(tmpdir) def test_enable_import_with_ext(): """Using exts any file extension can be importable.""" ext = ".html,.kid.html" sys.path.insert(0, tmpdir) try: raises(ImportError, "import test_suffixes1") raises(ImportError, "import test_suffixes2") raises(ImportError, "import test_suffixes3") kid.enable_import(ext=ext) dest = joinpath(tmpdir, "test_suffixes1.kid") copyfile(tfile, dest) import test_suffixes1 # *.kid files are always importable dest = joinpath(tmpdir, "test_suffixes2.html") copyfile(tfile, dest) import test_suffixes2 dest = joinpath(tmpdir, "test_suffixes3.kid.html") copyfile(tfile, dest) import test_suffixes3 dest = joinpath(tmpdir, "test_suffixes4.xhtml") copyfile(tfile, dest) raises(ImportError, "import test_suffixes4") kid.disable_import() finally: sys.path.remove(tmpdir) def test_enable_import_with_path(): """Using path any template directory can be importable.""" assert tmpdir not in sys.path raises(ImportError, "import test_suffixes4") kid.enable_import(path=tmpdir) dest = joinpath(tmpdir, "test_suffixes4.kid") copyfile(tfile, dest) import test_suffixes4 kid.disable_import(path=tmpdir) dest = joinpath(tmpdir, "test_suffixes5.kid") copyfile(tfile, dest) raises(ImportError, "import test_suffixes5") PKY8ð6ï©g²l l kid/test/test_templatepath.py"""Unit tests for the kid.TemplatePath class. The testing directory structure looks something like this: tmpdir1/ /index.kid /members/ /index.kid /stuff.kid /master.kid /nonmembers/ /index.kid /garbage.kid /master.kid /shared/ /message.kid /error.kid /errors/ /error1.kid /error2.kid /error3.kid tmpdir2/ /index.kid /indexz.kid /master.kid /members/ /master.kid /stuff.kid tmpdir3/ /test.kid /base.kid """ from os import mkdir from os.path import join as joinpath, normpath from tempfile import mkdtemp from shutil import rmtree import kid kfind = kid.path.find def setup_module(module): '''Create a testing directory structure.''' global files, tmpdir1, tmpdir2, tmpdir3 def _create(dir, subdir, files): '''Create files.''' if subdir: subdir = joinpath(dir, subdir) mkdir(subdir) else: subdir = dir for file in files.split(): open(joinpath(subdir, file), 'w').write('nothing') return subdir # create the directory structure tmpdir1 = mkdtemp(prefix='kid_test_templatepath1_') _create(tmpdir1, None, 'index.kid') _create(tmpdir1, 'members', 'index.kid stuff.kid master.kid') _create(tmpdir1, 'nonmembers', 'index.kid garbage.kid master.kid') _create(_create(tmpdir1, 'shared', 'message.kid error.kid'), 'errors', 'error1.kid error2.kid error3.kid') tmpdir2 = mkdtemp(prefix='kid_test_templatepath2_') _create(tmpdir2, None, 'index.kid indexz.kid master.kid') _create(tmpdir2, 'members', 'stuff.kid master.kid') kid.path.append(tmpdir1) kid.path.append(tmpdir2) # create another temporary directory tmpdir3 = mkdtemp(prefix='kid_test_templatepath3_') _create(tmpdir3, None, 'test.kid base.kid') def teardown_module(module): kid.path.remove(tmpdir1) kid.path.remove(tmpdir2) rmtree(tmpdir1) rmtree(tmpdir2) rmtree(tmpdir3) def test_simple_file_in_root(): assert kfind('index.kid') == normpath(joinpath(tmpdir1, 'index.kid')) assert kfind('indexz.kid') == normpath(joinpath(tmpdir2, 'indexz.kid')) def test_file_in_directory(): assert kfind(joinpath('members', 'index.kid')) == \ normpath(joinpath(tmpdir1, 'members', 'index.kid')) path = joinpath('shared', 'errors', 'error1.kid') assert kfind(path) == normpath(joinpath(tmpdir1, path)) def test_no_exist(): assert kfind('noexist.kid') == None def test_find_relative(): rel = normpath(joinpath(tmpdir1, 'shared', 'error.kid')) expected = normpath(joinpath(tmpdir1, 'shared', 'message.kid')) assert kfind('message.kid', rel=rel) == expected def test_crawl_path(): rel = normpath(joinpath(tmpdir1, 'nonmembers', 'stuff.kid')) expected = normpath(joinpath(tmpdir2, 'master.kid')) assert kfind('master.kid', rel=rel) == expected def test_mod_python_bug(): '''This recreates the problem reported in ticket #110.''' assert kfind('base.kid', rel=joinpath(tmpdir3, 'test.kid')) \ == joinpath(tmpdir3, 'base.kid') PKY8ð6^ Kgjjkid/test/test_unicode.py"""Unicode tests""" from kid.parser import to_unicode astr = '\xe2\x80\xa0\xc2\xa9\xe2\x80\x94' ustr = astr.decode('utf-8') def test_to_unicode(): assert to_unicode(ustr, 'utf-8') == ustr assert to_unicode(astr, 'utf-8') == ustr class C(object): def __unicode__(self): return ustr assert to_unicode(C(), 'utf-8') == ustr PKY8ð6ŽßL½ggkid/test/test_element.py# -*- coding: utf-8 -*- """kid.element tests""" __revision__ = "$Rev: 492 $" __date__ = "$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $" __author__ = "David Stanek " __copyright__ = "Copyright 2006, David Stanek" __license__ = "MIT " import re from kid.element import Element, SubElement, \ Comment, ProcessingInstruction, Fragment, QName, \ namespaces, encode_entity def test_element_init(): element = Element("test0") assert element.tag == "test0" print element.attrib assert element.attrib == {} assert element.text is None assert element.tail is None element = Element("test1", dict(a=0, b=1)) assert element.tag == "test1" assert element.attrib == {"a": 0, "b": 1} assert element.text is None assert element.tail is None element = Element("test2", a=0, b=1) assert element.tag == "test2" assert element.attrib == {"a": 0, "b": 1} assert element.text is None assert element.tail is None element = Element("test3", dict(a=0, b=1), c=2) assert element.tag == "test3" assert element.attrib == {"a": 0, "b": 1, "c": 2} assert element.text is None assert element.tail is None def test_element_repr(): element = Element("test0") print `element` match = re.match(r"^$", `element`) assert match is not None def test_element_children(): parent = Element("parent") parent.append(Element("child0")) parent.append(Element("child1")) parent.append(Element("child2")) parent.append(Element("child3")) assert len(parent) == 4 assert parent[0].tag == "child0" assert parent[3].tag == "child3" parent[3] = Element("child4") assert parent[3].tag == "child4" del parent[3] assert len(parent) == 3 child0, child1 = parent[:2] assert child0.tag == "child0" assert child1.tag == "child1" parent[:2] = Element("firstone"), Element("firsttwo") assert parent[0].tag == "firstone" assert parent[1].tag == "firsttwo" del parent[:2] assert len(parent) == 1 print parent[0].tag assert parent[0].tag == "child2" parent.insert(0, Element("insert1")) parent.insert(0, Element("insert0")) assert parent[0].tag == "insert0" assert parent[1].tag == "insert1" assert len(parent) == 3 child = parent[-1] parent.remove(child) assert len(parent) == 2 children = parent.getchildren() assert len(children) == 2 assert children[0].tag == "insert0" assert children[1].tag == "insert1" parent.clear() assert parent.tag == "parent" assert len(parent) == 0 def test_element_attributes(): element = Element("test", dict(a=0, b=1), c=2) assert element.get("d") is None assert element.get("d", "") == "" assert element.get("c") == 2 assert element.get("c", "") == 2 element.set("c", "c") assert element.get("c") == "c" keys = element.keys() assert len(keys) == 3 for k in ["a", "b", "c"]: assert k in keys items = element.items() assert len(items) == 3 for i in [("a", 0), ("b", 1), ("c", "c")]: assert i in items def test_subelement(): parent = Element("parent") child0 = SubElement(parent, "child0") assert parent[0].tag == "child0" assert parent[0].attrib == {} assert parent[0].text is None assert parent[0].tail is None child1 = SubElement(parent, "child1", dict(a=0, b=1)) assert parent[1].tag == "child1" assert parent[1].attrib == {"a": 0, "b": 1} assert parent[1].text is None assert parent[1].tail is None child2 = SubElement(parent, "child2", a=0, b=1) assert parent[2].tag == "child2" assert parent[2].attrib == {"a": 0, "b": 1} assert parent[2].text is None assert parent[2].tail is None child3 = SubElement(parent, "child3", dict(a=0, b=1), c=2) assert parent[3].tag == "child3" assert parent[3].attrib == {"a": 0, "b": 1, "c": 2} assert parent[3].text is None assert parent[3].tail is None assert parent.getchildren() == [child0, child1, child2, child3] def test_comment(): comment = Comment() assert comment.tag == Comment assert comment.text is None comment = Comment("some text here") assert comment.text == "some text here" def test_processing_instruction(): pi = ProcessingInstruction("test") assert pi.tag == ProcessingInstruction assert pi.text == "test" pi = ProcessingInstruction("test", "some text here") assert pi.text == "test some text here" def test_fragment(): fragment = Fragment() assert fragment.tag == Fragment assert fragment.text == "" fragment = Fragment("text here") assert fragment.text == "text here" def test_qname(): qname = QName("text") assert qname.text == "text" assert str(qname) == "text" qname = QName("urn:kid", "text") assert qname.text == "{urn:kid}text" assert str(qname) == "{urn:kid}text" def test_namespaces(): element = Element("test", { "xmlns": "default ns", "xmlns:junk-ns0": "junk-ns value 0", "xmlns:junk-ns1": "junk-ns value 1", "py:pyattr": "py value", "attr": "a new attr", }) ns = namespaces(element) expected = { "": "default ns", "junk-ns0": "junk-ns value 0", "junk-ns1": "junk-ns value 1", } assert ns == expected assert element.get("xmlns") == "default ns" assert element.get("xmlns:junk-ns0") == "junk-ns value 0" assert element.get("xmlns:junk-ns1") == "junk-ns value 1" assert element.get("py:pyattr") == "py value" assert element.get("attr") == "a new attr" ns = namespaces(element, remove=True) assert element.get("xmlns") is None assert element.get("xmlns:junk-ns0") is None assert element.get("xmlns:junk-ns1") is None assert element.get("py:pyattr") == "py value" assert element.get("attr") == "a new attr" def test_encode_entity(): """TODO: do a more complete set of tests""" assert encode_entity("my text") == "my text" expected = "1 is > 0 && 2 < 3" assert encode_entity("1 is > 0 && 2 < 3") == expected PKY8ð69Üà»»kid/test/test_options.py# -*- coding: utf-8 -*- """Kid properties tests.""" __revision__ = "$Rev: 492 $" __date__ = "$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $" __author__ = "David Stanek " __copyright__ = "Copyright 2006, David Stanek" __license__ = "MIT " import kid.options from kid.test.util import raises def test_init(): opts = dict(encoding="utf-8", output="html") options = kid.options.Options(opts) assert options.get("encoding") == "utf-8" assert options.get("output") == "html" options = kid.options.Options(opts, stuff=0) assert options.get("encoding") == "utf-8" assert options.get("output") == "html" assert options.get("stuff") == 0 options = kid.options.Options(encoding="utf-8", output="html") assert options.get("encoding") == "utf-8" assert options.get("output") == "html" def test_setters_getters0(): options = kid.options.Options() options.set("encoding", "utf-8") options.set("output", "html") assert options.get("encoding") == "utf-8" assert options.get("output") == "html" assert options.get("not there", 0) == 0 o = object() assert options.get("not there", o) == o options.remove("not there") options.remove("encoding") assert options.get("encoding") is None def test_setters_getters1(): options = kid.options.Options() options["encoding"] = "utf-8" options["output"] = "html" assert options["encoding"] == "utf-8" assert options["output"] == "html" def cause_error(name): return options[name] raises(KeyError, cause_error, "not there") def cause_error(name): del options[name] raises(KeyError, cause_error, "not there") del options["encoding"] assert options.get("encoding") is None def test_isset(): options = kid.options.Options(test=0) assert options.isset("test") == True assert options.isset("not there") == False PKY8ð6ÎR2! ! kid/test/test_extended_layout.py"""Unit Tests for Extended Layouts.""" __revision__ = "$Rev: 455 $" __author__ = "Christoph Zwerschke " __copyright__ = "Copyright 2006, Christoph Zwerschke" from os.path import join as joinpath from tempfile import mkdtemp from shutil import rmtree import kid def setup_module(module): global tmpdir tmpdir = mkdtemp(prefix='kid_test_extended_layout_') kid.path.insert(tmpdir) def teardown_module(module): kid.path.remove(tmpdir) rmtree(tmpdir) def test_extended_layout(): """Test layout template extended by another template.""" open(joinpath(tmpdir, 'master.kid'), 'w').write("""\

Master Title

""") t = kid.Template(file="master.kid") rslt = t.serialize(output='xhtml') assert '' in rslt assert '' in rslt assert 'head' not in rslt assert 'master.js' not in rslt assert 'body' not in rslt assert 'Title' not in rslt open(joinpath(tmpdir, 'section.kid'), 'w').write("""\ Section Title

Section Title

Section content
""") t = kid.Template(file="section.kid") rslt = t.serialize(output='xhtml') assert '' in rslt assert '' in rslt assert 'Section Title' in rslt assert 'sB(s HTMLTemplatestsexpecteds serializesrsltsAssertionError(sexpectedsrsltst((s9build/bdist.linux-i686/egg/kid/test/test_serialization.pystest_html_noescape_elements‰s  cCs:tdtƒ}d}|iƒ}||jpt‚dS(Ns9s*(s HTMLTemplatesxhtml_namespacestsexpecteds serializesrsltsAssertionError(sexpectedsrsltst((s9build/bdist.linux-i686/egg/kid/test/test_serialization.pystest_html_boolean_attributes’s cCs˜tdddtƒ}td|_t|_d}ti|ƒ}||_dk l }|dtƒ}|i d|ƒ}|id d ƒ}d }||jpt‚tdd dtƒ}t|_t|_d }ti|ƒ}||_|i ƒ}|iddƒ}||jpt‚|iddƒ}ti|ƒ}||_|i ƒ}|id d ƒ}|iddƒiddƒ}||jpt‚dS(Nsencodingsutf-8s transposes html-stricts(sFormatsno_empty_linessformats ss·sasciisßContent

Hello, World!

s/>s>s content-types garbage-typessJ���<meta content="text/html; charset=ascii" http-equiv="content-type"><title>(���s���HTMLSerializers���Trues ���serializers���doctypess���doctypes ���inject_types���sources���kids���Templates���ts ���kid.formats���Formats���formats ���serializes���rslts���replaces���expecteds���AssertionErrors���Falses���None(���s���Formats���formats���sources���ts���expecteds���rslts ���serializer(����(����s9���build/bdist.linux-i686/egg/kid/test/test_serialization.pys���test_doctype_and_injection™���s:����           c����������C���s[��d�t��}��t�i�|��ƒ�}�t�t�i�ƒ�d�j�p�t�‚�xt�i�D]}�|�i �d�|�ƒ�}�d�|�i �ƒ��j�o~|�i �d�ƒ�p�t�‚�|�i �ƒ��i �d�ƒ�p�t�‚�|�i �d�ƒ�o,�d�|�j�p�t�‚�d �|�j�p�t�‚�n)�d �|�j�p�t�‚�d �|�j�p�t�‚�d �|�j�p�t�‚�d �|�j�oR�d�|�i �ƒ��j�p�t�‚�d�|�i �ƒ��j�p�t�‚�d�|�i �ƒ��j�p�t�‚�nˆ�d �|�i �ƒ��j�p�t�‚�d�|�j�o2�d�|�i �ƒ��j�p�t�‚�d�|�j�p�t�‚�n/�d�|�i �ƒ��j�p�t�‚�d�|�j�p�t�‚�d�|�j�o,�d�|�j�p�t�‚�d�|�j�p�t�‚�nù�d�|�j�p�t�‚�d�|�j�p�t�‚�|�i �d�ƒ�ob�d �|�j�o�d�|�j�p�t�‚�q.d�|�j�o�d�|�j�p�t�‚�q.d�|�j�p�t�‚�n_�d �|�j�o�d�|�j�p�t�‚�n:�d�|�j�o�d�|�j�p�t�‚�n�d�|�j�p�t�‚�|��}�|�i�d�d�ƒ�}�|�i �d �ƒ� o,�|�i�d!�d"�ƒ�}�|�i�d#�t��d$�ƒ�}�n�|�i �ƒ��|�j�o.�|�i�ƒ��}�|�i�d%�d&�ƒ�i�d'�d(�ƒ�}�n�d)�|�}�|�i�|�ƒ�p�t�‚�q@�|�i�d*�ƒ�o2�|�i �d+�ƒ�p�t�‚�|�i�|��ƒ�p�t�‚�q@�|�d,�j�p�t�‚�|�d-�j�p�t�‚�q@�Wd��S(.���Ns.���<html xmlns="%s"><h1 />Hello<br />World</html>i���s���outputs���htmls ���<!DOCTYPE s���<!doctype html public "s���xhtmls���DOCTYPE html PUBLICs��� "-//W3C//DTD XHTML 1.0s���DOCTYPE HTML PUBLICs��� "-//W3C//DTD HTML 4.01s���//EN"s���stricts ���transitionals���framesets���looses ��� Framesets ��� Transitionals���quirkss���http://s���dtds���"http://www.w3.org/TR/s���.dtd"s���/xhtml1/DTD/xhtml1-strict.dtd"s ���/xhtml1/DTD/xhtml1-frameset.dtd"s$���/xhtml1/DTD/xhtml1-transitional.dtd"s���/html4/strict.dtd"s���/html4/frameset.dtd"s���/html4/loose.dtd"s���<h1 />s ���<h1></h1>s���xs���<br />s���<br>s ��� xmlns="%s"s����s���HELLOs���Hellos���WORLDs���Worlds��� s���mls'���<?xml version="1.0" encoding="utf-8"?> s���plains ���HelloWorld(���s���xhtml_namespaces���xmls���kids���Templates���ts���lens���output_methodss���AssertionErrors���outputs ���serializes���ss���lowers ���startswiths���rs���replaces���uppers���endswith(���s���xmls���ss���rs���ts���output(����(����s9���build/bdist.linux-i686/egg/kid/test/test_serialization.pys���test_output_methodsÂ���sp����  �        " c����������C���s^���t��d�t�ƒ�}�t�d�|�_�t�i�d�ƒ�}��|�|��_�d�}�|��i �ƒ��}�|�|�j�p�t �‚�d��S(���Ns ���transposes ���html-stricts ���<html xml:lang='en' lang='en' />sr���<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <HTML LANG="en"></HTML>( ���s���HTMLSerializers���Trues ���serializers���doctypess���doctypes���kids���Templates���ts���expecteds ���serializes���rslts���AssertionError(���s���ts���expecteds���rslts ���serializer(����(����s9���build/bdist.linux-i686/egg/kid/test/test_serialization.pys���test_strip_lang��s����   c����������C���si���t��ƒ��}�t�|�_�t�|�_�t�i�|�_�t �i �d�ƒ�}��|�|��_�d�}�|��i �ƒ��}�|�|�j�p�t�‚�d��S(���Ns���<HTML><HEAD /></HTML>s���<html><head></head></html>(���s���HTMLSerializers ���serializers���Nones���doctypes���Falses ���inject_types���strings���lowers ���transposes���kids���Templates���ts���expecteds ���serializes���rslts���AssertionError(���s���ts���expecteds���rslts ���serializer(����(����s9���build/bdist.linux-i686/egg/kid/test/test_serialization.pys���test_transpose_lower��s����      c����������C���sf���t��ƒ��}�t�|�_�t�|�_�t�|�_�t�i�d�ƒ�}��|�|��_�d�}�|��i �ƒ��}�|�|�j�p�t �‚�d��S(���Ns���<HTML><HEAD /></HTML>s���<HTML><HEAD></HEAD></HTML>(���s���HTMLSerializers ���serializers���Nones���doctypes���Falses ���inject_types ���transposes���kids���Templates���ts���expecteds ���serializes���rslts���AssertionError(���s���ts���expecteds���rslts ���serializer(����(����s9���build/bdist.linux-i686/egg/kid/test/test_serialization.pys���test_transpose_off��s����      c����������C���s­��xJ�d�D]B�}�t�i�d�|�ƒ�}�|�i�d�d�ƒ�}�|�i�d�ƒ�p�t�‚�q�Wt�i�d�ƒ�i�d�d�ƒ�}�|�i�d �ƒ�p�t�‚�d �k�l �}�x¤�d �D]œ�}�y)�t�i�d�|�ƒ�}�|�i�d�d�ƒ�}�WnO�|�j �oC�}��t �|��ƒ�}��d �|��j�o �d �|��j�o�d�|�}�qd�}�n�X|�i�d�|�ƒ�p�t�‚�q“�Wt�i�d�ƒ�i�d�d�d�d�ƒ�}�|�i�d�ƒ�p�t�‚�t�i�d�ƒ�}�|�i�d�d�d�d�ƒ�}�|�i�d�ƒ�p�t�‚�d�S(���s1���Only real XML whitespace should be stripped away.s��� s ���<p>%s</p>s���encodings���latin-1s���<p />s ���<p> </p>s���outputs���xhtmls���<p> </p>(���s ���ExpatErrors���  s���not well-formeds ���invalid tokens ���XML Errors ���<p> </p>s���<p> </p>s ���<p> </p>N( ���s���chars���kids���Templates���ts ���serializes���rslts���endswiths���AssertionErrors���xml.parsers.expats ���ExpatErrors���es���str(���s���es���chars���ts���rslts ���ExpatError(����(����s9���build/bdist.linux-i686/egg/kid/test/test_serialization.pys���test_whitespace%��s2������ �  !c����������C���s`���t��i�d�ƒ�i�d�d�ƒ�}��|��i�d�d�ƒ�i�d�d�ƒ�}��|��i�d�d�d �d �ƒ�p�t�‚�d �S( ���s7���Keep nonbreakable space inside paragraph (ticket #140).sÖ�� <?python def nbsp1(): return XML("nbsp") def nbsp2(): return XML(" ") def nbsp3(): return XML(" ") def nbsp4(): return u'\u00a0' ?> <div xmlns:py="http://purl.org/kid/ns#"> <h1>ticket #140</h1> <span py:content="nbsp1()"/> <span py:content="nbsp2()"/> <span py:content="nbsp3()"/> <span py:content="nbsp4()"/> </div>s���encodings���latin-1s��� s����s��� s)���<div><h1>ticket#140</h1><span>nbsp</span>i���s���<span> </span>s���</div>N(���s���kids���Templates ���serializes���rslts���replaces���endswiths���AssertionError(���s���rslt(����(����s9���build/bdist.linux-i686/egg/kid/test/test_serialization.pys���test_whitespace2B��s�����c����������C���s­���d�}��t�i�|��ƒ�i�d�d�ƒ�|��j�p�t�‚�t�t�d�ƒ�d�}��t�i�|��ƒ�i�d�d�ƒ�|��j�p�t�‚�t�t�d�ƒ�d�}��t�i�|��ƒ�i�d�d�ƒ�|��j�p�t�‚�d �S( ���s<���Comments should not add an additional newline (ticket #107).sT���<?xml version="1.0" encoding="utf-8"?> <html> <!-- a comment --> <element /> </html>s���outputs���xmls���htmls7��� <HTML> <!-- a comment --> <ELEMENT> </ELEMENT> </HTML>s���HTMLs���xhtmls7��� <html> <!-- a comment --> <element> </element> </html>N(���s���expecteds���kids���Templates ���serializes���AssertionErrors���serialize_doctypes���doctypes(���s���expected(����(����s9���build/bdist.linux-i686/egg/kid/test/test_serialization.pys���test_comment_whitespaceZ��s�����))c����������C���s{���t��i�d�ƒ�}�t�t�d�ƒ�d�}��|�i�d�d�ƒ�|��j�p�t�‚�t�t�d�ƒ�d�}��|�i�d�d�ƒ�|��j�p�t�‚�d�S( ���s��Handling of empty lines in templates. Empty lines between elements should be removed. We assume that balanced_blocks is enabled for both HTML and XHTML templates. Inline elements in template should remain so. Other elements should be indented. sª��� <html> <script>some lines and more lines</script><body> <a href="/"><img src="pic.jpg"/></a> </body> </html>s���htmls ��� <HTML> <SCRIPT>some lines and more lines</SCRIPT><BODY> <A HREF="/"><IMG SRC="pic.jpg"></A> </BODY> </HTML>s���outputs���HTMLs���xhtmls¢��� <html> <script>some lines and more lines</script><body> <a href="/"><img src="pic.jpg" /></a> </body> </html>N(���s���kids���Templates���ts���serialize_doctypes���doctypess���expecteds ���serializes���AssertionError(���s���expecteds���t(����(����s9���build/bdist.linux-i686/egg/kid/test/test_serialization.pys���test_empty_linesf��s ���� �   c����������C���s6���d�}��t�|��ƒ�i�ƒ��|��i�d�d�ƒ�j�p�t�‚�d�S(���s:���Check that no extra indentation is inserted (ticket #131).sE���<div> <a href="/"><img src="pic.jpg"/></a> </div>s���/>s���>N(���s���htmls ���HTMLTemplates ���serializes���replaces���AssertionError(���s���html(����(����s9���build/bdist.linux-i686/egg/kid/test/test_serialization.pys���test_extra_indentation��s�����c����������C���sô���d�}�d�}�t�i�|�d�d�ƒ}�t�i�|�d�|�i�ƒ��ƒ}��|��i�d�d�d�t�ƒ�}�d �}�|�|�j�p�t �‚�d �}�t�i�|�d�d�ƒ}�t�i�|�d�|�i�ƒ��ƒ}��|��i�d�d�d�t�ƒ�}�d �}�|�|�j�p�t �‚�d �}�|�|�j�p�t �‚�d �S(���s5���Check for extra indentation to textarea (ticket #83).sP��� <textarea xmlns:py="http://purl.org/kid/ns#" py:content="value" /> sQ��� <div xmlns:py="http://purl.org/kid/ns#"> ${widget} </div> s���values����s���widgets���outputs���xhtmls���fragments.���<div> <textarea></textarea> </div>sE��� <div xmlns:py="http://purl.org/kid/ns#">${widget}</div> s ���<div><textarea></textarea></div>sD��� <div xmlns:py="http://purl.org/kid/ns#"> ${widget}</div> N( ���s ���widgetsrcs���templates���kids���Templates���ts ���transforms���tmpls ���serializes���Trues���rslts���expecteds���AssertionError(���s���tmpls ���widgetsrcs���ts���templates���expecteds���rslt(����(����s9���build/bdist.linux-i686/egg/kid/test/test_serialization.pys���test_textarea_indentation–��s �����c����������C���sr���d�}�d�}�t�i�|�d�d�ƒ}�t�i�|�d�|�i�ƒ��ƒ}��|��i�d�d�d�t�ƒ�}�d �}�|�|�j�p�t �‚�d �S( ���s8���Check problem with handling of br in XHTML (ticket #83).s���<div><br/></div>s‹���<div xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://purl.org/kid/ns#"> ${widget}<br/> </div>s���values����s���widgets���outputs���xhtmls���fragmentsY���<div xmlns="http://www.w3.org/1999/xhtml"> <div><br /></div><br /> </div>N( ���s ���widgetsrcs���templates���kids���Templates���ts ���transforms���tmpls ���serializes���Trues���rslts���expecteds���AssertionError(���s���tmpls ���widgetsrcs���ts���templates���expecteds���rslt(����(����s9���build/bdist.linux-i686/egg/kid/test/test_serialization.pys���test_br_namespace_issues´��s�����c����������C���s��d�}��t�i�|��ƒ�}�xì�t�t�t�f�D]Û�}�|�ƒ��}�|�i �d�|�d�d�ƒ�}�|�i �|��i �d�d�ƒ�ƒ�p�t �‚�|�d�t�ƒ�}�|�i �d�|�d�d�ƒ�}�|�i �|��ƒ�p�t �‚�|�d�h��d�d �<ƒ�}�|�i �d�|�d�d�ƒ�}�|�i �|��i �d�d �ƒ�ƒ�p�t �‚�q%�Wd �S( ���s(���Check that   is rendered correctly.s���<p>Dr. Snuggles</p>s���outputs���encodings���asciis��� s��� s ���entity_mapu��� s��� Mooney N(���s���xmls���kids���Templates���ts ���XMLSerializers���HTMLSerializers���XHTMLSerializers���ss���outputs ���serializes���rs���endswiths���replaces���AssertionErrors���True(���s���xmls���ss���rs���ts���output(����(����s9���build/bdist.linux-i686/egg/kid/test/test_serialization.pys ���test_nbspÃ��s������ #c����������C���s`���d�}�d�}�t�i�|�d�t�i�|�ƒ�i�ƒ��ƒ}�|�i�d�d�d�t�ƒ�}��|��d�j�p�t �‚�d�S( ���s5���Check that namespaces are not repeated (ticket #144).s4��� <div xmlns="http://www.w3.org/1999/xhtml"/>sw��� <div xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://purl.org/kid/ns#" py:content="div1"/>s���div1s���outputs���xhtmls���fragments;���<div xmlns="http://www.w3.org/1999/xhtml"><div></div></div>N( ���s���div1s���div2s���kids���Templates ���transforms���ts ���serializes���Trues���ss���AssertionError(���s���ss���ts���div2s���div1(����(����s9���build/bdist.linux-i686/egg/kid/test/test_serialization.pys���test_no_repeated_namespacesÒ��s �����$(2���s���__doc__s ���__revision__s���__date__s ���__author__s ���__copyright__s ���__license__s���kids ���kid.namespaces���xhtmls���kid.serializations���serialize_doctypes���doctypess���strs���xhtml_namespaces���test_serialize_doctypes���test_html_output_methods���test_HTML_output_methods���test_xhtml_output_methods���test_html_strict_output_methods���test_html_quirks_output_methods���test_xml_output_methods���HTMLSerializers ���XMLSerializers���XHTMLSerializers ���serializers���Nones���doctypes���Falses ���inject_types ���HTMLTemplates���test_html_transposes���test_html_empty_elementss���test_xhtml_empty_elementss���test_html_noescape_elementss���test_html_boolean_attributess���test_doctype_and_injections���test_output_methodss���test_strip_langs���strings���test_transpose_lowers���test_transpose_offs���test_whitespaces���test_whitespace2s���test_comment_whitespaces���test_empty_liness���test_extra_indentations���test_textarea_indentations���test_br_namespace_issuess ���test_nbsps���test_no_repeated_namespaces(*���s���test_br_namespace_issuess ���test_nbsps���XHTMLSerializers���test_html_output_methods���test_empty_liness���test_xhtml_empty_elementss���test_output_methodss���test_transpose_offs���test_HTML_output_methods ���XMLSerializers ���HTMLTemplates���test_html_transposes���test_comment_whitespaces ���__revision__s���test_no_repeated_namespacess ���__license__s���test_whitespace2s���HTMLSerializers���test_doctype_and_injections���test_html_noescape_elementss���test_serialize_doctypes���test_transpose_lowers���xhtml_namespaces���xhtmls���test_xml_output_methods���doctypess���test_xhtml_output_methods���test_textarea_indentations���serialize_doctypes���test_extra_indentations ���__author__s���test_whitespaces���strings���kids���test_html_quirks_output_methods���test_strip_langs ���__copyright__s���test_html_boolean_attributess���test_html_strict_output_methods���__date__s���test_html_empty_elementss ���serializer(����(����s9���build/bdist.linux-i686/egg/kid/test/test_serialization.pys���?���sR���                 ) A    )    PK�����Æ=ð6ƒ¨>f°��°�����kid/test/test_layout.pyc;ò [P›Fc�����������@���sI���d��Z��d�Z�d�Z�d�Z�d�k�Z�d�„��Z�d�„��Z�d�„��Z�d�„��Z�d�S( ���s ���Unit Tests for layout templates.s ���$Rev: 421 $s#���Daniel Miller <millerdev@nwsdb.com>s���Copyright 2006, David StanekNc����������C���s¬���d�k��l�}�y�t�i�d�ƒ�i�ƒ��WnE�|�j �o�}��t�|��ƒ�}��n&�t�j �o �d�}��n�d�}��n�Xd�|��j�p�t�‚�d�|��j�p�t�‚�d�|��j�p�t�‚�d��S(���N(���s���TemplateLayoutErrors[��� <html xmlns:py="http://purl.org/kid/ns#" py:layout="no_layout" /> s ���wrong errors���silents ���'no_layout's ���not defineds���while processing layout=( ���s���kid.template_utils���TemplateLayoutErrors���kids���Templates ���serializes���es���strs ���Exceptions���AssertionError(���s���es���TemplateLayoutError(����(����s2���build/bdist.linux-i686/egg/kid/test/test_layout.pys���test_layout_error ���s����   c����������C���sZ���t��i�d�ƒ�}�t��i�d�d�t�|�ƒ�ƒ}�|�i�ƒ��}��|��i�d�ƒ�d�j�p �t�d�‚�d��S(���Nsg��� <html xmlns:py="http://purl.org/kid/ns#"> ${body_content()} </html> s¢��� <html py:layout="dynamic_layout" xmlns:py="http://purl.org/kid/ns#"> <body py:def="body_content()">body content</body> </html> s���dynamic_layouts ���body contentiÿÿÿÿs&���body_content function was not executed( ���s���kids���Templates���layouts���types���childs ���serializes���outputs���finds���AssertionError(���s���outputs���childs���layout(����(����s2���build/bdist.linux-i686/egg/kid/test/test_layout.pys���test_dynamic_layout���s���� c����������C���s`���t��i�d�ƒ�}�t��i�d�d�t�|�ƒ�d�d�ƒ}�|�i�ƒ��}��|��i�d�ƒ�d�j�p �t�d�‚�d��S( ���Ns¶�� <?python test_var = "WRONG VALUE" ?> <html xmlns:py="http://purl.org/kid/ns#"> <body> <?python assert "test_var" in locals(), "test_var is not defined in layout locals" assert test_var == "test value", "test_var has wrong value: %r" % test_var ?> <div /> </body> </html> s(�� <?python layout_params["test_var"] = "WRONG VALUE" ?> <html py:layout="layout" xmlns:py="http://purl.org/kid/ns#"> <content py:match="item.tag == 'div'" py:strip="True"> <?python assert "test_var" in locals(), "test_var is not defined in py:match locals" assert test_var == "test value", "test_var has wrong value in py:match: %r" % test_var ?> test_var=${test_var} </content> </html> s���layouts���test_vars ���test values���test_var=test valueiÿÿÿÿs���match template was not executed( ���s���kids���Templates���layouts���types���childs ���serializes���outputs���finds���AssertionError(���s���outputs���childs���layout(����(����s2���build/bdist.linux-i686/egg/kid/test/test_layout.pys���test_match_locals(���s����! c����������C���s`���t��i�d�ƒ�}�t��i�d�d�t�|�ƒ�d�d�ƒ}�|�i�ƒ��}��|��i�d�ƒ�d�j�p �t�d�‚�d��S( ���NsÁ�� <?python test_var = "WRONG VALUE" ?> <html xmlns:py="http://purl.org/kid/ns#"> <body> <?python assert "test_var" in locals(), "test_var is not defined in layout locals" assert test_var == "test value", "test_var has wrong value: %r" % test_var ?> ${child_content()} </body> </html> s �� <?python layout_params["test_var"] = "WRONG VALUE" ?> <html py:layout="layout" xmlns:py="http://purl.org/kid/ns#"> <content py:def="child_content()" py:strip="True"> <?python assert "test_var" in locals(), "test_var is not defined in py:def locals" assert test_var == "test value", "test_var has wrong value in py:def: %r" % test_var ?> test_var=${test_var} </content> </html> s���layouts���test_vars ���test values���test_var=test valueiÿÿÿÿs'���child_content function was not executed( ���s���kids���Templates���layouts���types���childs ���serializes���outputs���finds���AssertionError(���s���outputs���childs���layout(����(����s2���build/bdist.linux-i686/egg/kid/test/test_layout.pys���test_def_localsM���s����! ( ���s���__doc__s ���__revision__s ���__author__s ���__copyright__s���kids���test_layout_errors���test_dynamic_layouts���test_match_localss���test_def_locals(���s ���__copyright__s ���__revision__s���test_dynamic_layouts���test_match_localss ���__author__s���test_def_localss���kids���test_layout_error(����(����s2���build/bdist.linux-i686/egg/kid/test/test_layout.pys���?���s���    %PK�����Æ=ð6ü@ç€"��€"�����kid/test/test_match.pyc;ò ZP›Fc�����������@���s‚���d��Z��d�Z�d�Z�d�Z�d�k�l�Z�d�k�l�Z�d�k �l �Z �d�k �Z �d�„��Z �d �„��Z �d �„��Z�d �„��Z�d �„��Z�d �„��Z�d�S(���s%���Unit Tests for the template matching.s ���$Rev: 455 $s"���David Stanek <dstanek@dstanek.com>s���Copyright 2005, David Stanek(���s���join(���s���mkdtemp(���s���rmtreeNc���������C���s#���t��d�d�ƒ�a�t�i�i�t�ƒ�d��S(���Ns���prefixs���kid_test_match_(���s���mkdtemps���tmpdirs���kids���paths���insert(���s���module(����(����s1���build/bdist.linux-i686/egg/kid/test/test_match.pys ���setup_module ���s�����c���������C���s���t��i�i�t�ƒ�t�t�ƒ�d��S(���N(���s���kids���paths���removes���tmpdirs���rmtree(���s���module(����(����s1���build/bdist.linux-i686/egg/kid/test/test_match.pys���teardown_module���s����c����������C���s‚���t��t�t�d�ƒ�d�ƒ�i�d�ƒ�t��t�t�d�ƒ�d�ƒ�i�d�ƒ�t�i�d�d�ƒ�i�ƒ��}��d�|��j�p�t�‚�d�|��j�p�t�‚�d��S( ���Ns���match0_base.kids���ws�� <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://purl.org/kid/ns#"> <head py:match="item.tag=='{http://www.w3.org/1999/xhtml}head'"> <meta content="text/html; charset=UTF-8" http-equiv="content-type" py:replace="''" /> <title py:replace="''">Your title goes here

smatch0_page.kids¤ Welcome to TurboGears

My Main page with bold text

sfiles$Welcome to TurboGearssBOLD( sopensjoinpathstmpdirswriteskidsTemplates serializeshtmlsAssertionError(shtml((s1build/bdist.linux-i686/egg/kid/test/test_match.pys test_match0s cCs¾tttdƒdƒidƒtttdƒdƒidƒtiddƒiƒ}d|jpt‚d|jpt‚d |jpt‚d |jpt‚d |jpt‚dS( Nsmatch1_base.kidsws Some title here
Real content would go here.
smatch1_page.kidsÊ

This is a test link, or an e-mail address.

sfilessPtest linksPe-mail addressss&
Real content would go here.
( sopensjoinpathstmpdirswriteskidsTemplates serializeshtmlsAssertionError(shtml((s1build/bdist.linux-i686/egg/kid/test/test_match.pys test_match1Bs cCstttdƒdƒidƒtttdƒdƒidƒddf}xÆtdƒD]¸}d |}ttt|ƒdƒid |ƒti d |ƒ}||_ |i ƒ}d |jpt‚d |jpt‚d|jpt‚t|ƒ}|iƒt|ƒ}qWWdS(sFTest for a know bad case in the apply_matches function (ticket # 142).smatch2_master.kidsws%
smatch2_userform.kids°
smastersuserformismatch2_%s_%s.kids² sfilesTHIS IS THE TAGs MASTER MATCHsseasources:userformN(sopensjoinpathstmpdirswritesextendssrangesisfileskidsTemplatestsactions serializeshtmlsAssertionErrorslistsreversestuple(sishtmlsextendssfilest((s1build/bdist.linux-i686/egg/kid/test/test_match.pys test_match_2ks"   #     cCsUd}tid|ƒ}|iddƒ}d}|GH|GH|i|ƒpt‚dS(s=Check for an issue with additional blank lines (ticket #131).sù one

hello world!

two ssourcesoutputshtmlsH one two N( stemplateskidsTemplatests serializesrsltsexpectsendswithsAssertionError(sexpectsrsltststemplate((s1build/bdist.linux-i686/egg/kid/test/test_match.pys test_match_3—s (s__doc__s __revision__s __author__s __copyright__sos.pathsjoinsjoinpathstempfilesmkdtempsshutilsrmtreeskids setup_modulesteardown_modules test_match0s test_match1s test_match_2s test_match_3( s test_match1s test_match0s __copyright__s __revision__smkdtempsteardown_modules setup_modules __author__s test_match_3s test_match_2srmtreeskidsjoinpath((s1build/bdist.linux-i686/egg/kid/test/test_match.pys?s       , ) ,PKÆ=ð6`—Ü× × kid/test/test_namespace.pyc;ò ZP›Fc@sTdZdZdZdZdZdZdklZdkl Z d„Z d „Z d S( skid.namespace tests.s $Rev: 492 $s5$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $s!Ryan Tomayko (rtomayko@gmail.com)s!Copyright 2004-2005, Ryan Tomaykos8MIT (s Namespace(sNamespaceStackcCsÀtddddƒ}|idjpt‚|ddjpt‚|idƒdjpt‚tdtƒ}|idjpt‚|ddjpt‚|idƒdjpt‚dS(Nsurisurn:testsprefixstests{urn:test}namesnames test:name(s NamespacesnssnamesAssertionErrorsqnamesNone(sns((s5build/bdist.linux-i686/egg/kid/test/test_namespace.pystest_namespace_modulesc Csàtƒ}hdd(sElements load_templatesTemplate(s ElementStreamsXMLcCs\tddtƒ}t|ƒtjpt‚tddtƒ}t|ƒtjpt‚dS(Nshello worldsfragments hello world(sXMLsFalsesdocstypes ElementStreamsAssertionErrorsTrue(sdoc((s2build/bdist.linux-i686/egg/kid/test/test_parser.pys test_xml_typescCs¯tddtƒ}t|ƒtjpt‚|iƒ}t|ƒttdƒƒjpt‚|idjpt‚|didjpt‚|di djpt‚dS(Nsworldsfragmentsdocishellosworld( sXMLsFalsesdocstypes ElementStreamsAssertionErrorsexpandsElementstagstext(sdoc((s2build/bdist.linux-i686/egg/kid/test/test_parser.pys test_expands &cCs§d}t|dtƒ}t|ƒtjpt‚|iddƒ}t|ƒtjpt‚dk l }|dtƒ}|i |dt ƒ}|djpt‚dS(NsÀ The Title

Header 1

Header 1.1

Header 1.2

Header 1.2.1

Header 1.2.2

Hello, World!

Header 1.2.3

Header 1.3

sfragmentslevelsi(s XMLSerializersdecls Hello, World!(sxmlsXMLsFalses xml_streamstypes ElementStreamsAssertionErrorsstripsxml_stream_strippedskids XMLSerializers serializers serializesTrues xml_stripped(sxmls xml_streamsxml_stream_strippeds XMLSerializers xml_strippeds serializer((s2build/bdist.linux-i686/egg/kid/test/test_parser.pys test_strips cCsÒd}tt|ƒƒdddjpt‚d}ytt|ƒƒ}Wn!tj o}t|ƒ}nXd|jpt‚d}hdd <d d <}tt|d |ƒƒddd jpt‚dS(Ns iiu s &codswallop;sundefined entity &codswallop;s , &codswallop;!snbspuHellos codswallopuWorlds entity_mapu Hello, World!(sxmlslistsXMLsAssertionErrorses Exceptionsstrs entity_map(sxmlses entity_map((s2build/bdist.linux-i686/egg/kid/test/test_parser.pystest_xml_with_entity_map:s(cCsæd}t|ƒiddƒ}|idƒpt‚d}yt|ƒiddƒ}Wn!tj o}t|ƒ}nXd|jpt‚d}hdd <d d <}t|d |ƒiddƒ}|id ƒpt‚dS(Ns sencodingsasciis s&codswallop;sundefined entity &codswallop;s" , &codswallop;!snbspuHellos codswallopuWorlds entity_mapsHello, World!( sxmls load_templates serializesssendswithsAssertionErrorses Exceptionsstrs entity_map(sxmlsesss entity_map((s2build/bdist.linux-i686/egg/kid/test/test_parser.pys"test_load_template_with_entity_mapGscCs`d}t|ƒiddƒ}|idƒiddƒ}|idƒ}||jpt‚dS(NsE µ¹è»¾ýáísencodingsutf-8s iso-8859-2(sss load_templates serializesrsdecodesreplacesAssertionError(sssr((s2build/bdist.linux-i686/egg/kid/test/test_parser.pys test_encodingVs cCsBd}tdƒ}|idtƒ}d}||jpt‚t|i ƒƒi ƒ}td|d|ƒ}|idtƒ}||jpt‚tdƒ}|idtƒ}d}||jpt‚t|i ƒƒi ƒ}td|d|ƒ}|idtƒ}||jpt‚td ƒ}|idtƒ}d }||jpt‚t|i ƒƒi ƒ}td|d|ƒ}|idtƒ}||jpt‚td ƒ}|idtƒiƒ}d }||jpt‚t|i ƒƒi ƒ}td|d|ƒ}|idtƒiƒ}||jpt‚d S(s3Testcase for expanding XML fragments (ticket #145).sF

Hello World #$i

sfragmentsÛ

Hello World #0

Hello World #1

Hello World #2

ssourcesstreamsy

Hello World #$i

Hello World #0

Hello World #1

Hello World #2

s—

Hello World

s7

Hello World

sn

Hello World

s

Hello World

N(stemplatesTemplatests serializesTruesssexpectedsAssertionErrors ElementStreams transformsexpandsstreamst2ss2sstrip(stemplatesstreamss2st2ssstsexpected((s2build/bdist.linux-i686/egg/kid/test/test_parser.pystest_expand_fragments_sD     N(s__doc__s __revision__s__date__s __author__s __copyright__s __license__skidsElements load_templatesTemplates kid.parsers ElementStreamsXMLs test_xml_types test_expands test_stripstest_xml_with_entity_maps"test_load_template_with_entity_maps test_encodingstest_expand_fragments(sXMLs test_xml_types __copyright__s __revision__s test_strips __license__s load_templates test_encodings test_expandsElements__date__stest_xml_with_entity_maps ElementStreamsTemplates __author__stest_expand_fragmentss"test_load_template_with_entity_map((s2build/bdist.linux-i686/egg/kid/test/test_parser.pys?s    PKÆ=ð6Ï2Š 5 5 kid/test/test_codewriter.pyc;ò [P›Fc@sLdZdZdZdZdZdZd„Zd„Zd„Zd „Z d S( skid.codewriter tests.s $Rev: 492 $s5$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $s!Ryan Tomayko (rtomayko@gmail.com)s!Copyright 2004-2005, Ryan Tomaykos8MIT cCsŒdkl}ddddgfddddgfddfddfd d d gfd d d gfd ddgfdddgfdddgfdddgfdd ddgfdd ddgfdd ddgfdd ddgfddddgfdd d!gfd"d#d$gfd%d d&dgfd'd d&dgfd(d)fd*d*fg}x4|D],\}}||ƒ}||jpt‚qXWdS(+N(s interpolatesfoo ${bar} bazs'foo 'sbars' baz's foo $bar bazsfoo $${bar} bazs foo $$bar bazs${foo} bar bazsfoos ' bar baz's $foo bar bazsfoo bar ${baz}s 'foo bar 'sbazs foo bar $bazsfoo $${bar}${baz}s 'foo ${bar}'s foo $$bar$bazs 'foo $bar's${foo} bar ${baz}s' bar 's $foo bar $bazs${foo}$${bar}${baz}s'${bar}'s $foo$$bar$bazs'$bar'sfoo $object.attr bars object.attrs' bar's$ foo ${bar baz}s'$ foo 'sbar bazsfoo$ ${bar.baz}s'foo$ 'sbar.bazs$foo $100 $bars' $100 's$foo $$100 $bars$$foos$foos(skid.codewriters interpolatestestsstestsexpectsactualsAssertionError(steststestssactualsexpects interpolate((s6build/bdist.linux-i686/egg/kid/test/test_codewriter.pystest_interpolate_expr s ÿE  cCsWdkl}|dƒ}t|ƒdjpt‚t|dƒƒdjpt‚dS(N(s interpolatesfoo ${bar} bazs['foo ', bar, ' baz']s$foos[foo](skid.codewriters interpolatesexprsreprsAssertionError(sexprs interpolate((s6build/bdist.linux-i686/egg/kid/test/test_codewriter.pystest_interpolate_object's  cCspdkl}dkl}xO|D]G\}}t||iƒƒƒ}di |ƒ}||jpt ‚q!WdS(N(sblocks(s_adjust_python_blocks ( s test.blockssblocksskid.codewriters_adjust_python_blockstestsexpectslists splitlinessrsltsjoinsAssertionError(sblockss_adjust_python_blockstestsrsltsexpect((s6build/bdist.linux-i686/egg/kid/test/test_codewriter.pystest_adjust_block.s   cBs ddUedjpt‚dS(s Guido may break this some day...sx = 10Ni (sxsAssertionError(((s6build/bdist.linux-i686/egg/kid/test/test_codewriter.pystest_exec_hack6sN( s__doc__s __revision__s__date__s __author__s __copyright__s __license__stest_interpolate_exprstest_interpolate_objectstest_adjust_blockstest_exec_hack( s __copyright__s __revision__stest_interpolate_objects __license__stest_adjust_blockstest_interpolate_exprs __author__s__date__stest_exec_hack((s6build/bdist.linux-i686/egg/kid/test/test_codewriter.pys?s   PKÆ=ð6CNßÁÁkid/test/test_scope.pyc;ò [P›Fc@sgdZdZdZdZdklZdklZdk l Z dk Z d„Z d „Z d „ZdS( sUnit Tests for Python scope.s $Rev: 421 $s"David Stanek sCopyright 2005, David Stanek(sjoin(smkdtemp(srmtreeNcCs#tddƒatiitƒdS(Nsprefixskid_test_scope_(smkdtempstmpdirskidspathsinsert(smodule((s1build/bdist.linux-i686/egg/kid/test/test_scope.pys setup_module scCstiitƒttƒdS(N(skidspathsremovestmpdirsrmtree(smodule((s1build/bdist.linux-i686/egg/kid/test/test_scope.pysteardown_modulescCsUtttdƒdƒidƒtiddddƒiƒ}d|jpt‚dS( s§Test for scoping issue reported in ticket #101. Parameters passed into the Template constructor override the parameters of functions created with py:def. s scope.kidsws¢ sfilesbaris 0N( sopensjoinpathstmpdirswriteskidsTemplates serializesssAssertionError(ss((s1build/bdist.linux-i686/egg/kid/test/test_scope.pys test_scope_1s(s__doc__s __revision__s __author__s __copyright__sos.pathsjoinsjoinpathstempfilesmkdtempsshutilsrmtreeskids setup_modulesteardown_modules test_scope_1( s __copyright__s __revision__smkdtempsteardown_modules setup_modules test_scope_1s __author__srmtreeskidsjoinpath((s1build/bdist.linux-i686/egg/kid/test/test_scope.pys?s      PKÆ=ð6Ï\E¶zz(kid/test/test_serialization_escaping.pyc;ò [P›Fc@sÂdZdZdZdZdZdZdklZlZl Z eZ eZ e Z ddd d d fZ d d fZddfZd„Zed„Zd„Zd„Zd„Zd„Zd„ZdS(sTests exercising text escaping.s $Rev: 492 $s5$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $s"David Stanek sCopyright 2006, David Staneks8MIT (s XMLSerializersXHTMLSerializersHTMLSerializerss"s's&sstrsk„ses str<"&">strs k„se<'&'>k„seccsEx>tttfD]-}x$|i|ifD]}||fVq)WqWdS(s%Generator producing escape functions.N(sHTMLSerializers XMLSerializersXHTMLSerializers serializers escape_cdatas escape_attribsescape(s serializersescape((sBbuild/bdist.linux-i686/egg/kid/test/test_serialization_escaping.pysescape_functionss cCsBx;t|ƒD]-\}}|||ƒ||jpt‚q WdS(N(s enumerates test_charssxscharsfuncsencodings result_charssAssertionError(sfuncs test_charss result_charssencodingscharsx((sBbuild/bdist.linux-i686/egg/kid/test/test_serialization_escaping.pys do_escapes cCsÚhtidddddf<tidddddf<tidddddf<tidddddf<tidddddf<tidddddf<}x+tƒD] \}}t |t ||ƒq²WdS(Ns<s>s"s's&s"s<( sXMLs escape_cdatas escape_attribsXHTMLsHTMLsexpectedsescape_functionss serializersescapes do_escapes TEST_CHARS(sescapesexpecteds serializer((sBbuild/bdist.linux-i686/egg/kid/test/test_serialization_escaping.pys test_escapes¨ cCsYddf}ddf}x:tƒD]/\}}t|t|ƒt|t|dƒq"WdS(s1Test the encoding part of the escaping functions.sstrsk„ses k„sesutf-8N(sascii_expecteds utf8_expectedsescape_functionss serializersescapes do_escapes TEST_STRINGS(sascii_expecteds serializers utf8_expectedsescape((sBbuild/bdist.linux-i686/egg/kid/test/test_serialization_escaping.pystest_escape_encoding*s   cCs-htiddf<tiddf<tiddf<tiddf<tiddf<tiddf<}htiddf<tiddf<tiddf<tiddf<tiddf<tiddf<}xBtƒD]7\}}t |t ||ƒt |t ||d ƒqîWdS( Nsstr<"&">strsk„se<'&'>k„sesstr<"&">strsstr<"&">strsk„se<'&'>k„sesstr<"&"strs"1k„se<'&'>k„ses!k„se<'&'>k„sesutf-8( sXMLs escape_cdatas escape_attribsXHTMLsHTMLsascii_expecteds utf8_expectedsescape_functionss serializersescapes do_escapes TEST_COMBO(sascii_expecteds utf8_expectedsescapes serializer((sBbuild/bdist.linux-i686/egg/kid/test/test_serialization_escaping.pystest_escape_encoding_combo2s rr cCshxatƒD]V\}}y|dƒpt‚Wq tj o#}t|ƒdjpt‚q Xq WdS(Niscannot serialize 1 (type int)(sescape_functionss serializersescapesAssertionErrors TypeErrorsesstr(sesescapes serializer((sBbuild/bdist.linux-i686/egg/kid/test/test_serialization_escaping.pystest_escaping_intVs  cCsdx]tƒD]R\}}|ddƒdjpt‚|ddhdd<ƒdjpt‚q WdS(Ns sasciis sbingo(sescape_functionss serializersescapesAssertionError(s serializersescape((sBbuild/bdist.linux-i686/egg/kid/test/test_serialization_escaping.pystest_escaping_nbsp]s N(s__doc__s __revision__s__date__s __author__s __copyright__s __license__skid.serializations XMLSerializersXHTMLSerializersHTMLSerializersXMLsXHTMLsHTMLs TEST_CHARSs TEST_STRINGSs TEST_COMBOsescape_functionssNones do_escapes test_escapestest_escape_encodingstest_escape_encoding_combostest_escaping_intstest_escaping_nbsp(sXHTMLSerializers TEST_COMBOstest_escaping_ints XMLSerializers do_escapes TEST_CHARSs __revision__sHTMLSerializersHTMLstest_escape_encoding_combosescape_functionssXMLs __license__s test_escapes __author__stest_escape_encodingsXHTMLstest_escaping_nbsps __copyright__s TEST_STRINGSs__date__((sBbuild/bdist.linux-i686/egg/kid/test/test_serialization_escaping.pys?s&      $ PKÆ=ð6A)&úbBbBkid/test/test_error.pyc;ò ZP›Fc@súdZdZdZdZdkZdklZdkl Z dk l Z dk Z dk lZeid d d fjZd „Zd „Zd fd„ƒYZd„Zd„Zd„Zd„Zd„Zd„Zd„Zd„Zd„Zd„ZdS(sUnit Tests for error reporting.s $Rev: 496 $s$Christoph Zwerschke s#Copyright 2006, Christoph ZwerschkeN(sjoin(smkdtemp(srmtree(sraisesiicCs#tddƒatiitƒdS(Nsprefixskid_test_error_(smkdtempstmpdirskidspathsinsert(smodule((s1build/bdist.linux-i686/egg/kid/test/test_error.pys setup_modulescCstiitƒttƒdS(N(skidspathsremovestmpdirsrmtree(smodule((s1build/bdist.linux-i686/egg/kid/test/test_error.pysteardown_moduless KidFileWritercBs5tZdZd„Zd„Zed„Zd„ZRS(NicCstid7_d|_dS(Nii(s KidFileWriters test_numbersselfs file_number(sself((s1build/bdist.linux-i686/egg/kid/test/test_error.pys__init__scCsd|i|ifSdS(Nstest_error_%d_%d(sselfs test_numbers file_number(sself((s1build/bdist.linux-i686/egg/kid/test/test_error.pysname"scCs2d|iƒ}|ott|ƒ}n|SdS(Ns%s.kid(sselfsnamesfilenamesfullsjoinpathstmpdir(sselfsfullsfilename((s1build/bdist.linux-i686/egg/kid/test/test_error.pysfilename$scCs2|id7_t|itƒdƒi|ƒdS(Nisw(sselfs file_numbersopensfilenamesTrueswritesxml(sselfsxml((s1build/bdist.linux-i686/egg/kid/test/test_error.pyswrite)s(s__name__s __module__s test_numbers__init__snamesFalsesfilenameswrite(((s1build/bdist.linux-i686/egg/kid/test/test_error.pys KidFileWriters    cCsédkl}d}ti|ƒ|iddƒ}tt|tid|ƒƒ}d|jpt ‚d|jpt ‚|i ƒd|jpt ‚d d |jpt ‚d |jpt ‚d |jpt ‚d |jpt ‚d}tid|ddƒ}dkl}d}tid|d|ƒ}tt||i ƒƒ}d|jpt ‚d|jpt ‚|i ƒd|jpt ‚dd |jpt ‚d |jpt ‚d|jpt ‚d|jpt ‚dS(s%Check that erroneous XML is reported.(s ExpatErrors~

title

oops

That's all, folks.

ssssourcesError parsing XMLs!mismatched tag: line 3, column 24is %25s s^shtmlstitlesfolkssr

title

sxmls

ok

s@

start

this &is wrong

end

s2not well-formed (invalid token): line 2, column 16is %17s sstartsendN(sxml.parsers.expats ExpatErrorspageskidsTemplatesreplacesstrsraisessesAssertionErrors splitlinesstscontents serialize(sestscontentspages ExpatError((s1build/bdist.linux-i686/egg/kid/test/test_error.pystest_xml_error-s4   cCsÀdkl}ddd}tt|ti|ƒƒ}d|jpt‚d|jpt‚ddd|jpt‚d d |jpt‚d ddd }tt|ti|ƒƒ}d|jpt‚d |jpt‚dddd |jpt‚dd |jpt‚d ddd dd}tt|ti|ƒƒ}d|jpt‚d |jpt‚dddd dd|jpt‚dd |jpt‚dS(s5Check intelligent truncating of long XML error lines.(s ExpatErrorsxi'sxsError parsing XMLs mismatched tag: line 1, column 6s xiDs %7s s^sss$mismatched tag: line 1, column 10004s iHs %75s i$s %39s N( sxml.parsers.expats ExpatErrorspagesstrsraisesskidsTemplatesesAssertionError(sespages ExpatError((s1build/bdist.linux-i686/egg/kid/test/test_error.pystest_xml_long_lineTs(  (cCsÚtƒ}|idƒtid|iƒƒ}|idƒdkl}t t |tid|iƒƒƒ}d|jpt ‚|iƒ|jpt ‚d|jpt ‚d|jpt ‚d|jpt ‚dS( s.Check that erroneous XML filename is reported.sThis is XMLsfilesThis is not XML(s ExpatErrorsError parsing XMLssyntax error: line 1, column 0s ^ N( s KidFileWritersfswriteskidsTemplatesfilenamestsxml.parsers.expats ExpatErrorsstrsraisessesAssertionError(sesfsts ExpatError((s1build/bdist.linux-i686/egg/kid/test/test_error.pystest_xml_filename_errorjs    $cCs}d}tid|ƒ}dkl}tt||iƒƒ}d|jpt ‚d|jpt ‚d|jpt ‚dS(s8Check that erroneous py:layout expressions are reported.sAssource(sTemplateLayoutErrors not definedswhile processing layout=s no_layoutN( spageskidsTemplatestskid.template_utilsTemplateLayoutErrorsstrsraisess serializesesAssertionError(sesTemplateLayoutErrorstspage((s1build/bdist.linux-i686/egg/kid/test/test_error.pystest_layout_errorxs cCsqd}dkl}tt|tid|ƒƒ}d|jpt‚d|jpt‚d|jpt‚dS(s9Check that erroneous py:extends expressions are reported.sC(sTemplateExtendsErrorssources not definedswhile processing extends=s no_extendsN( spageskid.template_utilsTemplateExtendsErrorsstrsraisesskidsTemplatesesAssertionError(sTemplateExtendsErrorsespage((s1build/bdist.linux-i686/egg/kid/test/test_error.pystest_extends_error„s cCs³d}tid|dƒ}|iƒ}d|jo d|jpt‚dkl}tid|dƒ}t t ||iƒƒ}d|jpt‚d |jpt‚d|jpt‚tid|d ƒ}|iƒ}d |jpt‚tid|d ƒ}t t ||iƒƒ}d |jpt‚d |jpt‚tid|d ƒ}t t ||iƒƒ}d|jpt‚d|jo d|jpt‚dS(s7Check that erroneous py:attrs expressions are reported.sa

ssourcesabc=123, def=789s abc="123"s def="789"(sTemplateAttrsErrorsabc=123, 456=789sinvalidswhile processing attrs=s{'mickey':'mouse'}smickey="mouse"s mickey mouses{mickey:mouse}s not definedsmickeysmouseN( spageskidsTemplatests serializesssAssertionErrorskid.template_utilsTemplateAttrsErrorsstrsraisesse(sesTemplateAttrsErrorssstspage((s1build/bdist.linux-i686/egg/kid/test/test_error.pystest_attr_errorŽs, !  c Cs0dkl}tƒ}d}x™|titifD]‚}|i |ƒt t t |d|i ||jƒƒƒ}d|iƒ|jpt‚d|jo d|jpt‚d|jod|jo d |jpt‚d |jpt‚toZd |jpt‚|i ƒ|jpt‚d |jpt‚d |jpt‚nd|jo d|jpt‚d|jod|jo d|jpt‚d|jpt‚q2Wd}xk|titifD]T}|i |ƒt t t |d|i ||jƒƒƒ}d|iƒ|jpt‚d|jo d|jpt‚d|jpt‚d|jod|jo d |jpt‚toZd |jpt‚|i ƒ|jpt‚d|jpt‚d|jpt‚nd|jo d|jpt‚d|jpt‚qÔWdS(s3Check error tracking when compiling a Kid template.(s compile_files compilation fails the expression ${1/0} can be compiled the expression ${1//0} can be compiled the expression ${1///0} cannot be compiled the expression ${1+1} can be compiled sfilesinvalid syntax (%s.py, line s 1///0s ^ s1/0s1//0s1+1scan be compileds Error location in template file s#on line 5 between columns 8 and 54:s*the expression ${1///0} cannot be compiledsxml>stitle>sp1>sp2>sp4>scompilation failssb compilation fails s oops = 1///0s ^ sok =s0between line 10, column 8 and line 13, column 8:s oops = 1///0N(s kid.compilers compile_files KidFileWritersfsxmlskids load_templatesTemplatescallswritesstrsraisess SyntaxErrorsfilenamesesnamesAssertionErrorspython24(sxmlsesfscalls compile_file((s1build/bdist.linux-i686/egg/kid/test/test_error.pystest_tracking_1©sL    !!.!.  !!.!cCsqdkl}tƒ}d}|i|ƒy|d|itƒƒ}Wnt j o t }nX|tjp t d‚xòt i t ifD]Þ}|i|ƒttt|d|iƒƒƒ}d|jpt ‚toZd|jpt ‚|iƒ|jpt ‚d|jpt ‚d|jpt ‚nd |jo d |jpt ‚d |jpt ‚q‹Wd S( s3Check error tracking when importing a Kid template.(s compile_files¢ import fails sfiles&This file cannot be compiled properly.s"integer division or modulo by zeros Error location in template file s.between line 4, column 8 and line 5, column 8:ssxml>stitle>s import failsN(s kid.compilers compile_files KidFileWritersfsxmlswritesfilenamesTrueses ExceptionsNonesAssertionErrorskids load_templatesTemplatescallsstrsraisessZeroDivisionErrorspython24(sxmlsesfs compile_filescall((s1build/bdist.linux-i686/egg/kid/test/test_error.pystest_tracking_2çs,     !!cCsatƒ}d}|i|ƒtid|iƒƒ}d„}xæt dƒD]Ø}t t t |||ƒƒ}d|jpt‚to |djoZd|jpt‚|iƒ|jpt‚d|jpt‚d |jpt‚nd |jo d |jpt‚d |jpt‚qJWd }|i|ƒtid|iƒƒ}t t t |iƒƒ}d|jpt‚tond|jpt‚|iƒ|jpt‚d|jpt‚d|jpt‚d|jpt‚nd |jo d |jpt‚d |jpt‚d}|i|ƒtid|iƒƒ}t t t |iƒƒ}d|jpt‚toZd|jpt‚|iƒ|jpt‚d|jpt‚d|jpt‚nd|jpt‚d |jo d |jpt‚d|jo d|jpt‚d|jpt‚d |jpt‚dS(s3Check error tracking when executing a Kid template.s® execution fails the expression ${1/2} can be evaluated the expression ${1/0} cannot be evaluated sfilecCsƒ|djo?dk}|iƒ}|id|ƒ|iƒ}|iƒn0|djot|i ƒƒ}n |i ƒ}|SdS(Nisfilei( snsStringIOsoutputstswritesgetvaluesretscloseslistsgenerates serialize(stsnsStringIOsretsoutput((s1build/bdist.linux-i686/egg/kid/test/test_error.pysexecute_template_methods      is"integer division or modulo by zerois Error location in template file s#on line 4 between columns 8 and 53:s)the expression ${1/0} cannot be evaluatedsxml>stitle>sexecution failssw execution fails s.between line 4, column 8 and line 5, column 8:s execution fails

test1

test2

s/between line 4, column 22 and line 5, column 8:s py:content="1/0"s"1/2"sp1>sh1>sh2>N(s KidFileWritersfsxmlswriteskidsTemplatesfilenamestsexecute_template_methodsrangesnsstrsraisessZeroDivisionErrorsesAssertionErrorspython24s serialize(sxmlsesfsnstsexecute_template_method((s1build/bdist.linux-i686/egg/kid/test/test_error.pystest_tracking_3sZ   ! ! !!cCs.dkl}tƒ}d}|i|ƒtid|iƒƒ}t t |i ƒ}|iit ijpt‚|iit ijpt‚t|dƒo |idjpt‚t|ƒ}d|jpt‚d|jpt‚d|jpt‚|iƒ|jpt‚d|jpt‚d S( s3Check error tracking when compiling a Kid template.(s compile_files  execution fails test
sfilesreasonsordinal not in range(128)s$can't decode byte 0xe4 in position 1s, Error in code generated from template file sexecution failsN(s kid.compilers compile_files KidFileWritersfsxmlswriteskidsTemplatesfilenamestsraisessUnicodeDecodeErrors serializeses __class__s__name__sAssertionErrors __module__shasattrsreasonsstr(sxmlsesfs compile_filest((s1build/bdist.linux-i686/egg/kid/test/test_error.pystest_tracking_4Is    ' (s__doc__s __revision__s __author__s __copyright__ssyssos.pathsjoinsjoinpathstempfilesmkdtempsshutilsrmtreeskids kid.test.utilsraisess version_infospython24s setup_modulesteardown_modules KidFileWriterstest_xml_errorstest_xml_long_linestest_xml_filename_errorstest_layout_errorstest_extends_errorstest_attr_errorstest_tracking_1stest_tracking_2stest_tracking_3stest_tracking_4(stest_xml_filename_errorsmkdtempsraisess __revision__spython24sjoinpathstest_layout_errors KidFileWriterstest_extends_errorsteardown_modules setup_modules __author__ssyssrmtreestest_xml_errorskidstest_tracking_2stest_tracking_3s __copyright__stest_tracking_1stest_tracking_4stest_xml_long_linestest_attr_error((s1build/bdist.linux-i686/egg/kid/test/test_error.pys?s.         '    >  EPKÆ=ð6œtÖA88kid/test/util.pyc;ò [P›Fc@sÌdZdZdZdZdZdZdkZdkZdkZydk l Z Wn e j odk l Z nXdk Z dfd „ƒYZd „Zd „Zd „Zd „Zd„Zed„ZdS(sUtility stuff for tests.s $Rev: 492 $s5$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $s!Ryan Tomayko (rtomayko@gmail.com)s!Copyright 2004-2005, Ryan Tomaykos8MIT N(sStringIOsstdoldcBs tZdZeiZeiZRS(s#Original sys.stderr and sys.stdout.(s__name__s __module__s__doc__ssyssstdoutsoutsstderrserr(((s+build/bdist.linux-i686/egg/kid/test/util.pysstdolds  c Nsç|pt‚e|deƒo–|\}e|eƒpt‚eidƒ} | ii ƒ}|i |ƒy|| i |UWn-|j o }|Sq¬ej o }q¬Xe}nõ|d|df\}}e|ƒpt‚y|||ŽWn-|j o }|Snej o }nXe}gi}|D]}|d|ƒq;~}|igi}|iƒD]}|d|ƒqr~ƒd|idi|ƒf}|od|i}nd}ed |||fƒ‚d S( s?Raise AssertionError if code does not raise expected exception.iis%rs%s=%rs%s(%s)s, sraised %s instead ofs did not raises%s %s %sN(sargssAssertionErrors isinstancesstrsexprssyss _getframesframesf_localsscopyslocsupdateskwargss f_globalssExpectedExceptionses ExceptionsNonesfuncscallablesappends_[1]sxsextendsitemss__name__sjoins __class__( sExpectedExceptionsargsskwargsslocsesfuncsexprs_[1]sxsframe((s+build/bdist.linux-i686/egg/kid/test/util.pysraisess>   +8cCstiidƒdS(Ns.(sstdoldserrswrite(((s+build/bdist.linux-i686/egg/kid/test/util.pysdot?scCstiidƒdS(Nss(sstdoldserrswrite(((s+build/bdist.linux-i686/egg/kid/test/util.pysskipBscCsGt|ƒ}|idƒ}x!|dD]}t||ƒ}q&W|SdS(Ns.i(s __import__snamesmodssplits componentsscompsgetattr(snames componentsscompsmod((s+build/bdist.linux-i686/egg/kid/test/util.pys come_on_guido_this_is_just_wrongEs   cCsgg}xVt|ƒD]H}|d djo1t||ƒ}t|ƒo|i|ƒq[qqW|SdS(s<Return a list of test functions for the given module object.istestN(sfuncssdirsmodsnamesgetattrsattrscallablesappend(smodsfuncssattrsname((s+build/bdist.linux-i686/egg/kid/test/util.pys get_funcsLs  cCsKytitiiƒWn@tj o4tiƒd}t |i ƒdjo‚qZnXg}dti_ d}} }dkl}|ƒ}x\|D]T}yt|ƒ}WnCtj o7}dt|ƒjo‚n| d7} tƒq—nXt|dƒo|i|ƒnz²xt|ƒD]} |d7}tƒtƒf\t_t_y | ƒWn<|d7}ttiƒdt ƒ} | odpd}tƒ} t$i%d | ƒt&i'i(|ƒ|i)| |tiƒtii*ƒtii*ƒffƒ|o—t&i,t&i'f\t_t_tii(d |ƒ|d d \}}|otii(d |i-ƒƒn|otii(d|i-ƒƒn‚q£q$Xt.ƒq$Wt&i,t&i'f\t_t_Wdt|dƒo|i/|ƒnXq—W|ƒ}tii(dƒx×|D]Ï\} }} \}}tii(dhdd<ddsCopyright 2005, David StanekN(sjoin(smkdtemp(srmtreescopyfile(sraisescCsHtddƒatiitƒttdƒattdƒidƒdS(Nsprefixskid_test_suffixes_stest_suffixes0.kidsws~

my content

( smkdtempstmpdirskidspathsinsertsjoinpathstfilesopenswrite(smodule((s4build/bdist.linux-i686/egg/kid/test/test_suffixes.pys setup_modules cCstiitƒttƒdS(N(skidspathsremovestmpdirsrmtree(smodule((s4build/bdist.linux-i686/egg/kid/test/test_suffixes.pysteardown_modulescCsptiidtƒzEtiƒttdƒtiƒdk }ttdƒtiƒWdtii tƒXdS(s$By default *.kid files are imported.isimport test_suffixes0Nsimport test_suffixes1( ssysspathsinsertstmpdirskidsdisable_importsraisess ImportErrors enable_importstest_suffixes0sremove(stest_suffixes0((s4build/bdist.linux-i686/egg/kid/test/test_suffixes.pystest_enable_import_empty s     cCsd}tiidtƒzÝttdƒttdƒttdƒtid|ƒt tdƒ}t t |ƒdk }t td ƒ}t t |ƒdk}t td ƒ}t t |ƒdk}t td ƒ}t t |ƒttd ƒtiƒWdtiitƒXdS( s0Using exts any file extension can be importable.s.html,.kid.htmlisimport test_suffixes1simport test_suffixes2simport test_suffixes3sextstest_suffixes1.kidNstest_suffixes2.htmlstest_suffixes3.kid.htmlstest_suffixes4.xhtmlsimport test_suffixes4(sextssysspathsinsertstmpdirsraisess ImportErrorskids enable_importsjoinpathsdestscopyfilestfilestest_suffixes1stest_suffixes2stest_suffixes3sdisable_importsremove(stest_suffixes1stest_suffixes3sdestsextstest_suffixes2((s4build/bdist.linux-i686/egg/kid/test/test_suffixes.pystest_enable_import_with_ext-s.           cCs–ttijpt‚ttdƒtidtƒttdƒ}t t |ƒdk }ti dtƒttdƒ}t t |ƒttdƒdS(s4Using path any template directory can be importable.simport test_suffixes4spathstest_suffixes4.kidNstest_suffixes5.kidsimport test_suffixes5(stmpdirssysspathsAssertionErrorsraisess ImportErrorskids enable_importsjoinpathsdestscopyfilestfilestest_suffixes4sdisable_import(stest_suffixes4sdest((s4build/bdist.linux-i686/egg/kid/test/test_suffixes.pystest_enable_import_with_pathFs    (s__doc__s __revision__s __author__s __copyright__ssyssos.pathsjoinsjoinpathstempfilesmkdtempsshutilsrmtreescopyfileskids kid.test.utilsraisess setup_modulesteardown_modulestest_enable_import_emptystest_enable_import_with_extstest_enable_import_with_path(scopyfiles __copyright__s __revision__smkdtempstest_enable_import_with_extsteardown_modules setup_modules __author__ssysstest_enable_import_with_pathsraisessjoinpathstest_enable_import_emptyskidsrmtree((s4build/bdist.linux-i686/egg/kid/test/test_suffixes.pys?s       PKÆ=ð6®SXݳ³kid/test/test_templatepath.pyc;ò [P›Fc@s¡dZdklZdklZlZdklZdk l Z dk Z e i i Zd„Zd„Zd„Zd „Zd „Zd „Zd „Zd „ZdS(s.Unit tests for the kid.TemplatePath class. The testing directory structure looks something like this: tmpdir1/ /index.kid /members/ /index.kid /stuff.kid /master.kid /nonmembers/ /index.kid /garbage.kid /master.kid /shared/ /message.kid /error.kid /errors/ /error1.kid /error2.kid /error3.kid tmpdir2/ /index.kid /indexz.kid /master.kid /members/ /master.kid /stuff.kid tmpdir3/ /test.kid /base.kid (smkdir(sjoinsnormpath(smkdtemp(srmtreeNcCsÖd„}tddƒa|ttdƒ|tddƒ|tddƒ||td d ƒd d ƒtdd ƒa|ttdƒ|tddƒtiitƒtiitƒtddƒa|ttdƒdS(s%Create a testing directory structure.cCsh|ot||ƒ}t|ƒn|}x3|iƒD]%}tt||ƒdƒidƒq7W|SdS(s Create files.swsnothingN( ssubdirsjoinpathsdirsmkdirsfilesssplitsfilesopenswrite(sdirssubdirsfilessfile((s8build/bdist.linux-i686/egg/kid/test/test_templatepath.pys_create/s #sprefixskid_test_templatepath1_s index.kidsmemberssindex.kid stuff.kid master.kids nonmemberss index.kid garbage.kid master.kidssharedsmessage.kid error.kidserrorss error1.kid error2.kid error3.kidskid_test_templatepath2_sindex.kid indexz.kid master.kidsstuff.kid master.kidskid_test_templatepath3_stest.kid base.kidN( s_createsmkdtempstmpdir1sNonestmpdir2skidspathsappendstmpdir3(smodules_create((s8build/bdist.linux-i686/egg/kid/test/test_templatepath.pys setup_module+s   cCsBtiitƒtiitƒttƒttƒttƒdS(N(skidspathsremovestmpdir1stmpdir2srmtreestmpdir3(smodule((s8build/bdist.linux-i686/egg/kid/test/test_templatepath.pysteardown_moduleJs   cCsVtdƒtttdƒƒjpt‚tdƒtttdƒƒjpt‚dS(Ns index.kids indexz.kid(skfindsnormpathsjoinpathstmpdir1sAssertionErrorstmpdir2(((s8build/bdist.linux-i686/egg/kid/test/test_templatepath.pystest_simple_file_in_rootQs)cCstttddƒƒtttddƒƒjpt‚tdddƒ}t|ƒttt|ƒƒjpt‚dS(Nsmemberss index.kidssharedserrorss error1.kid(skfindsjoinpathsnormpathstmpdir1sAssertionErrorspath(spath((s8build/bdist.linux-i686/egg/kid/test/test_templatepath.pystest_file_in_directoryUs5cCstdƒtjpt‚dS(Ns noexist.kid(skfindsNonesAssertionError(((s8build/bdist.linux-i686/egg/kid/test/test_templatepath.pys test_no_exist[scCsTtttddƒƒ}tttddƒƒ}tdd|ƒ|jpt‚dS(Nsshareds error.kids message.kidsrel(snormpathsjoinpathstmpdir1srelsexpectedskfindsAssertionError(srelsexpected((s8build/bdist.linux-i686/egg/kid/test/test_templatepath.pystest_find_relative^scCsQtttddƒƒ}tttdƒƒ}tdd|ƒ|jpt‚dS(Ns nonmemberss stuff.kids master.kidsrel(snormpathsjoinpathstmpdir1srelstmpdir2sexpectedskfindsAssertionError(srelsexpected((s8build/bdist.linux-i686/egg/kid/test/test_templatepath.pystest_crawl_pathcscCs6tddttdƒƒttdƒjpt‚dS(s3This recreates the problem reported in ticket #110.sbase.kidsrelstest.kidN(skfindsjoinpathstmpdir3sAssertionError(((s8build/bdist.linux-i686/egg/kid/test/test_templatepath.pystest_mod_python_bughs(s__doc__sossmkdirsos.pathsjoinsjoinpathsnormpathstempfilesmkdtempsshutilsrmtreeskidspathsfindskfinds setup_modulesteardown_modulestest_simple_file_in_rootstest_file_in_directorys test_no_existstest_find_relativestest_crawl_pathstest_mod_python_bug(stest_mod_python_bugstest_find_relativesmkdtemps test_no_existsteardown_modules setup_modulestest_file_in_directorysmkdirsjoinpathsnormpathstest_crawl_pathstest_simple_file_in_rootsrmtreeskfindskid((s8build/bdist.linux-i686/egg/kid/test/test_templatepath.pys?!s            PKÆ=ð6[ð|ã88kid/test/test_unicode.pyc;ò [P›Fc@s5dZdklZdZeidƒZd„ZdS(s Unicode tests(s to_unicodes†©—sutf-8cCstttdƒtjpt‚ttdƒtjpt‚dtfd„ƒY}t|ƒdƒtjpt‚dS(Nsutf-8sCcBstZd„ZRS(NcCstSdS(N(sustr(sself((s3build/bdist.linux-i686/egg/kid/test/test_unicode.pys __unicode__ s(s__name__s __module__s __unicode__(((s3build/bdist.linux-i686/egg/kid/test/test_unicode.pysC s(s to_unicodesustrsAssertionErrorsastrsobjectsC(sC((s3build/bdist.linux-i686/egg/kid/test/test_unicode.pystest_to_unicodesN(s__doc__s kid.parsers to_unicodesastrsdecodesustrstest_to_unicode(sastrs to_unicodesustrstest_to_unicode((s3build/bdist.linux-i686/egg/kid/test/test_unicode.pys?s PKÆ=ð6¯ÄZäó"ó"kid/test/test_element.pyc;ò ZP›Fc@sËdZdZdZdZdZdZdkZdklZl Z l Z l Z l Z l Z lZlZd„Zd „Zd „Zd „Zd „Zd „Zd„Zd„Zd„Zd„Zd„ZdS(skid.element testss $Rev: 492 $s5$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $s"David Stanek sCopyright 2006, David Staneks8MIT N(sElements SubElementsCommentsProcessingInstructionsFragmentsQNames namespacess encode_entitycCs!tdƒ}|idjpt‚|iGH|ihjpt‚|itjpt‚|itjpt‚tdtddddƒƒ}|idjpt‚|ihdd<dd$(sElementselementsresmatchsNonesAssertionError(smatchselement((s3build/bdist.linux-i686/egg/kid/test/test_element.pystest_element_repr,s cCstdƒ}|itdƒƒ|itdƒƒ|itdƒƒ|itdƒƒt|ƒdjpt‚|didjpt‚|didjpt‚td ƒ|d<|did jpt‚|d=t|ƒdjpt‚|d \}}|idjpt‚|idjpt‚td ƒtd ƒf|d *|did jpt‚|d id jpt‚|d 4t|ƒd jpt‚|diGH|didjpt‚|idtdƒƒ|idtdƒƒ|didjpt‚|d idjpt‚t|ƒdjpt‚|d}|i |ƒt|ƒd jpt‚|i ƒ}t|ƒd jpt‚|didjpt‚|d idjpt‚|i ƒ|idjpt‚t|ƒdjpt‚dS(Nsparentschild0schild1schild2schild3iiischild4isfirstonesfirsttwoisinsert1sinsert0iÿÿÿÿ(sElementsparentsappendslensAssertionErrorstagschild0schild1sinsertschildsremoves getchildrenschildrensclear(schild0schild1sparentschildschildren((s3build/bdist.linux-i686/egg/kid/test/test_element.pystest_element_children2sJ      cCs‰tdtddddƒddƒ}|idƒtjpt‚|idd ƒd jpt‚|idƒdjpt‚|idd ƒdjpt‚|iddƒ|idƒdjpt‚|iƒ}t|ƒd jpt‚x+dddgD]}||jpt‚qW|i ƒ}t|ƒd jpt‚x=ddfddfddfgD]}||jpt‚qgWdS( Nstestsaisbiscisdsi( sElementsdictselementsgetsNonesAssertionErrorssetskeysslensksitemssi(skeyssitemssksiselement((s3build/bdist.linux-i686/egg/kid/test/test_element.pystest_element_attributescs"$    "cCs—tdƒ}t|dƒ}|didjpt‚|dihjpt‚|ditjpt‚|di tjpt‚t|dt ddddƒƒ}|didjpt‚|dihdd<ddtdƒdjpt‚d}tdƒ|jpt‚dS(s%TODO: do a more complete set of testssmy texts1 is > 0 && 2 < 3s1 is > 0 && 2 < 3N(s encode_entitysAssertionErrorsexpected(sexpected((s3build/bdist.linux-i686/egg/kid/test/test_element.pystest_encode_entityÎs(s__doc__s __revision__s__date__s __author__s __copyright__s __license__sres kid.elementsElements SubElementsCommentsProcessingInstructionsFragmentsQNames namespacess encode_entitystest_element_initstest_element_reprstest_element_childrenstest_element_attributesstest_subelements test_commentstest_processing_instructions test_fragments test_qnamestest_namespacesstest_encode_entity(s encode_entitystest_element_attributess test_commentstest_element_reprs __revision__stest_element_childrensFragmentstest_encode_entitysres __license__stest_processing_instructionstest_subelements __author__s test_fragments namespacesstest_namespacessElementsComments __copyright__stest_element_initsProcessingInstructions test_qnamesQNames__date__s SubElement((s3build/bdist.linux-i686/egg/kid/test/test_element.pys?s$ 7   1       PKÆ=ð6!A  kid/test/test_options.pyc;ò ZP›Fc@sbdZdZdZdZdZdZdkZdkl Z d„Z d „Z d „Z d „Z dS( sKid properties tests.s $Rev: 492 $s5$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $s"David Stanek sCopyright 2006, David Staneks8MIT N(sraisescCs)tddddƒ}tii|ƒ}|idƒdjpt‚|idƒdjpt‚tii|ddƒ}|idƒdjpt‚|idƒdjpt‚|idƒdjpt‚tiiddddƒ}|idƒdjpt‚|idƒdjpt‚dS(Nsencodingsutf-8soutputshtmlsstuffi(sdictsoptsskidsoptionssOptionssgetsAssertionError(soptionssopts((s3build/bdist.linux-i686/egg/kid/test/test_options.pys test_initscCsítiiƒ}|iddƒ|iddƒ|idƒdjpt‚|idƒdjpt‚|iddƒdjpt‚tƒ}|id|ƒ|jpt‚|idƒ|idƒ|idƒt jpt‚dS(Nsencodingsutf-8soutputshtmls not therei( skidsoptionssOptionsssetsgetsAssertionErrorsobjectsosremovesNone(soptionsso((s3build/bdist.linux-i686/egg/kid/test/test_options.pystest_setters_getters0s     cs³tiiƒ‰dˆds(s__doc__s __revision__s__date__s __author__s __copyright__s __license__s kid.optionsskids kid.test.utilsraisess test_initstest_setters_getters0stest_setters_getters1s test_isset( s __copyright__s __revision__s __license__s test_issetstest_setters_getters1stest_setters_getters0s __author__s__date__sraisess test_initskid((s3build/bdist.linux-i686/egg/kid/test/test_options.pys?s     PKÆ=ð6¯SuWDD!kid/test/test_extended_layout.pyc;ò [P›Fc@sgdZdZdZdZdklZdklZdk l Z dk Z d„Z d „Z d „ZdS( s Unit Tests for Extended Layouts.s $Rev: 455 $s$Christoph Zwerschke s#Copyright 2006, Christoph Zwerschke(sjoin(smkdtemp(srmtreeNcCs#tddƒatiitƒdS(Nsprefixskid_test_extended_layout_(smkdtempstmpdirskidspathsinsert(smodule((s;build/bdist.linux-i686/egg/kid/test/test_extended_layout.pys setup_module scCstiitƒttƒdS(N(skidspathsremovestmpdirsrmtree(smodule((s;build/bdist.linux-i686/egg/kid/test/test_extended_layout.pysteardown_modulescCs­tttdƒdƒidƒtiddƒ}|iddƒ}d|jpt ‚d|jpt ‚d |jpt ‚d |jpt ‚d |jpt ‚d |jpt ‚tttd ƒdƒidƒtidd ƒ}|iddƒ}d|jpt ‚d|jpt ‚d|jpt ‚d|jpt ‚d|jpt ‚d|jpt ‚d|jpt ‚d|jpt ‚d|jpt ‚tttdƒdƒidƒtiddƒ}|iddƒ}d|jpt ‚d|jpt ‚d|jpt ‚d|jpt ‚d|jpt ‚d|jpt ‚d|jpt ‚d|jpt ‚d|jpt ‚dS(s2Test layout template extended by another template.s master.kidswsÈ

Master Title

sfilesoutputsxhtmls+ssheads master.jssbodysTitles section.kidsF Section Title

Section Title

Section content
ssSection Titles