code
stringlengths
501
5.19M
package
stringlengths
2
81
path
stringlengths
9
304
filename
stringlengths
4
145
import re from . import stdom def indention(str, front=re.compile(r"^\s+").match): """Find the number of leading spaces. If none, return 0. """ result = front(str) if result is not None: start, end = result.span() return end - start else: return 0 # no leading spaces def insert(struct, top, level): """Find what will be the parant paragraph of a sentence and return that paragraph's sub-paragraphs. The new paragraph will be appended to those sub-paragraphs """ if top - 1 not in range(len(struct)): if struct: return struct[len(struct) - 1].getSubparagraphs() return struct run = struct[top - 1] i = 0 while i + 1 < level: run = run.getSubparagraphs()[len(run.getSubparagraphs()) - 1] i = i + 1 return run.getSubparagraphs() def display(struct): """Runs through the structure and prints out the paragraphs. If the insertion works correctly, display's results should mimic the orignal paragraphs. """ if struct.getColorizableTexts(): print('\n'.join(struct.getColorizableTexts())) if struct.getSubparagraphs(): for x in struct.getSubparagraphs(): display(x) def display2(struct): """Runs through the structure and prints out the paragraphs. If the insertion works correctly, display's results should mimic the orignal paragraphs. """ if struct.getNodeValue(): print(struct.getNodeValue(), "\n") if struct.getSubparagraphs(): for x in struct.getSubparagraphs(): display(x) def findlevel(levels, indent): """Remove all level information of levels with a greater level of indentation. Then return which level should insert this paragraph """ keys = list(levels.keys()) for key in keys: if levels[key] > indent: del levels[key] keys = levels.keys() if not keys: return 0 else: for key in keys: if levels[key] == indent: return key highest = 0 for key in keys: if key > highest: highest = key return highest - 1 def flatten(obj, append): if obj.getNodeType() == stdom.TEXT_NODE: append(obj.getNodeValue()) else: for child in obj.getChildNodes(): flatten(child, append) para_delim = r'(\n\s*\n|\r\n\s*\r\n)' # UNIX or DOS line endings, respectively def structurize(paragraphs, delimiter=re.compile(para_delim)): """Accepts paragraphs, which is a list of lines to be parsed. structurize creates a structure which mimics the structure of the paragraphs. Structure => [paragraph,[sub-paragraphs]] """ currentlevel = 0 currentindent = 0 levels = {0: 0} level = 0 # which header are we under struct = [] # the structure to be returned run = struct paragraphs = paragraphs.expandtabs() paragraphs = '{}{}{}'.format('\n\n', paragraphs, '\n\n') paragraphs = delimiter.split(paragraphs) paragraphs = [x for x in paragraphs if x.strip()] if not paragraphs: return StructuredTextDocument() ind = [] # structure based on indention levels for paragraph in paragraphs: ind.append([indention(paragraph), paragraph]) currentindent = indention(paragraphs[0]) levels[0] = currentindent for indent, paragraph in ind: if indent == 0: level = level + 1 currentlevel = 0 currentindent = 0 levels = {0: 0} struct.append(StructuredTextParagraph(paragraph, indent=indent, level=currentlevel)) elif indent > currentindent: currentlevel = currentlevel + 1 currentindent = indent levels[currentlevel] = indent run = insert(struct, level, currentlevel) run.append(StructuredTextParagraph(paragraph, indent=indent, level=currentlevel)) elif indent < currentindent: result = findlevel(levels, indent) if result > 0: currentlevel = result currentindent = indent if not level: # pragma: no cover Can we ever even get here? struct.append(StructuredTextParagraph(paragraph, indent=indent, level=currentlevel)) else: run = insert(struct, level, currentlevel) run.append(StructuredTextParagraph(paragraph, indent=indent, level=currentlevel)) else: if insert(struct, level, currentlevel): run = insert(struct, level, currentlevel) else: run = struct currentindent = indent run.append(StructuredTextParagraph(paragraph, indent=indent, level=currentlevel)) return StructuredTextDocument(struct) class StructuredTextParagraph(stdom.Element): indent = 0 def __init__(self, src, subs=None, **kw): if subs is None: subs = [] self._src = src self._subs = list(subs) self._attributes = kw.keys() for k, v in kw.items(): setattr(self, k, v) def getChildren(self): src = self._src if not isinstance(src, list): src = [src] return src + self._subs def getSubparagraphs(self): return self._subs def setSubparagraphs(self, subs): self._subs = subs def getColorizableTexts(self): return (self._src,) def setColorizableTexts(self, src): self._src = src[0] def __repr__(self): r = [] a = r.append a((' ' * (self.indent or 0)) + ('%s(' % self.__class__.__name__) + str(self._src) + ', [') for p in self._subs: a(repr(p)) a((' ' * (self.indent or 0)) + '])') return '\n'.join(r) class StructuredTextDocument(StructuredTextParagraph): """A StructuredTextDocument holds StructuredTextParagraphs as its subparagraphs. """ _attributes = () def __init__(self, subs=None, **kw): super().__init__('', subs, **kw) def getChildren(self): return self._subs def getColorizableTexts(self): return () def setColorizableTexts(self, src): pass def __repr__(self): r = [] a = r.append a('%s([' % self.__class__.__name__) for p in self._subs: a(repr(p) + ',') a('])') return '\n'.join(r) class StructuredTextExample(StructuredTextParagraph): """Represents a section of document with literal text, as for examples""" def __init__(self, subs, **kw): t = [] for s in subs: flatten(s, t.append) super().__init__('\n\n'.join(t), (), **kw) def getColorizableTexts(self): return () def setColorizableTexts(self, src): pass # never color examples class StructuredTextBullet(StructuredTextParagraph): """Represents a section of a document with a title and a body """ class StructuredTextNumbered(StructuredTextParagraph): """Represents a section of a document with a title and a body """ class StructuredTextDescriptionTitle(StructuredTextParagraph): """Represents a section of a document with a title and a body """ class StructuredTextDescriptionBody(StructuredTextParagraph): """Represents a section of a document with a title and a body """ class StructuredTextDescription(StructuredTextParagraph): """Represents a section of a document with a title and a body """ def __init__(self, title, src, subs, **kw): super().__init__(src, subs, **kw) self._title = title def getColorizableTexts(self): return self._title, self._src def setColorizableTexts(self, src): self._title, self._src = src def getChildren(self): return (StructuredTextDescriptionTitle(self._title), StructuredTextDescriptionBody(self._src, self._subs)) class StructuredTextSectionTitle(StructuredTextParagraph): """Represents a section of a document with a title and a body""" class StructuredTextSection(StructuredTextParagraph): """Represents a section of a document with a title and a body""" def __init__(self, src, subs=None, **kw): super().__init__( StructuredTextSectionTitle(src), subs, **kw) def getColorizableTexts(self): return self._src.getColorizableTexts() def setColorizableTexts(self, src): self._src.setColorizableTexts(src) # a StructuredTextTable holds StructuredTextRows class StructuredTextTable(StructuredTextParagraph): """ rows is a list of lists containing tuples, which represent the columns/cells in each rows. EX rows = [[('row 1:column1',1)],[('row2:column1',1)]] """ def __init__(self, rows, src, subs, **kw): super().__init__(subs, **kw) self._rows = [] for row in rows: if row: self._rows.append(StructuredTextRow(row, kw)) def getRows(self): return [self._rows] _getRows = getRows def getColumns(self): result = [] for row in self._rows: result.append(row.getColumns()) return result _getColumns = getColumns def setColumns(self, columns): for index, row in enumerate(self._rows): row.setColumns(columns[index]) _setColumns = setColumns def getColorizableTexts(self): """ return a tuple where each item is a column/cell's contents. The tuple, result, will be of this format. ("r1 col1", "r1=col2", "r2 col1", "r2 col2") """ result = [] for row in self._rows: for column in row.getColumns()[0]: result.append(column.getColorizableTexts()[0]) return result def setColorizableTexts(self, texts): """ texts is going to a tuple where each item is the result of being mapped to the colortext function. Need to insert the results appropriately into the individual columns/cells """ for row_index in range(len(self._rows)): for column_index in range(len(self._rows[row_index]._columns)): self._rows[row_index ]._columns[column_index ].setColorizableTexts((texts[0],)) texts = texts[1:] _getColorizableTexts = getColorizableTexts _setColorizableTexts = setColorizableTexts # StructuredTextRow holds StructuredTextColumns class StructuredTextRow(StructuredTextParagraph): def __init__(self, row, kw): """ row is a list of tuples, where each tuple is the raw text for a cell/column and the span of that cell/column. EX [('this is column one',1), ('this is column two',1)] """ super().__init__([], **kw) self._columns = [] for column in row: self._columns.append(StructuredTextColumn(column[0], column[1], column[2], column[3], column[4], kw)) def getColumns(self): return [self._columns] _getColumns = getColumns def setColumns(self, columns): self._columns = columns _setColumns = setColumns # this holds the text of a table cell class StructuredTextColumn(StructuredTextParagraph): """ StructuredTextColumn is a cell/column in a table. A cell can hold multiple paragraphs. The cell is either classified as a StructuredTextTableHeader or StructuredTextTableData. """ def __init__(self, text, span, align, valign, typ, kw): super().__init__(text, [], **kw) self._span = span self._align = align self._valign = valign self._type = typ def getSpan(self): return self._span _getSpan = getSpan def getAlign(self): return self._align _getAlign = getAlign def getValign(self): return self._valign _getValign = getValign def getType(self): return self._type _getType = getType class StructuredTextTableHeader(StructuredTextParagraph): pass class StructuredTextTableData(StructuredTextParagraph): pass class StructuredTextMarkup(stdom.Element): def __init__(self, value, **kw): self._value = value self._attributes = kw.keys() for key, value in kw.items(): setattr(self, key, value) def getChildren(self): v = self._value if not isinstance(v, list): v = [v] return v def getColorizableTexts(self): return self._value, def setColorizableTexts(self, v): self._value = v[0] def __repr__(self): return '{}({})'.format(self.__class__.__name__, repr(self._value)) class StructuredTextLiteral(StructuredTextMarkup): def getColorizableTexts(self): return () def setColorizableTexts(self, v): pass class StructuredTextEmphasis(StructuredTextMarkup): pass class StructuredTextStrong(StructuredTextMarkup): pass class StructuredTextInnerLink(StructuredTextMarkup): pass class StructuredTextNamedLink(StructuredTextMarkup): pass class StructuredTextUnderline(StructuredTextMarkup): pass class StructuredTextSGML(StructuredTextMarkup): pass class StructuredTextLink(StructuredTextMarkup): pass class StructuredTextXref(StructuredTextMarkup): pass class StructuredTextImage(StructuredTextMarkup): """A simple embedded image """
zope.structuredtext
/zope.structuredtext-5.0-py3-none-any.whl/zope/structuredtext/stng.py
stng.py
# Node type codes # --------------- ELEMENT_NODE = 1 ATTRIBUTE_NODE = 2 TEXT_NODE = 3 CDATA_SECTION_NODE = 4 ENTITY_REFERENCE_NODE = 5 ENTITY_NODE = 6 PROCESSING_INSTRUCTION_NODE = 7 COMMENT_NODE = 8 DOCUMENT_NODE = 9 DOCUMENT_TYPE_NODE = 10 DOCUMENT_FRAGMENT_NODE = 11 NOTATION_NODE = 12 # Exception codes # --------------- INDEX_SIZE_ERR = 1 DOMSTRING_SIZE_ERR = 2 HIERARCHY_REQUEST_ERR = 3 WRONG_DOCUMENT_ERR = 4 INVALID_CHARACTER_ERR = 5 NO_DATA_ALLOWED_ERR = 6 NO_MODIFICATION_ALLOWED_ERR = 7 NOT_FOUND_ERR = 8 NOT_SUPPORTED_ERR = 9 INUSE_ATTRIBUTE_ERR = 10 # Exceptions # ---------- class DOMException(Exception): pass class IndexSizeException(DOMException): code = INDEX_SIZE_ERR class DOMStringSizeException(DOMException): code = DOMSTRING_SIZE_ERR class HierarchyRequestException(DOMException): code = HIERARCHY_REQUEST_ERR class WrongDocumentException(DOMException): code = WRONG_DOCUMENT_ERR class InvalidCharacterException(DOMException): code = INVALID_CHARACTER_ERR class NoDataAllowedException(DOMException): code = NO_DATA_ALLOWED_ERR class NoModificationAllowedException(DOMException): code = NO_MODIFICATION_ALLOWED_ERR class NotFoundException(DOMException): code = NOT_FOUND_ERR class NotSupportedException(DOMException): code = NOT_SUPPORTED_ERR class InUseAttributeException(DOMException): code = INUSE_ATTRIBUTE_ERR # Node classes # ------------ class ParentNode: """ A node that can have children, or, more precisely, that implements the child access methods of the DOM. """ def getChildNodes(self, type=type, sts=str): """ Returns a NodeList that contains all children of this node. If there are no children, this is a empty NodeList """ r = [] for n in self.getChildren(): if isinstance(n, sts): n = TextNode(n) r.append(n.__of__(self)) return NodeList(r) def getFirstChild(self, type=type, sts=str): """ The first child of this node. If there is no such node this returns None """ raise NotImplementedError() def getLastChild(self, type=type, sts=str): """ The last child of this node. If there is no such node this returns None. """ raise NotImplementedError() class NodeWrapper(ParentNode): """ This is an acquisition-like wrapper that provides parent access for DOM sans circular references! """ def __init__(self, aq_self, aq_parent): self.aq_self = aq_self self.aq_parent = aq_parent def __getattr__(self, name): return getattr(self.aq_self, name) def getParentNode(self): """ The parent of this node. All nodes except Document DocumentFragment and Attr may have a parent """ raise NotImplementedError() def _getDOMIndex(self, children, getattr=getattr): i = 0 self = self.aq_self for child in children: if getattr(child, 'aq_self', child) is self: self._DOMIndex = i return i i = i + 1 def getPreviousSibling(self): """ The node immediately preceding this node. If there is no such node, this returns None. """ children = self.aq_parent.getChildren() if not children: # pragma: no cover return None index = getattr(self, '_DOMIndex', None) if index is None: index = self._getDOMIndex(children) if index is None: return None # pragma: no cover index = index - 1 if index < 0: return None try: n = children[index] except IndexError: # pragma: no cover return None else: if isinstance(n, str): n = TextNode(n) n._DOMIndex = index return n.__of__(self) def getNextSibling(self): """ The node immediately preceding this node. If there is no such node, this returns None. """ children = self.aq_parent.getChildren() if not children: # pragma: no cover return None index = getattr(self, '_DOMIndex', None) if index is None: # pragma: no cover index = self._getDOMIndex(children) if index is None: return None index = index + 1 try: n = children[index] except IndexError: # pragma: no cover return None else: if isinstance(n, str): # pragma: no cover n = TextNode(n) n._DOMIndex = index return n.__of__(self) def getOwnerDocument(self): """ The Document object associated with this node, if any. """ raise NotImplementedError() class Node(ParentNode): """Node Interface """ # Get a DOM wrapper with a parent link def __of__(self, parent): return NodeWrapper(self, parent) # DOM attributes def getNodeName(self): """The name of this node, depending on its type """ def getNodeValue(self): """The value of this node, depending on its type """ def getParentNode(self): """ The parent of this node. All nodes except Document DocumentFragment and Attr may have a parent """ def getChildren(self): """Get a Python sequence of children """ raise NotImplementedError() def getPreviousSibling(self): """ The node immediately preceding this node. If there is no such node, this returns None. """ def getNextSibling(self): """ The node immediately preceding this node. If there is no such node, this returns None. """ def getAttributes(self): """ Returns a NamedNodeMap containing the attributes of this node (if it is an element) or None otherwise. """ def getOwnerDocument(self): """The Document object associated with this node, if any. """ # DOM Methods # ----------- def hasChildNodes(self): """ Returns true if the node has any children, false if it doesn't. """ raise NotImplementedError() _NODE_TYPE = None def getNodeType(self): """A code representing the type of the node.""" return self._NODE_TYPE class TextNode(Node): def __init__(self, str): self._value = str _NODE_TYPE = TEXT_NODE def getNodeName(self): return '#text' def getNodeValue(self): return self._value class Element(Node): """Element interface """ # Element Attributes # ------------------ def getTagName(self): """The name of the element""" return self.__class__.__name__ getNodeName = getTagName _NODE_TYPE = ELEMENT_NODE def getNodeValue(self): r = [] for c in self.getChildren(): if not isinstance(c, str): c = c.getNodeValue() r.append(c) return ''.join(r) def getParentNode(self): """ The parent of this node. All nodes except Document DocumentFragment and Attr may have a parent """ # Element Methods # --------------- _attributes = () def getAttribute(self, name): """Retrieves an attribute value by name.""" return getattr(self, name, None) def getAttributeNode(self, name): """ Retrieves an Attr node by name or None if there is no such attribute. """ if hasattr(self, name): return Attr(name, getattr(self, name)) def getAttributes(self): d = {} for a in self._attributes: d[a] = getattr(self, a, '') return NamedNodeMap(d) def getElementsByTagName(self, tagname): """ Returns a NodeList of all the Elements with a given tag name in the order in which they would be encountered in a preorder traversal of the Document tree. Parameter: tagname The name of the tag to match (* = all tags). Return Value: A new NodeList object containing all the matched Elements. """ raise NotImplementedError() class NodeList: """NodeList interface - Provides the abstraction of an ordered collection of nodes. Python extensions: can use sequence-style 'len', 'getitem', and 'for..in' constructs. """ def __init__(self, list=None): self._data = list or [] def __getitem__(self, index, type=type, sts=str): return self._data[index] def item(self, index): """Returns the index-th item in the collection """ raise NotImplementedError() def getLength(self): """The length of the NodeList """ return len(self._data) __len__ = getLength class NamedNodeMap: """ NamedNodeMap interface - Is used to represent collections of nodes that can be accessed by name. NamedNodeMaps are not maintained in any particular order. Python extensions: can use sequence-style 'len', 'getitem', and 'for..in' constructs, and mapping-style 'getitem'. """ def __init__(self, data=None): self._data = data if data is not None else {} def item(self, index): """Returns the index-th item in the map. This is arbitrary because maps have no order. """ raise NotImplementedError() def __getitem__(self, key): raise NotImplementedError() def getLength(self): """ The length of the NodeList """ raise NotImplementedError() __len__ = getLength def getNamedItem(self, name): """ Retrieves a node specified by name. Parameters: name Name of a node to retrieve. Return Value A Node (of any type) with the specified name, or None if the specified name did not identify any node in the map. """ raise NotImplementedError() class Attr(Node): """ Attr interface - The Attr interface represents an attriubte in an Element object. Attr objects inherit the Node Interface """ def __init__(self, name, value, specified=1): self.name = name self.value = value self.specified = specified def getNodeName(self): """ The name of this node, depending on its type """ raise NotImplementedError() getName = getNodeName def getNodeValue(self): """ The value of this node, depending on its type """ raise NotImplementedError() _NODE_TYPE = ATTRIBUTE_NODE def getSpecified(self): """ If this attribute was explicitly given a value in the original document, this is true; otherwise, it is false. """ raise NotImplementedError()
zope.structuredtext
/zope.structuredtext-5.0-py3-none-any.whl/zope/structuredtext/stdom.py
stdom.py
========= Changes ========= 5.0.1 (2023-01-23) ================== - Add missing ``python_requires`` to ``setup.py``. 5.0 (2023-01-19) ================ - Add support for Python 3.11. - Drop support for Python 2.7, 3.5, 3.6. - Add support for Python 3.10. - Add ``nav`` to the list of HTML block level elements. (`#18 <https://github.com/zopefoundation/zope.tal/pull/18>`_) - Remove ``.talgettext.UpdatePOEngine`` and the ability to call ``zope/tal/talgettext.py`` (main function). The code was broken and unused. - Remove support to run the tests using deprecated ``python setup.py test``. 4.5 (2021-05-28) ================ - Avoid traceback reference cycle in ``TALInterpreter.do_onError_tal``. - Add support for Python 3.8 and 3.9. - Drop support for Python 3.4. 4.4 (2018-10-05) ================ - Add support for Python 3.7. 4.3.1 (2018-03-21) ================== - Host documentation at https://zopetal.readthedocs.io - Fix a ``NameError`` on Python 3 in talgettext.py affecting i18ndude. See https://github.com/zopefoundation/zope.tal/pull/11 4.3.0 (2017-08-08) ================== - Drop support for Python 3.3. - Add support for Python 3.6. 4.2.0 (2016-04-12) ================== - Drop support for Python 2.6 and 3.2. - Accept and ignore ``i18n:ignore`` and ``i18n:ignore-attributes`` attributes. For compatibility with other tools (such as ``i18ndude``). - Add support for Python 3.5. 4.1.1 (2015-06-05) ================== - Suppress deprecation under Python 3.4 for default ``convert_charrefs`` argument (passed to ``HTMLParser``). Also ensures that upcoming change to the default in Python 3.5 will not affect us. - Add support for Python 3.2 and PyPy3. 4.1.0 (2014-12-19) ================== .. note:: Support for PyPy3 is pending release of a fix for: https://bitbucket.org/pypy/pypy/issue/1946 - Add support for Python 3.4. - Add support for testing on Travis. 4.0.0 (2014-01-13) ================== - Fix possible UnicodeDecodeError in warning when msgid already exists. 4.0.0a1 (2013-02-15) ==================== - Replace deprecated ``zope.interface.implements`` usage with equivalent ``zope.interface.implementer`` decorator. - Add support for Python 3.3 and PyPy. - Drop support for Python 2.4 and 2.5. - Output attributes generate via ``tal:attributes`` and ``i18n:attributes`` directives in alphabetical order. 3.6.1 (2012-03-09) ================== - Avoid handling end tags within <script> tags in the HTML parser. This works around http://bugs.python.org/issue670664 - Fix documentation link in README.txt. 3.6.0 (2011-08-20) ================== - Update `talinterpreter.FasterStringIO` to faster list-based implementation. - Increase the default value of the `wrap` argument from 60 to 1023 characters, to avoid extra whitespace and line breaks. - Fix printing of error messages for msgid conflict with non-ASCII texts. 3.5.2 (2009-10-31) ================== - In ``talgettext.POEngine.translate``, print a warning if a msgid already exists in the domain with a different default. 3.5.1 (2009-03-08) ================== - Update tests of "bad" entities for compatibility with the stricter HTMLParser module shipped with Python 2.6.x. 3.5.0 (2008-06-06) ================== - Remove artificial addition of a trailing newline if the output doesn't end in one; this allows the template source to be the full specification of what should be included. (See https://bugs.launchpad.net/launchpad/+bug/218706.) 3.4.1 (2007-11-16) ================== - Remove unnecessary ``dummyengine`` dependency on zope.i18n to simplify distribution. The ``dummyengine.DummyTranslationDomain`` class no longer implements ``zope.i18n.interfaces.ITranslationDomain`` as a result. Installing zope.tal with easy_install or buildout no longer pulls in many unrelated distributions. - Support running tests using ``setup.py test``. - Stop pinning (no longer required) ``zope.traversing`` and ``zope.app.publisher`` versions in buildout.cfg. 3.4.0 (2007-10-03) ================== - Update package meta-data. 3.4.0b1 ======= - Update dependency on ``zope.i18n`` to a verions requiring the correct version of ``zope.security``, avoiding a hidden dependency issue in ``zope.security``. .. note:: Changes before 3.4.0b1 where not tracked as an individual package and have been documented in the Zope 3 changelog.
zope.tal
/zope.tal-5.0.1.tar.gz/zope.tal-5.0.1/CHANGES.rst
CHANGES.rst
========== zope.tal ========== .. image:: https://img.shields.io/pypi/v/zope.tal.svg :target: https://pypi.python.org/pypi/zope.tal/ :alt: Latest release .. image:: https://img.shields.io/pypi/pyversions/zope.tal.svg :target: https://pypi.org/project/zope.tal/ :alt: Supported Python versions .. image:: https://github.com/zopefoundation/zope.tal/actions/workflows/tests.yml/badge.svg :target: https://github.com/zopefoundation/zope.tal/actions/workflows/tests.yml .. image:: https://coveralls.io/repos/github/zopefoundation/zope.tal/badge.svg?branch=master :target: https://coveralls.io/github/zopefoundation/zope.tal?branch=master .. image:: https://readthedocs.org/projects/zopetal/badge/?version=latest :target: https://zopetal.readthedocs.io/en/latest/ :alt: Documentation Status The Zope3 Template Attribute Languate (TAL) specifies the custom namespace and attributes which are used by the Zope Page Templates renderer to inject dynamic markup into a page. It also includes the Macro Expansion for TAL (METAL) macro language used in page assembly. The dynamic values themselves are specified using a companion language, TALES (see the `zope.tales`_ package for more). The reference documentation for the TAL language is available at https://pagetemplates.readthedocs.io/en/latest/tal.html Detailed documentation for this implementation and its API is available at https://zopetal.readthedocs.io/ .. _`zope.tales` : https://zopetales.readthedocs.io
zope.tal
/zope.tal-5.0.1.tar.gz/zope.tal-5.0.1/README.rst
README.rst
Zope Public License (ZPL) Version 2.1 A copyright notice accompanies this license document that identifies the copyright holders. This license has been certified as open source. It has also been designated as GPL compatible by the Free Software Foundation (FSF). Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions in source code must retain the accompanying copyright notice, this list of conditions, and the following disclaimer. 2. Redistributions in binary form must reproduce the accompanying copyright notice, this list of conditions, and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Names of the copyright holders must not be used to endorse or promote products derived from this software without prior written permission from the copyright holders. 4. The right to distribute this software or to use it for any purpose does not give you the right to use Servicemarks (sm) or Trademarks (tm) of the copyright holders. Use of them is covered by separate agreement with the copyright holders. 5. If any files are modified, you must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. Disclaimer THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
zope.tal
/zope.tal-5.0.1.tar.gz/zope.tal-5.0.1/LICENSE.rst
LICENSE.rst
import warnings from zope.i18nmessageid import Message from zope.interface import implementer from zope.tal.dummyengine import DummyEngine from zope.tal.interfaces import ITALExpressionEngine from zope.tal.talinterpreter import TALInterpreter from zope.tal.talinterpreter import normalize pot_header = '''\ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR ORGANIZATION # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR. # msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\\n" "POT-Creation-Date: %(time)s\\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\\n" "Last-Translator: FULL NAME <EMAIL@ADDRESS>\\n" "Language-Team: LANGUAGE <[email protected]>\\n" "MIME-Version: 1.0\\n" "Content-Type: text/plain; charset=CHARSET\\n" "Content-Transfer-Encoding: ENCODING\\n" "Generated-By: talgettext.py %(version)s\\n" ''' NLSTR = '"\n"' class POTALInterpreter(TALInterpreter): def translate(self, msgid, default=None, i18ndict=None, obj=None): if default is None: default = getattr(msgid, 'default', str(msgid)) # If no i18n dict exists yet, create one. if i18ndict is None: i18ndict = {} if obj: i18ndict.update(obj) # Mmmh, it seems that sometimes the msgid is None; is that really # possible? if msgid is None: return None # TODO: We need to pass in one of context or target_language return self.engine.translate(msgid, self.i18nContext.domain, i18ndict, default=default, position=self.position) @implementer(ITALExpressionEngine) class POEngine(DummyEngine): def __init__(self, macros=None): self.catalog = {} DummyEngine.__init__(self, macros) def evaluate(*args): # If the result of evaluate ever gets into a message ID, we want # to notice the fact in the .pot file. return '${DYNAMIC_CONTENT}' def evaluatePathOrVar(*args): # Actually this method is never called. return 'XXX' def evaluateSequence(self, expr): return (0,) # dummy def evaluateBoolean(self, expr): return True # dummy def translate(self, msgid, domain=None, mapping=None, default=None, # Position is not part of the ITALExpressionEngine # interface position=None): if default is not None: default = normalize(default) if msgid == default: default = None msgid = Message(msgid, default=default) if domain not in self.catalog: self.catalog[domain] = {} domain = self.catalog[domain] if msgid not in domain: domain[msgid] = [] else: msgids = list(domain) idx = msgids.index(msgid) existing_msgid = msgids[idx] if msgid.default != existing_msgid.default: references = '\n'.join([location[0] + ':' + str(location[1]) for location in domain[msgid]]) # Note: a lot of encode calls here are needed so # it does not break. warnings.warn( "Warning: msgid '%s' in %s already exists " "with a different default (bad: %s, should be: %s)\n" "The references for the existent value are:\n%s\n" % (msgid.encode('utf-8'), self.file.encode('utf-8') + b':' + str(position).encode('utf-8'), msgid.default.encode('utf-8'), existing_msgid.default.encode('utf-8'), references.encode('utf-8'))) domain[msgid].append((self.file, position)) return 'x'
zope.tal
/zope.tal-5.0.1.tar.gz/zope.tal-5.0.1/src/zope/tal/talgettext.py
talgettext.py
import logging from urllib.request import urlopen class XMLParser: """ Parse XML using :mod:`xml.parsers.expat`. """ ordered_attributes = 0 handler_names = [ "StartElementHandler", "EndElementHandler", "ProcessingInstructionHandler", "CharacterDataHandler", "UnparsedEntityDeclHandler", "NotationDeclHandler", "StartNamespaceDeclHandler", "EndNamespaceDeclHandler", "CommentHandler", "StartCdataSectionHandler", "EndCdataSectionHandler", "DefaultHandler", "DefaultHandlerExpand", "NotStandaloneHandler", "ExternalEntityRefHandler", "XmlDeclHandler", "StartDoctypeDeclHandler", "EndDoctypeDeclHandler", "ElementDeclHandler", "AttlistDeclHandler" ] def __init__(self, encoding=None): self.parser = p = self.createParser(encoding) if self.ordered_attributes: try: self.parser.ordered_attributes = self.ordered_attributes except AttributeError: logging.warn("TAL.XMLParser: Can't set ordered_attributes") self.ordered_attributes = 0 for name in self.handler_names: method = getattr(self, name, None) if method is not None: try: setattr(p, name, method) except AttributeError: logging.error("TAL.XMLParser: Can't set " "expat handler %s" % name) def createParser(self, encoding=None): global XMLParseError from xml.parsers import expat XMLParseError = expat.ExpatError return expat.ParserCreate(encoding, ' ') def parseFile(self, filename): """Parse from the given filename.""" with open(filename, 'rb') as f: self.parseStream(f) def parseString(self, s): """Parse the given string.""" if isinstance(s, str): # Expat cannot deal with str, only with # bytes. Also, its range of encodings is rather # limited, UTF-8 is the safest bet here. s = s.encode('utf-8') self.parser.Parse(s, 1) def parseURL(self, url): """Parse the given URL.""" self.parseStream(urlopen(url)) def parseStream(self, stream): """Parse the given stream (open file).""" self.parser.ParseFile(stream) def parseFragment(self, s, end=0): self.parser.Parse(s, end) def getpos(self): # Apparently ErrorLineNumber and ErrorLineNumber contain the current # position even when there was no error. This contradicts the official # documentation[1], but expat.h[2] contains the following definition: # # /* For backwards compatibility with previous versions. */ # #define XML_GetErrorLineNumber XML_GetCurrentLineNumber # # [1] http://python.org/doc/current/lib/xmlparser-objects.html # [2] http://cvs.sourceforge.net/viewcvs.py/expat/expat/lib/expat.h return (self.parser.ErrorLineNumber, self.parser.ErrorColumnNumber)
zope.tal
/zope.tal-5.0.1.tar.gz/zope.tal-5.0.1/src/zope/tal/xmlparser.py
xmlparser.py
from html.parser import HTMLParser from zope.tal.taldefs import ZOPE_I18N_NS from zope.tal.taldefs import ZOPE_METAL_NS from zope.tal.taldefs import ZOPE_TAL_NS from zope.tal.taldefs import I18NError from zope.tal.taldefs import METALError from zope.tal.taldefs import TALError from zope.tal.talgenerator import TALGenerator class HTMLParseError(Exception): # Python 3.5 removed this class, but we need it as a base class # so here's a copy taken from Python 3.4 def __init__(self, msg, position=(None, None)): Exception.__init__(self) assert msg self.msg = msg self.lineno = position[0] self.offset = position[1] def __str__(self): result = self.msg if self.lineno is not None: result = result + ", at line %d" % self.lineno if self.offset is not None: result = result + ", column %d" % (self.offset + 1) return result _html_parser_extras = {} if 'convert_charrefs' in HTMLParser.__init__.__code__.co_names: _html_parser_extras['convert_charrefs'] = False # pragma: NO COVER py34 #: List of Boolean attributes in HTML that may be given in #: minimized form (e.g. ``<img ismap>`` rather than ``<img ismap="">``) #: From http://www.w3.org/TR/xhtml1/#guidelines (C.10) BOOLEAN_HTML_ATTRS = frozenset([ "compact", "nowrap", "ismap", "declare", "noshade", "checked", "disabled", "readonly", "multiple", "selected", "noresize", "defer" ]) #: List of HTML tags with an empty content model; these are #: rendered in minimized form, e.g. ``<img />``. #: From http://www.w3.org/TR/xhtml1/#dtds EMPTY_HTML_TAGS = frozenset([ "base", "meta", "link", "hr", "br", "param", "img", "area", "input", "col", "basefont", "isindex", "frame", ]) #: List of HTML elements that close open paragraph-level elements #: and are themselves paragraph-level. PARA_LEVEL_HTML_TAGS = frozenset([ "h1", "h2", "h3", "h4", "h5", "h6", "p", ]) #: Tags that automatically close other tags. BLOCK_CLOSING_TAG_MAP = { "tr": frozenset(["tr", "td", "th"]), "td": frozenset(["td", "th"]), "th": frozenset(["td", "th"]), "li": frozenset(["li"]), "dd": frozenset(["dd", "dt"]), "dt": frozenset(["dd", "dt"]), } #: List of HTML tags that denote larger sections than paragraphs. BLOCK_LEVEL_HTML_TAGS = frozenset([ "blockquote", "table", "tr", "th", "td", "thead", "tfoot", "tbody", "noframe", "ul", "ol", "li", "dl", "dt", "dd", "div", "nav", ]) #: Section level HTML tags SECTION_LEVEL_HTML_TAGS = PARA_LEVEL_HTML_TAGS.union(BLOCK_LEVEL_HTML_TAGS) TIGHTEN_IMPLICIT_CLOSE_TAGS = PARA_LEVEL_HTML_TAGS.union(BLOCK_CLOSING_TAG_MAP) class NestingError(HTMLParseError): """Exception raised when elements aren't properly nested.""" def __init__(self, tagstack, endtag, position=(None, None)): self.endtag = endtag if tagstack: if len(tagstack) == 1: msg = ('Open tag <%s> does not match close tag </%s>' % (tagstack[0], endtag)) else: msg = ('Open tags <%s> do not match close tag </%s>' % ('>, <'.join(tagstack), endtag)) else: msg = 'No tags are open to match </%s>' % endtag HTMLParseError.__init__(self, msg, position) class EmptyTagError(NestingError): """Exception raised when empty elements have an end tag.""" def __init__(self, tag, position=(None, None)): self.tag = tag msg = 'Close tag </%s> should be removed' % tag HTMLParseError.__init__(self, msg, position) class OpenTagError(NestingError): """Exception raised when a tag is not allowed in another tag.""" def __init__(self, tagstack, tag, position=(None, None)): self.tag = tag msg = 'Tag <{}> is not allowed in <{}>'.format(tag, tagstack[-1]) HTMLParseError.__init__(self, msg, position) class HTMLTALParser(HTMLParser): """ Parser for HTML. After you call either :meth:`parseFile` and :meth:`parseString` you can retrieve the compiled program using :meth:`getCode`. """ # External API def __init__(self, gen=None): """ :keyword TALGenerator gen: The configured (with an expression compiler) code generator to use. If one is not given, a default will be used. """ HTMLParser.__init__(self, **_html_parser_extras) if gen is None: gen = TALGenerator(xml=0) self.gen = gen self.tagstack = [] self.nsstack = [] self.nsdict = { 'tal': ZOPE_TAL_NS, 'metal': ZOPE_METAL_NS, 'i18n': ZOPE_I18N_NS, } def parseFile(self, file): """Parse data in the given file.""" with open(file) as f: data = f.read() try: self.parseString(data) except TALError as e: e.setFile(file) raise def parseString(self, data): """Parse data in the given string.""" self.feed(data) self.close() while self.tagstack: self.implied_endtag(self.tagstack[-1], 2) assert self.nsstack == [], self.nsstack def getCode(self): """ After parsing, this returns ``(program, macros)``. """ return self.gen.getCode() # Overriding HTMLParser methods def handle_starttag(self, tag, attrs): self.close_para_tags(tag) self.scan_xmlns(attrs) tag, attrlist, taldict, metaldict, i18ndict \ = self.process_ns(tag, attrs) if tag in EMPTY_HTML_TAGS and "content" in taldict: raise TALError( "empty HTML tags cannot use tal:content: %s" % repr(tag), self.getpos()) # Support for inline Python code. if tag == 'script': type_attr = [a for a in attrlist if a[0] == "type"] if type_attr and type_attr[0][1].startswith('text/server-'): attrlist.remove(type_attr[0]) taldict = {'script': type_attr[0][1], 'omit-tag': ''} self.tagstack.append(tag) self.gen.emitStartElement(tag, attrlist, taldict, metaldict, i18ndict, self.getpos()) if tag in EMPTY_HTML_TAGS: self.implied_endtag(tag, -1) def handle_startendtag(self, tag, attrs): self.close_para_tags(tag) self.scan_xmlns(attrs) tag, attrlist, taldict, metaldict, i18ndict \ = self.process_ns(tag, attrs) if "content" in taldict: if tag in EMPTY_HTML_TAGS: raise TALError( "empty HTML tags cannot use tal:content: %s" % repr(tag), self.getpos()) self.gen.emitStartElement(tag, attrlist, taldict, metaldict, i18ndict, self.getpos()) self.gen.emitEndElement(tag, implied=-1, position=self.getpos()) else: self.gen.emitStartElement(tag, attrlist, taldict, metaldict, i18ndict, self.getpos(), isend=1) self.pop_xmlns() def handle_endtag(self, tag): if self.tagstack and self.tagstack[-1] == 'script' and tag != 'script': self.handle_data('</%s>' % tag) return if tag in EMPTY_HTML_TAGS: # </img> etc. in the source is an error raise EmptyTagError(tag, self.getpos()) self.close_enclosed_tags(tag) self.gen.emitEndElement(tag, position=self.getpos()) self.pop_xmlns() self.tagstack.pop() def close_para_tags(self, tag): if tag in EMPTY_HTML_TAGS: return close_to = -1 if tag in BLOCK_CLOSING_TAG_MAP: blocks_to_close = BLOCK_CLOSING_TAG_MAP[tag] for i, t in enumerate(self.tagstack): if t in blocks_to_close: if close_to == -1: close_to = i elif t in BLOCK_LEVEL_HTML_TAGS: close_to = -1 elif tag in SECTION_LEVEL_HTML_TAGS: for i in range(len(self.tagstack) - 1, -1, -1): closetag = self.tagstack[i] if closetag in BLOCK_LEVEL_HTML_TAGS: break elif closetag in PARA_LEVEL_HTML_TAGS: if closetag != "p": raise OpenTagError(self.tagstack, tag, self.getpos()) close_to = i if close_to >= 0: while len(self.tagstack) > close_to: self.implied_endtag(self.tagstack[-1], 1) def close_enclosed_tags(self, tag): if tag not in self.tagstack: raise NestingError(self.tagstack, tag, self.getpos()) while tag != self.tagstack[-1]: self.implied_endtag(self.tagstack[-1], 1) assert self.tagstack[-1] == tag def implied_endtag(self, tag, implied): assert tag == self.tagstack[-1] assert implied in (-1, 1, 2) isend = (implied < 0) if tag in TIGHTEN_IMPLICIT_CLOSE_TAGS: # Pick out trailing whitespace from the program, and # insert the close tag before the whitespace. white = self.gen.unEmitWhitespace() else: white = None self.gen.emitEndElement(tag, isend=isend, implied=implied, position=self.getpos()) if white: self.gen.emitRawText(white) self.tagstack.pop() self.pop_xmlns() def handle_charref(self, name): self.gen.emitRawText("&#%s;" % name) def handle_entityref(self, name): self.gen.emitRawText("&%s;" % name) def handle_data(self, data): self.gen.emitRawText(data) def handle_comment(self, data): self.gen.emitRawText("<!--%s-->" % data) def handle_decl(self, data): self.gen.emitRawText("<!%s>" % data) def handle_pi(self, data): self.gen.emitRawText("<?%s>" % data) # Internal thingies def scan_xmlns(self, attrs): nsnew = {} for key, value in attrs: if key.startswith("xmlns:"): nsnew[key[6:]] = value self.nsstack.append(self.nsdict) if nsnew: self.nsdict = self.nsdict.copy() self.nsdict.update(nsnew) def pop_xmlns(self): self.nsdict = self.nsstack.pop() _namespaces = { ZOPE_TAL_NS: "tal", ZOPE_METAL_NS: "metal", ZOPE_I18N_NS: "i18n", } def fixname(self, name): if ':' in name: prefix, suffix = name.split(':', 1) if prefix == 'xmlns': nsuri = self.nsdict.get(suffix) if nsuri in self._namespaces: return name, name, prefix else: nsuri = self.nsdict.get(prefix) if nsuri in self._namespaces: return name, suffix, self._namespaces[nsuri] return name, name, 0 def process_ns(self, name, attrs): attrlist = [] taldict = {} metaldict = {} i18ndict = {} name, namebase, namens = self.fixname(name) for item in attrs: key, value = item key, keybase, keyns = self.fixname(key) ns = keyns or namens # default to tag namespace if ns and ns != 'unknown': item = (key, value, ns) if ns == 'tal': if keybase in taldict: raise TALError("duplicate TAL attribute " + repr(keybase), self.getpos()) taldict[keybase] = value elif ns == 'metal': if keybase in metaldict: raise METALError("duplicate METAL attribute " + repr(keybase), self.getpos()) metaldict[keybase] = value elif ns == 'i18n': if keybase in i18ndict: raise I18NError("duplicate i18n attribute " + repr(keybase), self.getpos()) i18ndict[keybase] = value attrlist.append(item) if namens in ('metal', 'tal', 'i18n'): taldict['tal tag'] = namens return name, attrlist, taldict, metaldict, i18ndict
zope.tal
/zope.tal-5.0.1.tar.gz/zope.tal-5.0.1/src/zope/tal/htmltalparser.py
htmltalparser.py
"""Common definitions used by TAL and METAL compilation and transformation. """ import re from zope.interface import implementer from zope.tal.interfaces import ITALExpressionErrorInfo #: Version of the specification we implement. TAL_VERSION = "1.6" #: URI for XML namespace XML_NS = "http://www.w3.org/XML/1998/namespace" #: URI for XML NS declarations XMLNS_NS = "http://www.w3.org/2000/xmlns/" #: TAL namespace URI ZOPE_TAL_NS = "http://xml.zope.org/namespaces/tal" #: METAL namespace URI ZOPE_METAL_NS = "http://xml.zope.org/namespaces/metal" #: I18N namespace URI ZOPE_I18N_NS = "http://xml.zope.org/namespaces/i18n" # This RE must exactly match the expression of the same name in the # zope.i18n.simpletranslationservice module: NAME_RE = "[a-zA-Z_][-a-zA-Z0-9_]*" #: Known METAL attributes KNOWN_METAL_ATTRIBUTES = frozenset([ "define-macro", "extend-macro", "use-macro", "define-slot", "fill-slot", ]) #: Known TAL attributes KNOWN_TAL_ATTRIBUTES = frozenset([ "define", "condition", "content", "replace", "repeat", "attributes", "on-error", "omit-tag", "script", "tal tag", # a pseudo attribute that holds the namespace of elements # like <tal:x>, <metal:y>, <i18n:z> ]) #: Known I18N attributes KNOWN_I18N_ATTRIBUTES = frozenset([ "translate", "domain", "target", "source", "attributes", "data", "name", "ignore", "ignore-attributes", ]) class TALError(Exception): """ A base exception for errors raised by this implementation. """ def __init__(self, msg, position=(None, None)): Exception.__init__(self) assert msg != "" self.msg = msg self.lineno = position[0] self.offset = position[1] self.filename = None def setFile(self, filename): self.filename = filename def __str__(self): result = self.msg if self.lineno is not None: result = result + ", at line %d" % self.lineno if self.offset is not None: result = result + ", column %d" % (self.offset + 1) if self.filename is not None: result = result + ', in file %s' % self.filename return result class METALError(TALError): """An error parsing on running METAL macros.""" class TALExpressionError(TALError): """An error parsing or running a TAL expression.""" class I18NError(TALError): """An error parsing a I18N expression.""" @implementer(ITALExpressionErrorInfo) class ErrorInfo: """ Default implementation of :class:`zope.tal.interfaces.ITALExpressionErrorInfo`. """ def __init__(self, err, position=(None, None)): if isinstance(err, Exception): self.type = err.__class__ self.value = err else: self.type = err self.value = None self.lineno = position[0] self.offset = position[1] _attr_re = re.compile(r"\s*([^\s]+)\s+([^\s].*)\Z", re.S) _subst_re = re.compile(r"\s*(?:(text|structure)\s+)?(.*)\Z", re.S) def parseAttributeReplacements(arg, xml): attr_dict = {} for part in splitParts(arg): m = _attr_re.match(part) if not m: raise TALError("Bad syntax in attributes: %r" % part) name, expr = m.groups() if not xml: name = name.lower() if name in attr_dict: raise TALError("Duplicate attribute name in attributes: %r" % part) attr_dict[name] = expr return attr_dict def parseSubstitution(arg, position=(None, None)): m = _subst_re.match(arg) if not m: raise TALError("Bad syntax in substitution text: %r" % arg, position) key, expr = m.groups() if not key: key = "text" return key, expr def splitParts(arg): # Break in pieces at undoubled semicolons and # change double semicolons to singles: arg = arg.replace(";;", "\0") parts = arg.split(';') parts = [p.replace("\0", ";") for p in parts] if len(parts) > 1 and not parts[-1].strip(): del parts[-1] # It ended in a semicolon return parts def isCurrentVersion(program): version = getProgramVersion(program) return version == TAL_VERSION def isinstance_(ob, kind): # Proxy-friendly and faster isinstance_ check for new-style objects try: return kind in ob.__class__.__mro__ except AttributeError: return False def getProgramMode(program): version = getProgramVersion(program) if (version == TAL_VERSION and isinstance_(program[1], tuple) and len(program[1]) == 2): opcode, mode = program[1] if opcode == "mode": return mode return None def getProgramVersion(program): if (len(program) >= 2 and isinstance_(program[0], tuple) and len(program[0]) == 2): opcode, version = program[0] if opcode == "version": return version return None _ent1_re = re.compile('&(?![A-Z#])', re.I) _entch_re = re.compile('&([A-Z][A-Z0-9]*)(?![A-Z0-9;])', re.I) _entn1_re = re.compile('&#(?![0-9X])', re.I) _entnx_re = re.compile('&(#X[A-F0-9]*)(?![A-F0-9;])', re.I) _entnd_re = re.compile('&(#[0-9][0-9]*)(?![0-9;])') def attrEscape(s): """Replace special characters '&<>' by character entities, except when '&' already begins a syntactically valid entity.""" s = _ent1_re.sub('&amp;', s) s = _entch_re.sub(r'&amp;\1', s) s = _entn1_re.sub('&amp;#', s) s = _entnx_re.sub(r'&amp;\1', s) s = _entnd_re.sub(r'&amp;\1', s) s = s.replace('<', '&lt;') s = s.replace('>', '&gt;') s = s.replace('"', '&quot;') return s def quote(s): s = s.replace("&", "&amp;") # Must be done first! s = s.replace("<", "&lt;") s = s.replace(">", "&gt;") s = s.replace('"', "&quot;") return '"%s"' % s
zope.tal
/zope.tal-5.0.1.tar.gz/zope.tal-5.0.1/src/zope/tal/taldefs.py
taldefs.py
from zope.interface import Attribute from zope.interface import Interface class ITALExpressionCompiler(Interface): """Compile-time interface provided by a TAL expression implementation. The TAL compiler needs an instance of this interface to support compilation of TAL expressions embedded in documents containing TAL and METAL constructs. """ def getCompilerError(): """Return the exception class raised for compilation errors. """ def compile(expression): """Return a compiled form of *expression* for later evaluation. *expression* is the source text of the expression. The return value may be passed to the various ``evaluate*()`` methods of the :class:`ITALExpressionEngine` interface. No compatibility is required for the values of the compiled expression between different :class:`ITALExpressionEngine` implementations. """ def getContext(namespace): """Create an expression execution context The given *namespace* provides the initial top-level names. """ class ITALExpressionEngine(Interface): """Render-time interface provided by a TAL expression implementation. The TAL interpreter uses this interface to TAL expression to support evaluation of the compiled expressions returned by :meth:`ITALExpressionCompiler.compile`. """ def getDefault(): """Return the value of the ``default`` TAL expression. Checking a value for a match with ``default`` should be done using the ``is`` operator in Python. """ def setPosition(position): """Inform the engine of the current position in the source file. *position* is a tuple (lineno, offset). This is used to allow the evaluation engine to report execution errors so that site developers can more easily locate the offending expression. """ def setSourceFile(filename): """Inform the engine of the name of the current source file. This is used to allow the evaluation engine to report execution errors so that site developers can more easily locate the offending expression. """ def beginScope(): """Push a new scope onto the stack of open scopes. """ def endScope(): """Pop one scope from the stack of open scopes. """ def evaluate(compiled_expression): """Evaluate an arbitrary expression. No constraints are imposed on the return value. """ def evaluateBoolean(compiled_expression): """Evaluate an expression that must return a Boolean value. """ def evaluateMacro(compiled_expression): """Evaluate an expression that must return a macro program. """ def evaluateStructure(compiled_expression): """Evaluate an expression that must return a structured document fragment. The result of evaluating *compiled_expression* must be a string containing a parsable HTML or XML fragment. Any TAL markup contained in the result string will be interpreted. """ def evaluateText(compiled_expression): """Evaluate an expression that must return text. The returned text should be suitable for direct inclusion in the output: any HTML or XML escaping or quoting is the responsibility of the expression itself. If the expression evaluates to None, then that is returned. It represents ``nothing`` in TALES. If the expression evaluates to what :meth:`getDefault()` returns, by comparison using ``is``, then that is returned. It represents ``default`` in TALES. """ def evaluateValue(compiled_expression): """Evaluate an arbitrary expression. No constraints are imposed on the return value. """ def createErrorInfo(exception, position): """Returns an :class:`ITALExpressionErrorInfo` object. *position* is a tuple (lineno, offset). The returned object is used to provide information about the error condition for the on-error handler. """ def setGlobal(name, value): """Set a global variable. The variable will be named *name* and have the value *value*. """ def setLocal(name, value): """Set a local variable in the current scope. The variable will be named *name* and have the value *value*. """ def getValue(name, default=None): """Get a variable by name. If the variable does not exist, return default. """ def setRepeat(name, compiled_expression): """Start a repetition, returning an :class:`ITALIterator`. The engine is expected to add the a value (typically the returned iterator) for the name to the variable namespace. """ def translate(msgid, domain=None, mapping=None, default=None): """See zope.i18n.interfaces.ITranslationDomain.translate""" # NB: This differs from the Zope 2 equivalent in the order of # the arguments. This will be a (hopefully minor) issue when # creating a unified TAL implementation. def evaluateCode(lang, code): """Evaluates code of the given language. Returns whatever the code outputs. This can be defined on a per-language basis. In Python this usually everything the print statement will return. """ class ITALIterator(Interface): """A TAL iterator Not to be confused with a Python iterator. """ def next(): """Advance to the next value in the iteration, if possible Return a true value if it was possible to advance and return a false value otherwise. """ class ITALExpressionErrorInfo(Interface): """Information about an error.""" type = Attribute("type", "The exception class.") value = Attribute("value", "The exception instance.") lineno = Attribute("lineno", "The line number the error occurred on in the source.") offset = Attribute("offset", "The character offset at which the error occurred.")
zope.tal
/zope.tal-5.0.1.tar.gz/zope.tal-5.0.1/src/zope/tal/interfaces.py
interfaces.py
"""Interpreter for a pre-compiled TAL program. """ import html import sys from zope.i18nmessageid import Message from zope.tal.taldefs import TAL_VERSION from zope.tal.taldefs import METALError from zope.tal.taldefs import getProgramMode from zope.tal.taldefs import getProgramVersion from zope.tal.taldefs import isCurrentVersion from zope.tal.taldefs import quote from zope.tal.talgenerator import TALGenerator from zope.tal.translationcontext import TranslationContext # Avoid constructing this tuple over and over I18nMessageTypes = (Message,) TypesToTranslate = I18nMessageTypes + (str, ) BOOLEAN_HTML_ATTRS = frozenset([ # List of Boolean attributes in HTML that should be rendered in # minimized form (e.g. <img ismap> rather than <img ismap="">) # From http://www.w3.org/TR/xhtml1/#guidelines (C.10) # TODO: The problem with this is that this is not valid XML and # can't be parsed back! # XXX: This is an exact duplicate of htmltalparser.BOOLEAN_HTML_ATTRS. Why? "compact", "nowrap", "ismap", "declare", "noshade", "checked", "disabled", "readonly", "multiple", "selected", "noresize", "defer" ]) _nulljoin = ''.join _spacejoin = ' '.join def normalize(text): # Now we need to normalize the whitespace in implicit message ids and # implicit $name substitution values by stripping leading and trailing # whitespace, and folding all internal whitespace to a single space. return _spacejoin(text.split()) class AltTALGenerator(TALGenerator): def __init__(self, repldict, expressionCompiler=None, xml=0): self.repldict = repldict self.enabled = 1 TALGenerator.__init__(self, expressionCompiler, xml) def enable(self, enabled): self.enabled = enabled def emit(self, *args): if self.enabled: TALGenerator.emit(self, *args) def emitStartElement(self, name, attrlist, taldict, metaldict, i18ndict, position=(None, None), isend=0): metaldict = {} taldict = {} i18ndict = {} if self.enabled and self.repldict: taldict["attributes"] = "x x" TALGenerator.emitStartElement(self, name, attrlist, taldict, metaldict, i18ndict, position, isend) def replaceAttrs(self, attrlist, repldict): if self.enabled and self.repldict: repldict = self.repldict self.repldict = None return TALGenerator.replaceAttrs(self, attrlist, repldict) class MacroStackItem(list): # This is a `list` subclass for backward compatibility. """Stack entry for the TALInterpreter.macroStack. This offers convenience attributes for more readable access. """ __slots__ = () @property def macroName(self): return self[0] @property def slots(self): return self[1] @property def definingName(self): return self[2] @property def extending(self): return self[3] @property def entering(self): return self[4] @entering.setter def entering(self, value): self[4] = value @property def i18nContext(self): return self[5] class TALInterpreter: """TAL interpreter. Some notes on source annotations. They are HTML/XML comments added to the output whenever ``sourceFile`` is changed by a ``setSourceFile`` bytecode. Source annotations are disabled by default, but you can turn them on by passing a ``sourceAnnotations`` argument to the constructor. You can change the format of the annotations by overriding formatSourceAnnotation in a subclass. The output of the annotation is delayed until some actual text is output for two reasons: 1. ``setPosition`` bytecode follows ``setSourceFile``, and we need position information to output the line number. 2. Comments are not allowed in XML documents before the ``<?xml?>`` declaration. For performance reasons (TODO: premature optimization?) instead of checking the value of ``_pending_source_annotation`` on every write to the output stream, the ``_stream_write`` attribute is changed to point to ``_annotated_stream_write`` method whenever ``_pending_source_annotation`` is set to True, and to _stream.write when it is False. The following invariant always holds:: if self._pending_source_annotation: assert self._stream_write is self._annotated_stream_write else: assert self._stream_write is self.stream.write """ def __init__(self, program, macros, engine, stream=None, debug=0, wrap=1023, metal=1, tal=1, showtal=-1, strictinsert=1, stackLimit=100, i18nInterpolate=1, sourceAnnotations=0): """Create a TAL interpreter. :param program: A compiled program, as generated by :class:`zope.tal.talgenerator.TALGenerator` :param macros: Namespace of macros, usually also from :class:`~.TALGenerator` Optional arguments: :keyword stream: output stream (defaults to sys.stdout). :keyword bool debug: enable debugging output to sys.stderr (off by default). :keyword int wrap: try to wrap attributes on opening tags to this number of column (default: 1023). :keyword bool metal: enable METAL macro processing (on by default). :keyword bool tal: enable TAL processing (on by default). :keyword int showtal: do not strip away TAL directives. A special value of -1 (which is the default setting) enables showtal when TAL processing is disabled, and disables showtal when TAL processing is enabled. Note that you must use 0, 1, or -1; true boolean values are not supported (for historical reasons). :keyword bool strictinsert: enable TAL processing and stricter HTML/XML checking on text produced by structure inserts (on by default). Note that Zope turns this value off by default. :keyword int stackLimit: set macro nesting limit (default: 100). :keyword bool i18nInterpolate: enable i18n translations (default: on). :keyword bool sourceAnnotations: enable source annotations with HTML comments (default: off). """ self.program = program self.macros = macros self.engine = engine # Execution engine (aka context) self.Default = engine.getDefault() self._pending_source_annotation = False self._currentTag = "" self._stream_stack = [stream or sys.stdout] self.popStream() self.debug = debug self.wrap = wrap self.metal = metal self.tal = tal if tal: self.dispatch = self.bytecode_handlers_tal else: self.dispatch = self.bytecode_handlers assert showtal in (-1, 0, 1) if showtal == -1: showtal = (not tal) self.showtal = showtal self.strictinsert = strictinsert self.stackLimit = stackLimit self.html = 0 self.endsep = "/>" self.endlen = len(self.endsep) # macroStack entries are MacroStackItem instances; # the entries are mutated while on the stack self.macroStack = [] # `inUseDirective` is set iff we're handling either a # metal:use-macro or a metal:extend-macro self.inUseDirective = False self.position = None, None # (lineno, offset) self.col = 0 self.level = 0 self.scopeLevel = 0 self.sourceFile = None self.i18nStack = [] self.i18nInterpolate = i18nInterpolate self.i18nContext = TranslationContext() self.sourceAnnotations = sourceAnnotations def StringIO(self): # Third-party products wishing to provide a full text-aware # StringIO can do so by monkey-patching this method. return FasterStringIO() def saveState(self): return (self.position, self.col, self.stream, self._stream_stack, self.scopeLevel, self.level, self.i18nContext) def restoreState(self, state): (self.position, self.col, self.stream, self._stream_stack, scopeLevel, level, i18n) = state if self._pending_source_annotation: self._stream_write = self._annotated_stream_write else: self._stream_write = self.stream.write assert self.level == level while self.scopeLevel > scopeLevel: self.engine.endScope() self.scopeLevel = self.scopeLevel - 1 self.engine.setPosition(self.position) self.i18nContext = i18n def restoreOutputState(self, state): (dummy, self.col, self.stream, self._stream_stack, scopeLevel, level, i18n) = state if self._pending_source_annotation: self._stream_write = self._annotated_stream_write else: self._stream_write = self.stream.write assert self.level == level assert self.scopeLevel == scopeLevel def pushMacro(self, macroName, slots, definingName, extending): if len(self.macroStack) >= self.stackLimit: raise METALError("macro nesting limit (%d) exceeded " "by %s" % (self.stackLimit, repr(macroName))) self.macroStack.append( MacroStackItem((macroName, slots, definingName, extending, True, self.i18nContext))) def popMacro(self): return self.macroStack.pop() def __call__(self): """ Interpret the current program. :return: Nothing. """ assert self.level == 0 assert self.scopeLevel == 0 assert self.i18nContext.parent is None self.interpret(self.program) assert self.level == 0 assert self.scopeLevel == 0 assert self.i18nContext.parent is None def pushStream(self, newstream): self._stream_stack.append(self.stream) self.stream = newstream if self._pending_source_annotation: self._stream_write = self._annotated_stream_write else: self._stream_write = self.stream.write def popStream(self): self.stream = self._stream_stack.pop() if self._pending_source_annotation: self._stream_write = self._annotated_stream_write else: self._stream_write = self.stream.write def _annotated_stream_write(self, s): idx = s.find('<?xml') if idx >= 0 or s.isspace(): # Do not preprend comments in front of the <?xml?> declaration. end_of_doctype = s.find('?>', idx) if end_of_doctype > idx: self.stream.write(s[:end_of_doctype + 2]) s = s[end_of_doctype + 2:] # continue else: self.stream.write(s) return self._pending_source_annotation = False self._stream_write = self.stream.write self._stream_write(self.formatSourceAnnotation()) self._stream_write(s) def formatSourceAnnotation(self): lineno = self.position[0] if lineno is None: location = self.sourceFile else: location = '{} (line {})'.format(self.sourceFile, lineno) sep = '=' * 78 return '<!--\n{}\n{}\n{}\n-->'.format(sep, location, sep) def stream_write(self, s, len=len): self._stream_write(s) i = s.rfind('\n') if i < 0: self.col = self.col + len(s) else: self.col = len(s) - (i + 1) bytecode_handlers = {} def interpret(self, program): oldlevel = self.level self.level = oldlevel + 1 handlers = self.dispatch try: if self.debug: for (opcode, args) in program: s = "{}do_{}({})\n".format(" " * self.level, opcode, repr(args)) if len(s) > 80: s = s[:76] + "...\n" sys.stderr.write(s) handlers[opcode](self, args) else: for (opcode, args) in program: handlers[opcode](self, args) finally: self.level = oldlevel def do_version(self, version): assert version == TAL_VERSION bytecode_handlers["version"] = do_version def do_mode(self, mode): assert mode in ("html", "xml") self.html = (mode == "html") if self.html: self.endsep = " />" else: self.endsep = "/>" self.endlen = len(self.endsep) bytecode_handlers["mode"] = do_mode def do_setSourceFile(self, source_file): self.sourceFile = source_file self.engine.setSourceFile(source_file) if self.sourceAnnotations: self._pending_source_annotation = True self._stream_write = self._annotated_stream_write bytecode_handlers["setSourceFile"] = do_setSourceFile def do_setPosition(self, position): self.position = position self.engine.setPosition(position) bytecode_handlers["setPosition"] = do_setPosition def do_startEndTag(self, stuff): self.do_startTag(stuff, self.endsep, self.endlen) bytecode_handlers["startEndTag"] = do_startEndTag def do_startTag(self, stuff, end=">", endlen=1, _len=len): # The bytecode generator does not cause calls to this method # for start tags with no attributes; those are optimized down # to rawtext events. Hence, there is no special "fast path" # for that case. (name, attrList) = stuff self._currentTag = name L = ["<", name] append = L.append col = self.col + _len(name) + 1 wrap = self.wrap align = col + 1 if align >= wrap / 2: align = 4 # Avoid a narrow column far to the right attrAction = self.dispatch["<attrAction>"] try: for item in attrList: if _len(item) == 2: rendered = item[1:] else: # item[2] is the 'action' field: if item[2] in ('metal', 'tal', 'xmlns', 'i18n'): if not self.showtal: continue rendered = self.attrAction(item) else: rendered = attrAction(self, item) if not rendered: continue for s in rendered: slen = _len(s) if (wrap and col >= align and col + 1 + slen > wrap): append("\n") append(" " * align) col = align + slen else: append(" ") col = col + 1 + slen append(s) append(end) col = col + endlen finally: self._stream_write(_nulljoin(L)) self.col = col bytecode_handlers["startTag"] = do_startTag def attrAction(self, item): name, value, action = item[:3] if action == 'insert': return () macs = self.macroStack if action == 'metal' and self.metal and macs: # Drop all METAL attributes at a use-depth beyond the first # use-macro and its extensions if len(macs) > 1: for macro in macs[1:]: if not macro.extending: return () if not macs[-1].entering: return () macs[-1].entering = False # Convert or drop depth-one METAL attributes. i = name.rfind(":") + 1 prefix, suffix = name[:i], name[i:] if suffix == "define-macro": # Convert define-macro as we enter depth one. useName = macs[0].macroName defName = macs[0].definingName res = [] if defName: res.append( '{}define-macro={}'.format(prefix, quote(defName))) if useName: res.append('{}use-macro={}'.format(prefix, quote(useName))) return res elif suffix == "define-slot": name = prefix + "fill-slot" elif suffix == "fill-slot": pass else: return () if value is None: value = name else: value = "{}={}".format(name, quote(value)) return [value] def attrAction_tal(self, item): name, value, action = item[:3] ok = 1 expr, xlat, msgid = item[3:] if self.html and name.lower() in BOOLEAN_HTML_ATTRS: evalue = self.engine.evaluateBoolean(item[3]) if evalue is self.Default: if action == 'insert': # Cancelled insert ok = 0 elif evalue: value = None else: ok = 0 elif expr is not None: evalue = self.engine.evaluateText(item[3]) if evalue is self.Default: if action == 'insert': # Cancelled insert ok = 0 else: if evalue is None: ok = 0 value = evalue if ok: if xlat: translated = self.translate(msgid or value, value) if translated is not None: value = translated elif isinstance(value, I18nMessageTypes): translated = self.translate(value) if translated is not None: value = translated if value is None: value = name return ["{}={}".format(name, quote(value))] else: return () bytecode_handlers["<attrAction>"] = attrAction def no_tag(self, start, program): state = self.saveState() self.stream = stream = self.StringIO() self._stream_write = stream.write self.interpret(start) self.restoreOutputState(state) self.interpret(program) def do_optTag(self, stuff, omit=0): (name, cexpr, tag_ns, isend, start, program) = stuff if tag_ns and not self.showtal: return self.no_tag(start, program) self.interpret(start) if not isend: self.interpret(program) s = '</%s>' % name self._stream_write(s) self.col = self.col + len(s) def do_optTag_tal(self, stuff): cexpr = stuff[1] if cexpr is not None and (cexpr == '' or self.engine.evaluateBoolean(cexpr)): self.no_tag(stuff[-2], stuff[-1]) else: self.do_optTag(stuff) bytecode_handlers["optTag"] = do_optTag def do_rawtextBeginScope(self, stuff): (s, col, position, closeprev, dict) = stuff self._stream_write(s) self.col = col self.do_setPosition(position) if closeprev: engine = self.engine engine.endScope() engine.beginScope() else: self.engine.beginScope() self.scopeLevel = self.scopeLevel + 1 def do_rawtextBeginScope_tal(self, stuff): (s, col, position, closeprev, dict) = stuff self._stream_write(s) self.col = col engine = self.engine self.position = position engine.setPosition(position) if closeprev: engine.endScope() engine.beginScope() else: engine.beginScope() self.scopeLevel = self.scopeLevel + 1 engine.setLocal("attrs", dict) bytecode_handlers["rawtextBeginScope"] = do_rawtextBeginScope def do_beginScope(self, dict): self.engine.beginScope() self.scopeLevel = self.scopeLevel + 1 def do_beginScope_tal(self, dict): engine = self.engine engine.beginScope() engine.setLocal("attrs", dict) self.scopeLevel = self.scopeLevel + 1 bytecode_handlers["beginScope"] = do_beginScope def do_endScope(self, notused=None): self.engine.endScope() self.scopeLevel = self.scopeLevel - 1 bytecode_handlers["endScope"] = do_endScope def do_setLocal(self, notused): pass def do_setLocal_tal(self, stuff): (name, expr) = stuff self.engine.setLocal(name, self.engine.evaluateValue(expr)) bytecode_handlers["setLocal"] = do_setLocal def do_setGlobal_tal(self, stuff): (name, expr) = stuff self.engine.setGlobal(name, self.engine.evaluateValue(expr)) bytecode_handlers["setGlobal"] = do_setLocal def do_beginI18nContext(self, settings): get = settings.get self.i18nContext = TranslationContext(self.i18nContext, domain=get("domain"), source=get("source"), target=get("target")) bytecode_handlers["beginI18nContext"] = do_beginI18nContext def do_endI18nContext(self, notused=None): self.i18nContext = self.i18nContext.parent assert self.i18nContext is not None bytecode_handlers["endI18nContext"] = do_endI18nContext def do_insertText(self, stuff): self.interpret(stuff[1]) bytecode_handlers["insertText"] = do_insertText bytecode_handlers["insertI18nText"] = do_insertText def _writeText(self, text): # '&' must be done first! s = text.replace( "&", "&amp;").replace("<", "&lt;").replace(">", "&gt;") self._stream_write(s) i = s.rfind('\n') if i < 0: self.col += len(s) else: self.col = len(s) - (i + 1) def do_insertText_tal(self, stuff): text = self.engine.evaluateText(stuff[0]) if text is None: return if text is self.Default: self.interpret(stuff[1]) return if isinstance(text, I18nMessageTypes): # Translate this now. text = self.translate(text) self._writeText(text) def do_insertI18nText_tal(self, stuff): # TODO: Code duplication is BAD, we need to fix it later text = self.engine.evaluateText(stuff[0]) if text is not None: if text is self.Default: self.interpret(stuff[1]) else: if isinstance(text, TypesToTranslate): text = self.translate(text) self._writeText(text) def do_i18nVariable(self, stuff): varname, program, expression, structure = stuff if expression is None: # The value is implicitly the contents of this tag, so we have to # evaluate the mini-program to get the value of the variable. state = self.saveState() try: tmpstream = self.StringIO() self.pushStream(tmpstream) try: self.interpret(program) finally: self.popStream() if self.html and self._currentTag == "pre": value = tmpstream.getvalue() else: value = normalize(tmpstream.getvalue()) finally: self.restoreState(state) else: # TODO: Seems like this branch not used anymore, we # need to remove it # Evaluate the value to be associated with the variable in the # i18n interpolation dictionary. if structure: value = self.engine.evaluateStructure(expression) else: value = self.engine.evaluate(expression) # evaluate() does not do any I18n, so we do it here. if isinstance(value, I18nMessageTypes): # Translate this now. value = self.translate(value) if not structure: value = html.escape(str(value)) # Either the i18n:name tag is nested inside an i18n:translate in which # case the last item on the stack has the i18n dictionary and string # representation, or the i18n:name and i18n:translate attributes are # in the same tag, in which case the i18nStack will be empty. In that # case we can just output the ${name} to the stream i18ndict, srepr = self.i18nStack[-1] i18ndict[varname] = value placeholder = '${%s}' % varname srepr.append(placeholder) self._stream_write(placeholder) bytecode_handlers['i18nVariable'] = do_i18nVariable def do_insertTranslation(self, stuff): i18ndict = {} srepr = [] obj = None self.i18nStack.append((i18ndict, srepr)) msgid = stuff[0] # We need to evaluate the content of the tag because that will give us # several useful pieces of information. First, the contents will # include an implicit message id, if no explicit one was given. # Second, it will evaluate any i18nVariable definitions in the body of # the translation (necessary for $varname substitutions). # # Use a temporary stream to capture the interpretation of the # subnodes, which should /not/ go to the output stream. currentTag = self._currentTag tmpstream = self.StringIO() self.pushStream(tmpstream) try: self.interpret(stuff[1]) finally: self.popStream() # We only care about the evaluated contents if we need an implicit # message id. All other useful information will be in the i18ndict on # the top of the i18nStack. default = tmpstream.getvalue() if not msgid: if self.html and currentTag == "pre": msgid = default else: msgid = normalize(default) self.i18nStack.pop() # See if there is was an i18n:data for msgid if len(stuff) > 2: obj = self.engine.evaluate(stuff[2]) xlated_msgid = self.translate(msgid, default, i18ndict, obj) # TODO: I can't decide whether we want to html.escape the translated # string or not. OTOH not doing this could introduce a cross-site # scripting vector by allowing translators to sneak JavaScript into # translations. OTOH, for implicit interpolation values, we don't # want to escape stuff like ${name} <= "<b>Timmy</b>". assert xlated_msgid is not None self._stream_write(xlated_msgid) bytecode_handlers['insertTranslation'] = do_insertTranslation def do_insertStructure(self, stuff): self.interpret(stuff[2]) bytecode_handlers["insertStructure"] = do_insertStructure bytecode_handlers["insertI18nStructure"] = do_insertStructure def do_insertStructure_tal(self, stuff): (expr, repldict, block) = stuff structure = self.engine.evaluateStructure(expr) if structure is None: return if structure is self.Default: self.interpret(block) return if isinstance(structure, I18nMessageTypes): text = self.translate(structure) else: text = str(structure) if not (repldict or self.strictinsert): # Take a shortcut, no error checking self.stream_write(text) return if self.html: self.insertHTMLStructure(text, repldict) else: self.insertXMLStructure(text, repldict) def do_insertI18nStructure_tal(self, stuff): # TODO: Code duplication is BAD, we need to fix it later (expr, repldict, block) = stuff structure = self.engine.evaluateStructure(expr) if structure is not None: if structure is self.Default: self.interpret(block) else: if not isinstance(structure, TypesToTranslate): structure = str(structure) text = self.translate(structure) if not (repldict or self.strictinsert): # Take a shortcut, no error checking self.stream_write(text) elif self.html: self.insertHTMLStructure(text, repldict) else: self.insertXMLStructure(text, repldict) def insertHTMLStructure(self, text, repldict): from zope.tal.htmltalparser import HTMLTALParser gen = AltTALGenerator(repldict, self.engine, 0) p = HTMLTALParser(gen) # Raises an exception if text is invalid p.parseString(text) program, macros = p.getCode() self.interpret(program) def insertXMLStructure(self, text, repldict): from zope.tal.talparser import TALParser gen = AltTALGenerator(repldict, self.engine, 0) p = TALParser(gen) gen.enable(0) p.parseFragment('<!DOCTYPE foo PUBLIC "foo" "bar"><foo>') gen.enable(1) p.parseFragment(text) # Raises an exception if text is invalid gen.enable(0) p.parseFragment('</foo>', 1) program, macros = gen.getCode() self.interpret(program) def do_evaluateCode(self, stuff): lang, program = stuff # Use a temporary stream to capture the interpretation of the # subnodes, which should /not/ go to the output stream. tmpstream = self.StringIO() self.pushStream(tmpstream) try: self.interpret(program) finally: self.popStream() code = tmpstream.getvalue() output = self.engine.evaluateCode(lang, code) self._stream_write(output) bytecode_handlers["evaluateCode"] = do_evaluateCode def do_loop(self, stuff): (name, expr, block) = stuff self.interpret(block) def do_loop_tal(self, stuff): (name, expr, block) = stuff iterator = self.engine.setRepeat(name, expr) while next(iterator): self.interpret(block) bytecode_handlers["loop"] = do_loop def translate(self, msgid, default=None, i18ndict=None, obj=None, domain=None): if default is None: default = getattr(msgid, 'default', str(msgid)) if i18ndict is None: i18ndict = {} if domain is None: domain = getattr(msgid, 'domain', self.i18nContext.domain) if obj: i18ndict.update(obj) if not self.i18nInterpolate: return msgid # TODO: We need to pass in one of context or target_language return self.engine.translate(msgid, self.i18nContext.domain, i18ndict, default=default) def do_rawtextColumn(self, stuff): (s, col) = stuff self._stream_write(s) self.col = col bytecode_handlers["rawtextColumn"] = do_rawtextColumn def do_rawtextOffset(self, stuff): (s, offset) = stuff self._stream_write(s) self.col = self.col + offset bytecode_handlers["rawtextOffset"] = do_rawtextOffset def do_condition(self, stuff): (condition, block) = stuff if not self.tal or self.engine.evaluateBoolean(condition): self.interpret(block) bytecode_handlers["condition"] = do_condition def do_defineMacro(self, stuff): (macroName, macro) = stuff wasInUse = self.inUseDirective self.inUseDirective = False self.interpret(macro) self.inUseDirective = wasInUse bytecode_handlers["defineMacro"] = do_defineMacro def do_useMacro(self, stuff, definingName=None, extending=False): (macroName, macroExpr, compiledSlots, block) = stuff if not self.metal: self.interpret(block) return macro = self.engine.evaluateMacro(macroExpr) if macro is self.Default: macro = block else: if not isCurrentVersion(macro): raise METALError( "macro %s has incompatible version %s" % (repr(macroName), repr( getProgramVersion(macro))), self.position) mode = getProgramMode(macro) if mode != (self.html and "html" or "xml"): raise METALError("macro %s has incompatible mode %s" % (repr(macroName), repr(mode)), self.position) self.pushMacro(macroName, compiledSlots, definingName, extending) # We want 'macroname' name to be always available as a variable outer = self.engine.getValue('macroname') self.engine.setLocal('macroname', macroName.rsplit('/', 1)[-1]) prev_source = self.sourceFile wasInUse = self.inUseDirective self.inUseDirective = True self.interpret(macro) self.inUseDirective = wasInUse if self.sourceFile != prev_source: self.engine.setSourceFile(prev_source) self.sourceFile = prev_source self.popMacro() # Push the outer macroname again. self.engine.setLocal('macroname', outer) bytecode_handlers["useMacro"] = do_useMacro def do_extendMacro(self, stuff): # extendMacro results from a combination of define-macro and # use-macro. definingName has the value of the # metal:define-macro attribute. (macroName, macroExpr, compiledSlots, block, definingName) = stuff extending = self.metal and self.inUseDirective self.do_useMacro((macroName, macroExpr, compiledSlots, block), definingName, extending) bytecode_handlers["extendMacro"] = do_extendMacro def do_fillSlot(self, stuff): # This is only executed if the enclosing 'use-macro' evaluates # to 'default'. (slotName, block) = stuff self.interpret(block) bytecode_handlers["fillSlot"] = do_fillSlot def do_defineSlot(self, stuff): (slotName, block) = stuff if not self.metal: self.interpret(block) return macs = self.macroStack if macs: len_macs = len(macs) # Measure the extension depth of this use-macro depth = 1 while depth < len_macs: if macs[-depth].extending: depth += 1 else: break # Search for a slot filler from the most specific to the # most general macro. The most general is at the top of # the stack. slot = None i = len_macs - 1 while i >= (len_macs - depth): slot = macs[i].slots.get(slotName) if slot is not None: break i -= 1 if slot is not None: # Found a slot filler. Temporarily chop the macro # stack starting at the macro that filled the slot and # render the slot filler. chopped = macs[i:] del macs[i:] try: self.interpret(slot) finally: # Restore the stack entries. for mac in chopped: mac.entering = False # Not entering macs.extend(chopped) return # Falling out of the 'if' allows the macro to be interpreted. self.interpret(block) bytecode_handlers["defineSlot"] = do_defineSlot def do_onError(self, stuff): (block, handler) = stuff self.interpret(block) def do_onError_tal(self, stuff): (block, handler) = stuff state = self.saveState() self.stream = stream = self.StringIO() self._stream_write = stream.write try: self.interpret(block) # TODO: this should not catch ZODB.POSException.ConflictError. # The ITALExpressionEngine interface should provide a way of # getting the set of exception types that should not be # handled. except BaseException: exc = sys.exc_info()[1] try: self.restoreState(state) engine = self.engine engine.beginScope() error = engine.createErrorInfo(exc, self.position) finally: # Avoid traceback reference cycle due to the __traceback__ # attribute. del exc engine.setLocal('error', error) try: self.interpret(handler) finally: engine.endScope() else: self.restoreOutputState(state) self.stream_write(stream.getvalue()) bytecode_handlers["onError"] = do_onError bytecode_handlers_tal = bytecode_handlers.copy() bytecode_handlers_tal["rawtextBeginScope"] = do_rawtextBeginScope_tal bytecode_handlers_tal["beginScope"] = do_beginScope_tal bytecode_handlers_tal["setLocal"] = do_setLocal_tal bytecode_handlers_tal["setGlobal"] = do_setGlobal_tal bytecode_handlers_tal["insertStructure"] = do_insertStructure_tal bytecode_handlers_tal["insertI18nStructure"] = do_insertI18nStructure_tal bytecode_handlers_tal["insertText"] = do_insertText_tal bytecode_handlers_tal["insertI18nText"] = do_insertI18nText_tal bytecode_handlers_tal["loop"] = do_loop_tal bytecode_handlers_tal["onError"] = do_onError_tal bytecode_handlers_tal["<attrAction>"] = attrAction_tal bytecode_handlers_tal["optTag"] = do_optTag_tal class FasterStringIO(list): # text-aware append-only version of StringIO. write = list.append def __init__(self, value=None): list.__init__(self) if value is not None: self.append(value) def getvalue(self): return ''.join(self) def _write_ValueError(s): raise ValueError("I/O operation on closed file")
zope.tal
/zope.tal-5.0.1.tar.gz/zope.tal-5.0.1/src/zope/tal/talinterpreter.py
talinterpreter.py
"""Dummy TAL expression engine so that I can test out the TAL implementation. """ import re from io import StringIO from zope.i18nmessageid import Message from zope.interface import implementer from zope.tal.interfaces import ITALExpressionCompiler from zope.tal.interfaces import ITALExpressionEngine from zope.tal.taldefs import NAME_RE from zope.tal.taldefs import ErrorInfo from zope.tal.taldefs import TALExpressionError Default = object() name_match = re.compile(r"(?s)(%s):(.*)\Z" % NAME_RE).match class CompilerError(Exception): pass @implementer(ITALExpressionCompiler, ITALExpressionEngine) class DummyEngine: position = None source_file = None def __init__(self, macros=None): if macros is None: macros = {} self.macros = macros dict = {'nothing': None, 'default': Default} self.locals = self.globals = dict self.stack = [dict] self.translationDomain = DummyTranslationDomain() self.useEngineAttrDicts = False # zope.tal.interfaces.ITALExpressionCompiler def getCompilerError(self): return CompilerError def compile(self, expr): return "$%s$" % expr # zope.tal.interfaces.ITALExpressionEngine def setSourceFile(self, source_file): self.source_file = source_file def setPosition(self, position): self.position = position def beginScope(self): self.stack.append(self.locals) def endScope(self): assert len(self.stack) > 1, "more endScope() than beginScope() calls" self.locals = self.stack.pop() def setLocal(self, name, value): if self.locals is self.stack[-1]: # Unmerge this scope's locals from previous scope of first set self.locals = self.locals.copy() self.locals[name] = value def setGlobal(self, name, value): self.globals[name] = value def getValue(self, name, default=None): value = self.globals.get(name, default) if value is default: value = self.locals.get(name, default) return value def evaluate(self, expression): assert expression.startswith("$") and expression.endswith("$"), \ expression expression = expression[1:-1] m = name_match(expression) if m: type, expr = m.group(1, 2) else: type = "path" expr = expression if type in ("string", "str"): return expr if type in ("path", "var", "global", "local"): return self.evaluatePathOrVar(expr) if type == "not": return not self.evaluate(expr) if type == "exists": return expr in self.locals or expr in self.globals if type == "python": try: return eval(expr, self.globals, self.locals) except BaseException: raise TALExpressionError("evaluation error in %s" % repr(expr)) if type == "position": # Insert the current source file name, line number, # and column offset. if self.position: lineno, offset = self.position else: lineno, offset = None, None return '{} ({},{})'.format(self.source_file, lineno, offset) raise TALExpressionError( "unrecognized expression: " + repr(expression)) # implementation; can be overridden def evaluatePathOrVar(self, expr): expr = expr.strip() if expr in self.locals: return self.locals[expr] elif expr in self.globals: return self.globals[expr] else: raise TALExpressionError("unknown variable: %s" % repr(expr)) def evaluateValue(self, expr): return self.evaluate(expr) def evaluateBoolean(self, expr): return self.evaluate(expr) def evaluateText(self, expr): text = self.evaluate(expr) if isinstance(text, (str, Message)): return text if text is not None and text is not Default: text = str(text) return text def evaluateStructure(self, expr): # TODO Should return None or a DOM tree return self.evaluate(expr) # implementation; can be overridden def evaluateSequence(self, expr): # TODO: Should return a sequence return self.evaluate(expr) def evaluateMacro(self, macroName): assert macroName.startswith("$") and macroName.endswith("$"), \ macroName macroName = macroName[1:-1] file, localName = self.findMacroFile(macroName) if not file: # Local macro macro = self.macros[localName] else: # External macro from . import driver program, macros = driver.compilefile(file) macro = macros.get(localName) if not macro: raise TALExpressionError("macro %s not found in file %s" % (localName, file)) return macro # internal def findMacroFile(self, macroName): if not macroName: raise TALExpressionError("empty macro name") i = macroName.rfind('/') if i < 0: # No slash -- must be a locally defined macro return None, macroName else: # Up to last slash is the filename fileName = macroName[:i] localName = macroName[i + 1:] return fileName, localName def setRepeat(self, name, expr): seq = self.evaluateSequence(expr) return Iterator(name, seq, self) def createErrorInfo(self, err, position): return ErrorInfo(err, position) def getDefault(self): return Default def translate(self, msgid, domain=None, mapping=None, default=None): self.translationDomain.domain = domain return self.translationDomain.translate( msgid, mapping, default=default) def evaluateCode(self, lang, code): # We probably implement too much, but I use the dummy engine to test # some of the issues that we will have. # For testing purposes only locals = {} globals = {} if self.useEngineAttrDicts: globals = self.globals.copy() locals = self.locals.copy() assert lang == 'text/server-python' import sys # Removing probable comments if code.strip().startswith('<!--') and code.strip().endswith('-->'): code = code.strip()[4:-3] # Prepare code. lines = code.split('\n') lines = [line for line in lines if line.strip() != ''] code = '\n'.join(lines) # This saves us from all indentation issues :) if code.startswith(' ') or code.startswith('\t'): code = 'if 1 == 1:\n' + code + '\n' tmp = sys.stdout sys.stdout = StringIO() try: exec(code, globals, locals) finally: result = sys.stdout sys.stdout = tmp # For testing purposes only self.codeLocals = locals self.codeGlobals = globals self.locals.update(locals) self.globals.update(globals) return result.getvalue() class Iterator: def __init__(self, name, seq, engine): self.name = name self.seq = seq self.engine = engine self.nextIndex = 0 def __next__(self): i = self.nextIndex try: item = self.seq[i] except IndexError: return 0 self.nextIndex = i + 1 self.engine.setLocal(self.name, item) return 1 class DummyTranslationDomain: domain = '' msgids = {} def appendMsgid(self, domain, data): if domain not in self.msgids: self.msgids[domain] = [] self.msgids[domain].append(data) def getMsgids(self, domain): return self.msgids[domain] def clearMsgids(self): self.msgids = {} def translate(self, msgid, mapping=None, context=None, target_language=None, default=None): domain = self.domain # This is a fake translation service which simply uppercases non # ${name} placeholder text in the message id. # # First, transform a string with ${name} placeholders into a list of # substrings. Then upcase everything but the placeholders, then glue # things back together. # If the domain is a string method, then transform the string # by calling that method. # MessageID attributes override arguments if isinstance(msgid, Message): domain = msgid.domain mapping = msgid.mapping default = msgid.default if default is None: # Message doesn't substitute itself for default = msgid # missing default # simulate an unknown msgid by returning None if msgid == "don't translate me": text = default elif domain and hasattr('', domain): text = getattr(msgid, domain)() else: domain = 'default' text = msgid.upper() self.appendMsgid(domain, (msgid, mapping)) def repl(m): return str(mapping[m.group(m.lastindex).lower()]) cre = re.compile(r'\$(?:([_A-Za-z][-\w]*)|\{([_A-Za-z][-\w]*)\})') return cre.sub(repl, text) class MultipleDomainsDummyEngine(DummyEngine): def translate(self, msgid, domain=None, mapping=None, default=None): if isinstance(msgid, Message): domain = msgid.domain if domain == 'a_very_explicit_domain_setup_by_template_developer_that_wont_be_taken_into_account_by_the_ZPT_engine': # noqa: E501 line too long domain = 'lower' self.translationDomain.domain = domain return self.translationDomain.translate( msgid, mapping, default=default)
zope.tal
/zope.tal-5.0.1.tar.gz/zope.tal-5.0.1/src/zope/tal/dummyengine.py
dummyengine.py
import optparse import os import sys # Import local classes import zope.tal.taldefs from zope.tal.dummyengine import DummyEngine from zope.tal.dummyengine import DummyTranslationDomain class TestTranslations(DummyTranslationDomain): def translate(self, msgid, mapping=None, context=None, target_language=None, default=None): if msgid == 'timefmt': return '%(minutes)s minutes after %(hours)s %(ampm)s' % mapping elif msgid == 'jobnum': return '%(jobnum)s is the JOB NUMBER' % mapping elif msgid == 'verify': s = 'Your contact email address is recorded as %(email)s' return s % mapping elif msgid == 'mailto:${request/submitter}': return 'mailto:[email protected]' elif msgid == 'origin': return '%(name)s was born in %(country)s' % mapping return DummyTranslationDomain.translate( self, msgid, mapping, context, target_language, default=default) class TestEngine(DummyEngine): def __init__(self, macros=None): DummyEngine.__init__(self, macros) self.translationDomain = TestTranslations() def evaluatePathOrVar(self, expr): if expr == 'here/currentTime': return {'hours': 6, 'minutes': 59, 'ampm': 'PM', } elif expr == 'context/@@object_name': return '7' elif expr == 'request/submitter': return '[email protected]' return DummyEngine.evaluatePathOrVar(self, expr) # This is a disgusting hack so that we can use engines that actually know # something about certain object paths. ENGINES = {'test23.html': TestEngine, 'test24.html': TestEngine, 'test26.html': TestEngine, 'test27.html': TestEngine, 'test28.html': TestEngine, 'test29.html': TestEngine, 'test30.html': TestEngine, 'test31.html': TestEngine, 'test32.html': TestEngine, } OPTIONS = [ optparse.make_option( '-H', '--html', action='store_const', const='html', dest='mode', help='explicitly choose HTML input (default: use file extension)'), optparse.make_option( '-x', '--xml', action='store_const', const='xml', dest='mode', help='explicitly choose XML input (default: use file extension)'), optparse.make_option('-l', '--lenient', action='store_true', help='lenient structure insertion'), # aka don't validate HTML/XML inserted by # tal:content="structure expr" optparse.make_option( '-m', '--macro-only', action='store_true', help='macro expansion only'), optparse.make_option( '-s', '--show-code', action='store_true', help='print intermediate opcodes only'), optparse.make_option( '-t', '--show-tal', action='store_true', help='leave TAL/METAL attributes in output'), optparse.make_option( '-i', '--show-i18n', action='store_true', help='leave I18N substitution string un-interpolated'), optparse.make_option( '-a', '--annotate', action='store_true', help='enable source annotations'), ] def main(values=None): parser = optparse.OptionParser('usage: %prog [options] testfile', description=__doc__, option_list=OPTIONS) opts, args = parser.parse_args(values=values) if not args: parser.print_help() sys.exit(1) if len(args) > 1: parser.error('Too many arguments') file = args[0] it = compilefile(file, opts.mode) if opts.show_code: showit(it) else: # See if we need a special engine for this test engine = None engineClass = ENGINES.get(os.path.basename(file)) if engineClass is not None: engine = engineClass(opts.macro_only) interpretit(it, engine=engine, tal=not opts.macro_only, showtal=1 if opts.show_tal else -1, strictinsert=not opts.lenient, i18nInterpolate=not opts.show_i18n, sourceAnnotations=opts.annotate) def interpretit(it, engine=None, stream=None, tal=1, showtal=-1, strictinsert=1, i18nInterpolate=1, sourceAnnotations=0): from zope.tal.talinterpreter import TALInterpreter program, macros = it assert zope.tal.taldefs.isCurrentVersion(program) if engine is None: engine = DummyEngine(macros) TALInterpreter(program, macros, engine, stream, wrap=0, tal=tal, showtal=showtal, strictinsert=strictinsert, i18nInterpolate=i18nInterpolate, sourceAnnotations=sourceAnnotations)() def compilefile(file, mode=None): assert mode in ("html", "xml", None) if mode is None: ext = os.path.splitext(file)[1] if ext.lower() in (".html", ".htm"): mode = "html" else: mode = "xml" # make sure we can find the file prefix = os.path.dirname(os.path.abspath(__file__)) + os.path.sep if (not os.path.exists(file) and os.path.exists(os.path.join(prefix, file))): file = os.path.join(prefix, file) # normalize filenames for test output filename = os.path.abspath(file) if filename.startswith(prefix): filename = filename[len(prefix):] filename = filename.replace(os.sep, '/') # test files expect slashes # parse from zope.tal.talgenerator import TALGenerator if mode == "html": from zope.tal.htmltalparser import HTMLTALParser p = HTMLTALParser(gen=TALGenerator(source_file=filename, xml=0)) else: from zope.tal.talparser import TALParser p = TALParser(gen=TALGenerator(source_file=filename)) p.parseFile(file) return p.getCode() def showit(it): from pprint import pprint pprint(it) if __name__ == "__main__": main()
zope.tal
/zope.tal-5.0.1.tar.gz/zope.tal-5.0.1/src/zope/tal/driver.py
driver.py
import re from html import escape from zope.tal import taldefs from zope.tal.taldefs import NAME_RE from zope.tal.taldefs import TAL_VERSION from zope.tal.taldefs import I18NError from zope.tal.taldefs import METALError from zope.tal.taldefs import TALError from zope.tal.taldefs import parseSubstitution from zope.tal.translationcontext import DEFAULT_DOMAIN from zope.tal.translationcontext import TranslationContext _name_rx = re.compile(NAME_RE) class TALGenerator: """ Generate intermediate code. """ inMacroUse = 0 inMacroDef = 0 source_file = None def __init__(self, expressionCompiler=None, xml=1, source_file=None): """ :keyword expressionCompiler: The implementation of :class:`zope.tal.interfaces.ITALExpressionCompiler` to use. If not given, we'll use a simple, undocumented, compiler. """ if not expressionCompiler: from zope.tal.dummyengine import DummyEngine expressionCompiler = DummyEngine() self.expressionCompiler = expressionCompiler self.CompilerError = expressionCompiler.getCompilerError() # This holds the emitted opcodes representing the input self.program = [] # The program stack for when we need to do some sub-evaluation for an # intermediate result. E.g. in an i18n:name tag for which the # contents describe the ${name} value. self.stack = [] # Another stack of postponed actions. Elements on this stack are a # dictionary; key/values contain useful information that # emitEndElement needs to finish its calculations self.todoStack = [] self.macros = {} # {slot-name --> default content program} self.slots = {} self.slotStack = [] self.xml = xml # true --> XML, false --> HTML self.emit("version", TAL_VERSION) self.emit("mode", xml and "xml" or "html") if source_file is not None: self.source_file = source_file self.emit("setSourceFile", source_file) self.i18nContext = TranslationContext() self.i18nLevel = 0 def getCode(self): assert not self.stack assert not self.todoStack return self.optimize(self.program), self.macros def optimize(self, program): output = [] collect = [] cursor = 0 for cursor in range(len(program) + 1): try: item = program[cursor] except IndexError: item = (None, None) opcode = item[0] if opcode == "rawtext": collect.append(item[1]) continue if opcode == "endTag": collect.append("</%s>" % item[1]) continue if opcode == "startTag": if self.optimizeStartTag(collect, item[1], item[2], ">"): continue if opcode == "startEndTag": endsep = "/>" if self.xml else " />" if self.optimizeStartTag(collect, item[1], item[2], endsep): continue if opcode in ("beginScope", "endScope"): # Push *Scope instructions in front of any text instructions; # this allows text instructions separated only by *Scope # instructions to be joined together. output.append(self.optimizeArgsList(item)) continue if opcode == 'noop': # This is a spacer for end tags in the face of i18n:name # attributes. We can't let the optimizer collect immediately # following end tags into the same rawtextOffset. opcode = None pass text = "".join(collect) if text: i = text.rfind("\n") if i >= 0: i = len(text) - (i + 1) output.append(("rawtextColumn", (text, i))) else: output.append(("rawtextOffset", (text, len(text)))) if opcode is not None: output.append(self.optimizeArgsList(item)) collect = [] return self.optimizeCommonTriple(output) def optimizeArgsList(self, item): if len(item) == 2: return item else: return item[0], tuple(item[1:]) # These codes are used to indicate what sort of special actions # are needed for each special attribute. (Simple attributes don't # get action codes.) # # The special actions (which are modal) are handled by # TALInterpreter.attrAction() and .attrAction_tal(). # # Each attribute is represented by a tuple: # # (name, value) -- a simple name/value pair, with # no special processing # # (name, value, action, *extra) -- attribute with special # processing needs, action is a # code that indicates which # branch to take, and *extra # contains additional, # action-specific information # needed by the processing # def optimizeStartTag(self, collect, name, attrlist, end): # return true if the tag can be converted to plain text if not attrlist: collect.append("<{}{}".format(name, end)) return 1 opt = 1 new = ["<" + name] for i in range(len(attrlist)): item = attrlist[i] if len(item) > 2: opt = 0 name, value, action = item[:3] attrlist[i] = (name, value, action) + item[3:] else: if item[1] is None: s = item[0] else: s = '{}="{}"'.format(item[0], taldefs.attrEscape(item[1])) attrlist[i] = item[0], s new.append(" " + s) # if no non-optimizable attributes were found, convert to plain text if opt: new.append(end) collect.extend(new) return opt def optimizeCommonTriple(self, program): if len(program) < 3: return program output = program[:2] prev2, prev1 = output for item in program[2:]: if (item[0] == "beginScope" and prev1[0] == "setPosition" and prev2[0] == "rawtextColumn"): position = output.pop()[1] text, column = output.pop()[1] prev1 = None, None closeprev = 0 if output and output[-1][0] == "endScope": closeprev = 1 output.pop() item = ("rawtextBeginScope", (text, column, position, closeprev, item[1])) output.append(item) prev2 = prev1 prev1 = item return output def todoPush(self, todo): self.todoStack.append(todo) def todoPop(self): return self.todoStack.pop() def compileExpression(self, expr): try: return self.expressionCompiler.compile(expr) except self.CompilerError as err: raise TALError( '{} in expression {}'.format( err.args[0], repr(expr)), self.position) def pushProgram(self): self.stack.append(self.program) self.program = [] def popProgram(self): program = self.program self.program = self.stack.pop() return self.optimize(program) def pushSlots(self): self.slotStack.append(self.slots) self.slots = {} def popSlots(self): slots = self.slots self.slots = self.slotStack.pop() return slots def emit(self, *instruction): self.program.append(instruction) def emitStartTag(self, name, attrlist, isend=0): if isend: opcode = "startEndTag" else: opcode = "startTag" self.emit(opcode, name, attrlist) def emitEndTag(self, name): if self.xml and self.program and self.program[-1][0] == "startTag": # Minimize empty element self.program[-1] = ("startEndTag",) + self.program[-1][1:] else: self.emit("endTag", name) def emitOptTag(self, name, optTag, isend): program = self.popProgram() # block start = self.popProgram() # start tag if (isend or not program) and self.xml: # Minimize empty element start[-1] = ("startEndTag",) + start[-1][1:] isend = 1 cexpr = optTag[0] if cexpr: cexpr = self.compileExpression(optTag[0]) self.emit("optTag", name, cexpr, optTag[1], isend, start, program) def emitRawText(self, text): self.emit("rawtext", text) def emitText(self, text): self.emitRawText(escape(text, False)) def emitDefines(self, defines): for part in taldefs.splitParts(defines): m = re.match( r"(?s)\s*(?:(global|local)\s+)?(%s)\s+(.*)\Z" % NAME_RE, part) if not m: raise TALError("invalid define syntax: " + repr(part), self.position) scope, name, expr = m.group(1, 2, 3) scope = scope or "local" cexpr = self.compileExpression(expr) if scope == "local": self.emit("setLocal", name, cexpr) else: self.emit("setGlobal", name, cexpr) def emitOnError(self, name, onError, TALtag, isend): block = self.popProgram() key, expr = parseSubstitution(onError) cexpr = self.compileExpression(expr) if key == "text": self.emit("insertText", cexpr, []) else: assert key == "structure" self.emit("insertStructure", cexpr, {}, []) if TALtag: self.emitOptTag(name, (None, 1), isend) else: self.emitEndTag(name) handler = self.popProgram() self.emit("onError", block, handler) def emitCondition(self, expr): cexpr = self.compileExpression(expr) program = self.popProgram() self.emit("condition", cexpr, program) def emitRepeat(self, arg): m = re.match(r"(?s)\s*(%s)\s+(.*)\Z" % NAME_RE, arg) if not m: raise TALError("invalid repeat syntax: " + repr(arg), self.position) name, expr = m.group(1, 2) cexpr = self.compileExpression(expr) program = self.popProgram() self.emit("loop", name, cexpr, program) def emitSubstitution(self, arg, attrDict={}): key, expr = parseSubstitution(arg) cexpr = self.compileExpression(expr) program = self.popProgram() if key == "text": self.emit("insertText", cexpr, program) else: assert key == "structure" self.emit("insertStructure", cexpr, attrDict, program) def emitI18nSubstitution(self, arg, attrDict={}): # TODO: Code duplication is BAD, we need to fix it later key, expr = parseSubstitution(arg) cexpr = self.compileExpression(expr) program = self.popProgram() if key == "text": self.emit("insertI18nText", cexpr, program) else: assert key == "structure" self.emit("insertI18nStructure", cexpr, attrDict, program) def emitEvaluateCode(self, lang): program = self.popProgram() self.emit('evaluateCode', lang, program) def emitI18nVariable(self, varname): # Used for i18n:name attributes. m = _name_rx.match(varname) if m is None or m.group() != varname: raise TALError("illegal i18n:name: %r" % varname, self.position) program = self.popProgram() self.emit('i18nVariable', varname, program, None, False) def emitTranslation(self, msgid, i18ndata): program = self.popProgram() if i18ndata is None: self.emit('insertTranslation', msgid, program) else: key, expr = parseSubstitution(i18ndata) cexpr = self.compileExpression(expr) assert key == 'text' self.emit('insertTranslation', msgid, program, cexpr) def emitDefineMacro(self, macroName): program = self.popProgram() macroName = macroName.strip() if macroName in self.macros: raise METALError( "duplicate macro definition: %s" % repr(macroName), self.position) if not re.match('%s$' % NAME_RE, macroName): raise METALError("invalid macro name: %s" % repr(macroName), self.position) self.macros[macroName] = program self.inMacroDef = self.inMacroDef - 1 self.emit("defineMacro", macroName, program) def emitUseMacro(self, expr): cexpr = self.compileExpression(expr) program = self.popProgram() self.inMacroUse = 0 self.emit("useMacro", expr, cexpr, self.popSlots(), program) def emitExtendMacro(self, defineName, useExpr): cexpr = self.compileExpression(useExpr) program = self.popProgram() self.inMacroUse = 0 self.emit("extendMacro", useExpr, cexpr, self.popSlots(), program, defineName) self.emitDefineMacro(defineName) def emitDefineSlot(self, slotName): program = self.popProgram() slotName = slotName.strip() if not re.match('%s$' % NAME_RE, slotName): raise METALError("invalid slot name: %s" % repr(slotName), self.position) self.emit("defineSlot", slotName, program) def emitFillSlot(self, slotName): program = self.popProgram() slotName = slotName.strip() if slotName in self.slots: raise METALError("duplicate fill-slot name: %s" % repr(slotName), self.position) if not re.match('%s$' % NAME_RE, slotName): raise METALError("invalid slot name: %s" % repr(slotName), self.position) self.slots[slotName] = program self.inMacroUse = 1 self.emit("fillSlot", slotName, program) def unEmitWhitespace(self): collect = [] i = len(self.program) - 1 while i >= 0: item = self.program[i] if item[0] != "rawtext": break text = item[1] if not re.match(r"\A\s*\Z", text): break collect.append(text) i = i - 1 del self.program[i + 1:] if i >= 0 and self.program[i][0] == "rawtext": text = self.program[i][1] m = re.search(r"\s+\Z", text) if m: self.program[i] = ("rawtext", text[:m.start()]) collect.append(m.group()) collect.reverse() return "".join(collect) def unEmitNewlineWhitespace(self): collect = [] i = len(self.program) while i > 0: i = i - 1 item = self.program[i] if item[0] != "rawtext": break text = item[1] if re.match(r"\A[ \t]*\Z", text): collect.append(text) continue m = re.match(r"(?s)^(.*?)(\r?\n[ \t]*)\Z", text) if not m: break text, rest = m.group(1, 2) collect.reverse() rest = rest + "".join(collect) del self.program[i:] if text: self.emit("rawtext", text) return rest return None def replaceAttrs(self, attrlist, repldict): # Each entry in attrlist starts like (name, value). Result is # (name, value, action, expr, xlat, msgid) if there is a # tal:attributes entry for that attribute. Additional attrs # defined only by tal:attributes are added here. # # (name, value, action, expr, xlat, msgid) if not repldict: return attrlist newlist = [] for item in attrlist: key = item[0] if key in repldict: expr, xlat, msgid = repldict[key] item = item[:2] + ("replace", expr, xlat, msgid) del repldict[key] newlist.append(item) # Add dynamic-only attributes for key, (expr, xlat, msgid) in sorted(repldict.items()): newlist.append((key, None, "insert", expr, xlat, msgid)) return newlist def emitStartElement(self, name, attrlist, taldict, metaldict, i18ndict, position=(None, None), isend=0): if not taldict and not metaldict and not i18ndict: # Handle the simple, common case self.emitStartTag(name, attrlist, isend) self.todoPush({}) if isend: self.emitEndElement(name, isend) return self.position = position # TODO: Ugly hack to work around tal:replace and i18n:translate issue. # I (DV) need to cleanup the code later. replaced = False if "replace" in taldict: if "content" in taldict: raise TALError( "tal:content and tal:replace are mutually exclusive", position) taldict["omit-tag"] = taldict.get("omit-tag", "") taldict["content"] = taldict.pop("replace") replaced = True for key, value in taldict.items(): if key not in taldefs.KNOWN_TAL_ATTRIBUTES: raise TALError("bad TAL attribute: " + repr(key), position) if not (value or key == 'omit-tag'): raise TALError("missing value for TAL attribute: " + repr(key), position) for key, value in metaldict.items(): if key not in taldefs.KNOWN_METAL_ATTRIBUTES: raise METALError("bad METAL attribute: " + repr(key), position) if not value: raise TALError("missing value for METAL attribute: " + repr(key), position) for key, value in i18ndict.items(): if key not in taldefs.KNOWN_I18N_ATTRIBUTES: raise I18NError("bad i18n attribute: " + repr(key), position) if not value and key in ("attributes", "data", "id"): raise I18NError("missing value for i18n attribute: " + repr(key), position) todo = {} defineMacro = metaldict.get("define-macro") extendMacro = metaldict.get("extend-macro") useMacro = metaldict.get("use-macro") defineSlot = metaldict.get("define-slot") fillSlot = metaldict.get("fill-slot") define = taldict.get("define") condition = taldict.get("condition") repeat = taldict.get("repeat") content = taldict.get("content") script = taldict.get("script") attrsubst = taldict.get("attributes") onError = taldict.get("on-error") omitTag = taldict.get("omit-tag") TALtag = taldict.get("tal tag") i18nattrs = i18ndict.get("attributes") # Preserve empty string if implicit msgids are used. We'll generate # code with the msgid='' and calculate the right implicit msgid during # interpretation phase. msgid = i18ndict.get("translate") varname = i18ndict.get('name') i18ndata = i18ndict.get('data') if varname and not self.i18nLevel: raise I18NError( "i18n:name can only occur inside a translation unit", position) if i18ndata and not msgid: raise I18NError("i18n:data must be accompanied by i18n:translate", position) if extendMacro: if useMacro: raise METALError( "extend-macro cannot be used with use-macro", position) if not defineMacro: raise METALError( "extend-macro must be used with define-macro", position) if defineMacro or extendMacro or useMacro: if fillSlot or defineSlot: raise METALError( "define-slot and fill-slot cannot be used with " "define-macro, extend-macro, or use-macro", position) if defineMacro and useMacro: raise METALError( "define-macro may not be used with use-macro", position) useMacro = useMacro or extendMacro if content and msgid: raise I18NError( "explicit message id and tal:content can't be used together", position) repeatWhitespace = None if repeat: # Hack to include preceding whitespace in the loop program repeatWhitespace = self.unEmitNewlineWhitespace() if position != (None, None): # TODO: at some point we should insist on a non-trivial position self.emit("setPosition", position) if self.inMacroUse: if fillSlot: self.pushProgram() # generate a source annotation at the beginning of fill-slot if self.source_file is not None: if position != (None, None): self.emit("setPosition", position) self.emit("setSourceFile", self.source_file) todo["fillSlot"] = fillSlot self.inMacroUse = 0 else: if fillSlot: raise METALError("fill-slot must be within a use-macro", position) if not self.inMacroUse: if defineMacro: self.pushProgram() self.emit("version", TAL_VERSION) self.emit("mode", self.xml and "xml" or "html") # generate a source annotation at the beginning of the macro if self.source_file is not None: if position != (None, None): self.emit("setPosition", position) self.emit("setSourceFile", self.source_file) todo["defineMacro"] = defineMacro self.inMacroDef = self.inMacroDef + 1 if useMacro: self.pushSlots() self.pushProgram() todo["useMacro"] = useMacro self.inMacroUse = 1 if defineSlot: if not self.inMacroDef: raise METALError( "define-slot must be within a define-macro", position) self.pushProgram() todo["defineSlot"] = defineSlot if defineSlot or i18ndict: domain = i18ndict.get("domain") or self.i18nContext.domain source = i18ndict.get("source") or self.i18nContext.source target = i18ndict.get("target") or self.i18nContext.target if (domain != DEFAULT_DOMAIN or source is not None or target is not None): self.i18nContext = TranslationContext(self.i18nContext, domain=domain, source=source, target=target) self.emit("beginI18nContext", {"domain": domain, "source": source, "target": target}) todo["i18ncontext"] = 1 if taldict or i18ndict: dict = {} for item in attrlist: key, value = item[:2] dict[key] = value self.emit("beginScope", dict) todo["scope"] = 1 if onError: self.pushProgram() # handler if TALtag: self.pushProgram() # start self.emitStartTag(name, list(attrlist)) # Must copy attrlist! if TALtag: self.pushProgram() # start self.pushProgram() # block todo["onError"] = onError if define: self.emitDefines(define) todo["define"] = define if condition: self.pushProgram() todo["condition"] = condition if repeat: todo["repeat"] = repeat self.pushProgram() if repeatWhitespace: self.emitText(repeatWhitespace) if content: if varname: todo['i18nvar'] = varname todo["content"] = content self.pushProgram() else: todo["content"] = content # i18n:name w/o tal:replace uses the content as the interpolation # dictionary values elif varname: todo['i18nvar'] = varname self.pushProgram() if msgid is not None: self.i18nLevel += 1 todo['msgid'] = msgid if i18ndata: todo['i18ndata'] = i18ndata optTag = omitTag is not None or TALtag if optTag: todo["optional tag"] = omitTag, TALtag self.pushProgram() if attrsubst or i18nattrs: if attrsubst: repldict = taldefs.parseAttributeReplacements(attrsubst, self.xml) else: repldict = {} if i18nattrs: i18nattrs = _parseI18nAttributes(i18nattrs, self.position, self.xml) else: i18nattrs = {} # Convert repldict's name-->expr mapping to a # name-->(compiled_expr, translate) mapping for key, value in sorted(repldict.items()): if i18nattrs.get(key, None): raise I18NError( "attribute [%s] cannot both be part of tal:attributes" " and have a msgid in i18n:attributes" % key, position) ce = self.compileExpression(value) repldict[key] = ce, key in i18nattrs, i18nattrs.get(key) for key in sorted(i18nattrs): if key not in repldict: repldict[key] = None, 1, i18nattrs.get(key) else: repldict = {} if replaced: todo["repldict"] = repldict repldict = {} if script: todo["script"] = script self.emitStartTag(name, self.replaceAttrs(attrlist, repldict), isend) if optTag: self.pushProgram() if content and not varname: self.pushProgram() if not content and msgid is not None: self.pushProgram() if content and varname: self.pushProgram() if script: self.pushProgram() if todo and position != (None, None): todo["position"] = position self.todoPush(todo) if isend: self.emitEndElement(name, isend, position=position) def emitEndElement(self, name, isend=0, implied=0, position=(None, None)): todo = self.todoPop() if not todo: # Shortcut if not isend: self.emitEndTag(name) return self.position = todo.get("position", (None, None)) defineMacro = todo.get("defineMacro") useMacro = todo.get("useMacro") defineSlot = todo.get("defineSlot") fillSlot = todo.get("fillSlot") repeat = todo.get("repeat") content = todo.get("content") script = todo.get("script") condition = todo.get("condition") onError = todo.get("onError") repldict = todo.get("repldict", {}) scope = todo.get("scope") optTag = todo.get("optional tag") msgid = todo.get('msgid') i18ncontext = todo.get("i18ncontext") varname = todo.get('i18nvar') i18ndata = todo.get('i18ndata') if implied > 0: if defineMacro or useMacro or defineSlot or fillSlot: exc = METALError what = "METAL" else: exc = TALError what = "TAL" raise exc("%s attributes on <%s> require explicit </%s>" % (what, name, name), self.position) if script: self.emitEvaluateCode(script) # If there's no tal:content or tal:replace in the tag with the # i18n:name, tal:replace is the default. if content: if msgid is not None: self.emitI18nSubstitution(content, repldict) else: self.emitSubstitution(content, repldict) # If we're looking at an implicit msgid, emit the insertTranslation # opcode now, so that the end tag doesn't become part of the implicit # msgid. If we're looking at an explicit msgid, it's better to emit # the opcode after the i18nVariable opcode so we can better handle # tags with both of them in them (and in the latter case, the contents # would be thrown away for msgid purposes). # # Still, we should emit insertTranslation opcode before i18nVariable # in case tal:content, i18n:translate and i18n:name in the same tag if not content and msgid is not None: self.emitTranslation(msgid, i18ndata) self.i18nLevel -= 1 if optTag: self.emitOptTag(name, optTag, isend) elif not isend: # If we're processing the end tag for a tag that contained # i18n:name, we need to make sure that optimize() won't collect # immediately following end tags into the same rawtextOffset, so # put a spacer here that the optimizer will recognize. if varname: self.emit('noop') self.emitEndTag(name) if varname: self.emitI18nVariable(varname) if repeat: self.emitRepeat(repeat) if condition: self.emitCondition(condition) if onError: self.emitOnError(name, onError, optTag and optTag[1], isend) if scope: self.emit("endScope") if i18ncontext: self.emit("endI18nContext") assert self.i18nContext.parent is not None self.i18nContext = self.i18nContext.parent if defineSlot: self.emitDefineSlot(defineSlot) if fillSlot: self.emitFillSlot(fillSlot) if useMacro or defineMacro: if useMacro and defineMacro: self.emitExtendMacro(defineMacro, useMacro) elif useMacro: self.emitUseMacro(useMacro) elif defineMacro: self.emitDefineMacro(defineMacro) if useMacro or defineSlot: # generate a source annotation after define-slot or use-macro # because the source file might have changed if self.source_file is not None: if position != (None, None): self.emit("setPosition", position) self.emit("setSourceFile", self.source_file) def _parseI18nAttributes(i18nattrs, position, xml): d = {} # Filter out empty items, eg: # i18n:attributes="value msgid; name msgid2;" # would result in 3 items where the last one is empty attrs = [spec for spec in i18nattrs.split(";") if spec] for spec in attrs: parts = spec.split() if len(parts) == 2: attr, msgid = parts elif len(parts) == 1: attr = parts[0] msgid = None else: raise TALError("illegal i18n:attributes specification: %r" % spec, position) if not xml: attr = attr.lower() if attr in d: raise TALError( "attribute may only be specified once in i18n:attributes: %r" % attr, position) d[attr] = msgid return d def test(): t = TALGenerator() t.pushProgram() t.emit("bar") p = t.popProgram() t.emit("foo", p) if __name__ == "__main__": test()
zope.tal
/zope.tal-5.0.1.tar.gz/zope.tal-5.0.1/src/zope/tal/talgenerator.py
talgenerator.py
from zope.tal.taldefs import XML_NS from zope.tal.taldefs import ZOPE_I18N_NS from zope.tal.taldefs import ZOPE_METAL_NS from zope.tal.taldefs import ZOPE_TAL_NS from zope.tal.talgenerator import TALGenerator from zope.tal.xmlparser import XMLParser class TALParser(XMLParser): """ Parser for XML. After parsing with :meth:`~.XMLParser.parseFile`, :meth:`~.XMLParser.parseString`, :meth:`~.XMLParser.parseURL` or :meth:`~.XMLParser.parseStream`, you can call :meth:`getCode` to retrieve the parsed program and macros. """ ordered_attributes = 1 def __init__(self, gen=None, encoding=None): # Override """ :keyword TALGenerator gen: The configured (with an expression compiler) code generator to use. If one is not given, a default will be used. """ XMLParser.__init__(self, encoding) if gen is None: gen = TALGenerator() self.gen = gen self.nsStack = [] self.nsDict = {XML_NS: 'xml'} self.nsNew = [] def getCode(self): """Return the compiled program and macros after parsing.""" return self.gen.getCode() def StartNamespaceDeclHandler(self, prefix, uri): self.nsStack.append(self.nsDict.copy()) self.nsDict[uri] = prefix self.nsNew.append((prefix, uri)) def EndNamespaceDeclHandler(self, prefix): self.nsDict = self.nsStack.pop() def StartElementHandler(self, name, attrs): if self.ordered_attributes: # attrs is a list of alternating names and values attrlist = [] for i in range(0, len(attrs), 2): key = attrs[i] value = attrs[i + 1] attrlist.append((key, value)) else: # attrs is a dict of {name: value} attrlist = sorted(attrs.items()) # sort for definiteness name, attrlist, taldict, metaldict, i18ndict \ = self.process_ns(name, attrlist) attrlist = self.xmlnsattrs() + attrlist self.gen.emitStartElement(name, attrlist, taldict, metaldict, i18ndict, self.getpos()) def process_ns(self, name, attrlist): taldict = {} metaldict = {} i18ndict = {} fixedattrlist = [] name, namebase, namens = self.fixname(name) for key, value in attrlist: key, keybase, keyns = self.fixname(key) ns = keyns or namens # default to tag namespace item = key, value if ns == 'metal': metaldict[keybase] = value item = item + ("metal",) elif ns == 'tal': taldict[keybase] = value item = item + ("tal",) elif ns == 'i18n': i18ndict[keybase] = value item = item + ('i18n',) fixedattrlist.append(item) if namens in ('metal', 'tal', 'i18n'): taldict['tal tag'] = namens return name, fixedattrlist, taldict, metaldict, i18ndict _namespaces = { ZOPE_TAL_NS: "tal", ZOPE_METAL_NS: "metal", ZOPE_I18N_NS: "i18n", } def xmlnsattrs(self): newlist = [] for prefix, uri in self.nsNew: if prefix: key = "xmlns:" + prefix else: key = "xmlns" if uri in self._namespaces: item = (key, uri, "xmlns") else: item = (key, uri) newlist.append(item) self.nsNew = [] return newlist def fixname(self, name): if ' ' in name: uri, name = name.split(' ', 1) prefix = self.nsDict[uri] prefixed = name if prefix: prefixed = "{}:{}".format(prefix, name) ns = self._namespaces.get(uri, "x") return (prefixed, name, ns) return (name, name, None) def EndElementHandler(self, name): name = self.fixname(name)[0] self.gen.emitEndElement(name, position=self.getpos()) def DefaultHandler(self, text): self.gen.emitRawText(text) def test(): import sys p = TALParser() file = "tests/input/test01.xml" if sys.argv[1:]: file = sys.argv[1] p.parseFile(file) program, macros = p.getCode() from zope.tal.dummyengine import DummyEngine from zope.tal.talinterpreter import TALInterpreter engine = DummyEngine(macros) TALInterpreter(program, macros, engine, sys.stdout, wrap=0)() if __name__ == "__main__": test()
zope.tal
/zope.tal-5.0.1.tar.gz/zope.tal-5.0.1/src/zope/tal/talparser.py
talparser.py
.. include:: ../README.rst Using ``zope.tal`` requires three steps: choosing an expression engine (usually :mod:`zope.tales`), creating a generator and parser, and then interpreting the compiled program:: from io import StringIO from zope.tal.talgenerator import TALGenerator from zope.tal.htmltalparser import HTMLTALParser from zope.tal.talinterpreter import TALInterpreter compiler = None # Will use a compiler for a dummy language source_file = '<string>' source_text = '<html><body><p>Hi</p></body></html>' gen = TALGenerator(compiler, source_file=source_file) parser = TALParser(gen) parser.parseString(source_text) program, macros = parser.getCode() output = StringIO() context = None # Usually will create a zope.tales context interpreter = TALInterpreter(self.program, macros, context, stream=output) interpreter() result = output.getvalue() These aspects are all brought together in :mod:`zope.pagetemplate`. API Documentation: .. toctree:: :maxdepth: 2 interfaces taldefs talgenerator htmltalparser talparser talinterpreter .. toctree:: :maxdepth: 1 changelog Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search`
zope.tal
/zope.tal-5.0.1.tar.gz/zope.tal-5.0.1/docs/index.rst
index.rst
import re from html import escape from zope.interface import Interface from zope.interface import implementer from zope.tales.interfaces import ITALESIterator class ITALExpressionEngine(Interface): pass class ITALExpressionCompiler(Interface): pass class ITALExpressionErrorInfo(Interface): pass try: # Override with real, if present from zope.tal.interfaces import ITALExpressionCompiler # noqa: F811 from zope.tal.interfaces import ITALExpressionEngine # noqa: F811 from zope.tal.interfaces import ITALExpressionErrorInfo # noqa: F811 except ImportError: pass NAME_RE = r"[a-zA-Z][a-zA-Z0-9_]*" _parse_expr = re.compile(r"(%s):" % NAME_RE).match _valid_name = re.compile('%s$' % NAME_RE).match class TALESError(Exception): """Error during TALES evaluation""" class Undefined(TALESError): """Exception raised on traversal of an undefined path.""" class CompilerError(Exception): """TALES Compiler Error""" class RegistrationError(Exception): """Expression type or base name registration Error.""" _default = object() @implementer(ITALESIterator) class Iterator: """ TALES Iterator. Default implementation of :class:`zope.tales.interfaces.ITALESIterator`. """ def __init__(self, name, seq, context): """Construct an iterator Iterators are defined for a name, a sequence, or an iterator and a context, where a context simply has a setLocal method: >>> context = Context(ExpressionEngine(), {}) >>> it = Iterator('foo', ("apple", "pear", "orange"), context) A local variable is not set until the iterator is used: >>> int("foo" in context.vars) 0 We can create an iterator on an empty sequence: >>> it = Iterator('foo', (), context) An iterator works as well: >>> it = Iterator('foo', {"apple":1, "pear":1, "orange":1}, context) >>> next(it) True >>> it = Iterator('foo', {}, context) >>> next(it) False >>> it = Iterator('foo', iter((1, 2, 3)), context) >>> next(it) True >>> next(it) True """ self._seq = seq self._iter = i = iter(seq) self._nextIndex = 0 self._name = name self._setLocal = context.setLocal # This is tricky. We want to know if we are on the last item, # but we can't know that without trying to get it. :( self._last = False try: self._next = next(i) except StopIteration: self._done = True else: self._done = False def __next__(self): """Advance the iterator, if possible. >>> context = Context(ExpressionEngine(), {}) >>> it = Iterator('foo', ("apple", "pear", "orange"), context) >>> bool(next(it)) True >>> context.vars['foo'] 'apple' >>> bool(next(it)) True >>> context.vars['foo'] 'pear' >>> bool(next(it)) True >>> context.vars['foo'] 'orange' >>> bool(next(it)) False >>> it = Iterator('foo', {"apple":1, "pear":1, "orange":1}, context) >>> bool(next(it)) True >>> bool(next(it)) True >>> bool(next(it)) True >>> bool(next(it)) False >>> it = Iterator('foo', (), context) >>> bool(next(it)) False >>> it = Iterator('foo', {}, context) >>> bool(next(it)) False If we can advance, set a local variable to the new value. """ # Note that these are *NOT* Python iterators! if self._done: return False self._item = v = self._next try: self._next = next(self._iter) except StopIteration: self._done = True self._last = True self._nextIndex += 1 self._setLocal(self._name, v) return True def index(self): """Get the iterator index >>> context = Context(ExpressionEngine(), {}) >>> it = Iterator('foo', ("apple", "pear", "orange"), context) >>> it.index() Traceback (most recent call last): ... TypeError: No iteration position >>> int(bool(next(it))) 1 >>> it.index() 0 >>> int(bool(next(it))) 1 >>> it.index() 1 >>> int(bool(next(it))) 1 >>> it.index() 2 """ index = self._nextIndex - 1 if index < 0: raise TypeError("No iteration position") return index def number(self): """Get the iterator position >>> context = Context(ExpressionEngine(), {}) >>> it = Iterator('foo', ("apple", "pear", "orange"), context) >>> int(bool(next(it))) 1 >>> it.number() 1 >>> int(bool(next(it))) 1 >>> it.number() 2 >>> int(bool(next(it))) 1 >>> it.number() 3 """ return self._nextIndex def even(self): """Test whether the position is even >>> context = Context(ExpressionEngine(), {}) >>> it = Iterator('foo', ("apple", "pear", "orange"), context) >>> next(it) True >>> it.even() True >>> next(it) True >>> it.even() False >>> next(it) True >>> it.even() True """ return not ((self._nextIndex - 1) % 2) def odd(self): """Test whether the position is odd >>> context = Context(ExpressionEngine(), {}) >>> it = Iterator('foo', ("apple", "pear", "orange"), context) >>> next(it) True >>> it.odd() False >>> next(it) True >>> it.odd() True >>> next(it) True >>> it.odd() False """ return bool((self._nextIndex - 1) % 2) def parity(self): """Return 'odd' or 'even' depending on the position's parity >>> context = Context(ExpressionEngine(), {}) >>> it = Iterator('foo', ("apple", "pear", "orange"), context) >>> next(it) True >>> it.parity() 'odd' >>> next(it) True >>> it.parity() 'even' >>> next(it) True >>> it.parity() 'odd' """ if self._nextIndex % 2: return 'odd' return 'even' def letter(self, base=ord('a'), radix=26): """Get the iterator position as a lower-case letter >>> context = Context(ExpressionEngine(), {}) >>> it = Iterator('foo', ("apple", "pear", "orange"), context) >>> it.letter() Traceback (most recent call last): ... TypeError: No iteration position >>> next(it) True >>> it.letter() 'a' >>> next(it) True >>> it.letter() 'b' >>> next(it) True >>> it.letter() 'c' """ index = self._nextIndex - 1 if index < 0: raise TypeError("No iteration position") s = '' while 1: index, off = divmod(index, radix) s = chr(base + off) + s if not index: return s def Letter(self): """Get the iterator position as an upper-case letter >>> context = Context(ExpressionEngine(), {}) >>> it = Iterator('foo', ("apple", "pear", "orange"), context) >>> next(it) True >>> it.Letter() 'A' >>> next(it) True >>> it.Letter() 'B' >>> next(it) True >>> it.Letter() 'C' """ return self.letter(base=ord('A')) def Roman(self, rnvalues=( (1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I'))): """Get the iterator position as an upper-case roman numeral >>> context = Context(ExpressionEngine(), {}) >>> it = Iterator('foo', ("apple", "pear", "orange"), context) >>> next(it) True >>> it.Roman() 'I' >>> next(it) True >>> it.Roman() 'II' >>> next(it) True >>> it.Roman() 'III' """ n = self._nextIndex s = '' for v, r in rnvalues: rct, n = divmod(n, v) s = s + r * rct return s def roman(self): """Get the iterator position as a lower-case roman numeral >>> context = Context(ExpressionEngine(), {}) >>> it = Iterator('foo', ("apple", "pear", "orange"), context) >>> next(it) True >>> it.roman() 'i' >>> next(it) True >>> it.roman() 'ii' >>> next(it) True >>> it.roman() 'iii' """ return self.Roman().lower() def start(self): """Test whether the position is the first position >>> context = Context(ExpressionEngine(), {}) >>> it = Iterator('foo', ("apple", "pear", "orange"), context) >>> next(it) True >>> it.start() True >>> next(it) True >>> it.start() False >>> next(it) True >>> it.start() False >>> it = Iterator('foo', {}, context) >>> it.start() False >>> next(it) False >>> it.start() False """ return self._nextIndex == 1 def end(self): """Test whether the position is the last position >>> context = Context(ExpressionEngine(), {}) >>> it = Iterator('foo', ("apple", "pear", "orange"), context) >>> next(it) True >>> it.end() False >>> next(it) True >>> it.end() False >>> next(it) True >>> it.end() True >>> it = Iterator('foo', {}, context) >>> it.end() False >>> next(it) False >>> it.end() False """ return self._last def item(self): """Get the iterator value >>> context = Context(ExpressionEngine(), {}) >>> it = Iterator('foo', ("apple", "pear", "orange"), context) >>> it.item() Traceback (most recent call last): ... TypeError: No iteration position >>> next(it) True >>> it.item() 'apple' >>> next(it) True >>> it.item() 'pear' >>> next(it) True >>> it.item() 'orange' >>> it = Iterator('foo', {1:2}, context) >>> next(it) True >>> it.item() 1 """ if self._nextIndex == 0: raise TypeError("No iteration position") return self._item def length(self): """Get the length of the iterator sequence >>> context = Context(ExpressionEngine(), {}) >>> it = Iterator('foo', ("apple", "pear", "orange"), context) >>> it.length() 3 You can even get the length of a mapping: >>> it = Iterator('foo', {"apple":1, "pear":2, "orange":3}, context) >>> it.length() 3 But you can't get the length of an iterable which doesn't support len(): >>> class MyIter(object): ... def __init__(self, seq): ... self._iter = iter(seq) ... def __iter__(self): ... return self ... def __next__(self): ... return next(self._iter) ... next = __next__ >>> it = Iterator('foo', MyIter({"apple":1, "pear":2}), context) >>> try: ... it.length() ... except TypeError: ... pass ... else: ... print('Expected TypeError') """ return len(self._seq) @implementer(ITALExpressionErrorInfo) class ErrorInfo: """Information about an exception passed to an on-error handler.""" # XXX: This is a duplicate of zope.tal.taldefs.ErrorInfo value = None def __init__(self, err, position=(None, None)): self.type = err if isinstance(err, Exception): self.type = err.__class__ self.value = err self.lineno = position[0] self.offset = position[1] @implementer(ITALExpressionCompiler) class ExpressionEngine: """ Expression compiler, an implementation of :class:`zope.tal.interfaces.ITALExpressionCompiler`. An instance of this class keeps :meth:`a mutable collection of expression type handlers <zope.tales.tales.ExpressionEngine.registerType>`. It can compile expression strings by delegating to these handlers. It can :meth:`provide an expression engine <zope.tales.tales.ExpressionEngine.getContext>`, which is capable of holding state and evaluating compiled expressions. By default, this object does not know how to compile any expression types. See :data:`zope.tales.engine.Engine` and :func:`zope.tales.engine.DefaultEngine` for pre-configured instances supporting the standard expression types. """ def __init__(self): self.types = {} self.base_names = {} self.namespaces = {} self.iteratorFactory = Iterator def registerFunctionNamespace(self, namespacename, namespacecallable): """ Register a function namespace :param str namespace: a string containing the name of the namespace to be registered :param callable namespacecallable: a callable object which takes the following parameter: :context: the object on which the functions provided by this namespace will be called This callable should return an object which can be traversed to get the functions provided by the this namespace. For example:: class stringFuncs(object): def __init__(self,context): self.context = str(context) def upper(self): return self.context.upper() def lower(self): return self.context.lower() engine.registerFunctionNamespace('string', stringFuncs) """ self.namespaces[namespacename] = namespacecallable def getFunctionNamespace(self, namespacename): """ Returns the function namespace """ return self.namespaces[namespacename] def registerType(self, name, handler): """ Register an expression of *name* to be handled with *handler*. :raises RegistrationError: If this is a duplicate registration for *name*, or if *name* is not a valid expression type name. """ if not _valid_name(name): raise RegistrationError( 'Invalid expression type name "%s".' % name) types = self.types if name in types: raise RegistrationError( 'Multiple registrations for Expression type "%s".' % name) types[name] = handler def getTypes(self): return self.types def registerBaseName(self, name, object): if not _valid_name(name): raise RegistrationError('Invalid base name "%s".' % name) base_names = self.base_names if name in base_names: raise RegistrationError( 'Multiple registrations for base name "%s".' % name) base_names[name] = object def getBaseNames(self): return self.base_names def compile(self, expression): m = _parse_expr(expression) if m: type = m.group(1) expr = expression[m.end():] else: type = "standard" expr = expression try: handler = self.types[type] except KeyError: raise CompilerError('Unrecognized expression type "%s".' % type) return handler(type, expr, self) def getContext(self, contexts=None, **kwcontexts): """ Return a new expression engine. The keyword arguments passed in *kwcantexts* become the default variable context for the returned engine. If *contexts* is given, it should be a mapping, and the values it contains will override the keyword arguments. :rtype: Context """ if contexts is not None: if kwcontexts: kwcontexts.update(contexts) else: kwcontexts = contexts return Context(self, kwcontexts) def getCompilerError(self): return CompilerError @implementer(ITALExpressionEngine) class Context: """ Expression engine, an implementation of :class:`zope.tal.interfaces.ITALExpressionEngine`. This class is called ``Context`` because an instance of this class holds context information (namespaces) that it uses when evaluating compiled expressions. """ position = (None, None) source_file = None def __init__(self, engine, contexts): """ :param engine: A :class:`ExpressionEngine` (a :class:`zope.tal.interfaces.ITALExpressionCompiler`) :param contexts: A mapping (namespace) of variables that forms the base variable scope. """ self._engine = engine self.contexts = contexts self.setContext('nothing', None) self.setContext('default', _default) self.repeat_vars = rv = {} # Wrap this, as it is visible to restricted code self.setContext('repeat', rv) self.setContext('loop', rv) # alias self.vars = vars = contexts.copy() self._vars_stack = [vars] # Keep track of what needs to be popped as each scope ends. self._scope_stack = [] def setContext(self, name, value): """Hook to allow subclasses to do things like adding security proxies. """ self.contexts[name] = value def beginScope(self): self.vars = vars = self.vars.copy() self._vars_stack.append(vars) self._scope_stack.append([]) def endScope(self): self._vars_stack.pop() self.vars = self._vars_stack[-1] scope = self._scope_stack.pop() # Pop repeat variables, if any i = len(scope) while i: i = i - 1 name, value = scope[i] if value is None: del self.repeat_vars[name] else: self.repeat_vars[name] = value def setLocal(self, name, value): self.vars[name] = value def setGlobal(self, name, value): for vars in self._vars_stack: vars[name] = value def getValue(self, name, default=None): value = default for vars in self._vars_stack: value = vars.get(name, default) if value is not default: break return value def setRepeat(self, name, expr): expr = self.evaluate(expr) if not expr: return self._engine.iteratorFactory(name, (), self) it = self._engine.iteratorFactory(name, expr, self) old_value = self.repeat_vars.get(name) self._scope_stack[-1].append((name, old_value)) self.repeat_vars[name] = it return it def evaluate(self, expression): """ Evaluate the *expression* by calling it, passing in this object, and return the raw results. If *expression* is a string, it is first compiled. """ if isinstance(expression, str): expression = self._engine.compile(expression) __traceback_supplement__ = ( TALESTracebackSupplement, self, expression) return expression(self) evaluateValue = evaluate def evaluateBoolean(self, expr): """ Evaluate the expression and return the boolean value of its result. """ # "not not", while frowned upon by linters might be faster # than bool() because it avoids a builtin lookup. Plus it can't be # reassigned. return not not self.evaluate(expr) def evaluateText(self, expr): text = self.evaluate(expr) if text is self.getDefault() or text is None: return text if isinstance(text, str): # text could already be something text-ish, e.g. a Message object return text return str(text) evaluateStructure = evaluate # TODO: Should return None or a macro definition evaluateMacro = evaluate def createErrorInfo(self, err, position): return ErrorInfo(err, position) def getDefault(self): return _default def setSourceFile(self, source_file): self.source_file = source_file def setPosition(self, position): self.position = position def translate(self, msgid, domain=None, mapping=None, default=None): # custom Context implementations are supposed to customize # this to call whichever translation routine they want to use return str(msgid) class TALESTracebackSupplement: """Implementation of zope.exceptions.ITracebackSupplement""" def __init__(self, context, expression): self.context = context self.source_url = context.source_file self.line = context.position[0] self.column = context.position[1] self.expression = repr(expression) def getInfo(self, as_html=0): import pprint data = self.context.contexts.copy() if 'modules' in data: del data['modules'] # the list is really long and boring s = pprint.pformat(data) if not as_html: return ' - Names:\n %s' % s.replace('\n', '\n ') return '<b>Names:</b><pre>%s</pre>' % (escape(s))
zope.tales
/zope.tales-6.0-py3-none-any.whl/zope/tales/tales.py
tales.py
from zope.interface import Interface try: from zope.tal.interfaces import ITALIterator except ImportError: class ITALIterator(Interface): """Stub: See zope.tal.interfaces.ITALIterator""" def next(): """Advance to the next value in the iteration, if possible""" class ITALESFunctionNamespace(Interface): """Function namespaces can be used in TALES path expressions to extract information in non-default ways.""" def setEngine(engine): """Sets the engine that is used to evaluate TALES expressions.""" class ITALESExpression(Interface): """TALES expression These are expression handlers that handle a specific type of expression in TALES, e.g. ``path`` or ``string`` expression. """ def __call__(econtext): """ Evaluate expression according to the given execution context *econtext* and return computed value. """ class ITALESIterator(ITALIterator): """TAL Iterator provided by TALES. Values of this iterator are assigned to items in the ``repeat`` namespace. For example, with a TAL statement like: ``tal:repeat="item items"``, an iterator will be assigned to ``repeat/item`` (using a path expression). The iterator provides a number of handy methods useful in writing TAL loops. The results are undefined of calling any of the methods except ``length`` before the first iteration. """ def index(): """Return the position (starting with "0") within the iteration """ def number(): """Return the position (starting with "1") within the iteration """ def even(): """Return whether the current position is even. """ def odd(): """Return whether the current position is odd """ def parity(): """Return 'odd' or 'even' depending on the position's parity Useful for assigning CSS class names to table rows. """ def start(): """Return whether the current position is the first position """ def end(): """Return whether the current position is the last position """ def letter(): """Return the position (starting with "a") within the iteration """ def Letter(): """Return the position (starting with "A") within the iteration """ def roman(): """Return the position (starting with "i") within the iteration """ def Roman(): """Return the position (starting with "I") within the iteration """ def item(): """Return the item at the current position """ def length(): """Return the length of the sequence Note that this may fail if the TAL iterator was created on a Python iterator. """
zope.tales
/zope.tales-6.0-py3-none-any.whl/zope/tales/interfaces.py
interfaces.py
import re from zope.interface import implementer from zope.tales.interfaces import ITALESExpression from zope.tales.interfaces import ITALESFunctionNamespace from zope.tales.tales import NAME_RE from zope.tales.tales import Undefined from zope.tales.tales import _parse_expr from zope.tales.tales import _valid_name Undefs = (Undefined, AttributeError, LookupError, TypeError) _marker = object() namespace_re = re.compile(r'(\w+):(.+)') def simpleTraverse(object, path_items, econtext): """Traverses a sequence of names, first trying attributes then items. """ for name in path_items: next = getattr(object, name, _marker) if next is not _marker: object = next elif hasattr(object, '__getitem__'): object = object[name] else: # Allow AttributeError to propagate object = getattr(object, name) return object class SubPathExpr: """ Implementation of a single path expression. """ ALLOWED_BUILTINS = {} def __init__(self, path, traverser, engine): self._traverser = traverser self._engine = engine # Parse path compiledpath = [] currentpath = [] try: path = str(path) except Exception as e: raise engine.getCompilerError()( 'could not convert %r to `str`: %s: %s' % (path, e.__class__.__name__, str(e))) for element in path.strip().split('/'): if not element: raise engine.getCompilerError()( 'Path element may not be empty in %r' % path) if element.startswith('?'): if currentpath: compiledpath.append(tuple(currentpath)) currentpath = [] if not _valid_name(element[1:]): raise engine.getCompilerError()( 'Invalid variable name "%s"' % element[1:]) compiledpath.append(element[1:]) else: match = namespace_re.match(element) if match: if currentpath: compiledpath.append(tuple(currentpath)) currentpath = [] namespace, functionname = match.groups() if not _valid_name(namespace): raise engine.getCompilerError()( 'Invalid namespace name "%s"' % namespace) try: compiledpath.append( self._engine.getFunctionNamespace(namespace)) except KeyError: raise engine.getCompilerError()( 'Unknown namespace "%s"' % namespace) currentpath.append(functionname) else: currentpath.append(element) if currentpath: compiledpath.append(tuple(currentpath)) first = compiledpath[0] if callable(first): # check for initial function raise engine.getCompilerError()( 'Namespace function specified in first subpath element') elif isinstance(first, str): # check for initial ? raise engine.getCompilerError()( 'Dynamic name specified in first subpath element') base = first[0] if base and not _valid_name(base): raise engine.getCompilerError()( 'Invalid variable name "%s"' % base) self._base = base compiledpath[0] = first[1:] self._compiled_path = tuple(compiledpath) def _eval(self, econtext, isinstance=isinstance): vars = econtext.vars compiled_path = self._compiled_path base = self._base if base == 'CONTEXTS' or not base: # Special base name ob = econtext.contexts else: try: ob = vars[base] except KeyError: ob = self.ALLOWED_BUILTINS.get(base, _marker) if ob is _marker: raise if isinstance(ob, DeferWrapper): ob = ob() for element in compiled_path: if isinstance(element, tuple): ob = self._traverser(ob, element, econtext) elif isinstance(element, str): val = vars[element] # If the value isn't a string, assume it's a sequence # of path names. if isinstance(val, str): val = (val,) ob = self._traverser(ob, val, econtext) elif callable(element): ob = element(ob) # TODO: Once we have n-ary adapters, use them. if ITALESFunctionNamespace.providedBy(ob): ob.setEngine(econtext) else: raise ValueError(repr(element)) return ob @implementer(ITALESExpression) class PathExpr: """ One or more :class:`subpath expressions <SubPathExpr>`, separated by ``|``. """ # _default_type_names contains the expression type names this # class is usually registered for. _default_type_names = ( 'standard', 'path', 'exists', 'nocall', ) SUBEXPR_FACTORY = SubPathExpr def __init__(self, name, expr, engine, traverser=simpleTraverse): self._s = expr self._name = name self._hybrid = False paths = expr.split('|') self._subexprs = [] add = self._subexprs.append for i, path in enumerate(paths): path = path.lstrip() if _parse_expr(path): # This part is the start of another expression type, # so glue it back together and compile it. add(engine.compile('|'.join(paths[i:]).lstrip())) self._hybrid = True break add(self.SUBEXPR_FACTORY(path, traverser, engine)._eval) def _exists(self, econtext): for expr in self._subexprs: try: expr(econtext) except Undefs: pass else: return 1 return 0 def _eval(self, econtext): for expr in self._subexprs[:-1]: # Try all but the last subexpression, skipping undefined ones. try: ob = expr(econtext) except Undefs: pass else: break else: # On the last subexpression allow exceptions through, and # don't autocall if the expression was not a subpath. ob = self._subexprs[-1](econtext) if self._hybrid: return ob if self._name == 'nocall': return ob # Call the object if it is callable. Note that checking for # callable() isn't safe because the object might be security # proxied (and security proxies report themselves callable, no # matter what the underlying object is). We therefore check # for the __call__ attribute, but not with hasattr as that # eats babies, err, exceptions. if getattr(ob, '__call__', _marker) is not _marker: return ob() return ob def __call__(self, econtext): if self._name == 'exists': return self._exists(econtext) return self._eval(econtext) def __str__(self): return '{} expression ({})'.format(self._name, repr(self._s)) def __repr__(self): return '<PathExpr {}:{}>'.format(self._name, repr(self._s)) _interp = re.compile( r'\$(%(n)s)|\${(%(n)s(?:/[^}|]*)*(?:\|\s*%(n)s(?:/[^}|]*)*)*)}' % {'n': NAME_RE}) @implementer(ITALESExpression) class StringExpr: """ An expression that produces a string. Sub-sequences of the string that begin with ``$`` are interpreted as path expressions to evaluate. """ def __init__(self, name, expr, engine): self._s = expr if '%' in expr: expr = expr.replace('%', '%%') self._vars = vars = [] if '$' in expr: # Use whatever expr type is registered as "path". path_type = engine.getTypes()['path'] parts = [] for exp in expr.split('$$'): if parts: parts.append('$') m = _interp.search(exp) while m is not None: parts.append(exp[:m.start()]) parts.append('%s') vars.append(path_type( 'path', m.group(1) or m.group(2), engine)) exp = exp[m.end():] m = _interp.search(exp) if '$' in exp: raise engine.getCompilerError()( '$ must be doubled or followed by a simple path') parts.append(exp) expr = ''.join(parts) self._expr = expr def __call__(self, econtext): vvals = [] for var in self._vars: v = var(econtext) vvals.append(v) return self._expr % tuple(vvals) def __str__(self): return 'string expression (%s)' % repr(self._s) def __repr__(self): return '<StringExpr %s>' % repr(self._s) @implementer(ITALESExpression) class NotExpr: """ An expression that negates the boolean value of its sub-expression. """ def __init__(self, name, expr, engine): self._s = expr = expr.lstrip() self._c = engine.compile(expr) def __call__(self, econtext): return int(not econtext.evaluateBoolean(self._c)) def __repr__(self): return '<NotExpr %s>' % repr(self._s) class DeferWrapper: def __init__(self, expr, econtext): self._expr = expr self._econtext = econtext def __str__(self): return str(self()) def __call__(self): return self._expr(self._econtext) @implementer(ITALESExpression) class DeferExpr: """ An expression that will defer evaluation of the sub-expression until necessary, preserving the execution context it was created with. This is useful in ``tal:define`` expressions:: <div tal:define="thing defer:some/path"> ... <!-- some/path is only evaluated if condition is true --> <span tal:condition="condition" tal:content="thing"/> </div> """ def __init__(self, name, expr, compiler): self._s = expr = expr.lstrip() self._c = compiler.compile(expr) def __call__(self, econtext): return DeferWrapper(self._c, econtext) def __repr__(self): return '<DeferExpr %s>' % repr(self._s) class LazyWrapper(DeferWrapper): """Wrapper for lazy: expression """ _result = _marker def __init__(self, expr, econtext): DeferWrapper.__init__(self, expr, econtext) def __call__(self): r = self._result if r is _marker: self._result = r = self._expr(self._econtext) return r class LazyExpr(DeferExpr): """ An expression that will defer evaluation of its sub-expression until the first time it is necessary. This is like :class:`DeferExpr`, but caches the result of evaluating the expression. """ def __call__(self, econtext): return LazyWrapper(self._c, econtext) def __repr__(self): return 'lazy:%s' % repr(self._s) class SimpleModuleImporter: """Minimal module importer with no security.""" def __getitem__(self, module): mod = self._get_toplevel_module(module) path = module.split('.') for name in path[1:]: mod = getattr(mod, name) return mod def _get_toplevel_module(self, module): # This can be overridden to add security proxies. return __import__(module)
zope.tales
/zope.tales-6.0-py3-none-any.whl/zope/tales/expressions.py
expressions.py
"""Generic Python Expression Handler """ import types class PythonExpr: """ Evaluates a python expression by calling :func:`eval` after compiling it with :func:`compile`. """ def __init__(self, name, expr, engine): """ :param str expr: The Python expression. :param ExpressionEngine engine: The expression compiler that is creating us. """ text = '\n'.join(expr.splitlines()) # normalize line endings text = '(' + text + ')' # Put text in parens so newlines don't matter self.text = text try: code = self._compile(text, '<string>') except SyntaxError as e: raise engine.getCompilerError()(str(e)) self._code = code self._varnames = code.co_names # Variables used inside list comprehensions are not # directly available via co_names. for const in code.co_consts: if isinstance(const, types.CodeType): self._varnames += const.co_names def _compile(self, text, filename): return compile(text, filename, 'eval') def _bind_used_names(self, econtext, builtins): # Construct a dictionary of globals with which the Python # expression should be evaluated. names = {} vars = econtext.vars marker = self if not isinstance(builtins, dict): builtins = builtins.__dict__ for vname in self._varnames: val = vars.get(vname, marker) if val is not marker: names[vname] = val elif vname not in builtins: # Fall back to using expression types as variable values. val = econtext._engine.getTypes().get(vname, marker) if val is not marker: val = ExprTypeProxy(vname, val, econtext) names[vname] = val names['__builtins__'] = builtins return names def __call__(self, econtext): __traceback_info__ = self.text vars = self._bind_used_names(econtext, __builtins__) return eval(self._code, vars) def __str__(self): return 'Python expression "%s"' % self.text def __repr__(self): return '<PythonExpr %s>' % self.text class ExprTypeProxy: '''Class that proxies access to an expression type handler''' def __init__(self, name, handler, econtext): self._name = name self._handler = handler self._econtext = econtext def __call__(self, text): return self._handler(self._name, text, self._econtext._engine)(self._econtext)
zope.tales
/zope.tales-6.0-py3-none-any.whl/zope/tales/pythonexpr.py
pythonexpr.py
======= CHANGES ======= 6.0 (2023-03-27) ---------------- - Drop support for Python 2.7, 3.5, 3.6. - Drop support for deprecated ``python setup.py test``. - Add support for Python 3.11. - Do not break in ``mechRepr`` when using ``<input type="date">``. 5.6.1 (2022-01-21) ------------------ - Ensure all objects have consistent resolution orders. 5.6.0 (2022-01-21) ------------------ - Add support for Python 3.9 and 3.10. 5.5.1 (2019-11-12) ------------------ - Stop sending a ``Referer`` header when ``browser.open`` or ``browser.post`` is called directly. See `issue 87 <https://github.com/zopefoundation/zope.testbrowser/issues/87>`_. - Add error checking to the setters for ``ListControl.displayValue`` and ``CheckboxListControl.displayValue``: in line with the old ``mechanize``-based implementation, these will now raise ``ItemNotFoundError`` if any of the given values are not found, or ``ItemCountError`` on trying to set more than one value on a single-valued control. See `issue 44 <https://github.com/zopefoundation/zope.testbrowser/issues/44>`_. - Fix AttributeError in `add_file` when trying to add to a control which is not a file upload. 5.5.0 (2019-11-11) ------------------ - Fix a bug where ``browser.goBack()`` did not invalidate caches, so subsequent queries could use data from the wrong response. See `issue 83 <https://github.com/zopefoundation/zope.testbrowser/issues/83>`_. - Support telling the browser not to follow redirects by setting ``Browser.follow_redirects`` to False. See `issue 79 <https://github.com/zopefoundation/zope.testbrowser/issues/79>`_. 5.4.0 (2019-11-01) ------------------ - Fix a bug where browser.reload() would not follow redirects or raise exceptions for bad HTTP statuses. See `issue 75 <https://github.com/zopefoundation/zope.testbrowser/issues/75>`_. - Add Python 3.8 support. See `issue 80 <https://github.com/zopefoundation/zope.testbrowser/issues/80>`_. 5.3.3 (2019-07-02) ------------------ - Fix a bug where clicking the selected radio button would unselect it. See `issue 68 <https://github.com/zopefoundation/zope.testbrowser/issues/68>`_. - Fix another incompatibility with BeautifulSoup4 >= 4.7 that could result in a SyntaxError from browser.getLink(). See `issue 61 <https://github.com/zopefoundation/zope.testbrowser/issues/61>`_. 5.3.2 (2019-02-06) ------------------ - Fix an incompatibility with BeautifulSoup4 >= 4.7 that could result in a SyntaxError from browser.getControl(). See `issue 61 <https://github.com/zopefoundation/zope.testbrowser/issues/61>`_. - Fix a bug where you couldn't set a cookie expiration date when your locale was not English. See `issue 65 <https://github.com/zopefoundation/zope.testbrowser/issues/65>`_. - Fix narrative doctests that started failing on January 1st, 2019 due to a hardcoded "future" date. See `issue 62 <https://github.com/zopefoundation/zope.testbrowser/issues/62>`_. 5.3.1 (2018-10-23) ------------------ - Fix a ``DeprecationWarning`` on Python 3. See `issue 51 <https://github.com/zopefoundation/zope.testbrowser/issues/51>`_. 5.3.0 (2018-10-10) ------------------ - Add support for Python 3.7. - Drop support for Python 3.3 and 3.4. - Drop support for pystone as Python 3.7 dropped pystone. So ``Browser.lastRequestPystones`` no longer exists. Rename ``.browser.PystoneTimer`` to ``.browser.Timer``. - Fix ``mechRepr`` of CheckboxListControl to always return a native str. (https://github.com/zopefoundation/zope.testbrowser/pull/46). - Add ``mechRepr`` to input fields having the type ``email``. (https://github.com/zopefoundation/zope.testbrowser/pull/47). 5.2.4 (2017-11-24) ------------------ - Fix form submit with GET method if the form action contains a query string (https://github.com/zopefoundation/zope.testbrowser/pull/42). - Restore ignoring hidden elements when searching by label (https://github.com/zopefoundation/zope.testbrowser/pull/41). 5.2.3 (2017-10-18) ------------------ - Fix ``mechRepr`` on controls to always return a native str (https://github.com/zopefoundation/zope.testbrowser/issues/38). 5.2.2 (2017-10-10) ------------------ - Restore raising of AttributeError when trying to set value of a read only control. - Fix selecting radio and select control options by index (https://github.com/zopefoundation/zope.testbrowser/issues/31). 5.2.1 (2017-09-01) ------------------ - Exclude version 2.0.27 of `WebTest` from allowed versions as it breaks some tests. - Adapt tests to version 2.0.28 of `WebTest` but keeping compatibility to older versions. 5.2 (2017-02-25) ---------------- - Fixed ``toStr`` to handle lists, for example a list of class names. [maurits] - Fixed browser to only follow redirects for HTTP statuses 301, 302, 303, and 307; not other 30x statuses such as 304. - Fix passing a real file to ``add_file``. - Add ``controls`` property to Form class to list all form controls. - Restore the ability to use parts of the actually displayed select box titles. - Allow to set a string value instead of a list on ``Browser.displayValue``. - Fix setting empty values on a select control. - Support Python 3.6, PyPy2.7 an PyPy3.3. 5.1 (2017-01-31) ---------------- - Alias ``.browser.urllib_request.HTTPError`` to ``.browser.HTTPError`` to have a better API. 5.0.0 (2016-09-30) ------------------ - Converted most doctests to Sphinx documentation, and published to https://zopetestbrowser.readthedocs.io/ . - Internal implementation now uses WebTest instead of ``mechanize``. The ``mechanize`` dependency is completely dropped. **This is a backwards-incompatible change.** - Remove APIs: - ``zope.testbrowser.testing.Browser`` (this is a big one). Instead of using ``zope.testbrowser.testing.Browser()`` and relying on it to magically pick up the ``zope.app.testing.functional`` singleton application, you now have to define a test layer inheriting from ``zope.testbrowser.wsgi.Layer``, overrride the ``make_wsgi_app`` method to create a WSGI application, and then use ``zope.testbrowser.wsgi.Browser()`` in your tests. (Or you can set up a WSGI application yourself in whatever way you like and pass it explicitly to ``zope.testbrowser.browser.Browser(wsgi_app=my_app)``.) Example: if your test file looked like this :: # my/package/tests.py from zope.app.testing.functional import defineLayer from zope.app.testing.functional import FunctionalDocFileSuite defineLayer('MyFtestLayer', 'ftesting.zcml', allow_teardown=True) def test_suite(): suite = FunctionalDocFileSuite('test.txt', ...) suite.layer = MyFtestLayer return suite now you'll have to use :: # my/package/tests.py from unittest import TestSuite import doctest import zope.app.wsgi.testlayer import zope.testbrowser.wsgi class Layer(zope.testbrowser.wsgi.TestBrowserLayer, zope.app.wsgi.testlayer.BrowserLayer): """Layer to prepare zope.testbrowser using the WSGI app.""" layer = Layer(my.package, 'ftesting.zcml', allowTearDown=True) def test_suite(): suite = doctest.DocFileSuite('test.txt', ...) suite.layer = layer return suite and then change all your tests from :: >>> from zope.testbrowser.testing import Browser to :: >>> from zope.testbrowser.wsgi import Browser Maybe the blog post `Getting rid of zope.app.testing`_ could help you adapting to this new version, too. - Remove modules: - ``zope.testbrowser.connection`` - Remove internal classes you were not supposed to use anyway: - ``zope.testbrowser.testing.PublisherResponse`` - ``zope.testbrowser.testing.PublisherConnection`` - ``zope.testbrowser.testing.PublisherHTTPHandler`` - ``zope.testbrowser.testing.PublisherMechanizeBrowser`` - ``zope.testbrowser.wsgi.WSGIConnection`` - ``zope.testbrowser.wsgi.WSGIHTTPHandler`` - ``zope.testbrowser.wsgi.WSGIMechanizeBrowser`` - Remove internal attributes you were not supposed to use anyway (this list is not necessarily complete): - ``Browser._mech_browser`` - Remove setuptools extras: - ``zope.testbrowser[zope-functional-testing]`` - Changed behavior: - The testbrowser no longer follows HTML redirects aka ``<meta http-equiv="refresh" ... />``. This was a `mechanize` feature which does not seem to be provided by `WebTest`. - Add support for Python 3.3, 3.4 and 3.5. - Drop support for Python 2.5 and 2.6. - Drop the ``WebTest <= 1.3.4`` pin. We require ``WebTest >= 2.0.8`` now. - Remove dependency on deprecated ``zope.app.testing``. - Bugfix: ``browser.getLink()`` could fail if your HTML contained ``<a>`` elements with no href attribute (https://github.com/zopefoundation/zope.testbrowser/pull/3). .. _`Getting rid of zope.app.testing` : https://icemac15.wordpress.com/2010/07/10/appswordpressicemac20100710get-rid-of-zope-app-testing-dependency/ 4.0.3 (2013-09-04) ------------------ - pinning version 'WebTest <= 1.3.4', because of some incompatibility and test failures - Make zope.testbrowser installable via pip (https://github.com/zopefoundation/zope.testbrowser/issues/6). - When ``Browser.handleErrors`` is False, also add ``x-wsgiorg.throw_errors`` to the environment. http://wsgi.org/wsgi/Specifications/throw_errors - Prevent WebTest from always sending ``paste.throw_errors=True`` in the environment by setting it to ``None`` when ``Browser.handleErrors`` is ``True``. This makes it easier to test error pages. - Make Browser.submit() handle ``raiseHttpErrors`` (https://github.com/zopefoundation/zope.testbrowser/pull/4). - More friendly error messages from getControl() et al: - when you specify an index that is out of bounds, show the available choices - when you fail to find anything, show all the available items 4.0.2 (2011-05-25) ------------------ - Remove test dependency on zope.pagetemplate. 4.0.1 (2011-05-04) ------------------ - Add a hint in documentation how to use ``zope.testbrowser.wsgi.Browser`` to test a Zope 2/Zope 3/Bluebream WSGI application. 4.0.0 (2011-03-14) ------------------ - LP #721252: AmbiguityError now shows all matching controls. - Integrate with WebTest. ``zope.testbrowser.wsgi.Browser`` is a ``Browser`` implementation that uses ``webtest.TestApp`` to drive a WSGI application. This this replaces the wsgi_intercept support added in 3.11. - Re-write the test application as a pure WSGI application using WebOb. Run the existing tests using the WebTest based Browser - Move zope.app.testing based Browser into ``zope.app.testing`` (leaving backwards compatibility imports in-place). Released in ``zope.app.testing`` 3.9.0. 3.11.1 (2011-01-24) ------------------- - Fixing brown bag release 3.11.0. 3.11.0 (2011-01-24) ------------------- - Add ``wsgi_intercept`` support (came from ``zope.app.wsgi.testlayer``). 3.10.4 (2011-01-14) ------------------- - Move the over-the-wire.txt doctest out of the TestBrowserLayer as it doesn't need or use it. - Fix test compatibility with zope.app.testing 3.8.1. 3.10.3 (2010-10-15) ------------------- - Fixed backwards compatibility with ``zope.app.wsgi.testlayer``. 3.10.2 (2010-10-15) ------------------- - Fixed Python 2.7 compatibility in Browser.handleErrors. 3.10.1 (2010-09-21) ------------------- - Fixed a bug that caused the ``Browser`` to keep it's previous ``contents`` The places are: - Link.click() - SubmitControl.click() - ImageControl.click() - Form.submit() - Also adjusted exception messages at the above places to match pre version 3.4.1 messages. 3.10.0 (2010-09-14) ------------------- - LP #98437: use ``mechanize``'s built-in ``submit()`` to submit forms, allowing ``mechanize`` to set the "Referer:" (sic) header appropriately. - Fixed tests to run with ``zope.app.testing`` 3.8 and above. 3.9.0 (2010-05-17) ------------------ - LP #568806: Update dependency ``mechanize >= 0.2.0``, which now includes the ``ClientForm`` APIs. Remove use of ``urllib2`` APIs (incompatible with ``mechanize 0.2.0``) in favor of ``mechanize`` equivalents. Thanks to John J. Lee for the patch. - Use stdlib ``doctest`` module, instead of ``zope.testing.doctest``. - **Caution:** This version is no longer fully compatible with Python 2.4: ``handleErrors = False`` no longer works. 3.8.1 (2010-04-19) ------------------ - Pin dependency on ``mechanize`` to prevent use of the upcoming 0.2.0 release before we have time to adjust to its API changes. - Fix LP #98396: testbrowser resolves relative URLs incorrectly. 3.8.0 (2010-03-05) ------------------ - Add ``follow`` convenience method which gets and follows a link. 3.7.0 (2009-12-17) ------------------ - Move ``zope.app.testing`` dependency into the scope of the ``PublisherConnection`` class. Zope2 specifies its own version of ``PublisherConnection`` which isn't dependent on ``zope.app.testing``. - Fix LP #419119: return ``None`` when the browser has no contents instead of raising an exception. 3.7.0a1 (2009-08-29) -------------------- - Update dependency from ``zope.app.publisher`` to ``zope.browserpage``, ``zope.browserresource`` and ``zope.ptresource``. - Remove dependencies on ``zope.app.principalannotation`` and ``zope.securitypolicy`` by using the simple ``PermissiveSecurityPolicy``. - Replace the testing dependency on ``zope.app.zcmlfiles`` with explicit dependencies of a minimal set of packages. - Remove unneeded ``zope.app.authentication`` from ftesting.zcml. - Update dependency from ``zope.app.securitypolicy`` to ``zope.securitypolicy``. 3.6.0a2 (2009-01-31) -------------------- - Update dependency from ``zope.app.folder`` to ``zope.site.folder``. - Remove unnecessary test dependency in ``zope.app.component``. 3.6.0a1 (2009-01-08) -------------------- - Update author e-mail to ``zope-dev`` rather than ``zope3-dev``. - No longer strip newlines in XML and HTML code contained in a ``<textarea>``; fix requires ClientForm >= 0.2.10 (LP #268139). - Add ``cookies`` attribute to browser for easy manipulation of browser cookies. See brief example in main documentation, plus new ``cookies.txt`` documentation. 3.5.1 (2008-10-10) ------------------ - Work around for a ``mechanize``/``urllib2`` bug on Python 2.6 missing ``timeout`` attribute on ``Request`` base class. - Work around for a ``mechanize``/``urllib2`` bug in creating request objects that won't handle fragment URLs correctly. 3.5.0 (2008-03-30) ------------------ - Add a ``zope.testbrowser.testing.Browser.post`` method that allows tests to supply a body and a content type. This is handy for testing Ajax requests with non-form input (e.g. JSON). - Remove vendor import of ``mechanize``. - Fix bug that caused HTTP exception tracebacks to differ between version 3.4.0 and 3.4.1. - Work around a bug in Python ``Cookie.SimpleCookie`` when handling unicode strings. - Fix bug introduced in 3.4.1 that created incompatible tracebacks in doctests. This necessitated adding a patched ``mechanize`` to the source tree; patches have been sent to the ``mechanize`` project. - Fix https://bugs.launchpad.net/bugs/149517 by adding ``zope.interface`` and ``zope.schema`` as real dependencies - Fix ``browser.getLink`` documentation that was not updated since the last API modification. - Move tests for fixed bugs to a separate file. - Remove non-functional and undocumented code intended to help test servers using virtual hosting. 3.4.2 (2007-10-31) ------------------ - Resolve ``ZopeSecurityPolicy`` deprecation warning. 3.4.1 (2007-09-01) ------------------ * Update dependencies to ``mechanize 0.1.7b`` and ``ClientForm 0.2.7``. * Add support for Python 2.5. 3.4.0 (2007-06-04) ------------------ * Add the ability to suppress raising exceptions on HTTP errors (``raiseHttpErrors`` attribute). * Make the tests more resilient to HTTP header formatting changes with the REnormalizer. 3.4.0a1 (2007-04-22) -------------------- Initial release as a separate project, corresponds to zope.testbrowser from Zope 3.4.0a1
zope.testbrowser
/zope.testbrowser-6.0.tar.gz/zope.testbrowser-6.0/CHANGES.rst
CHANGES.rst
``zope.testbrowser`` README =========================== .. image:: https://img.shields.io/pypi/v/zope.testbrowser.svg :target: https://pypi.org/project/zope.testbrowser/ :alt: Latest Version .. image:: https://github.com/zopefoundation/zope.testbrowser/actions/workflows/tests.yml/badge.svg :target: https://github.com/zopefoundation/zope.testbrowser/actions/workflows/tests.yml .. image:: https://readthedocs.org/projects/zopetestbrowser/badge/?version=latest :target: http://zopetestbrowser.readthedocs.org/en/latest/ :alt: Documentation Status ``zope.testbrowser`` provides an easy-to-use programmable web browser with special focus on testing. It is used in Zope, but it's not Zope specific at all. For instance, it can be used to test or otherwise interact with any web site. Documentation is available at: https://zopetestbrowser.readthedocs.org
zope.testbrowser
/zope.testbrowser-6.0.tar.gz/zope.testbrowser-6.0/README.rst
README.rst
Zope Public License (ZPL) Version 2.1 A copyright notice accompanies this license document that identifies the copyright holders. This license has been certified as open source. It has also been designated as GPL compatible by the Free Software Foundation (FSF). Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions in source code must retain the accompanying copyright notice, this list of conditions, and the following disclaimer. 2. Redistributions in binary form must reproduce the accompanying copyright notice, this list of conditions, and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Names of the copyright holders must not be used to endorse or promote products derived from this software without prior written permission from the copyright holders. 4. The right to distribute this software or to use it for any purpose does not give you the right to use Servicemarks (sm) or Trademarks (tm) of the copyright holders. Use of them is covered by separate agreement with the copyright holders. 5. If any files are modified, you must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. Disclaimer THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
zope.testbrowser
/zope.testbrowser-6.0.tar.gz/zope.testbrowser-6.0/LICENSE.rst
LICENSE.rst
import base64 import re import zope.testbrowser.browser from zope.testbrowser.browser import HostNotAllowed # noqa BBB class Browser(zope.testbrowser.browser.Browser): def __init__(self, url=None, wsgi_app=None): if wsgi_app is None: wsgi_app = Layer.get_app() if wsgi_app is None: raise AssertionError("wsgi_app not provided or " "zope.testbrowser.wsgi.Layer not setup") super().__init__(url, wsgi_app) basicre = re.compile('Basic (.+)?:(.+)?$') def auth_header(header): """This function takes an authorization HTTP header and encode the couple user, password into base 64 like the HTTP protocol wants it. """ match = basicre.match(header) if match: u, p = match.group(1, 2) if u is None: u = '' if p is None: p = '' plain = '{}:{}'.format(u, p) auth = base64.encodebytes(plain.encode('utf-8')) return 'Basic %s' % str(auth.rstrip().decode('latin1')) return header def is_wanted_header(header): """Return True if the given HTTP header key is wanted. """ key, value = header return key.lower() not in ('x-content-type-warning', 'x-powered-by') class AuthorizationMiddleware: """This middleware makes the WSGI application compatible with the HTTPCaller behavior defined in zope.app.testing.functional: - It modifies the HTTP Authorization header to encode user and password into base64 if it is Basic authentication. """ def __init__(self, wsgi_stack): self.wsgi_stack = wsgi_stack def __call__(self, environ, start_response): # Handle authorization auth_key = 'HTTP_AUTHORIZATION' if auth_key in environ: environ[auth_key] = auth_header(environ[auth_key]) # Remove unwanted headers def application_start_response(status, headers, exc_info=None): headers = [h for h in headers if is_wanted_header(h)] start_response(status, headers) yield from self.wsgi_stack(environ, application_start_response) _APP_UNDER_TEST = None # setup and torn down by the Layer class class Layer: """Test layer which sets up WSGI app for use with WebTest/testbrowser. Inherit from this layer and overwrite `make_wsgi_app` for setup. Composing multiple layers into one is supported using plone.testing.Layer. """ __bases__ = () __name__ = 'Layer' @classmethod def get_app(cls): return _APP_UNDER_TEST def make_wsgi_app(self): # Override this method in subclasses of this layer in order to set up # the WSGI application. raise NotImplementedError def cooperative_super(self, method_name): # Calling `super` for multiple inheritance: method = getattr(super(), method_name, None) if method is not None: method() def setUp(self): self.cooperative_super('setUp') global _APP_UNDER_TEST if _APP_UNDER_TEST is not None: raise AssertionError("Already Setup") _APP_UNDER_TEST = self.make_wsgi_app() def tearDown(self): global _APP_UNDER_TEST _APP_UNDER_TEST = None self.cooperative_super('tearDown') class TestBrowserLayer: """Test layer which sets up WSGI app for use with WebTest/testbrowser. This layer is intended for use cases, where `make_wsgi_app` is implemented by another class using multiple inheritance. We used `testSetUp` and `testTearDown` instead of `setUp` and `tearDown` to cooperate with layers from other zope packages, e.g. `zope.app.wsgi.testlayer.BrowserLayer`, since they re-create the DB connection during `testSetUp`. Therefore we need to re-create the app, too. Make sure this layer always comes first in multiple inheritance, because the requirements of other layers should be set up before calling `make_wsgi_app`. In addition, many layers do not make sure to call multiple superclasses using something like `cooperative_super`, thus the methods of this layer may not be called if it comes later. """ def cooperative_super(self, method_name): # Calling `super` for multiple inheritance: method = getattr(super(), method_name, None) if method is not None: return method() def make_wsgi_app(self): if not hasattr(super(), 'make_wsgi_app'): raise NotImplementedError return super().make_wsgi_app() def testSetUp(self): self.cooperative_super('testSetUp') global _APP_UNDER_TEST if _APP_UNDER_TEST is not None: raise AssertionError("Already Setup") _APP_UNDER_TEST = self.make_wsgi_app() def testTearDown(self): global _APP_UNDER_TEST _APP_UNDER_TEST = None self.cooperative_super('testTearDown')
zope.testbrowser
/zope.testbrowser-6.0.tar.gz/zope.testbrowser-6.0/src/zope/testbrowser/wsgi.py
wsgi.py
import zope.interface import zope.interface.common.mapping import zope.schema __docformat__ = "reStructuredText" class AlreadyExpiredError(ValueError): pass class ICookies(zope.interface.common.mapping.IExtendedReadMapping, zope.interface.common.mapping.IExtendedWriteMapping, zope.interface.common.mapping.IMapping): # NOT copy """A mapping of cookies for a given url""" url = zope.schema.URI( title="URL", description="The URL the mapping is currently exposing.", required=True) header = zope.schema.TextLine( title="Header", description="The current value for the Cookie header for the URL", required=True) def forURL(url): """Returns another ICookies instance for the given URL.""" def getinfo(name): """returns dict of settings for the given cookie name. This includes only the following cookie values: - name (str) - value (str), - port (int or None), - domain (str), - path (str or None), - secure (bool), and - expires (datetime.datetime with pytz.UTC timezone or None), - comment (str or None), - commenturl (str or None). (Method name is not camelCase because it is intended to feel like an extension to the mapping interface, which uses all lower case, e.g. iterkeys.) """ def iterinfo(name=None): """iterate over the information about all the cookies for the URL. Each result is a dictionary as described for ``getinfo``. If name is given, iterates over all cookies for given name. (Method name is not camelCase because it is intended to feel like an extension to the mapping interface, which uses all lower case, e.g. iterkeys.) """ def create(name, value, domain=None, expires=None, path=None, secure=None, comment=None, commenturl=None, port=None): """Create a new cookie with the given values. If cookie of the same name, domain, and path exists, raises a ValueError. Expires is a string or a datetime.datetime. timezone-naive datetimes are interpreted as in UTC. If expires is before now, raises AlreadyExpiredError. If the domain or path do not generally match the current URL, raises ValueError. """ def change(name, value=None, domain=None, expires=None, path=None, secure=None, comment=None, commenturl=None, port=None): """Change an attribute of an existing cookie. If cookie does not exist, raises a KeyError.""" def clearAll(): """Clear all cookies for the associated browser, irrespective of URL """ def clearAllSession(): """Clear session cookies for associated browser, irrespective of URL """ class IBrowser(zope.interface.Interface): """A Programmatic Web Browser.""" cookies = zope.schema.Field( title="Cookies", description=("An ICookies mapping for the browser's current URL."), required=True) url = zope.schema.URI( title="URL", description="The URL the browser is currently showing.", required=True) headers = zope.schema.Field( title="Headers", description=("Headers of the HTTP response; a " "``httplib.HTTPMessage``."), required=True) contents = zope.schema.Text( title="Contents", description="The complete response body of the HTTP request.", required=True) isHtml = zope.schema.Bool( title="Is HTML", description="Tells whether the output is HTML or not.", required=True) title = zope.schema.TextLine( title="Title", description="Title of the displayed page", required=False) handleErrors = zope.schema.Bool( title="Handle Errors", description=("Describes whether server-side errors will be handled " "by the publisher. If set to ``False``, the error will " "progress all the way to the test, which is good for " "debugging."), default=True, required=True) followRedirects = zope.schema.Bool( title="Follow Redirects", description=("Describes whether the browser follows redirects. If " "set to ``True``, it will automatically issue ``GET`` " "requests for redirect responses; if set to ``False``, " "it will return redirect responses directly, allowing " "the caller to make assertions about them."), default=True, required=True) def addHeader(key, value): """Adds a header to each HTTP request. Adding additional headers can be useful in many ways, from setting the credentials token to specifying the browser identification string. """ def open(url, data=None): """Open a URL in the browser. The URL must be fully qualified. However, note that the server name and port is arbitrary for Zope 3 functional tests, since the request is sent to the publisher directly. The ``data`` argument describes the data that will be sent as the body of the request. """ def reload(): """Reload the current page. Like a browser reload, if the past request included a form submission, the form data will be resubmitted.""" def goBack(count=1): """Go back in history by a certain amount of visisted pages. The ``count`` argument specifies how far to go back. It is set to 1 by default. """ def getLink(text=None, url=None, id=None, index=0): """Return an ILink from the page. The link is found by the arguments of the method. One or more may be used together. o ``text`` -- A regular expression trying to match the link's text, in other words everything between <a> and </a> or the value of the submit button. o ``url`` -- The URL the link is going to. This is either the ``href`` attribute of an anchor tag or the action of a form. o ``id`` -- The id attribute of the anchor tag submit button. o ``index`` -- When there's more than one link that matches the text/URL, you can specify which one you want. """ lastRequestSeconds = zope.schema.Field( title="Seconds to Process Last Request", description=( """Return how many seconds (or fractions) the last request took. The values returned have the same resolution as the results from ``time.clock``. """), required=True, readonly=True) def getControl(label=None, name=None, index=None): """Get a control from the page. Only one of ``label`` and ``name`` may be provided. ``label`` searches form labels (including submit button values, per the HTML 4.0 spec), and ``name`` searches form field names. Label value is searched as case-sensitive whole words within the labels for each control--that is, a search for 'Add' will match 'Add a contact' but not 'Address'. A word is defined as one or more alphanumeric characters or the underline. If no values are found, the code raises a LookupError. If ``index`` is None (the default) and more than one field matches the search, the code raises an AmbiguityError. If an index is provided, it is used to choose the index from the ambiguous choices. If the index does not exist, the code raises a LookupError. """ def getForm(id=None, name=None, action=None, index=None): """Get a form from the page. Zero or one of ``id``, ``name``, and ``action`` may be provided. If none are provided the index alone is used to determine the return value. If no values are found, the code raises a LookupError. If ``index`` is None (the default) and more than one form matches the search, the code raises an AmbiguityError. If an index is provided, it is used to choose the index from the ambiguous choices. If the index does not exist, the code raises a LookupError. """ class ExpiredError(Exception): """The browser page to which this was attached is no longer active""" class IControl(zope.interface.Interface): """A control (input field) of a page.""" name = zope.schema.TextLine( title="Name", description="The name of the control.", required=True) value = zope.schema.Field( title="Value", description="The value of the control", default=None, required=True) type = zope.schema.Choice( title="Type", description="The type of the control", values=['text', 'password', 'hidden', 'submit', 'checkbox', 'select', 'radio', 'image', 'file'], required=True) disabled = zope.schema.Bool( title="Disabled", description="Describes whether a control is disabled.", default=False, required=False) multiple = zope.schema.Bool( title="Multiple", description=( "Describes whether this control can hold multiple values."), default=False, required=False) def clear(): """Clear the value of the control.""" class IListControl(IControl): """A radio button, checkbox, or select control""" options = zope.schema.List( title="Options", description="""\ A list of possible values for the control.""", required=True) displayOptions = zope.schema.List( # TODO: currently only implemented for select title="Options", description="""\ A list of possible display values for the control.""", required=True) displayValue = zope.schema.Field( # TODO: currently only implemented for select title="Value", description="The value of the control, as rendered by the display", default=None, required=True) def getControl(label=None, value=None, index=None): """return subcontrol for given label or value, disambiguated by index if given. Label value is searched as case-sensitive whole words within the labels for each item--that is, a search for 'Add' will match 'Add a contact' but not 'Address'. A word is defined as one or more alphanumeric characters or the underline.""" controls = zope.interface.Attribute( """a list of subcontrols for the control. mutating list has no effect on control (although subcontrols may be changed as usual).""") class ISubmitControl(IControl): def click(): "click the submit button" class IImageSubmitControl(ISubmitControl): def click(coord=(1, 1)): "click the submit button with optional coordinates" class IItemControl(zope.interface.Interface): """a radio button or checkbox within a larger multiple-choice control""" control = zope.schema.Object( title="Control", description=("The parent control element."), schema=IControl, required=True) disabled = zope.schema.Bool( title="Disabled", description="Describes whether a subcontrol is disabled.", default=False, required=False) selected = zope.schema.Bool( title="Selected", description="Whether the subcontrol is selected", default=None, required=True) optionValue = zope.schema.TextLine( title="Value", description="The value of the subcontrol", default=None, required=False) class ILink(zope.interface.Interface): def click(): """click the link, going to the URL referenced""" url = zope.schema.TextLine( title="URL", description="The normalized URL of the link", required=False) attrs = zope.schema.Dict( title='Attributes', description='The attributes of the link tag', required=False) text = zope.schema.TextLine( title='Text', description='The contained text of the link', required=False) tag = zope.schema.TextLine( title='Tag', description='The tag name of the link (a or area, typically)', required=True) class IForm(zope.interface.Interface): """An HTML form of the page.""" action = zope.schema.TextLine( title="Action", description="The action (or URI) that is opened upon submittance.", required=True) method = zope.schema.Choice( title="Method", description="The method used to submit the form.", values=['post', 'get', 'put'], required=True) enctype = zope.schema.TextLine( title="Encoding Type", description="The type of encoding used to encode the form data.", required=True) name = zope.schema.TextLine( title="Name", description="The value of the `name` attribute in the form tag, " "if specified.", required=True) id = zope.schema.TextLine( title="Id", description="The value of the `id` attribute in the form tag, " "if specified.", required=True) def getControl(label=None, name=None, index=None): """Get a control in the page. Only one of ``label`` and ``name`` may be provided. ``label`` searches form labels (including submit button values, per the HTML 4.0 spec), and ``name`` searches form field names. Label value is searched as case-sensitive whole words within the labels for each control--that is, a search for 'Add' will match 'Add a contact' but not 'Address'. A word is defined as one or more alphanumeric characters or the underline. If no values are found, the code raises a LookupError. If ``index`` is None (the default) and more than one field matches the search, the code raises an AmbiguityError. If an index is provided, it is used to choose the index from the ambiguous choices. If the index does not exist, the code raises a LookupError. """ def submit(label=None, name=None, index=None, coord=(1, 1)): """Submit this form. The `label`, `name`, and `index` arguments select the submit button to use to submit the form. You may label or name, with index to disambiguate. Label value is searched as case-sensitive whole words within the labels for each control--that is, a search for 'Add' will match 'Add a contact' but not 'Address'. A word is defined as one or more alphanumeric characters or the underline. The control code works identically to 'get' except that searches are filtered to find only submit and image controls. """
zope.testbrowser
/zope.testbrowser-6.0.tar.gz/zope.testbrowser-6.0/src/zope/testbrowser/interfaces.py
interfaces.py
import http.client import io import re import time import urllib.parse import urllib.request import urllib.robotparser from contextlib import contextmanager import webtest from bs4 import BeautifulSoup from soupsieve import escape as css_escape from wsgiproxy.proxies import TransparentProxy from zope.cachedescriptors.property import Lazy from zope.interface import implementer import zope.testbrowser.cookies from zope.testbrowser import interfaces __docformat__ = "reStructuredText" HTTPError = urllib.request.HTTPError RegexType = type(re.compile('')) _compress_re = re.compile(r"\s+") class HostNotAllowed(Exception): pass class RobotExclusionError(HTTPError): def __init__(self, *args): super().__init__(*args) # RFC 2606 _allowed_2nd_level = {'example.com', 'example.net', 'example.org'} _allowed = {'localhost', '127.0.0.1'} _allowed.update(_allowed_2nd_level) REDIRECTS = (301, 302, 303, 307) class TestbrowserApp(webtest.TestApp): _last_fragment = "" restricted = False def _assertAllowed(self, url): parsed = urllib.parse.urlparse(url) if self.restricted: # We are in restricted mode, check host part only host = parsed.netloc.partition(':')[0] if host in _allowed: return for dom in _allowed_2nd_level: if host.endswith('.%s' % dom): return raise HostNotAllowed(url) else: # Unrestricted mode: retrieve robots.txt and check against it robotsurl = urllib.parse.urlunsplit( (parsed.scheme, parsed.netloc, '/robots.txt', '', '')) rp = urllib.robotparser.RobotFileParser() rp.set_url(robotsurl) rp.read() if not rp.can_fetch("*", url): msg = "request disallowed by robots.txt" raise RobotExclusionError(url, 403, msg, [], None) def do_request(self, req, status, expect_errors): self._assertAllowed(req.url) response = super().do_request(req, status, expect_errors) # Store _last_fragment in response to preserve fragment for history # (goBack() will not lose fragment). response._last_fragment = self._last_fragment return response def _remove_fragment(self, url): # HACK: we need to preserve fragment part of url, but webtest strips it # from url on every request. So we override this protected method, # assuming it is called on every request and therefore _last_fragment # will not get outdated. ``getRequestUrlWithFragment()`` will # reconstruct url with fragment for the last request. scheme, netloc, path, query, fragment = urllib.parse.urlsplit(url) self._last_fragment = fragment return super()._remove_fragment(url) def getRequestUrlWithFragment(self, response): url = response.request.url if not self._last_fragment: return url return "{}#{}".format(url, response._last_fragment) class SetattrErrorsMixin: _enable_setattr_errors = False def __setattr__(self, name, value): if self._enable_setattr_errors: # cause an attribute error if the attribute doesn't already exist getattr(self, name) # set the value object.__setattr__(self, name, value) @implementer(interfaces.IBrowser) class Browser(SetattrErrorsMixin): """A web user agent.""" _contents = None _controls = None _counter = 0 _response = None _req_headers = None _req_content_type = None _req_referrer = None _history = None __html = None def __init__(self, url=None, wsgi_app=None): self.timer = Timer() self.raiseHttpErrors = True self.handleErrors = True self.followRedirects = True if wsgi_app is None: self.testapp = TestbrowserApp(TransparentProxy()) else: self.testapp = TestbrowserApp(wsgi_app) self.testapp.restricted = True self._req_headers = {} self._history = History() self._enable_setattr_errors = True self._controls = {} if url is not None: self.open(url) @property def url(self): """See zope.testbrowser.interfaces.IBrowser""" if self._response is None: return None return self.testapp.getRequestUrlWithFragment(self._response) @property def isHtml(self): """See zope.testbrowser.interfaces.IBrowser""" return self._response and 'html' in self._response.content_type @property def lastRequestSeconds(self): """See zope.testbrowser.interfaces.IBrowser""" return self.timer.elapsedSeconds @property def title(self): """See zope.testbrowser.interfaces.IBrowser""" if not self.isHtml: raise BrowserStateError('not viewing HTML') titles = self._html.find_all('title') if not titles: return None return self.toStr(titles[0].text) def reload(self): """See zope.testbrowser.interfaces.IBrowser""" if self._response is None: raise BrowserStateError("no URL has yet been .open()ed") def make_request(args): return self.testapp.request(self._response.request) # _req_referrer is left intact, so will be the referrer (if any) of # the request being reloaded. self._processRequest(self.url, make_request) def goBack(self, count=1): """See zope.testbrowser.interfaces.IBrowser""" resp = self._history.back(count, self._response) self._setResponse(resp) @property def contents(self): """See zope.testbrowser.interfaces.IBrowser""" if self._response is not None: return self.toStr(self._response.body) else: return None @property def headers(self): """See zope.testbrowser.interfaces.IBrowser""" resptxt = [] resptxt.append('Status: %s' % self._response.status) for h, v in sorted(self._response.headers.items()): resptxt.append(str("{}: {}".format(h, v))) inp = '\n'.join(resptxt) stream = io.BytesIO(inp.encode('latin1')) return http.client.parse_headers(stream) @property def cookies(self): if self.url is None: raise RuntimeError("no request found") return zope.testbrowser.cookies.Cookies(self.testapp, self.url, self._req_headers) def addHeader(self, key, value): """See zope.testbrowser.interfaces.IBrowser""" if (self.url and key.lower() in ('cookie', 'cookie2') and self.cookies.header): raise ValueError('cookies are already set in `cookies` attribute') self._req_headers[key] = value def open(self, url, data=None, referrer=None): """See zope.testbrowser.interfaces.IBrowser""" url = self._absoluteUrl(url) if data is not None: def make_request(args): return self.testapp.post(url, data, **args) else: def make_request(args): return self.testapp.get(url, **args) self._req_referrer = referrer self._processRequest(url, make_request) def post(self, url, data, content_type=None, referrer=None): if content_type is not None: self._req_content_type = content_type self._req_referrer = referrer return self.open(url, data) def _clickSubmit(self, form, control=None, coord=None): # find index of given control in the form url = self._absoluteUrl(form.action) if control: def make_request(args): index = form.fields[control.name].index(control) return self._submit( form, control.name, index, coord=coord, **args) else: def make_request(args): return self._submit(form, coord=coord, **args) self._req_referrer = self.url self._processRequest(url, make_request) def _processRequest(self, url, make_request): with self._preparedRequest(url) as reqargs: self._history.add(self._response) resp = make_request(reqargs) if self.followRedirects: remaining_redirects = 100 # infinite loops protection while resp.status_int in REDIRECTS and remaining_redirects: remaining_redirects -= 1 self._req_referrer = url url = urllib.parse.urljoin(url, resp.headers['location']) with self._preparedRequest(url) as reqargs: resp = self.testapp.get(url, **reqargs) assert remaining_redirects > 0, ( "redirects chain looks infinite") self._setResponse(resp) self._checkStatus() def _checkStatus(self): # if the headers don't have a status, I suppose there can't be an error if 'Status' in self.headers: code, msg = self.headers['Status'].split(' ', 1) code = int(code) if self.raiseHttpErrors and code >= 400: raise HTTPError(self.url, code, msg, [], None) def _submit(self, form, name=None, index=None, coord=None, **args): # A reimplementation of webtest.forms.Form.submit() to allow to insert # coords into the request fields = form.submit_fields(name, index=index) if coord is not None: fields.extend([('%s.x' % name, coord[0]), ('%s.y' % name, coord[1])]) url = self._absoluteUrl(form.action) if form.method.upper() != "GET": args.setdefault("content_type", form.enctype) else: parsed = urllib.parse.urlparse(url)._replace(query='', fragment='') url = urllib.parse.urlunparse(parsed) return form.response.goto(url, method=form.method, params=fields, **args) def _setResponse(self, response): self._response = response self._changed() def getLink(self, text=None, url=None, id=None, index=0): """See zope.testbrowser.interfaces.IBrowser""" qa = 'a' if id is None else 'a#%s' % css_escape(id) qarea = 'area' if id is None else 'area#%s' % css_escape(id) html = self._html links = html.select(qa) links.extend(html.select(qarea)) matching = [] for elem in links: matches = (isMatching(elem.text, text) and isMatching(elem.get('href', ''), url)) if matches: matching.append(elem) if index >= len(matching): raise LinkNotFoundError() elem = matching[index] baseurl = self._getBaseUrl() return Link(elem, self, baseurl) def follow(self, *args, **kw): """Select a link and follow it.""" self.getLink(*args, **kw).click() def _getBaseUrl(self): # Look for <base href> tag and use it as base, if it exists url = self._response.request.url if b"<base" not in self._response.body: return url # we suspect there is a base tag in body, try to find href there html = self._html if not html.head: return url base = html.head.base if not base: return url return base['href'] or url def getForm(self, id=None, name=None, action=None, index=None): """See zope.testbrowser.interfaces.IBrowser""" zeroOrOne([id, name, action], '"id", "name", and "action"') matching_forms = [] allforms = self._getAllResponseForms() for form in allforms: if ((id is not None and form.id == id) or (name is not None and form.html.form.get('name') == name) or (action is not None and re.search(action, form.action)) or id == name == action is None): matching_forms.append(form) if index is None and not any([id, name, action]): if len(matching_forms) == 1: index = 0 else: raise ValueError( 'if no other arguments are given, index is required.') form = disambiguate(matching_forms, '', index) return Form(self, form) def getControl(self, label=None, name=None, index=None): """See zope.testbrowser.interfaces.IBrowser""" intermediate, msg, available = self._getAllControls( label, name, self._getAllResponseForms(), include_subcontrols=True) control = disambiguate(intermediate, msg, index, controlFormTupleRepr, available) return control def _getAllResponseForms(self): """ Return set of response forms in the order they appear in ``self._response.form``.""" respforms = self._response.forms idxkeys = [k for k in respforms.keys() if isinstance(k, int)] return [respforms[k] for k in sorted(idxkeys)] def _getAllControls(self, label, name, forms, include_subcontrols=False): onlyOne([label, name], '"label" and "name"') # might be an iterator, and we need to iterate twice forms = list(forms) available = None if label is not None: res = self._findByLabel(label, forms, include_subcontrols) msg = 'label %r' % label elif name is not None: include_subcontrols = False res = self._findByName(name, forms) msg = 'name %r' % name if not res: available = list(self._findAllControls(forms, include_subcontrols)) return res, msg, available def _findByLabel(self, label, forms, include_subcontrols=False): # forms are iterable of mech_forms matches = re.compile(r'(^|\b|\W)%s(\b|\W|$)' % re.escape(normalizeWhitespace(label))).search found = [] for wtcontrol in self._findAllControls(forms, include_subcontrols): control = getattr(wtcontrol, 'control', wtcontrol) if control.type == 'hidden': continue for label in wtcontrol.labels: if matches(label): found.append(wtcontrol) break return found def _indexControls(self, form): # Unfortunately, webtest will remove all 'name' attributes from # form.html after parsing. But we need them (at least to locate labels # for radio buttons). So we are forced to reparse part of html, to # extract elements. html = BeautifulSoup(form.text, 'html.parser') tags = ('input', 'select', 'textarea', 'button') return html.find_all(tags) def _findByName(self, name, forms): return [c for c in self._findAllControls(forms) if c.name == name] def _findAllControls(self, forms, include_subcontrols=False): res = [] for f in forms: if f not in self._controls: fc = [] allelems = self._indexControls(f) already_processed = set() for cname, wtcontrol in f.field_order: # we need to group checkboxes by name, but leave # the other controls in the original order, # even if the name repeats if isinstance(wtcontrol, webtest.forms.Checkbox): if cname in already_processed: continue already_processed.add(cname) wtcontrols = f.fields[cname] else: wtcontrols = [wtcontrol] for c in controlFactory(cname, wtcontrols, allelems, self): fc.append((c, False)) for subcontrol in c.controls: fc.append((subcontrol, True)) self._controls[f] = fc controls = [c for c, subcontrol in self._controls[f] if not subcontrol or include_subcontrols] res.extend(controls) return res def _changed(self): self._counter += 1 self._contents = None self._controls = {} self.__html = None @contextmanager def _preparedRequest(self, url): self.timer.start() headers = {} if self._req_referrer is not None: headers['Referer'] = self._req_referrer if self._req_content_type: headers['Content-Type'] = self._req_content_type headers['Connection'] = 'close' headers['Host'] = urllib.parse.urlparse(url).netloc headers['User-Agent'] = 'Python-urllib/2.4' headers.update(self._req_headers) extra_environ = {} if self.handleErrors: extra_environ['paste.throw_errors'] = None headers['X-zope-handle-errors'] = 'True' else: extra_environ['wsgi.handleErrors'] = False extra_environ['paste.throw_errors'] = True extra_environ['x-wsgiorg.throw_errors'] = True headers.pop('X-zope-handle-errors', None) kwargs = {'headers': sorted(headers.items()), 'extra_environ': extra_environ, 'expect_errors': True} yield kwargs self._req_content_type = None self.timer.stop() def _absoluteUrl(self, url): absolute = url.startswith('http://') or url.startswith('https://') if absolute: return str(url) if self._response is None: raise BrowserStateError( "can't fetch relative reference: not viewing any document") return str(urllib.parse.urljoin(self._getBaseUrl(), url)) def toStr(self, s): """Convert possibly unicode object to native string using response charset""" if not self._response.charset: return s if s is None: return None # Might be an iterable, especially the 'class' attribute. if isinstance(s, (list, tuple)): subs = [self.toStr(sub) for sub in s] if isinstance(s, tuple): return tuple(subs) return subs if isinstance(s, bytes): return s.decode(self._response.charset) return s @property def _html(self): if self.__html is None: self.__html = self._response.html return self.__html def controlFactory(name, wtcontrols, elemindex, browser): assert len(wtcontrols) > 0 first_wtc = wtcontrols[0] checkbox = isinstance(first_wtc, webtest.forms.Checkbox) # Create control list if checkbox: ctrlelems = [(wtc, elemindex[wtc.pos]) for wtc in wtcontrols] controls = [CheckboxListControl(name, ctrlelems, browser)] else: controls = [] for wtc in wtcontrols: controls.append(simpleControlFactory( wtc, wtc.form, elemindex, browser)) return controls def simpleControlFactory(wtcontrol, form, elemindex, browser): if isinstance(wtcontrol, webtest.forms.Radio): elems = [e for e in elemindex if e.attrs.get('name') == wtcontrol.name] return RadioListControl(wtcontrol, form, elems, browser) elem = elemindex[wtcontrol.pos] if isinstance(wtcontrol, (webtest.forms.Select, webtest.forms.MultipleSelect)): return ListControl(wtcontrol, form, elem, browser) elif isinstance(wtcontrol, webtest.forms.Submit): if wtcontrol.attrs.get('type', 'submit') == 'image': return ImageControl(wtcontrol, form, elem, browser) else: return SubmitControl(wtcontrol, form, elem, browser) else: return Control(wtcontrol, form, elem, browser) @implementer(interfaces.ILink) class Link(SetattrErrorsMixin): def __init__(self, link, browser, baseurl=""): self._link = link self.browser = browser self._baseurl = baseurl self._browser_counter = self.browser._counter self._enable_setattr_errors = True def click(self): if self._browser_counter != self.browser._counter: raise interfaces.ExpiredError self.browser.open(self.url, referrer=self.browser.url) @property def url(self): relurl = self._link['href'] return self.browser._absoluteUrl(relurl) @property def text(self): txt = normalizeWhitespace(self._link.text) return self.browser.toStr(txt) @property def tag(self): return str(self._link.name) @property def attrs(self): toStr = self.browser.toStr return {toStr(k): toStr(v) for k, v in self._link.attrs.items()} def __repr__(self): return "<{} text='{}' url='{}'>".format( self.__class__.__name__, normalizeWhitespace(self.text), self.url) def controlFormTupleRepr(wtcontrol): return wtcontrol.mechRepr() @implementer(interfaces.IControl) class Control(SetattrErrorsMixin): _enable_setattr_errors = False def __init__(self, control, form, elem, browser): self._control = control self._form = form self._elem = elem self.browser = browser self._browser_counter = self.browser._counter # disable addition of further attributes self._enable_setattr_errors = True @property def disabled(self): return 'disabled' in self._control.attrs @property def readonly(self): return 'readonly' in self._control.attrs @property def type(self): typeattr = self._control.attrs.get('type', None) if typeattr is None: # try to figure out type by tag if self._control.tag == 'textarea': return 'textarea' else: # By default, inputs are of 'text' type return 'text' return self.browser.toStr(typeattr) @property def name(self): if self._control.name is None: return None return self.browser.toStr(self._control.name) @property def multiple(self): return 'multiple' in self._control.attrs @property def value(self): if self.type == 'file': if not self._control.value: return None if self.type == 'image': if not self._control.value: return '' if isinstance(self._control, webtest.forms.Submit): return self.browser.toStr(self._control.value_if_submitted()) val = self._control.value if val is None: return None return self.browser.toStr(val) @value.setter def value(self, value): if self._browser_counter != self.browser._counter: raise interfaces.ExpiredError if self.readonly: raise AttributeError("Trying to set value of readonly control") if self.type == 'file': self.add_file(value, content_type=None, filename=None) else: self._control.value = value def add_file(self, file, content_type, filename): if self.type != 'file': raise TypeError("Can't call add_file on %s controls" % self.type) if hasattr(file, 'read'): contents = file.read() else: contents = file self._form[self.name] = webtest.forms.Upload(filename or '', contents, content_type) def clear(self): if self._browser_counter != self.browser._counter: raise zope.testbrowser.interfaces.ExpiredError self.value = None def __repr__(self): return "<{} name='{}' type='{}'>".format( self.__class__.__name__, self.name, self.type) @Lazy def labels(self): return [self.browser.toStr(label) for label in getControlLabels(self._elem, self._form.html)] @property def controls(self): return [] def mechRepr(self): # emulate mechanize control representation toStr = self.browser.toStr ctrl = self._control if isinstance(ctrl, (webtest.forms.Text, webtest.forms.Email)): tp = ctrl.attrs.get('type') infos = [] if 'readonly' in ctrl.attrs or tp == 'hidden': infos.append('readonly') if 'disabled' in ctrl.attrs: infos.append('disabled') classnames = {'password': "PasswordControl", 'hidden': "HiddenControl", 'email': "EMailControl", } clname = classnames.get(tp, "TextControl") return "<{}({}={}){}>".format( clname, toStr(ctrl.name), toStr(ctrl.value), ' (%s)' % (', '.join(infos)) if infos else '') if isinstance(ctrl, (webtest.forms.File, webtest.forms.Field)): return repr(ctrl) + "<-- unknown" raise NotImplementedError(str((self, ctrl))) @implementer(interfaces.ISubmitControl) class SubmitControl(Control): def click(self): if self._browser_counter != self.browser._counter: raise interfaces.ExpiredError self.browser._clickSubmit(self._form, self._control) @Lazy def labels(self): labels = super().labels labels.append(self._control.value_if_submitted()) if self._elem.text: labels.append(normalizeWhitespace(self._elem.text)) return [label for label in labels if label] def mechRepr(self): name = self.name if self.name is not None else "<None>" value = self.value if self.value is not None else "<None>" extra = ' (disabled)' if self.disabled else '' # Mechanize explicitly told us submit controls were readonly, as # if they could be any other way.... *sigh* Let's take this # opportunity and strip that off. return "<SubmitControl({}={}){}>".format(name, value, extra) @implementer(interfaces.IListControl) class ListControl(Control): def __init__(self, control, form, elem, browser): super().__init__(control, form, elem, browser) # HACK: set default value of a list control and then forget about # initial default values. Otherwise webtest will not allow to set None # as a value of select and radio controls. v = control.value if v: control.value = v # Uncheck all the options Carefully: WebTest used to have # 2-tuples here before commit 1031d82e, and 3-tuples since then. control.options = [option[:1] + (False,) + option[2:] for option in control.options] @property def type(self): return 'select' @property def value(self): val = self._control.value if val is None: return [] if self.multiple and isinstance(val, (list, tuple)): return [self.browser.toStr(v) for v in val] else: return [self.browser.toStr(val)] @value.setter def value(self, value): if not value: self._set_falsy_value(value) else: if not self.multiple and isinstance(value, (list, tuple)): value = value[0] self._control.value = value @property def _selectedIndex(self): return self._control.selectedIndex @_selectedIndex.setter def _selectedIndex(self, index): self._control.force_value(webtest.forms.NoValue) self._control.selectedIndex = index def _set_falsy_value(self, value): self._control.force_value(value) @property def displayValue(self): """See zope.testbrowser.interfaces.IListControl""" # not implemented for anything other than select; cvalue = self._control.value if cvalue is None: return [] if not isinstance(cvalue, list): cvalue = [cvalue] alltitles = [] for key, titles in self._getOptions(): if key in cvalue: alltitles.append(titles[0]) return alltitles @displayValue.setter def displayValue(self, value): if self._browser_counter != self.browser._counter: raise interfaces.ExpiredError if isinstance(value, str): value = [value] if not self.multiple and len(value) > 1: raise ItemCountError( "single selection list, must set sequence of length 0 or 1") values = [] found = set() for key, titles in self._getOptions(): matches = {v for t in titles for v in value if v in t} if matches: values.append(key) found.update(matches) for v in value: if v not in found: raise ItemNotFoundError(v) self.value = values @property def displayOptions(self): """See zope.testbrowser.interfaces.IListControl""" return [titles[0] for key, titles in self._getOptions()] @property def options(self): """See zope.testbrowser.interfaces.IListControl""" return [key for key, title in self._getOptions()] def getControl(self, label=None, value=None, index=None): if self._browser_counter != self.browser._counter: raise interfaces.ExpiredError return getControl(self.controls, label, value, index) @property def controls(self): if self._browser_counter != self.browser._counter: raise interfaces.ExpiredError ctrls = [] for idx, elem in enumerate(self._elem.select('option')): ctrls.append(ItemControl(self, elem, self._form, self.browser, idx)) return ctrls def _getOptions(self): return [(c.optionValue, c.labels) for c in self.controls] def mechRepr(self): # TODO: figure out what is replacement for "[*, ambiguous])" return "<SelectControl(%s=[*, ambiguous])>" % self.name class RadioListControl(ListControl): _elems = None def __init__(self, control, form, elems, browser): super().__init__( control, form, elems[0], browser) self._elems = elems @property def type(self): return 'radio' def __repr__(self): # Return backwards compatible representation return "<ListControl name='%s' type='radio'>" % self.name @property def controls(self): if self._browser_counter != self.browser._counter: raise interfaces.ExpiredError for idx, opt in enumerate(self._elems): yield RadioItemControl(self, opt, self._form, self.browser, idx) @Lazy def labels(self): # Parent radio button control has no labels. Children are labeled. return [] def _set_falsy_value(self, value): # HACK: Force unsetting selected value, by avoiding validity check. # Note, that force_value will not work for webtest.forms.Radio # controls. self._control.selectedIndex = None @implementer(interfaces.IListControl) class CheckboxListControl(SetattrErrorsMixin): def __init__(self, name, ctrlelems, browser): self.name = name self.browser = browser self._browser_counter = self.browser._counter self._ctrlelems = ctrlelems self._enable_setattr_errors = True @property def options(self): opts = [self._trValue(c.optionValue) for c in self.controls] return opts @property def displayOptions(self): return [c.labels[0] for c in self.controls] @property def value(self): ctrls = self.controls val = [self._trValue(c.optionValue) for c in ctrls if c.selected] if len(self._ctrlelems) == 1 and val == [True]: return True return val @value.setter def value(self, value): ctrls = self.controls if isinstance(value, (list, tuple)): for c in ctrls: c.selected = c.optionValue in value else: ctrls[0].selected = value @property def displayValue(self): return [c.labels[0] for c in self.controls if c.selected] @displayValue.setter def displayValue(self, value): found = set() for c in self.controls: matches = {v for v in value if v in c.labels} c.selected = bool(matches) found.update(matches) for v in value: if v not in found: raise ItemNotFoundError(v) @property def multiple(self): return True @property def disabled(self): return all('disabled' in e.attrs for c, e in self._ctrlelems) @property def type(self): return 'checkbox' def getControl(self, label=None, value=None, index=None): if self._browser_counter != self.browser._counter: raise interfaces.ExpiredError return getControl(self.controls, label, value, index) @property def controls(self): return [CheckboxItemControl(self, c, e, c.form, self.browser, i) for i, (c, e) in enumerate(self._ctrlelems)] def clear(self): if self._browser_counter != self.browser._counter: raise zope.testbrowser.interfaces.ExpiredError self.value = [] def mechRepr(self): return "<SelectControl(%s=[*, ambiguous])>" % self.browser.toStr( self.name) @Lazy def labels(self): return [] def __repr__(self): # Return backwards compatible representation return "<ListControl name='%s' type='checkbox'>" % self.name def _trValue(self, chbval): return True if chbval == 'on' else chbval @implementer(interfaces.IImageSubmitControl) class ImageControl(Control): def click(self, coord=(1, 1)): if self._browser_counter != self.browser._counter: raise interfaces.ExpiredError self.browser._clickSubmit(self._form, self._control, coord) def mechRepr(self): return "ImageControl???" # TODO @implementer(interfaces.IItemControl) class ItemControl(SetattrErrorsMixin): def __init__(self, parent, elem, form, browser, index): self._parent = parent self._elem = elem self._index = index self._form = form self.browser = browser self._browser_counter = self.browser._counter self._enable_setattr_errors = True @property def control(self): if self._browser_counter != self.browser._counter: raise interfaces.ExpiredError return self._parent @property def _value(self): return self._elem.attrs.get('value', self._elem.text) @property def disabled(self): return 'disabled' in self._elem.attrs @property def selected(self): """See zope.testbrowser.interfaces.IControl""" if self._parent.multiple: return self._value in self._parent.value else: return self._parent._selectedIndex == self._index @selected.setter def selected(self, value): if self._browser_counter != self.browser._counter: raise interfaces.ExpiredError if self._parent.multiple: values = list(self._parent.value) if value: values.append(self._value) else: values = [v for v in values if v != self._value] self._parent.value = values else: if value: self._parent._selectedIndex = self._index else: self._parent.value = None @property def optionValue(self): return self.browser.toStr(self._value) @property def value(self): # internal alias for convenience implementing getControl() return self.optionValue def click(self): if self._browser_counter != self.browser._counter: raise interfaces.ExpiredError self.selected = not self.selected def __repr__(self): return ( "<ItemControl name='%s' type='select' optionValue=%r selected=%r>" ) % (self._parent.name, self.optionValue, self.selected) @Lazy def labels(self): labels = [self._elem.attrs.get('label'), self._elem.text] return [self.browser.toStr(normalizeWhitespace(lbl)) for lbl in labels if lbl] def mechRepr(self): toStr = self.browser.toStr contents = toStr(normalizeWhitespace(self._elem.text)) id = toStr(self._elem.attrs.get('id')) label = toStr(self._elem.attrs.get('label', contents)) value = toStr(self._value) name = toStr(self._elem.attrs.get('name', value)) # XXX wha???? return ( "<Item name='%s' id=%s contents='%s' value='%s' label='%s'>" ) % (name, id, contents, value, label) class RadioItemControl(ItemControl): @property def optionValue(self): return self.browser.toStr(self._elem.attrs.get('value')) @Lazy def labels(self): return [self.browser.toStr(label) for label in getControlLabels(self._elem, self._form.html)] def __repr__(self): return ( "<ItemControl name='%s' type='radio' optionValue=%r selected=%r>" ) % (self._parent.name, self.optionValue, self.selected) def click(self): # Radio buttons cannot be unselected by clicking on them, see # https://github.com/zopefoundation/zope.testbrowser/issues/68 if not self.selected: super().click() def mechRepr(self): toStr = self.browser.toStr id = toStr(self._elem.attrs.get('id')) value = toStr(self._elem.attrs.get('value')) name = toStr(self._elem.attrs.get('name')) props = [] if self._elem.parent.name == 'label': props.append(( '__label', {'__text': toStr(self._elem.parent.text)})) if self.selected: props.append(('checked', 'checked')) props.append(('type', 'radio')) props.append(('name', name)) props.append(('value', value)) props.append(('id', id)) propstr = ' '.join('{}={!r}'.format(pk, pv) for pk, pv in props) return "<Item name='{}' id='{}' {}>".format(value, id, propstr) class CheckboxItemControl(ItemControl): _control = None def __init__(self, parent, wtcontrol, elem, form, browser, index): super().__init__(parent, elem, form, browser, index) self._control = wtcontrol @property def selected(self): """See zope.testbrowser.interfaces.IControl""" return self._control.checked @selected.setter def selected(self, value): if self._browser_counter != self.browser._counter: raise interfaces.ExpiredError self._control.checked = value @property def optionValue(self): return self.browser.toStr(self._control._value or 'on') @Lazy def labels(self): return [self.browser.toStr(label) for label in getControlLabels(self._elem, self._form.html)] def __repr__(self): return ( "<ItemControl name='%s' type='checkbox' " "optionValue=%r selected=%r>" ) % (self._control.name, self.optionValue, self.selected) def mechRepr(self): id = self.browser.toStr(self._elem.attrs.get('id')) value = self.browser.toStr(self._elem.attrs.get('value')) name = self.browser.toStr(self._elem.attrs.get('name')) props = [] if self._elem.parent.name == 'label': props.append(('__label', {'__text': self.browser.toStr( self._elem.parent.text)})) if self.selected: props.append(('checked', 'checked')) props.append(('name', name)) props.append(('type', 'checkbox')) props.append(('id', id)) props.append(('value', value)) propstr = ' '.join('{}={!r}'.format(pk, pv) for pk, pv in props) return "<Item name='{}' id='{}' {}>".format(value, id, propstr) @implementer(interfaces.IForm) class Form(SetattrErrorsMixin): """HTML Form""" def __init__(self, browser, form): """Initialize the Form browser - a Browser instance form - a webtest.Form instance """ self.browser = browser self._form = form self._browser_counter = self.browser._counter self._enable_setattr_errors = True @property def action(self): return self.browser._absoluteUrl(self._form.action) @property def method(self): return str(self._form.method) @property def enctype(self): return str(self._form.enctype) @property def name(self): return str(self._form.html.form.get('name')) @property def id(self): """See zope.testbrowser.interfaces.IForm""" return str(self._form.id) def submit(self, label=None, name=None, index=None, coord=None): """See zope.testbrowser.interfaces.IForm""" if self._browser_counter != self.browser._counter: raise interfaces.ExpiredError form = self._form if label is not None or name is not None: controls, msg, available = self.browser._getAllControls( label, name, [form]) controls = [c for c in controls if isinstance(c, (ImageControl, SubmitControl))] control = disambiguate( controls, msg, index, controlFormTupleRepr, available) self.browser._clickSubmit(form, control._control, coord) else: # JavaScript sort of submit if index is not None or coord is not None: raise ValueError( 'May not use index or coord without a control') self.browser._clickSubmit(form) def getControl(self, label=None, name=None, index=None): """See zope.testbrowser.interfaces.IBrowser""" if self._browser_counter != self.browser._counter: raise interfaces.ExpiredError intermediate, msg, available = self.browser._getAllControls( label, name, [self._form], include_subcontrols=True) return disambiguate(intermediate, msg, index, controlFormTupleRepr, available) @property def controls(self): return list(self.browser._findAllControls( [self._form], include_subcontrols=True)) def disambiguate(intermediate, msg, index, choice_repr=None, available=None): if intermediate: if index is None: if len(intermediate) > 1: if choice_repr: msg += ' matches:' + ''.join([ '\n %s' % choice_repr(choice) for choice in intermediate]) raise AmbiguityError(msg) else: return intermediate[0] else: try: return intermediate[index] except IndexError: msg = ( '%s\nIndex %d out of range, available choices are 0...%d' ) % (msg, index, len(intermediate) - 1) if choice_repr: msg += ''.join(['\n %d: %s' % (n, choice_repr(choice)) for n, choice in enumerate(intermediate)]) else: if available: msg += '\navailable items:' + ''.join([ '\n %s' % choice_repr(choice) for choice in available]) elif available is not None: # empty list msg += '\n(there are no form items in the HTML)' raise LookupError(msg) def onlyOne(items, description): total = sum([bool(i) for i in items]) if total == 0 or total > 1: raise ValueError( "Supply one and only one of %s as arguments" % description) def zeroOrOne(items, description): if sum([bool(i) for i in items]) > 1: raise ValueError( "Supply no more than one of %s as arguments" % description) def getControl(controls, label=None, value=None, index=None): onlyOne([label, value], '"label" and "value"') if label is not None: options = [c for c in controls if any(isMatching(control_label, label) for control_label in c.labels)] msg = 'label %r' % label elif value is not None: options = [c for c in controls if isMatching(c.value, value)] msg = 'value %r' % value res = disambiguate(options, msg, index, controlFormTupleRepr, available=controls) return res def getControlLabels(celem, html): labels = [] # In case celem is contained in label element, use its text as a label if celem.parent.name == 'label': labels.append(normalizeWhitespace(celem.parent.text)) # find all labels, connected by 'for' attribute controlid = celem.attrs.get('id') if controlid: forlbls = html.select('label[for="%s"]' % controlid) labels.extend([normalizeWhitespace(label.text) for label in forlbls]) return [label for label in labels if label is not None] def normalizeWhitespace(string): return ' '.join(string.split()) def isMatching(string, expr): """Determine whether ``expr`` matches to ``string`` ``expr`` can be None, plain text or regular expression. * If ``expr`` is ``None``, ``string`` is considered matching * If ``expr`` is plain text, its equality to ``string`` will be checked * If ``expr`` is regexp, regexp matching agains ``string`` will be performed """ if expr is None: return True if isinstance(expr, RegexType): return expr.match(normalizeWhitespace(string)) else: return normalizeWhitespace(expr) in normalizeWhitespace(string) class Timer: start_time = 0 end_time = 0 def _getTime(self): return time.perf_counter() def start(self): """Begin a timing period""" self.start_time = self._getTime() self.end_time = None def stop(self): """End a timing period""" self.end_time = self._getTime() @property def elapsedSeconds(self): """Elapsed time from calling `start` to calling `stop` or present time If `stop` has been called, the timing period stopped then, otherwise the end is the current time. """ if self.end_time is None: end_time = self._getTime() else: end_time = self.end_time return end_time - self.start_time def __enter__(self): self.start() def __exit__(self, exc_type, exc_value, traceback): self.stop() class History: """ Though this will become public, the implied interface is not yet stable. """ def __init__(self): self._history = [] # LIFO def add(self, response): self._history.append(response) def back(self, n, _response): response = _response while n > 0 or response is None: try: response = self._history.pop() except IndexError: raise BrowserStateError("already at start of history") n -= 1 return response def clear(self): del self._history[:] class AmbiguityError(ValueError): pass class BrowserStateError(Exception): pass class LinkNotFoundError(IndexError): pass class ItemCountError(ValueError): pass class ItemNotFoundError(ValueError): pass
zope.testbrowser
/zope.testbrowser-6.0.tar.gz/zope.testbrowser-6.0/src/zope/testbrowser/browser.py
browser.py
import re import time import urllib.parse from calendar import timegm strict_re = re.compile(r"^[SMTWF][a-z][a-z], (\d\d) ([JFMASOND][a-z][a-z]) " r"(\d\d\d\d) (\d\d):(\d\d):(\d\d) GMT$") days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] months_lower = [] for month in months: months_lower.append(month.lower()) wkday_re = re.compile( r"^(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)[a-z]*,?\s*", re.I) EPOCH = 1970 def my_timegm(tt): year, month, mday, hour, min, sec = tt[:6] if ((year >= EPOCH) and (1 <= month <= 12) and (1 <= mday <= 31) and (0 <= hour <= 24) and (0 <= min <= 59) and (0 <= sec <= 61)): return timegm(tt) else: return None loose_http_re = re.compile( r"""^ (\d\d?) # day (?:\s+|[-\/]) (\w+) # month (?:\s+|[-\/]) (\d+) # year (?: (?:\s+|:) # separator before clock (\d\d?):(\d\d) # hour:min (?::(\d\d))? # optional seconds )? # optional clock \s* ([-+]?\d{2,4}|(?![APap][Mm]\b)[A-Za-z]+)? # timezone \s* (?:\(\w+\))? # ASCII representation of timezone in parens. \s*$""", re.X) def http2time(text): """Returns time in seconds since epoch of time represented by a string. Return value is an integer. None is returned if the format of str is unrecognized, the time is outside the representable range, or the timezone string is not recognized. If the string contains no timezone, UTC is assumed. The timezone in the string may be numerical (like "-0800" or "+0100") or a string timezone (like "UTC", "GMT", "BST" or "EST"). Currently, only the timezone strings equivalent to UTC (zero offset) are known to the function. The function loosely parses the following formats: Wed, 09 Feb 1994 22:23:32 GMT -- HTTP format Tuesday, 08-Feb-94 14:15:29 GMT -- old rfc850 HTTP format Tuesday, 08-Feb-1994 14:15:29 GMT -- broken rfc850 HTTP format 09 Feb 1994 22:23:32 GMT -- HTTP format (no weekday) 08-Feb-94 14:15:29 GMT -- rfc850 format (no weekday) 08-Feb-1994 14:15:29 GMT -- broken rfc850 format (no weekday) The parser ignores leading and trailing whitespace. The time may be absent. If the year is given with only 2 digits, the function will select the century that makes the year closest to the current date. Note: This was ported from mechanize' _utils.py """ # fast exit for strictly conforming string m = strict_re.search(text) if m: g = m.groups() mon = months_lower.index(g[1].lower()) + 1 tt = (int(g[2]), mon, int(g[0]), int(g[3]), int(g[4]), float(g[5])) return my_timegm(tt) # No, we need some messy parsing... # clean up text = text.lstrip() text = wkday_re.sub("", text, 1) # Useless weekday # tz is time zone specifier string day, mon, yr, hr, min, sec, tz = [None] * 7 # loose regexp parse m = loose_http_re.search(text) if m is not None: day, mon, yr, hr, min, sec, tz = m.groups() else: return None # bad format return _str2time(day, mon, yr, hr, min, sec, tz) UTC_ZONES = {"GMT": None, "UTC": None, "UT": None, "Z": None} timezone_re = re.compile(r"^([-+])?(\d\d?):?(\d\d)?$") def offset_from_tz_string(tz): offset = None if tz in UTC_ZONES: offset = 0 else: m = timezone_re.search(tz) if m: offset = 3600 * int(m.group(2)) if m.group(3): offset = offset + 60 * int(m.group(3)) if m.group(1) == '-': offset = -offset return offset def _str2time(day, mon, yr, hr, min, sec, tz): # translate month name to number # month numbers start with 1 (January) try: mon = months_lower.index(mon.lower()) + 1 except ValueError: # maybe it's already a number try: imon = int(mon) except ValueError: return None if 1 <= imon <= 12: mon = imon else: return None # make sure clock elements are defined if hr is None: hr = 0 if min is None: min = 0 if sec is None: sec = 0 yr = int(yr) day = int(day) hr = int(hr) min = int(min) sec = int(sec) if yr < 1000: # find "obvious" year cur_yr = time.localtime(time.time())[0] m = cur_yr % 100 tmp = yr yr = yr + cur_yr - m m = m - tmp if abs(m) > 50: if m > 0: yr = yr + 100 else: yr = yr - 100 # convert UTC time tuple to seconds since epoch (not timezone-adjusted) t = my_timegm((yr, mon, day, hr, min, sec, tz)) if t is not None: # adjust time using timezone string, to get absolute time since epoch if tz is None: tz = "UTC" tz = tz.upper() offset = offset_from_tz_string(tz) if offset is None: return None t = t - offset return t cut_port_re = re.compile(r":\d+$") IPV4_RE = re.compile(r"\.\d+$") def request_host(request): """Return request-host, as defined by RFC 2965. Variation from RFC: returned value is lowercased, for convenient comparison. """ url = request.get_full_url() host = urllib.parse.urlsplit(url)[1] if host is None: host = request.get_header("Host", "") # remove port, if present return cut_port_re.sub("", host, 1) def effective_request_host(request): """Return a tuple (request-host, effective request-host name).""" erhn = request_host(request) if '.' not in erhn and not IPV4_RE.search(erhn): erhn = erhn + ".local" return erhn
zope.testbrowser
/zope.testbrowser-6.0.tar.gz/zope.testbrowser-6.0/src/zope/testbrowser/utils.py
utils.py
import datetime import http.cookies import time import urllib.parse import urllib.request from collections.abc import MutableMapping from urllib.parse import quote as url_quote import pytz import zope.interface from zope.testbrowser import interfaces from zope.testbrowser import utils # Cookies class helpers class BrowserStateError(Exception): pass class _StubHTTPMessage: def __init__(self, cookies): self._cookies = cookies def getheaders(self, name, default=[]): if name.lower() != 'set-cookie': return default else: return self._cookies get_all = getheaders class _StubResponse: def __init__(self, cookies): self.message = _StubHTTPMessage(cookies) def info(self): return self.message DAY_OF_WEEK = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] MONTH = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ] def expiration_string(expires): # this is not protected so usable in tests. if isinstance(expires, datetime.datetime): if expires.tzinfo is not None: expires = expires.astimezone(pytz.UTC) expires = expires.strftime( '{dow}, %d {mon} %Y %H:%M:%S GMT'.format( dow=DAY_OF_WEEK[expires.weekday()], mon=MONTH[expires.month - 1], ) ) return expires # end Cookies class helpers @zope.interface.implementer(interfaces.ICookies) class Cookies(MutableMapping): """Cookies for testbrowser. """ def __init__(self, testapp, url=None, req_headers=None): self.testapp = testapp self._url = url self._jar = testapp.cookiejar self._req_headers = req_headers if req_headers is not None else {} @property def strict_domain_policy(self): policy = self._jar._policy flags = (policy.DomainStrictNoDots | policy.DomainRFC2965Match | policy.DomainStrictNonDomain) return policy.strict_ns_domain & flags == flags @strict_domain_policy.setter def strict_domain_policy(self, value): jar = self._jar policy = jar._policy flags = (policy.DomainStrictNoDots | policy.DomainRFC2965Match | policy.DomainStrictNonDomain) policy.strict_ns_domain |= flags if not value: policy.strict_ns_domain ^= flags def forURL(self, url): return self.__class__(self.testapp, url) @property def url(self): return self._url @property def _request(self): return urllib.request.Request(self._url) @property def header(self): request = self._request self._jar.add_cookie_header(request) if not request.has_header('Cookie'): return '' hdr = request.get_header('Cookie') # We need a predictable order of cookies for tests, so we reparse and # sort the header here. return '; '.join(sorted(hdr.split('; '))) def __str__(self): return self.header def __repr__(self): # get the cookies for the current url return '<{}.{} object at {!r} for {} ({})>'.format( self.__class__.__module__, self.__class__.__name__, id(self), self.url, self.header) def _raw_cookies(self): # We are using protected cookielib _cookies_for_request() here to avoid # code duplication. # Comply with cookielib internal protocol self._jar._policy._now = self._jar._now = int(time.time()) cookies = self._jar._cookies_for_request(self._request) # Sort cookies so that the longer paths would come first. This allows # masking parent cookies. cookies.sort(key=lambda c: (len(c.path), len(c.domain)), reverse=True) return cookies def _get_cookies(self, key=None): if key is None: seen = set() for ck in self._raw_cookies(): if ck.name not in seen: yield ck seen.add(ck.name) else: for ck in self._raw_cookies(): if ck.name == key: yield ck _marker = object() def _get(self, key, default=_marker): for ck in self._raw_cookies(): if ck.name == key: return ck if default is self._marker: raise KeyError(key) return default def __getitem__(self, key): return self._get(key).value def getinfo(self, key): return self._getinfo(self._get(key)) def _getinfo(self, ck): res = {'name': ck.name, 'value': ck.value, 'port': ck.port, 'domain': ck.domain, 'path': ck.path, 'secure': ck.secure, 'expires': None, 'comment': ck.comment, 'commenturl': ck.comment_url} if ck.expires is not None: res['expires'] = datetime.datetime.fromtimestamp( ck.expires, pytz.UTC) return res def keys(self): return [ck.name for ck in self._get_cookies()] def __iter__(self): return (ck.name for ck in self._get_cookies()) iterkeys = __iter__ def iterinfo(self, key=None): return (self._getinfo(ck) for ck in self._get_cookies(key)) def iteritems(self): return ((ck.name, ck.value) for ck in self._get_cookies()) def has_key(self, key): return self._get(key, None) is not None __contains__ = has_key def __len__(self): return len(list(self._get_cookies())) def __delitem__(self, key): ck = self._get(key) self._jar.clear(ck.domain, ck.path, ck.name) def create(self, name, value, domain=None, expires=None, path=None, secure=None, comment=None, commenturl=None, port=None): if value is None: raise ValueError('must provide value') ck = self._get(name, None) if (ck is not None and (path is None or ck.path == path) and (domain is None or ck.domain == domain or ck.domain == domain) and (port is None or ck.port == port)): # cookie already exists raise ValueError('cookie already exists') if domain is not None: self._verifyDomain(domain, ck) if path is not None: self._verifyPath(path, ck) now = int(time.time()) if expires is not None and self._is_expired(expires, now): raise zope.testbrowser.interfaces.AlreadyExpiredError( 'May not create a cookie that is immediately expired') self._setCookie(name, value, domain, expires, path, secure, comment, commenturl, port, now=now) def change(self, name, value=None, domain=None, expires=None, path=None, secure=None, comment=None, commenturl=None, port=None): now = int(time.time()) if expires is not None and self._is_expired(expires, now): # shortcut del self[name] else: self._change(self._get(name), value, domain, expires, path, secure, comment, commenturl, port, now) def _change(self, ck, value=None, domain=None, expires=None, path=None, secure=None, comment=None, commenturl=None, port=None, now=None): if value is None: value = ck.value if domain is None: domain = ck.domain else: self._verifyDomain(domain, None) if expires is None: expires = ck.expires if path is None: path = ck.path else: self._verifyPath(domain, None) if secure is None: secure = ck.secure if comment is None: comment = ck.comment if commenturl is None: commenturl = ck.comment_url if port is None: port = ck.port self._setCookie(ck.name, value, domain, expires, path, secure, comment, commenturl, port, ck.version, ck=ck, now=now) def _verifyDomain(self, domain, ck): tmp_domain = domain if domain is not None and domain.startswith('.'): tmp_domain = domain[1:] self_host = utils.effective_request_host(self._request) if (self_host != tmp_domain and not self_host.endswith('.' + tmp_domain)): raise ValueError('current url must match given domain') if (ck is not None and ck.domain != tmp_domain and ck.domain.endswith(tmp_domain)): raise ValueError( 'cannot set a cookie that will be hidden by another ' 'cookie for this url (%s)' % (self.url,)) def _verifyPath(self, path, ck): self_path = urllib.parse.urlparse(self.url)[2] if not self_path.startswith(path): raise ValueError('current url must start with path, if given') if ck is not None and ck.path != path and ck.path.startswith(path): raise ValueError( 'cannot set a cookie that will be hidden by another ' 'cookie for this url (%s)' % (self.url,)) def _setCookie(self, name, value, domain, expires, path, secure, comment, commenturl, port, version=None, ck=None, now=None): for nm, val in self._req_headers.items(): if nm.lower() in ('cookie', 'cookie2'): raise ValueError('cookies are already set in `Cookie` header') if domain and not domain.startswith('.'): # we do a dance here so that we keep names that have been passed # in consistent (i.e., if we get an explicit 'example.com' it stays # 'example.com', rather than converting to '.example.com'). tmp_domain = domain domain = None if secure: protocol = 'https' else: protocol = 'http' url = '{}://{}{}'.format(protocol, tmp_domain, path or '/') request = urllib.request.Request(url) else: request = self._request if request is None: # TODO: fix exception raise BrowserStateError( 'cannot create cookie without request or domain') c = http.cookies.SimpleCookie() name = str(name) # Cookie value must be native string c[name] = value if secure: c[name]['secure'] = True if domain: c[name]['domain'] = domain if path: c[name]['path'] = path if expires: c[name]['expires'] = expiration_string(expires) if comment: c[name]['comment'] = url_quote( comment.encode('utf-8'), safe="/?:@&+") if port: c[name]['port'] = port if commenturl: c[name]['commenturl'] = commenturl if version: c[name]['version'] = version # this use of objects like _StubResponse and _StubHTTPMessage is in # fact supported by the documented client cookie API. cookies = self._jar.make_cookies( _StubResponse([c.output(header='').strip()]), request) assert len(cookies) == 1, ( 'programmer error: %d cookies made' % (len(cookies),)) policy = self._jar._policy if now is None: now = int(time.time()) policy._now = self._jar._now = now if not policy.set_ok(cookies[0], request): raise ValueError('policy does not allow this cookie') if ck is not None: self._jar.clear(ck.domain, ck.path, ck.name) self._jar.set_cookie(cookies[0]) def __setitem__(self, key, value): ck = self._get(key, None) if ck is None: self.create(key, value) else: self._change(ck, value) def _is_expired(self, value, now): # now = int(time.time()) dnow = datetime.datetime.fromtimestamp(now, pytz.UTC) if isinstance(value, datetime.datetime): if value.tzinfo is None: if value <= dnow.replace(tzinfo=None): return True elif value <= dnow: return True elif isinstance(value, str): if datetime.datetime.fromtimestamp( utils.http2time(value), pytz.UTC) <= dnow: return True return False def clear(self): # to give expected mapping behavior of resulting in an empty dict, # we use _raw_cookies rather than _get_cookies. for ck in self._raw_cookies(): self._jar.clear(ck.domain, ck.path, ck.name) def clearAllSession(self): self._jar.clear_session_cookies() def clearAll(self): self._jar.clear() def pop(self, k, *args): """See zope.interface.common.mapping.IExtendedWriteMapping """ # Python3' MutableMapping doesn't offer pop() with variable arguments, # so we are reimplementing it here as defined in IExtendedWriteMapping super().pop(k, *args) def itervalues(self): # Method, missing in Py3' MutableMapping, but required by # IIterableMapping return self.values() def iterkeys(self): # Method, missing in Py3' MutableMapping, but required by # IIterableMapping return self.keys()
zope.testbrowser
/zope.testbrowser-6.0.tar.gz/zope.testbrowser-6.0/src/zope/testbrowser/cookies.py
cookies.py
:mod:`zope.testbrowser` API =========================== :mod:`zope.testbrowser.interfaces` ---------------------------------- .. automodule:: zope.testbrowser.interfaces Interfaces ~~~~~~~~~~ .. autointerface:: ICookies :members: .. autointerface:: IBrowser :members: .. autointerface:: ILink :members: .. autointerface:: IForm :members: .. autointerface:: IControl :members: .. autointerface:: IListControl :members: .. autointerface:: ISubmitControl :members: .. autointerface:: IImageSubmitControl :members: .. autointerface:: IItemControl :members: Exceptions ~~~~~~~~~~ .. autoexception:: AlreadyExpiredError .. autoexception:: ExpiredError :mod:`zope.testbrowser.browser` ------------------------------- .. automodule:: zope.testbrowser.browser Classes ~~~~~~~ .. autoclass:: Browser :members:
zope.testbrowser
/zope.testbrowser-6.0.tar.gz/zope.testbrowser-6.0/docs/api.rst
api.rst
Using :mod:`zope.testbrowser` ============================= Different Browsers ------------------ HTTP Browser ~~~~~~~~~~~~ The ``zope.testbrowser.browser`` module exposes a ``Browser`` class that simulates a web browser similar to Mozilla Firefox or IE. .. doctest:: >>> from zope.testbrowser.browser import Browser >>> browser = Browser() This version of the browser object can be used to access any web site just as you would do using a normal web browser. WSGI Test Browser ~~~~~~~~~~~~~~~~~ General usage +++++++++++++ There is also a special version of the ``Browser`` class which uses `WebTest`_ and can be used to do functional testing of WSGI applications. It can be imported from ``zope.testbrowser.wsgi``: .. doctest:: >>> from zope.testbrowser.wsgi import Browser >>> from zope.testbrowser.testing import demo_app >>> browser = Browser('http://localhost/', wsgi_app=demo_app) >>> print(browser.contents) Hello world! ... .. _`WebTest`: http://pypi.python.org/pypi/WebTest You can also use it with zope layers if you * write a subclass of ``zope.testbrowser.wsgi.Layer`` and override the ``make_wsgi_app`` method, then * use an instance of the class as the test layer of your test. Example: .. doctest:: >>> import zope.testbrowser.wsgi >>> class SimpleLayer(zope.testbrowser.wsgi.Layer): ... def make_wsgi_app(self): ... return simple_app Where ``simple_app`` is the callable of your WSGI application. Testing a Zope 2/Zope 3/Bluebream WSGI application ++++++++++++++++++++++++++++++++++++++++++++++++++ When testing a Zope 2/Zope 3/Bluebream WSGI application you should wrap your WSGI application under test into ``zope.testbrowser.wsgi.AuthorizationMiddleware`` as all these application servers expect basic authentication headers to be base64 encoded. This middleware handles this for you. Example when using the layer: .. doctest:: >>> import zope.testbrowser.wsgi >>> class ZopeSimpleLayer(zope.testbrowser.wsgi.Layer): ... def make_wsgi_app(self): ... return zope.testbrowser.wsgi.AuthorizationMiddleware(simple_app) There is also a ``BrowserLayer`` in `zope.app.wsgi.testlayer`_ which does this for you and includes a ``TransactionMiddleware``, too, which could be handy when testing a ZODB based application. However, since the ``BrowserLayer`` in `zope.app.wsgi.testlayer`_ re-creates the ZODB in ``testSetUp``, we need to re-create the WSGI App during ``testSetUp``, too. Therefore use ``TestBrowserLayer`` of ``zope.testbrowser.wsgi`` instead of the simpler ``Layer`` to combine it with the ``BrowserLayer`` in `zope.app.wsgi.testlayer`_: .. doctest:: >>> import zope.testbrowser.wsgi >>> import zope.app.wsgi.testlayer >>> class Layer(zope.testbrowser.wsgi.TestBrowserLayer, ... zope.app.wsgi.testlayer.BrowserLayer): ... pass .. _`zope.app.wsgi.testlayer` : http://pypi.python.org/pypi/zope.app.wsgi Browser Usage ------------- We will test this browser against a WSGI test application: .. doctest:: >>> from zope.testbrowser.ftests.wsgitestapp import WSGITestApplication >>> wsgi_app = WSGITestApplication() An initial page to load can be passed to the ``Browser`` constructor: .. doctest:: >>> browser = Browser('http://localhost/@@/testbrowser/simple.html', wsgi_app=wsgi_app) >>> browser.url 'http://localhost/@@/testbrowser/simple.html' The browser can send arbitrary headers; this is helpful for setting the "Authorization" header or a language value, so that your tests format values the way you expect in your tests, if you rely on zope.i18n locale-based formatting or a similar approach. .. doctest:: >>> browser.addHeader('Authorization', 'Basic mgr:mgrpw') >>> browser.addHeader('Accept-Language', 'en-US') An existing browser instance can also `open` web pages: .. doctest:: >>> browser.open('http://localhost/@@/testbrowser/simple.html') >>> browser.url 'http://localhost/@@/testbrowser/simple.html' Once you have opened a web page initially, best practice for writing testbrowser doctests suggests using 'click' to navigate further (as discussed below), except in unusual circumstances. The test browser complies with the IBrowser interface; see ``zope.testbrowser.interfaces`` for full details on the interface. .. doctest:: >>> from zope.testbrowser import interfaces >>> from zope.interface.verify import verifyObject >>> verifyObject(interfaces.IBrowser, browser) True Page Contents ------------- The contents of the current page are available: .. doctest:: :options: +NORMALIZE_WHITESPACE >>> print(browser.contents) <html> <head> <title>Simple Page</title> </head> <body> <h1>Simple Page</h1> </body> </html> Making assertions about page contents is easy. .. doctest:: >>> '<h1>Simple Page</h1>' in browser.contents True Utilizing the doctest facilities, it also possible to do: .. doctest:: >>> browser.contents '...<h1>Simple Page</h1>...' Note: Unfortunately, ellipsis (...) cannot be used at the beginning of the output (this is a limitation of doctest). Checking for HTML ----------------- Not all URLs return HTML. Of course our simple page does: .. doctest:: >>> browser.open('http://localhost/@@/testbrowser/simple.html') >>> browser.isHtml True But if we load an image (or other binary file), we do not get HTML: .. doctest:: >>> browser.open('http://localhost/@@/testbrowser/zope3logo.gif') >>> browser.isHtml False HTML Page Title ---------------- Another useful helper property is the title: .. doctest:: >>> browser.open('http://localhost/@@/testbrowser/simple.html') >>> browser.title 'Simple Page' If a page does not provide a title, it is simply ``None``: .. doctest:: >>> browser.open('http://localhost/@@/testbrowser/notitle.html') >>> browser.title However, if the output is not HTML, then an error will occur trying to access the title: .. doctest:: >>> browser.open('http://localhost/@@/testbrowser/zope3logo.gif') >>> browser.title Traceback (most recent call last): ... BrowserStateError: not viewing HTML Headers ------- As you can see, the `contents` of the browser does not return any HTTP headers. The headers are accessible via a separate attribute, which is an ``http.client.HTTPMessage`` instance (from the Python's standard library): .. doctest:: >>> from six.moves import http_client >>> browser.open('http://localhost/@@/testbrowser/simple.html') >>> isinstance(browser.headers, http_client.HTTPMessage) True The headers can be accessed as a string: .. doctest:: >>> print(browser.headers) ... # doctest: +NORMALIZE_WHITESPACE Status: 200 OK Content-Length: 109 Content-Type: text/html; charset=UTF-8 Or as a mapping: .. doctest:: >>> browser.headers['content-type'] 'text/html; charset=UTF-8' Cookies ------- When a Set-Cookie header is available, it can be found in the headers, as seen above. Here, we use a view that will make the server set cookies with the values we provide. .. doctest:: >>> browser.open('http://localhost/set_cookie.html?name=foo&value=bar') >>> browser.headers['set-cookie'].replace(';', '') 'foo=bar' It is also available in the browser's ``cookies`` attribute. This is an extended mapping interface that allows getting, setting, and deleting the cookies that the browser is remembering *for the current url*. Here are a few examples. .. doctest:: >>> browser.cookies['foo'] 'bar' >>> browser.cookies.keys() ['foo'] >>> list(browser.cookies.values()) ['bar'] >>> list(browser.cookies.items()) [('foo', 'bar')] >>> 'foo' in browser.cookies True >>> 'bar' in browser.cookies False >>> len(browser.cookies) 1 >>> print(dict(browser.cookies)) {'foo': 'bar'} >>> browser.cookies['sha'] = 'zam' >>> len(browser.cookies) 2 >>> sorted(browser.cookies.items()) [('foo', 'bar'), ('sha', 'zam')] >>> browser.open('http://localhost/get_cookie.html') >>> print(browser.headers.get('set-cookie')) None >>> print(browser.contents) # server got the cookie change foo: bar sha: zam >>> sorted(browser.cookies.items()) [('foo', 'bar'), ('sha', 'zam')] >>> browser.cookies.clearAll() >>> len(browser.cookies) 0 Many more examples, and a discussion of the additional methods available, can be found in cookies.txt. Navigation and Link Objects --------------------------- If you want to simulate clicking on a link, get the link and `click` on it. In the `navigate.html` file there are several links set up to demonstrate the capabilities of the link objects and their `click` method. The simplest way to get a link is via the anchor text. In other words the text you would see in a browser (text and url searches are substring searches): .. doctest:: >>> browser.open('http://localhost/@@/testbrowser/navigate.html') >>> browser.contents '...<a href="navigate.html?message=By+Link+Text">Link Text</a>...' >>> link = browser.getLink('Link Text') >>> link <Link text='Link Text' url='http://localhost/@@/testbrowser/navigate.html?message=By+Link+Text'> Link objects comply with the ILink interface. .. doctest:: >>> verifyObject(interfaces.ILink, link) True Links expose several attributes for easy access. .. doctest:: >>> link.text 'Link Text' >>> link.tag # links can also be image maps. 'a' >>> link.url # it's normalized 'http://localhost/@@/testbrowser/navigate.html?message=By+Link+Text' >>> link.attrs {'href': 'navigate.html?message=By+Link+Text'} Links can be "clicked" and the browser will navigate to the referenced URL. .. doctest:: >>> link.click() >>> browser.url 'http://localhost/@@/testbrowser/navigate.html?message=By+Link+Text' >>> browser.contents '...Message: <em>By Link Text</em>...' When finding a link by its text, whitespace is normalized. .. doctest:: >>> browser.open('http://localhost/@@/testbrowser/navigate.html') >>> browser.contents '...> Link Text \n with Whitespace\tNormalization (and parens) </...' >>> link = browser.getLink('Link Text with Whitespace Normalization ' ... '(and parens)') >>> link <Link text='Link Text with Whitespace Normalization (and parens)'...> >>> link.text 'Link Text with Whitespace Normalization (and parens)' >>> link.click() >>> browser.url 'http://localhost/@@/testbrowser/navigate.html?message=By+Link+Text+with+Normalization' >>> browser.contents '...Message: <em>By Link Text with Normalization</em>...' When a link text matches more than one link, by default the first one is chosen. You can, however, specify the index of the link and thus retrieve a later matching link: .. doctest:: >>> browser.getLink('Link Text') <Link text='Link Text' ...> >>> browser.getLink('Link Text', index=1) <Link text='Link Text with Whitespace Normalization (and parens)' ...> Note that clicking a link object after its browser page has expired will generate an error. .. doctest:: >>> link.click() Traceback (most recent call last): ... ExpiredError You can also find the link by its URL, .. doctest:: >>> browser.open('http://localhost/@@/testbrowser/navigate.html') >>> browser.contents '...<a href="navigate.html?message=By+URL">Using the URL</a>...' >>> browser.getLink(url='?message=By+URL').click() >>> browser.url 'http://localhost/@@/testbrowser/navigate.html?message=By+URL' >>> browser.contents '...Message: <em>By URL</em>...' or its id: .. doctest:: >>> browser.open('http://localhost/@@/testbrowser/navigate.html') >>> browser.contents '...<a href="navigate.html?message=By+Id" id="anchorid">By Anchor Id</a>...' >>> browser.getLink(id='anchorid').click() >>> browser.url 'http://localhost/@@/testbrowser/navigate.html?message=By+Id' >>> browser.contents '...Message: <em>By Id</em>...' You thought we were done here? Not so quickly. The `getLink` method also supports image maps, though not by specifying the coordinates, but using the area's id: .. doctest:: >>> browser.open('http://localhost/@@/testbrowser/navigate.html') >>> link = browser.getLink(id='zope3') >>> link.tag 'area' >>> link.click() >>> browser.url 'http://localhost/@@/testbrowser/navigate.html?message=Zope+3+Name' >>> browser.contents '...Message: <em>Zope 3 Name</em>...' Getting a nonexistent link raises an exception. .. doctest:: >>> browser.open('http://localhost/@@/testbrowser/navigate.html') >>> browser.getLink('This does not exist') Traceback (most recent call last): ... LinkNotFoundError A convenience method is provided to follow links; this uses the same arguments as `getLink`, but clicks on the link instead of returning the link object. .. doctest:: >>> browser.open('http://localhost/@@/testbrowser/navigate.html') >>> browser.contents '...<a href="navigate.html?message=By+Link+Text">Link Text</a>...' >>> browser.follow('Link Text') >>> browser.url 'http://localhost/@@/testbrowser/navigate.html?message=By+Link+Text' >>> browser.contents '...Message: <em>By Link Text</em>...' >>> browser.open('http://localhost/@@/testbrowser/navigate.html') >>> browser.follow(url='?message=By+URL') >>> browser.url 'http://localhost/@@/testbrowser/navigate.html?message=By+URL' >>> browser.contents '...Message: <em>By URL</em>...' >>> browser.open('http://localhost/@@/testbrowser/navigate.html') >>> browser.follow(id='zope3') >>> browser.url 'http://localhost/@@/testbrowser/navigate.html?message=Zope+3+Name' >>> browser.contents '...Message: <em>Zope 3 Name</em>...' Attempting to follow links that don't exist raises the same exception as asking for the link object: .. doctest:: >>> browser.follow('This does not exist') Traceback (most recent call last): ... LinkNotFoundError Other Navigation ---------------- Like in any normal browser, you can reload a page: .. doctest:: >>> browser.open('http://localhost/@@/testbrowser/simple.html') >>> browser.url 'http://localhost/@@/testbrowser/simple.html' >>> browser.reload() >>> browser.url 'http://localhost/@@/testbrowser/simple.html' You can also go back: .. doctest:: >>> browser.open('http://localhost/@@/testbrowser/notitle.html') >>> browser.url 'http://localhost/@@/testbrowser/notitle.html' >>> browser.goBack() >>> browser.url 'http://localhost/@@/testbrowser/simple.html' Controls -------- One of the most important features of the browser is the ability to inspect and fill in values for the controls of input forms. To do so, let's first open a page that has a bunch of controls: .. doctest:: >>> browser.open('http://localhost/@@/testbrowser/controls.html') Obtaining a Control ~~~~~~~~~~~~~~~~~~~ You look up browser controls with the 'getControl' method. The default first argument is 'label', and looks up the form on the basis of any associated label. .. doctest:: >>> control = browser.getControl('Text Control') >>> control <Control name='text-value' type='text'> >>> browser.getControl(label='Text Control') # equivalent <Control name='text-value' type='text'> If you request a control that doesn't exist, the code raises a LookupError: .. doctest:: >>> browser.getControl('Does Not Exist') Traceback (most recent call last): ... LookupError: label 'Does Not Exist' available items: <TextControl(text-value=Some Text)> <PasswordControl(password-value=Password)> <HiddenControl(hidden-value=Hidden) (readonly)> ... If you request a control with an ambiguous lookup, the code raises an AmbiguityError. .. doctest:: >>> browser.getControl('Ambiguous Control') Traceback (most recent call last): ... AmbiguityError: label 'Ambiguous Control' matches: <TextControl(ambiguous-control-name=First)> <TextControl(ambiguous-control-name=Second)> This is also true if an option in a control is ambiguous in relation to the control itself. .. doctest:: >>> browser.getControl('Sub-control Ambiguity') Traceback (most recent call last): ... AmbiguityError: label 'Sub-control Ambiguity' matches: <SelectControl(ambiguous-subcontrol=[*, ambiguous])> <Item name='ambiguous' id=None contents='Sub-control Ambiguity Exemplified' value='ambiguous' label='Sub-control Ambiguity Exemplified'> Ambiguous controls may be specified using an index value. We use the control's value attribute to show the two controls; this attribute is properly introduced below. .. doctest:: >>> browser.getControl('Ambiguous Control', index=0) <Control name='ambiguous-control-name' type='text'> >>> browser.getControl('Ambiguous Control', index=0).value 'First' >>> browser.getControl('Ambiguous Control', index=1).value 'Second' >>> browser.getControl('Sub-control Ambiguity', index=0) <ListControl name='ambiguous-subcontrol' type='select'> >>> browser.getControl('Sub-control Ambiguity', index=1).optionValue 'ambiguous' >>> browser.getControl('Sub-control Ambiguity', index=2) Traceback (most recent call last): ... LookupError: label 'Sub-control Ambiguity' Index 2 out of range, available choices are 0...1 0: <SelectControl(ambiguous-subcontrol=[*, ambiguous])> 1: <Item name='ambiguous' id=None contents='Sub-control Ambiguity Exemplified' value='ambiguous' label='Sub-control Ambiguity Exemplified'> Label searches are against stripped, whitespace-normalized, no-tag versions of the text. Text applied to searches is also stripped and whitespace normalized. The search finds results if the text search finds the whole words of your text in a label. Thus, for instance, a search for 'Add' will match the label 'Add a Client' but not 'Address'. Case is honored. .. doctest:: >>> browser.getControl('Label Needs Whitespace Normalization') <Control name='label-needs-normalization' type='text'> >>> browser.getControl('label needs whitespace normalization') Traceback (most recent call last): ... LookupError: label 'label needs whitespace normalization' ... >>> browser.getControl(' Label Needs Whitespace ') <Control name='label-needs-normalization' type='text'> >>> browser.getControl('Whitespace') <Control name='label-needs-normalization' type='text'> >>> browser.getControl('hitespace') Traceback (most recent call last): ... LookupError: label 'hitespace' ... >>> browser.getControl('[non word characters should not confuse]') <Control name='non-word-characters' type='text'> Multiple labels can refer to the same control (simply because that is possible in the HTML 4.0 spec). .. doctest:: >>> browser.getControl('Multiple labels really') <Control name='two-labels' type='text'> >>> browser.getControl('really are possible') <Control name='two-labels' type='text'> >>> browser.getControl('really') # OK: ambiguous labels, but not ambiguous control <Control name='two-labels' type='text'> A label can be connected with a control using the 'for' attribute and also by containing a control. .. doctest:: >>> browser.getControl( ... 'Labels can be connected by containing their respective fields') <Control name='contained-in-label' type='text'> Get also accepts one other search argument, 'name'. Only one of 'label' and 'name' may be used at a time. The 'name' keyword searches form field names. .. doctest:: >>> browser.getControl(name='text-value') <Control name='text-value' type='text'> >>> browser.getControl(name='ambiguous-control-name') Traceback (most recent call last): ... AmbiguityError: name 'ambiguous-control-name' matches: <TextControl(ambiguous-control-name=First)> <TextControl(ambiguous-control-name=Second)> >>> browser.getControl(name='does-not-exist') Traceback (most recent call last): ... LookupError: name 'does-not-exist' available items: <TextControl(text-value=Some Text)> ... >>> browser.getControl(name='ambiguous-control-name', index=1).value 'Second' Combining 'label' and 'name' raises a ValueError, as does supplying neither of them. .. doctest:: >>> browser.getControl(label='Ambiguous Control', name='ambiguous-control-name') Traceback (most recent call last): ... ValueError: Supply one and only one of "label" and "name" as arguments >>> browser.getControl() Traceback (most recent call last): ... ValueError: Supply one and only one of "label" and "name" as arguments Radio and checkbox fields are unusual in that their labels and names may point to different objects: names point to logical collections of radio buttons or checkboxes, but labels may only be used for individual choices within the logical collection. This means that obtaining a radio button by label gets a different object than obtaining the radio collection by name. Select options may also be searched by label. .. doctest:: >>> browser.getControl(name='radio-value') <ListControl name='radio-value' type='radio'> >>> browser.getControl('Zwei') <ItemControl name='radio-value' type='radio' optionValue='2' selected=True> >>> browser.getControl('One') <ItemControl name='multi-checkbox-value' type='checkbox' optionValue='1' selected=True> >>> browser.getControl('Tres') <ItemControl name='single-select-value' type='select' optionValue='3' selected=False> Radio fields can even have the same name and value and only be distinguished by the id. >>> browser.getControl(name='radio-value-a') <ListControl name='radio-value-a' type='radio'> >>> browser.getControl(name='radio-value-a').getControl(value='true', index=0) <ItemControl name='radio-value-a' type='radio' optionValue='true' selected=False> >>> browser.getControl(name='radio-value-a').getControl(value='true', index=1) <ItemControl name='radio-value-a' type='radio' optionValue='true' selected=False> >>> browser.getControl(name='radio-value-a').getControl(value='true', index=1).selected = True >>> browser.getControl(name='radio-value-a').getControl(value='true', index=0) <ItemControl name='radio-value-a' type='radio' optionValue='true' selected=False> >>> browser.getControl(name='radio-value-a').getControl(value='true', index=1) <ItemControl name='radio-value-a' type='radio' optionValue='true' selected=True> Characteristics of controls and subcontrols are discussed below. Control Objects ~~~~~~~~~~~~~~~ Controls provide IControl. .. doctest:: >>> ctrl = browser.getControl('Text Control') >>> ctrl <Control name='text-value' type='text'> >>> verifyObject(interfaces.IControl, ctrl) True They have several useful attributes: - the name as which the control is known to the form: .. doctest:: >>> ctrl.name 'text-value' - the value of the control, which may also be set: .. doctest:: >>> ctrl.value 'Some Text' >>> ctrl.value = 'More Text' >>> ctrl.value 'More Text' - the type of the control: .. doctest:: >>> ctrl.type 'text' - a flag describing whether the control is disabled: .. doctest:: >>> ctrl.disabled False - and a flag to tell us whether the control can have multiple values: .. doctest:: >>> ctrl.multiple False Additionally, controllers for select, radio, and checkbox provide IListControl. These fields have four other attributes and an additional method: .. doctest:: >>> ctrl = browser.getControl('Multiple Select Control') >>> ctrl <ListControl name='multi-select-value' type='select'> >>> ctrl.disabled False >>> ctrl.multiple True >>> verifyObject(interfaces.IListControl, ctrl) True - 'options' lists all available value options. .. doctest:: >>> ctrl.options ['1', '2', '3'] - 'displayOptions' lists all available options by label. The 'label' attribute on an option has precedence over its contents, which is why our last option is 'Third' in the display. .. doctest:: >>> ctrl.displayOptions ['Un', 'Deux', 'Third'] - 'displayValue' lets you get and set the displayed values of the control of the select box, rather than the actual values. .. doctest:: >>> ctrl.value [] >>> ctrl.displayValue [] >>> ctrl.displayValue = ['Un', 'Deux'] >>> ctrl.displayValue ['Un', 'Deux'] >>> ctrl.value ['1', '2'] >>> ctrl.displayValue = ['Quatre'] Traceback (most recent call last): ... ItemNotFoundError: Quatre - 'controls' gives you a list of the subcontrol objects in the control (subcontrols are discussed below). .. doctest:: :options: +NORMALIZE_WHITESPACE >>> ctrl.controls [<ItemControl name='multi-select-value' type='select' optionValue='1' selected=True>, <ItemControl name='multi-select-value' type='select' optionValue='2' selected=True>, <ItemControl name='multi-select-value' type='select' optionValue='3' selected=False>] - The 'getControl' method lets you get subcontrols by their label or their value. .. doctest:: >>> ctrl.getControl('Un') <ItemControl name='multi-select-value' type='select' optionValue='1' selected=True> >>> ctrl.getControl('Deux') <ItemControl name='multi-select-value' type='select' optionValue='2' selected=True> >>> ctrl.getControl('Trois') # label attribute <ItemControl name='multi-select-value' type='select' optionValue='3' selected=False> >>> ctrl.getControl('Third') # contents <ItemControl name='multi-select-value' type='select' optionValue='3' selected=False> >>> browser.getControl('Third') # ambiguous in the browser, so useful Traceback (most recent call last): ... AmbiguityError: label 'Third' matches: <Item name='3' id=None contents='Tres' value='3' label='Third'> <Item name='3' id=None contents='Trois' value='3' label='Third'> <Item name='3' id='multi-checkbox-value-3' __label={'__text': 'Three\n '} checked='checked' name='multi-checkbox-value' type='checkbox' id='multi-checkbox-value-3' value='3'> <Item name='3' id='radio-value-3' __label={'__text': ' Drei'} type='radio' name='radio-value' value='3' id='radio-value-3'> Finally, submit controls provide ``ISubmitControl``, and image controls provide ``IImageSubmitControl``, which extents ``ISubmitControl``. These both simply add a 'click' method. For image submit controls, you may also provide a coordinates argument, which is a tuple of (x, y). These submit the forms, and are demonstrated below as we examine each control individually. ItemControl Objects ~~~~~~~~~~~~~~~~~~~ As introduced briefly above, using labels to obtain elements of a logical radio button or checkbox collection returns item controls, which are parents. Manipulating the value of these controls affects the parent control. .. doctest:: >>> browser.getControl(name='radio-value').value ['2'] >>> browser.getControl('Zwei').optionValue # read-only. '2' >>> browser.getControl('Zwei').selected True >>> verifyObject(interfaces.IItemControl, browser.getControl('Zwei')) True >>> browser.getControl('Ein').selected = True >>> browser.getControl('Ein').selected True >>> browser.getControl('Zwei').selected False >>> browser.getControl(name='radio-value').value ['1'] >>> browser.getControl('Ein').selected = False >>> browser.getControl(name='radio-value').value [] >>> browser.getControl('Zwei').selected = True Checkbox collections behave similarly, as shown below. Various Controls ~~~~~~~~~~~~~~~~ The various types of controls are demonstrated here. Text Control ~~~~~~~~~~~~ The text control we already introduced above. Password Control ~~~~~~~~~~~~~~~~ .. doctest:: >>> ctrl = browser.getControl('Password Control') >>> ctrl <Control name='password-value' type='password'> >>> verifyObject(interfaces.IControl, ctrl) True >>> ctrl.value 'Password' >>> ctrl.value = 'pass now' >>> ctrl.value 'pass now' >>> ctrl.disabled False >>> ctrl.multiple False Hidden Control ~~~~~~~~~~~~~~ .. doctest:: >>> ctrl = browser.getControl(name='hidden-value') >>> ctrl <Control name='hidden-value' type='hidden'> >>> verifyObject(interfaces.IControl, ctrl) True >>> ctrl.value 'Hidden' >>> ctrl.value = 'More Hidden' >>> ctrl.disabled False >>> ctrl.multiple False Read Only Control ~~~~~~~~~~~~~~~~~ .. doctest:: >>> ctrl = browser.getControl(name='readonly-value') >>> ctrl <Control name='readonly-value' type='text'> >>> verifyObject(interfaces.IControl, ctrl) True >>> ctrl.value 'Read Only Text' >>> ctrl.value = 'Overwrite' Traceback (most recent call last): ... AttributeError: Trying to set value of readonly control >>> ctrl.readonly True >>> ctrl.multiple False Text Area Control ~~~~~~~~~~~~~~~~~ .. doctest:: :options: +NORMALIZE_WHITESPACE >>> ctrl = browser.getControl('Text Area Control') >>> ctrl <Control name='textarea-value' type='textarea'> >>> verifyObject(interfaces.IControl, ctrl) True >>> ctrl.value ' Text inside\n area!\n ' >>> ctrl.value = 'A lot of\n text.' >>> ctrl.disabled False >>> ctrl.multiple False File Control ~~~~~~~~~~~~ File controls are used when a form has a file-upload field. To specify data, call the add_file method, passing: - A file-like object - a content type, and - a file name .. doctest:: >>> ctrl = browser.getControl('File Control') >>> ctrl <Control name='file-value' type='file'> >>> verifyObject(interfaces.IControl, ctrl) True >>> ctrl.value is None True >>> import io >>> ctrl.add_file(io.BytesIO(b'File contents'), ... 'text/plain', 'test.txt') The file control (like the other controls) also knows if it is disabled or if it can have multiple values. >>> ctrl.disabled False >>> ctrl.multiple False Selection Control (Single-Valued) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. doctest:: >>> ctrl = browser.getControl('Single Select Control') >>> ctrl <ListControl name='single-select-value' type='select'> >>> verifyObject(interfaces.IListControl, ctrl) True >>> ctrl.value ['1'] >>> ctrl.value = ['2'] >>> ctrl.disabled False >>> ctrl.multiple False >>> ctrl.options ['1', '2', '3'] >>> ctrl.displayOptions ['Uno', 'Dos', 'Third'] >>> ctrl.displayValue ['Dos'] >>> ctrl.displayValue = ['Tres'] >>> ctrl.displayValue ['Third'] >>> ctrl.displayValue = ['Dos'] >>> ctrl.displayValue ['Dos'] >>> ctrl.displayValue = ['Third'] >>> ctrl.displayValue ['Third'] >>> ctrl.value ['3'] >>> ctrl.displayValue = ['Quatre'] Traceback (most recent call last): ... ItemNotFoundError: Quatre >>> ctrl.displayValue = ['Uno', 'Dos'] Traceback (most recent call last): ... ItemCountError: single selection list, must set sequence of length 0 or 1 Selection Control (Multi-Valued) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This was already demonstrated in the introduction to control objects above. Checkbox Control (Single-Valued; Unvalued) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. doctest:: >>> ctrl = browser.getControl(name='single-unvalued-checkbox-value') >>> ctrl <ListControl name='single-unvalued-checkbox-value' type='checkbox'> >>> verifyObject(interfaces.IListControl, ctrl) True >>> ctrl.value True >>> ctrl.value = False >>> ctrl.disabled False >>> ctrl.multiple True >>> ctrl.options [True] >>> ctrl.displayOptions ['Single Unvalued Checkbox'] >>> ctrl.displayValue [] >>> verifyObject( ... interfaces.IItemControl, ... browser.getControl('Single Unvalued Checkbox')) True >>> browser.getControl('Single Unvalued Checkbox').optionValue 'on' >>> browser.getControl('Single Unvalued Checkbox').selected False >>> ctrl.displayValue = ['Single Unvalued Checkbox'] >>> ctrl.displayValue ['Single Unvalued Checkbox'] >>> browser.getControl('Single Unvalued Checkbox').selected True >>> browser.getControl('Single Unvalued Checkbox').selected = False >>> browser.getControl('Single Unvalued Checkbox').selected False >>> ctrl.displayValue [] >>> browser.getControl( ... name='single-disabled-unvalued-checkbox-value').disabled True >>> ctrl.displayValue = ['Nonsense'] Traceback (most recent call last): ... ItemNotFoundError: Nonsense Checkbox Control (Single-Valued, Valued) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. doctest:: >>> ctrl = browser.getControl(name='single-valued-checkbox-value') >>> ctrl <ListControl name='single-valued-checkbox-value' type='checkbox'> >>> verifyObject(interfaces.IListControl, ctrl) True >>> ctrl.value ['1'] >>> ctrl.value = [] >>> ctrl.disabled False >>> ctrl.multiple True >>> ctrl.options ['1'] >>> ctrl.displayOptions ['Single Valued Checkbox'] >>> ctrl.displayValue [] >>> verifyObject( ... interfaces.IItemControl, ... browser.getControl('Single Valued Checkbox')) True >>> browser.getControl('Single Valued Checkbox').selected False >>> browser.getControl('Single Valued Checkbox').optionValue '1' >>> ctrl.displayValue = ['Single Valued Checkbox'] >>> ctrl.displayValue ['Single Valued Checkbox'] >>> browser.getControl('Single Valued Checkbox').selected True >>> browser.getControl('Single Valued Checkbox').selected = False >>> browser.getControl('Single Valued Checkbox').selected False >>> ctrl.displayValue [] >>> ctrl.displayValue = ['Nonsense'] Traceback (most recent call last): ... ItemNotFoundError: Nonsense - Checkbox Control (Multi-Valued) >>> ctrl = browser.getControl(name='multi-checkbox-value') >>> ctrl <ListControl name='multi-checkbox-value' type='checkbox'> >>> verifyObject(interfaces.IListControl, ctrl) True >>> ctrl.value ['1', '3'] >>> ctrl.value = ['1', '2'] >>> ctrl.disabled False >>> ctrl.multiple True >>> ctrl.options ['1', '2', '3'] >>> ctrl.displayOptions ['One', 'Two', 'Three'] >>> ctrl.displayValue ['One', 'Two'] >>> ctrl.displayValue = ['Two'] >>> ctrl.value ['2'] >>> browser.getControl('Two').optionValue '2' >>> browser.getControl('Two').selected True >>> verifyObject(interfaces.IItemControl, browser.getControl('Two')) True >>> browser.getControl('Three').selected = True >>> browser.getControl('Three').selected True >>> browser.getControl('Two').selected True >>> ctrl.value ['2', '3'] >>> browser.getControl('Two').selected = False >>> ctrl.value ['3'] >>> browser.getControl('Three').selected = False >>> ctrl.value [] >>> ctrl.displayValue = ['Four'] Traceback (most recent call last): ... ItemNotFoundError: Four Radio Control ~~~~~~~~~~~~~ This is how you get a radio button based control: .. doctest:: >>> ctrl = browser.getControl(name='radio-value') This shows the existing value of the control, as it was in the HTML received from the server: .. doctest:: >>> ctrl.value ['2'] We can then unselect it: .. doctest:: >>> ctrl.value = [] >>> ctrl.value [] We can also reselect it: .. doctest:: >>> ctrl.value = ['2'] >>> ctrl.value ['2'] displayValue shows the text the user would see next to the control: .. doctest:: >>> ctrl.displayValue ['Zwei'] This is just unit testing: .. doctest:: >>> ctrl <ListControl name='radio-value' type='radio'> >>> verifyObject(interfaces.IListControl, ctrl) True >>> ctrl.disabled False >>> ctrl.multiple False >>> ctrl.options ['1', '2', '3'] >>> ctrl.displayOptions ['Ein', 'Zwei', 'Drei'] >>> ctrl.displayValue = ['Ein'] >>> ctrl.value ['1'] >>> ctrl.displayValue ['Ein'] >>> ctrl.displayValue = ['Vier'] Traceback (most recent call last): ... ItemNotFoundError: Vier >>> ctrl.displayValue = ['Ein', 'Zwei'] Traceback (most recent call last): ... ItemCountError: single selection list, must set sequence of length 0 or 1 The radio control subcontrols were illustrated above. Image Control ~~~~~~~~~~~~~ .. doctest:: >>> ctrl = browser.getControl(name='image-value') >>> ctrl <ImageControl name='image-value' type='image'> >>> verifyObject(interfaces.IImageSubmitControl, ctrl) True >>> ctrl.value '' >>> ctrl.disabled False >>> ctrl.multiple False Submit Control ~~~~~~~~~~~~~~ .. doctest:: >>> ctrl = browser.getControl(name='submit-value') >>> ctrl <SubmitControl name='submit-value' type='submit'> >>> browser.getControl('Submit This') # value of submit button is a label <SubmitControl name='submit-value' type='submit'> >>> browser.getControl('Standard Submit Control') # label tag is legal <SubmitControl name='submit-value' type='submit'> >>> browser.getControl('Submit') # multiple labels, but same control <SubmitControl name='submit-value' type='submit'> >>> verifyObject(interfaces.ISubmitControl, ctrl) True >>> ctrl.value 'Submit This' >>> ctrl.disabled False >>> ctrl.multiple False Using Submitting Controls ~~~~~~~~~~~~~~~~~~~~~~~~~ Both the submit and image type should be clickable and submit the form: .. doctest:: :options: +NORMALIZE_WHITESPACE >>> browser.getControl('Text Control').value = 'Other Text' >>> browser.getControl('Submit').click() >>> print(browser.contents) <html> ... <em>Other Text</em> <input type="text" name="text-value" id="text-value" value="Some Text" /> ... <em>Submit This</em> <input type="submit" name="submit-value" id="submit-value" value="Submit This" /> ... </html> Note that if you click a submit object after the associated page has expired, you will get an error. .. doctest:: >>> browser.open('http://localhost/@@/testbrowser/controls.html') >>> ctrl = browser.getControl('Submit') >>> ctrl.click() >>> ctrl.click() Traceback (most recent call last): ... ExpiredError All the above also holds true for the image control: .. doctest:: :options: +NORMALIZE_WHITESPACE >>> browser.open('http://localhost/@@/testbrowser/controls.html') >>> browser.getControl('Text Control').value = 'Other Text' >>> browser.getControl(name='image-value').click() >>> print(browser.contents) <html> ... <em>Other Text</em> <input type="text" name="text-value" id="text-value" value="Some Text" /> ... <em>1</em> <em>1</em> <input type="image" name="image-value" id="image-value" src="zope3logo.gif" /> ... </html> >>> browser.open('http://localhost/@@/testbrowser/controls.html') >>> ctrl = browser.getControl(name='image-value') >>> ctrl.click() >>> ctrl.click() Traceback (most recent call last): ... ExpiredError But when sending an image, you can also specify the coordinate you clicked: .. doctest:: :options: +NORMALIZE_WHITESPACE >>> browser.open('http://localhost/@@/testbrowser/controls.html') >>> browser.getControl(name='image-value').click((50,25)) >>> print(browser.contents) <html> ... <em>50</em> <em>25</em> <input type="image" name="image-value" id="image-value" src="zope3logo.gif" /> ... </html> Pages Without Controls ~~~~~~~~~~~~~~~~~~~~~~ What would happen if we tried to look up a control on a page that has none? .. doctest:: >>> browser.open('http://localhost/@@/testbrowser/simple.html') >>> browser.getControl('anything') Traceback (most recent call last): ... LookupError: label 'anything' (there are no form items in the HTML) Forms ----- Because pages can have multiple forms with like-named controls, it is sometimes necessary to access forms by name or id. The browser's `forms` attribute can be used to do so. The key value is the form's name or id. If more than one form has the same name or id, the first one will be returned. .. doctest:: >>> browser.open('http://localhost/@@/testbrowser/forms.html') >>> form = browser.getForm(name='one') Form instances conform to the IForm interface. .. doctest:: >>> verifyObject(interfaces.IForm, form) True The form exposes several attributes related to forms: - The name of the form: .. doctest:: >>> form.name 'one' - The id of the form: .. doctest:: >>> form.id '1' - The action (target URL) when the form is submitted: .. doctest:: >>> form.action 'http://localhost/@@/testbrowser/forms.html' - The method (HTTP verb) used to transmit the form data: .. doctest:: >>> form.method 'GET' Besides those attributes, you have also a couple of methods. Like for the browser, you can get control objects, but limited to the current form... .. doctest:: >>> form.getControl(name='text-value') <Control name='text-value' type='text'> ...and submit the form. .. doctest:: :options: +NORMALIZE_WHITESPACE >>> form.submit('Submit') >>> print(browser.contents) <html> ... <em>First Text</em> ... </html> Submitting also works without specifying a control, as shown below, which is it's primary reason for existing in competition with the control submission discussed above. Now let me show you briefly that looking up forms is sometimes important. In the `forms.html` template, we have four forms all having a text control named `text-value`. Now, if I use the browser's `get` method, .. doctest:: >>> browser.getControl(name='text-value') Traceback (most recent call last): ... AmbiguityError: name 'text-value' matches: <TextControl(text-value=First Text)> <TextControl(text-value=Second Text)> <TextControl(text-value=Third Text)> <TextControl(text-value=Fourth Text)> >>> browser.getControl('Text Control') Traceback (most recent call last): ... AmbiguityError: label 'Text Control' matches: <TextControl(text-value=Third Text)> <TextControl(text-value=Fourth Text)> I'll always get an ambiguous form field. I can use the index argument, or with the `getForm` method I can disambiguate by searching only within a given form: .. doctest:: >>> form = browser.getForm('2') >>> form.getControl(name='text-value').value 'Second Text' >>> form.submit('Submit') >>> browser.contents '...<em>Second Text</em>...' >>> form = browser.getForm('2') >>> form.getControl('Submit').click() >>> browser.contents '...<em>Second Text</em>...' >>> browser.getForm('3').getControl('Text Control').value 'Third Text' The last form on the page does not have a name, an id, or a submit button. Working with it is still easy, thanks to a index attribute that guarantees order. (Forms without submit buttons are sometimes useful for JavaScript.) .. doctest:: >>> form = browser.getForm(index=3) >>> form.submit() >>> browser.contents '...<em>Fourth Text</em>...<em>Submitted without the submit button.</em>...' If a form is requested that does not exists, an exception will be raised. .. doctest:: >>> form = browser.getForm('does-not-exist') Traceback (most recent call last): LookupError If the HTML page contains only one form, no arguments to `getForm` are needed: .. doctest:: >>> oneform = Browser(wsgi_app=wsgi_app) >>> oneform.open('http://localhost/@@/testbrowser/oneform.html') >>> form = oneform.getForm() If the HTML page contains more than one form, `index` is needed to disambiguate if no other arguments are provided: .. doctest:: >>> browser.getForm() Traceback (most recent call last): ValueError: if no other arguments are given, index is required. Submitting a posts body directly -------------------------------- In addition to the open method, Browser has a ``post`` method that allows a request body to be supplied. This method is particularly helpful when testing AJAX methods. Let's visit a page that echos some interesting values from it's request: .. doctest:: >>> browser.open('http://localhost/echo.html') >>> print(browser.contents) HTTP_ACCEPT_LANGUAGE: en-US HTTP_CONNECTION: close HTTP_HOST: localhost HTTP_USER_AGENT: Python-urllib/2.4 PATH_INFO: /echo.html REQUEST_METHOD: GET Body: '' Now, we'll try a post. The post method takes a URL, a data string, and an optional content type. If we just pass a string, then a URL-encoded query string is assumed: .. doctest:: >>> browser.post('http://localhost/echo.html', 'x=1&y=2') >>> print(browser.contents) CONTENT_LENGTH: 7 CONTENT_TYPE: application/x-www-form-urlencoded HTTP_ACCEPT_LANGUAGE: en-US HTTP_CONNECTION: close HTTP_HOST: localhost HTTP_USER_AGENT: Python-urllib/2.4 PATH_INFO: /echo.html REQUEST_METHOD: POST x: 1 y: 2 Body: '' The body is empty because it is consumed to get form data. We can pass a content-type explicitly: .. doctest:: >>> browser.post('http://localhost/echo.html', ... '{"x":1,"y":2}', 'application/x-javascript') >>> print(browser.contents) CONTENT_LENGTH: 13 CONTENT_TYPE: application/x-javascript HTTP_ACCEPT_LANGUAGE: en-US HTTP_CONNECTION: close HTTP_HOST: localhost HTTP_USER_AGENT: Python-urllib/2.4 PATH_INFO: /echo.html REQUEST_METHOD: POST Body: '{"x":1,"y":2}' Here, the body is left in place because it isn't form data. Performance Testing ------------------- Browser objects keep up with how much time each request takes. This can be used to ensure a particular request's performance is within a tolerable range. Be very careful using raw seconds, cross-machine differences can be huge. .. doctest:: >>> browser.open('http://localhost/@@/testbrowser/simple.html') >>> browser.lastRequestSeconds < 10 # really big number for safety True Handling Errors --------------- Often WSGI middleware or the application itself gracefully handle application errors, such as invalid URLs: **Caution:** Because of https://github.com/python/cpython/issues/90113 we currently are not able to demonstrate this feature here as it breaks on Python 3.11. .. doctest:: >>> # Work around https://github.com/python/cpython/issues/90113 >>> browser.raiseHttpErrors = False >>> # Without the workaround we would see a traceback for the next call: >>> browser.open('http://localhost/invalid') >>> browser.headers['status'] '404 Not Found' >>> # Reset work around: >>> browser.raiseHttpErrors = True Note that the above error was thrown by ``mechanize`` and not by the application. For debugging purposes, however, it can be very useful to see the original exception caused by the application. In those cases you can set the ``handleErrors`` property of the browser to ``False``. It is defaulted to ``True``: >>> browser.handleErrors True So when we tell the application not to handle the errors, .. doctest:: >>> browser.handleErrors = False we get a different, internal error from the application: .. doctest:: >>> browser.open('http://localhost/invalid') Traceback (most recent call last): ... NotFound: /invalid .. note:: Setting the ``handleErrors`` attribute to False will only change anything if the WSGI application obeys the ``wsgi.handleErrors`` or ``paste.throw_errors`` WSGI environment variables. i.e. it does not catch and handle the original exception when these are set appropriately. When the testbrowser is raising HttpErrors, the errors still hit the test. Sometimes we don't want that to happen, in situations where there are edge cases that will cause the error to be predictably but infrequently raised. Time is a primary cause of this. To get around this, one can set the raiseHttpErrors to False. .. doctest:: >>> browser.handleErrors = True >>> browser.raiseHttpErrors = False This will cause HttpErrors not to propagate. .. doctest:: >>> browser.open('http://localhost/invalid') The headers are still there, though. .. doctest:: >>> '404 Not Found' in str(browser.headers) True If we don't handle the errors, and allow internal ones to propagate, however, this flag doesn't affect things. .. doctest:: >>> browser.handleErrors = False >>> browser.open('http://localhost/invalid') Traceback (most recent call last): ... NotFound: /invalid >>> browser.raiseHttpErrors = True Hand-Holding ------------ Instances of the various objects ensure that users don't set incorrect instance attributes accidentally. .. doctest:: >>> browser.nonexistant = None Traceback (most recent call last): ... AttributeError: 'Browser' object has no attribute 'nonexistant' >>> form.nonexistant = None Traceback (most recent call last): ... AttributeError: 'Form' object has no attribute 'nonexistant' >>> control.nonexistant = None Traceback (most recent call last): ... AttributeError: 'Control' object has no attribute 'nonexistant' >>> link.nonexistant = None Traceback (most recent call last): ... AttributeError: 'Link' object has no attribute 'nonexistant' HTTPS support ------------- Depending on the scheme of the request the variable wsgi.url_scheme will be set correctly on the request: .. doctest:: >>> browser.open('http://localhost/echo_one.html?var=wsgi.url_scheme') >>> print(browser.contents) 'http' >>> browser.open('https://localhost/echo_one.html?var=wsgi.url_scheme') >>> print(browser.contents) 'https' see http://www.python.org/dev/peps/pep-3333/ for details.
zope.testbrowser
/zope.testbrowser-6.0.tar.gz/zope.testbrowser-6.0/docs/narrative.rst
narrative.rst
Working with Cookies ==================== Getting started --------------- The cookies mapping has an extended mapping interface that allows getting, setting, and deleting the cookies that the browser is remembering for the current url, or for an explicitly provided URL. .. doctest:: >>> from zope.testbrowser.ftests.wsgitestapp import WSGITestApplication >>> from zope.testbrowser.wsgi import Browser >>> wsgi_app = WSGITestApplication() >>> browser = Browser(wsgi_app=wsgi_app) Initially the browser does not point to a URL, and the cookies cannot be used. .. doctest:: >>> len(browser.cookies) Traceback (most recent call last): ... RuntimeError: no request found >>> browser.cookies.keys() Traceback (most recent call last): ... RuntimeError: no request found Once you send the browser to a URL, the cookies attribute can be used. .. doctest:: >>> browser.open('http://localhost/@@/testbrowser/simple.html') >>> len(browser.cookies) 0 >>> browser.cookies.keys() [] >>> browser.url 'http://localhost/@@/testbrowser/simple.html' >>> browser.cookies.url 'http://localhost/@@/testbrowser/simple.html' >>> import zope.testbrowser.interfaces >>> from zope.interface.verify import verifyObject >>> verifyObject(zope.testbrowser.interfaces.ICookies, browser.cookies) True Alternatively, you can use the ``forURL`` method to get another instance of the cookies mapping for the given URL. .. doctest:: >>> len(browser.cookies.forURL('http://www.example.com')) 0 >>> browser.cookies.forURL('http://www.example.com').keys() [] >>> browser.cookies.forURL('http://www.example.com').url 'http://www.example.com' >>> browser.url 'http://localhost/@@/testbrowser/simple.html' >>> browser.cookies.url 'http://localhost/@@/testbrowser/simple.html' Here, we use a view that will make the server set cookies with the values we provide. .. doctest:: >>> browser.open('http://localhost/set_cookie.html?name=foo&value=bar') >>> browser.headers['set-cookie'].replace(';', '') 'foo=bar' Basic Mapping Interface ----------------------- Now the cookies for localhost have a value. These are examples of just the basic accessor operators and methods. .. doctest:: >>> browser.cookies['foo'] 'bar' >>> list(browser.cookies.keys()) ['foo'] >>> list(browser.cookies.values()) ['bar'] >>> list(browser.cookies.items()) [('foo', 'bar')] >>> 'foo' in browser.cookies True >>> 'bar' in browser.cookies False >>> len(browser.cookies) 1 >>> print(dict(browser.cookies)) {'foo': 'bar'} As you would expect, the cookies attribute can also be used to examine cookies that have already been set in a previous request. To demonstrate this, we use another view that does not set cookies but reports on the cookies it receives from the browser. .. doctest:: >>> browser.open('http://localhost/get_cookie.html') >>> print(browser.headers.get('set-cookie')) None >>> browser.contents 'foo: bar' >>> browser.cookies['foo'] 'bar' The standard mapping mutation methods and operators are also available, as seen here. .. doctest:: >>> browser.cookies['sha'] = 'zam' >>> len(browser.cookies) 2 >>> import pprint >>> pprint.pprint(sorted(browser.cookies.items())) [('foo', 'bar'), ('sha', 'zam')] >>> browser.open('http://localhost/get_cookie.html') >>> print(browser.headers.get('set-cookie')) None >>> print(browser.contents) # server got the cookie change foo: bar sha: zam >>> browser.cookies.update({'va': 'voom', 'tweedle': 'dee'}) >>> pprint.pprint(sorted(browser.cookies.items())) [('foo', 'bar'), ('sha', 'zam'), ('tweedle', 'dee'), ('va', 'voom')] >>> browser.open('http://localhost/get_cookie.html') >>> print(browser.headers.get('set-cookie')) None >>> print(browser.contents) foo: bar sha: zam tweedle: dee va: voom >>> del browser.cookies['foo'] >>> del browser.cookies['tweedle'] >>> browser.open('http://localhost/get_cookie.html') >>> print(browser.contents) sha: zam va: voom Headers ~~~~~~~ You can see the Cookies header that will be sent to the browser in the ``header`` attribute and the repr and str. .. doctest:: >>> browser.cookies.header 'sha=zam; va=voom' >>> browser.cookies # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE <zope.testbrowser.cookies.Cookies object at ... for http://localhost/get_cookie.html (sha=zam; va=voom)> >>> str(browser.cookies) 'sha=zam; va=voom' Extended Mapping Interface -------------------------- Read Methods: ``getinfo`` and ``iterinfo`` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ``getinfo`` ########### The ``cookies`` mapping also has an extended interface to get and set extra information about each cookie. :meth:`zope.testbrowser.interfaces.ICookie.getinfo` returns a dictionary. Here are some examples. .. doctest:: >>> browser.open('http://localhost/set_cookie.html?name=foo&value=bar') >>> pprint.pprint(browser.cookies.getinfo('foo')) {'comment': None, 'commenturl': None, 'domain': 'localhost.local', 'expires': None, 'name': 'foo', 'path': '/', 'port': None, 'secure': False, 'value': 'bar'} >>> pprint.pprint(browser.cookies.getinfo('sha')) {'comment': None, 'commenturl': None, 'domain': 'localhost.local', 'expires': None, 'name': 'sha', 'path': '/', 'port': None, 'secure': False, 'value': 'zam'} >>> import datetime >>> expires = datetime.datetime(2030, 1, 1, 12, 22, 33).strftime( ... '%a, %d %b %Y %H:%M:%S GMT') >>> browser.open( ... 'http://localhost/set_cookie.html?name=wow&value=wee&' ... 'expires=%s' % ... (expires,)) >>> pprint.pprint(browser.cookies.getinfo('wow')) {'comment': None, 'commenturl': None, 'domain': 'localhost.local', 'expires': datetime.datetime(2030, 1, 1, 12, 22, ...tzinfo=<UTC>), 'name': 'wow', 'path': '/', 'port': None, 'secure': False, 'value': 'wee'} Max-age is converted to an "expires" value. .. doctest:: >>> browser.open( ... 'http://localhost/set_cookie.html?name=max&value=min&' ... 'max-age=3000&&comment=silly+billy') >>> pprint.pprint(browser.cookies.getinfo('max')) # doctest: +ELLIPSIS {'comment': '"silly billy"', 'commenturl': None, 'domain': 'localhost.local', 'expires': datetime.datetime(..., tzinfo=<UTC>), 'name': 'max', 'path': '/', 'port': None, 'secure': False, 'value': 'min'} ``iterinfo`` ############ You can iterate over all of the information about the cookies for the current page using the ``iterinfo`` method. .. doctest:: >>> pprint.pprint(sorted(browser.cookies.iterinfo(), ... key=lambda info: info['name'])) ... # doctest: +ELLIPSIS [{'comment': None, 'commenturl': None, 'domain': 'localhost.local', 'expires': None, 'name': 'foo', 'path': '/', 'port': None, 'secure': False, 'value': 'bar'}, {'comment': '"silly billy"', 'commenturl': None, 'domain': 'localhost.local', 'expires': datetime.datetime(..., tzinfo=<UTC>), 'name': 'max', 'path': '/', 'port': None, 'secure': False, 'value': 'min'}, {'comment': None, 'commenturl': None, 'domain': 'localhost.local', 'expires': None, 'name': 'sha', 'path': '/', 'port': None, 'secure': False, 'value': 'zam'}, {'comment': None, 'commenturl': None, 'domain': 'localhost.local', 'expires': None, 'name': 'va', 'path': '/', 'port': None, 'secure': False, 'value': 'voom'}, {'comment': None, 'commenturl': None, 'domain': 'localhost.local', 'expires': datetime.datetime(2030, 1, 1, 12, 22, ...tzinfo=<UTC>), 'name': 'wow', 'path': '/', 'port': None, 'secure': False, 'value': 'wee'}] Extended Examples ################# If you want to look at the cookies for another page, you can either navigate to the other page in the browser, or, as already mentioned, you can use the ``forURL`` method, which returns an ICookies instance for the new URL. .. doctest:: >>> sorted(browser.cookies.forURL( ... 'http://localhost/inner/set_cookie.html').keys()) ['foo', 'max', 'sha', 'va', 'wow'] >>> extra_cookie = browser.cookies.forURL( ... 'http://localhost/inner/set_cookie.html') >>> extra_cookie['gew'] = 'gaw' >>> extra_cookie.getinfo('gew')['path'] '/inner' >>> sorted(extra_cookie.keys()) ['foo', 'gew', 'max', 'sha', 'va', 'wow'] >>> sorted(browser.cookies.keys()) ['foo', 'max', 'sha', 'va', 'wow'] >>> browser.open('http://localhost/inner/get_cookie.html') >>> print(browser.contents) # has gewgaw foo: bar gew: gaw max: min sha: zam va: voom wow: wee >>> browser.open('http://localhost/inner/path/get_cookie.html') >>> print(browser.contents) # has gewgaw foo: bar gew: gaw max: min sha: zam va: voom wow: wee >>> browser.open('http://localhost/get_cookie.html') >>> print(browser.contents) # NO gewgaw foo: bar max: min sha: zam va: voom wow: wee Here's an example of the server setting a cookie that is only available on an inner page. .. doctest:: >>> browser.open( ... 'http://localhost/inner/path/set_cookie.html?name=big&value=kahuna' ... ) >>> browser.cookies['big'] 'kahuna' >>> browser.cookies.getinfo('big')['path'] '/inner/path' >>> browser.cookies.getinfo('gew')['path'] '/inner' >>> browser.cookies.getinfo('foo')['path'] '/' >>> print(browser.cookies.forURL('http://localhost/').get('big')) None Write Methods: ``create`` and ``change`` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The basic mapping API only allows setting values. If a cookie already exists for the given name, it's value will be changed; or else a new cookie will be created for the current request's domain and a path of '/', set to last for only this browser session (a "session" cookie). To create or change cookies with different additional information, use the ``create`` and ``change`` methods, respectively. Here is an example of ``create``. .. doctest:: >>> from pytz import UTC >>> browser.cookies.create( ... 'bling', value='blang', path='/inner', ... expires=datetime.datetime(2030, 1, 1, tzinfo=UTC), ... comment='follow swallow') >>> pprint.pprint(browser.cookies.getinfo('bling')) {'comment': 'follow%20swallow', 'commenturl': None, 'domain': 'localhost.local', 'expires': datetime.datetime(2030, 1, 1, 0, 0, tzinfo=<UTC>), 'name': 'bling', 'path': '/inner', 'port': None, 'secure': False, 'value': 'blang'} In these further examples of ``create``, note that the testbrowser sends all domains to Zope, and both http and https. .. doctest:: >>> browser.open('https://dev.example.com/inner/path/get_cookie.html') >>> browser.cookies.keys() # a different domain [] >>> browser.cookies.create('tweedle', 'dee') >>> pprint.pprint(browser.cookies.getinfo('tweedle')) {'comment': None, 'commenturl': None, 'domain': 'dev.example.com', 'expires': None, 'name': 'tweedle', 'path': '/inner/path', 'port': None, 'secure': False, 'value': 'dee'} >>> browser.cookies.create( ... 'boo', 'yah', domain='.example.com', path='/inner', secure=True) >>> pprint.pprint(browser.cookies.getinfo('boo')) {'comment': None, 'commenturl': None, 'domain': '.example.com', 'expires': None, 'name': 'boo', 'path': '/inner', 'port': None, 'secure': True, 'value': 'yah'} >>> sorted(browser.cookies.keys()) ['boo', 'tweedle'] >>> browser.open('https://dev.example.com/inner/path/get_cookie.html') >>> print(browser.contents) boo: yah tweedle: dee >>> browser.open( # not https, so not secure, so not 'boo' ... 'http://dev.example.com/inner/path/get_cookie.html') >>> sorted(browser.cookies.keys()) ['tweedle'] >>> print(browser.contents) tweedle: dee >>> browser.open( # not tweedle's domain ... 'https://prod.example.com/inner/path/get_cookie.html') >>> sorted(browser.cookies.keys()) ['boo'] >>> print(browser.contents) boo: yah >>> browser.open( # not tweedle's domain ... 'https://example.com/inner/path/get_cookie.html') >>> sorted(browser.cookies.keys()) ['boo'] >>> print(browser.contents) boo: yah >>> browser.open( # not tweedle's path ... 'https://dev.example.com/inner/get_cookie.html') >>> sorted(browser.cookies.keys()) ['boo'] >>> print(browser.contents) boo: yah Masking by Path ############### The API allows creation of cookies that mask existing cookies, but it does not allow creating a cookie that will be immediately masked upon creation. Having multiple cookies with the same name for a given URL is rare, and is a pathological case for using a mapping API to work with cookies, but it is supported to some degree, as demonstrated below. Note that the Cookie RFCs (2109, 2965) specify that all matching cookies be sent to the server, but with an ordering so that more specific paths come first. We also prefer more specific domains, though the RFCs state that the ordering of cookies with the same path is indeterminate. The best-matching cookie is the one that the mapping API uses. Also note that ports, as sent by RFC 2965's Cookie2 and Set-Cookie2 headers, are parsed and stored by this API but are not used for filtering as of this writing. This is an example of making one cookie that masks another because of path. First, unless you pass an explicit path, you will be modifying the existing cookie. .. doctest:: >>> browser.open('https://dev.example.com/inner/path/get_cookie.html') >>> print(browser.contents) boo: yah tweedle: dee >>> browser.cookies.getinfo('boo')['path'] '/inner' >>> browser.cookies['boo'] = 'hoo' >>> browser.cookies.getinfo('boo')['path'] '/inner' >>> browser.cookies.getinfo('boo')['secure'] True Now we mask the cookie, using the path. .. doctest:: >>> browser.cookies.create('boo', 'boo', path='/inner/path') >>> browser.cookies['boo'] 'boo' >>> browser.cookies.getinfo('boo')['path'] '/inner/path' >>> browser.cookies.getinfo('boo')['secure'] False >>> browser.cookies['boo'] 'boo' >>> sorted(browser.cookies.keys()) ['boo', 'tweedle'] To identify the additional cookies, you can change the URL... .. doctest:: >>> extra_cookies = browser.cookies.forURL( ... 'https://dev.example.com/inner/get_cookie.html') >>> extra_cookies['boo'] 'hoo' >>> extra_cookies.getinfo('boo')['path'] '/inner' >>> extra_cookies.getinfo('boo')['secure'] True ...or use ``iterinfo`` and pass in a name. .. doctest:: >>> pprint.pprint(list(browser.cookies.iterinfo('boo'))) [{'comment': None, 'commenturl': None, 'domain': 'dev.example.com', 'expires': None, 'name': 'boo', 'path': '/inner/path', 'port': None, 'secure': False, 'value': 'boo'}, {'comment': None, 'commenturl': None, 'domain': '.example.com', 'expires': None, 'name': 'boo', 'path': '/inner', 'port': None, 'secure': True, 'value': 'hoo'}] An odd situation in this case is that deleting a cookie can sometimes reveal another one. .. doctest:: >>> browser.open('https://dev.example.com/inner/path/get_cookie.html') >>> browser.cookies['boo'] 'boo' >>> del browser.cookies['boo'] >>> browser.cookies['boo'] 'hoo' Creating a cookie that will be immediately masked within the current url is not allowed. .. doctest:: >>> browser.cookies.getinfo('tweedle')['path'] '/inner/path' >>> browser.cookies.create('tweedle', 'dum', path='/inner') ... # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ValueError: cannot set a cookie that will be hidden by another cookie for this url (https://dev.example.com/inner/path/get_cookie.html) >>> browser.cookies['tweedle'] 'dee' Masking by Domain ################# All of the same behavior is also true for domains. The only difference is a theoretical one: while the behavior of masking cookies via paths is defined by the relevant IRCs, it is not defined for domains. Here, we simply follow a "best match" policy. We initialize by setting some cookies for example.org. .. doctest:: >>> browser.open('https://dev.example.org/get_cookie.html') >>> browser.cookies.keys() # a different domain [] >>> browser.cookies.create('tweedle', 'dee') >>> browser.cookies.create('boo', 'yah', domain='example.org', ... secure=True) Before we look at the examples, note that the default behavior of the cookies is to be liberal in the matching of domains. .. doctest:: >>> browser.cookies.strict_domain_policy False According to the RFCs, a domain of 'example.com' can only be set implicitly from the server, and implies an exact match, so example.com URLs will get the cookie, but not ``*.example.com`` (i.e., ``dev.example.com``). Real browsers vary in their behavior in this regard. The cookies collection, by default, has a looser interpretation of this, such that domains are always interpreted as effectively beginning with a ".", so ``dev.example.com`` will include a cookie from the ``example.com`` domain filter as if it were a ``.example.com`` filter. Here's an example. If we go to ``dev.example.org``, we should only see the "tweedle" cookie if we are using strict rules. But right now we are using loose rules, so 'boo' is around too. >>> browser.open('https://dev.example.org/get_cookie.html') >>> sorted(browser.cookies) ['boo', 'tweedle'] >>> print(browser.contents) boo: yah tweedle: dee If we set ``strict_domain_policy`` to True, then only tweedle is included. .. doctest:: >>> browser.cookies.strict_domain_policy = True >>> sorted(browser.cookies) ['tweedle'] >>> browser.open('https://dev.example.org/get_cookie.html') >>> print(browser.contents) tweedle: dee If we set the "boo" domain to ``.example.org`` (as it would be set under the more recent Cookie RFC if a server sent the value) then maybe we get the "boo" value again. .. doctest:: >>> browser.cookies.forURL('https://example.org').change( ... 'boo', domain=".example.org") Traceback (most recent call last): ... ValueError: policy does not allow this cookie Whoa! Why couldn't we do that? Well, the strict_domain_policy affects what cookies we can set also. With strict rules, ".example.org" can only be set by "*.example.org" domains, *not* example.org itself. OK, we'll create a new cookie then. .. doctest:: >>> browser.cookies.forURL('https://snoo.example.org').create( ... 'snoo', 'kums', domain=".example.org") >>> sorted(browser.cookies) ['snoo', 'tweedle'] >>> browser.open('https://dev.example.org/get_cookie.html') >>> print(browser.contents) snoo: kums tweedle: dee Let's set things back to the way they were. .. doctest:: >>> del browser.cookies['snoo'] >>> browser.cookies.strict_domain_policy = False >>> browser.open('https://dev.example.org/get_cookie.html') >>> sorted(browser.cookies) ['boo', 'tweedle'] >>> print(browser.contents) boo: yah tweedle: dee Now back to the the examples of masking by domain. First, unless you pass an explicit domain, you will be modifying the existing cookie. .. doctest:: >>> browser.cookies.getinfo('boo')['domain'] 'example.org' >>> browser.cookies['boo'] = 'hoo' >>> browser.cookies.getinfo('boo')['domain'] 'example.org' >>> browser.cookies.getinfo('boo')['secure'] True Now we mask the cookie, using the domain. .. doctest:: >>> browser.cookies.create('boo', 'boo', domain='dev.example.org') >>> browser.cookies['boo'] 'boo' >>> browser.cookies.getinfo('boo')['domain'] 'dev.example.org' >>> browser.cookies.getinfo('boo')['secure'] False >>> browser.cookies['boo'] 'boo' >>> sorted(browser.cookies.keys()) ['boo', 'tweedle'] To identify the additional cookies, you can change the URL... .. doctest:: >>> extra_cookies = browser.cookies.forURL( ... 'https://example.org/get_cookie.html') >>> extra_cookies['boo'] 'hoo' >>> extra_cookies.getinfo('boo')['domain'] 'example.org' >>> extra_cookies.getinfo('boo')['secure'] True ...or use ``iterinfo`` and pass in a name. .. doctest:: >>> pprint.pprint(list(browser.cookies.iterinfo('boo'))) # doctest: +REPORT_NDIFF [{'comment': None, 'commenturl': None, 'domain': 'dev.example.org', 'expires': None, 'name': 'boo', 'path': '/', 'port': None, 'secure': False, 'value': 'boo'}, {'comment': None, 'commenturl': None, 'domain': 'example.org', 'expires': None, 'name': 'boo', 'path': '/', 'port': None, 'secure': True, 'value': 'hoo'}] An odd situation in this case is that deleting a cookie can sometimes reveal another one. .. doctest:: >>> browser.open('https://dev.example.org/get_cookie.html') >>> browser.cookies['boo'] 'boo' >>> del browser.cookies['boo'] >>> browser.cookies['boo'] 'hoo' Setting a cookie with a foreign domain from the current URL is not allowed (use forURL to get around this). .. doctest:: >>> browser.cookies.create('tweedle', 'dum', domain='locahost.local') Traceback (most recent call last): ... ValueError: current url must match given domain >>> browser.cookies['tweedle'] 'dee' Setting a cookie that will be immediately masked within the current url is also not allowed. .. doctest:: >>> browser.cookies.getinfo('tweedle')['domain'] 'dev.example.org' >>> browser.cookies.create('tweedle', 'dum', domain='.example.org') ... # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ValueError: cannot set a cookie that will be hidden by another cookie for this url (https://dev.example.org/get_cookie.html) >>> browser.cookies['tweedle'] 'dee' ``change`` ########## So far all of our examples in this section have centered on ``create``. ``change`` allows making changes to existing cookies. Changing expiration is a good example. .. doctest:: >>> browser.open("http://localhost/@@/testbrowser/cookies.html") >>> browser.cookies['foo'] = 'bar' >>> browser.cookies.change('foo', expires=datetime.datetime(2031, 1, 1)) >>> browser.cookies.getinfo('foo')['expires'] datetime.datetime(2031, 1, 1, 0, 0, tzinfo=<UTC>) That's the main story. Now here are some edge cases. .. doctest:: >>> browser.cookies.change( ... 'foo', ... expires=zope.testbrowser.cookies.expiration_string( ... datetime.datetime(2030, 1, 1))) >>> browser.cookies.getinfo('foo')['expires'] datetime.datetime(2030, 1, 1, 0, 0, tzinfo=<UTC>) >>> browser.cookies.forURL( ... 'http://localhost/@@/testbrowser/cookies.html').change( ... 'foo', ... expires=zope.testbrowser.cookies.expiration_string( ... datetime.datetime(2029, 1, 1))) >>> browser.cookies.getinfo('foo')['expires'] datetime.datetime(2029, 1, 1, 0, 0, tzinfo=<UTC>) >>> browser.cookies['foo'] 'bar' >>> browser.cookies.change('foo', expires=datetime.datetime(1999, 1, 1)) >>> len(browser.cookies) 4 While we are at it, it is worth noting that trying to create a cookie that has already expired raises an error. .. doctest:: >>> browser.cookies.create('foo', 'bar', ... expires=datetime.datetime(1999, 1, 1)) Traceback (most recent call last): ... AlreadyExpiredError: May not create a cookie that is immediately expired Clearing cookies ~~~~~~~~~~~~~~~~ clear, clearAll, clearAllSession allow various clears of the cookies. The ``clear`` method clears all of the cookies for the current page. .. doctest:: >>> browser.open('http://localhost/@@/testbrowser/cookies.html') >>> len(browser.cookies) 4 >>> browser.cookies.clear() >>> len(browser.cookies) 0 The ``clearAllSession`` method clears *all* session cookies (for all domains and paths, not just the current URL), as if the browser had been restarted. .. doctest:: >>> browser.cookies.clearAllSession() >>> len(browser.cookies) 0 The ``clearAll`` removes all cookies for the browser. .. doctest:: >>> browser.cookies.clearAll() >>> len(browser.cookies) 0 Note that explicitly setting a Cookie header is an error if the ``cookies`` mapping has any values; and adding a new cookie to the ``cookies`` mapping is an error if the Cookie header is already set. This is to prevent hard-to- diagnose intermittent errors when one header or the other wins. >>> browser.cookies['boo'] = 'yah' >>> browser.addHeader('Cookie', 'gee=gaw') Traceback (most recent call last): ... ValueError: cookies are already set in `cookies` attribute >>> browser.cookies.clearAll() >>> browser.addHeader('Cookie', 'gee=gaw') >>> browser.cookies['fee'] = 'fi' Traceback (most recent call last): ... ValueError: cookies are already set in `Cookie` header
zope.testbrowser
/zope.testbrowser-6.0.tar.gz/zope.testbrowser-6.0/docs/cookies.rst
cookies.rst
========= Changes ========= 5.0.1 (2022-12-20) ================== - Make wheels no longer universal. 5.0 (2022-12-20) ================ Backwards incompatible changes ------------------------------ - Drop support for Python 2.7, 3.5, 3.6. - Drop modules which do not seem to be Python compatible: + ``zope.testing.loghandler`` + ``zope.testing.server`` - Drop doctest option ``IGNORE_EXCEPTION_MODULE_IN_PYTHON2``. - Remove functions: + ``zope.testing.renormalizing.strip_dottedname_from_traceback`` + ``zope.testing.renormalizing.is_dotted_name`` Features -------- - Add support for Python 3.11. 4.10 (2022-03-07) ================= - Show deprecation warnings when importing modules which are not ported to Python 3. - Improve test coverage. - Port ``zope.testing.formparser`` to Python 3. - Add support for Python 3.10. 4.9 (2021-01-08) ================ - Make ``setupstack.txt`` test work again if the current directory is empty. 4.8 (2021-01-04) ================ - Add support for Python 3.8 and 3.9. - Drop support for Python 3.3 and 3.4. - Extend IGNORE_EXCEPTION_MODULE_IN_PYTHON2 to cover also exceptions without arguments (thus without a colon on the last line of the traceback output). 4.7 (2018-10-04) ================ - Added support for Python 3.7. 4.6.2 (2017-06-12) ================== - Remove dependencies on ``zope.interface`` and ``zope.exceptions``; they're not used here. - Remove use of 2to3 for outdated versions of PyPy3, letting us build universal wheels. 4.6.1 (2017-01-04) ================== - Add support for Python 3.6. 4.6.0 (2016-10-20) ================== - Introduce option flag ``IGNORE_EXCEPTION_MODULE_IN_PYTHON2`` to normalize exception class names in traceback output. In Python 3 they are displayed as the full dotted name. In Python 2 they are displayed as "just" the class name. When running doctests in Python 3, the option flag will not have any effect, however when running the same test in Python 2, the segments in the full dotted name leading up to the class name are stripped away from the "expected" string. - Drop support for Python 2.6 and 3.2. - Add support for Python 3.5. - Cleaned up useless 2to3 conversion. 4.5.0 (2015-09-02) ================== - Added meta data for test case methods created with ``zope.testing.doctestcase``. - Reasonable values for ``__name__``, making sure that ``__name__`` starts with ``test``. - For ``doctestfile`` methods, provide ``filename`` and ``filepath`` attributes. The meta data us useful, for example, for selecting tests with the nose attribute mechanism. - Added ``doctestcase.doctestfiles`` - Define multiple doctest files at once. - Automatically assign test class members. So rather than:: class MYTests(unittest.TestCase): ... test_foo = doctestcase.doctestfile('foo.txt') You can use:: @doctestcase.doctestfiles('foo.txt', 'bar.txt', ...) class MYTests(unittest.TestCase): ... 4.4.0 (2015-07-16) ================== - Added ``zope.testing.setupstack.mock`` as a convenience function for setting up mocks in tests. (The Python ``mock`` package must be in the path for this to work. The excellent ``mock`` package isn't a dependency of ``zope.testing``.) - Added the base class ``zope.testing.setupstack.TestCase`` to make it much easier to use ``zope.testing.setupstack`` in ``unittest`` test cases. 4.3.0 (2015-07-15) ================== - Added support for creating doctests as methods of ``unittest.TestCase`` classes so that they can found automatically by test runners, like *nose* that ignore test suites. 4.2.0 (2015-06-01) ================== - **Actually** remove long-deprecated ``zope.testing.doctest`` (announced as removed in 4.0.0) and ``zope.testing.doctestunit``. - Add support for PyPy and PyPy3. 4.1.3 (2014-03-19) ================== - Add support for Python 3.4. - Update ``boostrap.py`` to version 2.2. 4.1.2 (2013-02-19) ================== - Adjust Trove classifiers to reflect the currently supported Python versions. Officially drop Python 2.4 and 2.5. Add Python 3.3. - LP: #1055720: Fix failing test on Python 3.3 due to changed exception messaging. 4.1.1 (2012-02-01) ================== - Fix: Windows test failure. 4.1.0 (2012-01-29) ================== - Add context-manager support to ``zope.testing.setupstack`` - Make ``zope.testing.setupstack`` usable with all tests, not just doctests and added ``zope.testing.setupstack.globs``, which makes it easier to write test setup code that workes with doctests and other kinds of tests. - Add the ``wait`` module, which makes it easier to deal with non-deterministic timing issues. - Rename ``zope.testing.renormalizing.RENormalizing`` to ``zope.testing.renormalizing.OutputChecker``. The old name is an alias. - Update tests to run with Python 3. - Label more clearly which features are supported by Python 3. - Reorganize documentation. 4.0.0 (2011-11-09) ================== - Remove the deprecated ``zope.testing.doctest``. - Add Python 3 support. - Fix test which fails if there is a file named `Data.fs` in the current working directory. 3.10.2 (2010-11-30) =================== - Fix test of broken symlink handling to not break on Windows. 3.10.1 (2010-11-29) =================== - Fix removal of broken symlinks on Unix. 3.10.0 (2010-07-21) =================== - Remove ``zope.testing.testrunner``, which now is moved to zope.testrunner. - Update fix for LP #221151 to a spelling compatible with Python 2.4. 3.9.5 (2010-05-19) ================== - LP #579019: When layers are run in parallel, ensure that each ``tearDown`` is called, including the first layer which is run in the main thread. - Deprecate ``zope.testing.testrunner`` and ``zope.testing.exceptions``. They have been moved to a separate zope.testrunner module, and will be removed from zope.testing in 4.0.0, together with ``zope.testing.doctest``. 3.9.4 (2010-04-13) ================== - LP #560259: Fix subunit output formatter to handle layer setup errors. - LP #399394: Add a ``--stop-on-error`` / ``--stop`` / ``-x`` option to the testrunner. - LP #498162: Add a ``--pdb`` alias for the existing ``--post-mortem`` / ``-D`` option to the testrunner. - LP #547023: Add a ``--version`` option to the testrunner. - Add tests for LP #144569 and #69988. https://bugs.launchpad.net/bugs/69988 https://bugs.launchpad.net/zope3/+bug/144569 3.9.3 (2010-03-26) ================== - Remove import of ``zope.testing.doctest`` from ``zope.testing.renormalizer``. - Suppress output to ``sys.stderr`` in ``testrunner-layers-ntd.txt``. - Suppress ``zope.testing.doctest`` deprecation warning when running our own test suite. 3.9.2 (2010-03-15) ================== - Fix broken ``from zope.testing.doctest import *`` 3.9.1 (2010-03-15) ================== - No changes; reupload to fix broken 3.9.0 release on PyPI. 3.9.0 (2010-03-12) ================== - Modify the testrunner to use the standard Python ``doctest`` module instead of the deprecated ``zope.testing.doctest``. - Fix ``testrunner-leaks.txt`` to use the ``run_internal`` helper, so that ``sys.exit`` isn't triggered during the test run. - Add support for conditionally using a subunit-based output formatter upon request if subunit and testtools are available. Patch contributed by Jonathan Lange. 3.8.7 (2010-01-26) ================== - Downgrade the ``zope.testing.doctest`` deprecation warning into a PendingDeprecationWarning. 3.8.6 (2009-12-23) ================== - Add ``MANIFEST.in`` and reupload to fix broken 3.8.5 release on PyPI. 3.8.5 (2009-12-23) ================== - Add back ``DocFileSuite``, ``DocTestSuite``, ``debug_src`` and ``debug`` BBB imports back into ``zope.testing.doctestunit``; apparently many packages still import them from there! - Deprecate ``zope.testing.doctest`` and ``zope.testing.doctestunit`` in favor of the stdlib ``doctest`` module. 3.8.4 (2009-12-18) ================== - Fix missing imports and undefined variables reported by pyflakes, adding tests to exercise the blind spots. - Cleaned up unused imports reported by pyflakes. - Add two new options to generate randomly ordered list of tests and to select a specific order of tests. - Allow combining RENormalizing checkers via ``+`` now: ``checker1 + checker2`` creates a checker with the transformations of both checkers. - Fix tests under Python 2.7. 3.8.3 (2009-09-21) ================== - Fix test failures due to using ``split()`` on filenames when running from a directory with spaces in it. - Fix testrunner behavior on Windows for ``-j2`` (or greater) combined with ``-v`` (or greater). 3.8.2 (2009-09-15) ================== - Remove hotshot profiler when using Python 2.6. That makes zope.testing compatible with Python 2.6 3.8.1 (2009-08-12) ================== - Avoid hardcoding ``sys.argv[0]`` as script; allow, for instance, Zope 2's `bin/instance test` (LP#407916). - Produce a clear error message when a subprocess doesn't follow the ``zope.testing.testrunner`` protocol (LP#407916). - Avoid unnecessarily squelching verbose output in a subprocess when there are not multiple subprocesses. - Avoid unnecessarily batching subprocess output, which can stymie automated and human processes for identifying hung tests. - Include incremental output when there are multiple subprocesses and a verbosity of ``-vv`` or greater is requested. This again is not batched, supporting automated processes and humans looking for hung tests. 3.8.0 (2009-07-24) ================== - Allow testrunner to include descendants of ``unittest.TestCase`` in test modules, which no longer need to provide ``test_suite()``. 3.7.7 (2009-07-15) ================== - Clean up support for displaying tracebacks with supplements by turning it into an always-enabled feature and making the dependency on ``zope.exceptions`` explicit. - Fix #251759: prevent the testrunner descending into directories that aren't Python packages. - Code cleanups. 3.7.6 (2009-07-02) ================== - Add zope-testrunner ``console_scripts`` entry point. This exposes a ``zope-testrunner`` script with default installs allowing the testrunner to be run from the command line. 3.7.5 (2009-06-08) ================== - Fix bug when running subprocesses on Windows. - The option ``REPORT_ONLY_FIRST_FAILURE`` (command line option "-1") is now respected even when a doctest declares its own ``REPORTING_FLAGS``, such as ``REPORT_NDIFF``. - Fix bug that broke readline with pdb when using doctest (see http://bugs.python.org/issue5727). - Make tests pass on Windows and Linux at the same time. 3.7.4 (2009-05-01) ================== - Filenames of doctest examples now contain the line number and not only the example number. So a stack trace in pdb tells the exact line number of the current example. This fixes https://bugs.launchpad.net/bugs/339813 - Colorization of doctest output correctly handles blank lines. 3.7.3 (2009-04-22) ================== - Improve handling of rogue threads: always exit with status so even spinning daemon threads won't block the runner from exiting. This deprecated the ``--with-exit-status`` option. 3.7.2 (2009-04-13) ================== - Fix test failure on Python 2.4 due to slight difference in the way coverage is reported (__init__ files with only a single comment line are now not reported) - Fix bug that caused the test runner to hang when running subprocesses (as a result Python 2.3 is no longer supported). - Work around a bug in Python 2.6 (related to http://bugs.python.org/issue1303673) that causes the profile tests to fail. - Add explanitory notes to ``buildout.cfg`` about how to run the tests with multiple versions of Python 3.7.1 (2008-10-17) ================== - The ``setupstack`` temporary directory support now properly handles read-only files by making them writable before removing them. 3.7.0 (2008-09-22) ================== - Add alterate setuptools / distutils commands for running all tests using our testrunner. See 'zope.testing.testrunner.eggsupport:ftest'. - Add a setuptools-compatible test loader which skips tests with layers: the testrunner used by ``setup.py test`` doesn't know about them, and those tests then fail. See ``zope.testing.testrunner.eggsupport:SkipLayers``. - Add support for Jython, when a garbage collector call is sent. - Add support to bootstrap on Jython. - Fix NameError in StartUpFailure. - Open doctest files in universal mode, so that packages released on Windows can be tested on Linux, for example. 3.6.0 (2008-07-10) ================== - Add ``-j`` option to parallel tests run in subprocesses. - RENormalizer accepts plain Python callables. - Add ``--slow-test`` option. - Add ``--no-progress`` and ``--auto-progress`` options. - Complete refactoring of the test runner into multiple code files and a more modular (pipeline-like) architecture. - Unify unit tests with the layer support by introducing a real unit test layer. - Add a doctest for ``zope.testing.module``. There were several bugs that were fixed: * ``README.txt`` was a really bad default argument for the module name, as it is not a proper dotted name. The code would immediately fail as it would look for the ``txt`` module in the ``README`` package. The default is now ``__main__``. * The ``tearDown`` function did not clean up the ``__name__`` entry in the global dictionary. - Fix a bug that caused a SubprocessError to be generated if a subprocess sent any output to stderr. - Fix a bug that caused the unit tests to be skipped if run in a subprocess. 3.5.1 (2007-08-14) ================== - Invoke post-mortem debugging for layer-setup failures. 3.5.0 (2007-07-19) ================== - Ensure that the test runner works on Python 2.5. - Add support for ``cProfile``. - Add output colorizing (``-c`` option). - Add ``--hide-secondary-failures`` and ``--show-secondary-failures`` options (https://bugs.launchpad.net/zope3/+bug/115454). - Fix some problems with Unicode in doctests. - Fix "Error reading from subprocess" errors on Unix-like systems. 3.4 (2007-03-29) ================ - Add ``exit-with-status`` support (supports use with buildbot and ``zc.recipe.testing``) - Add a small framework for automating set up and tear down of doctest tests. See ``setupstack.txt``. - Allow ``testrunner-wo-source.txt`` and ``testrunner-errors.txt`` to run within a read-only source tree. 3.0 (2006-09-20) ================ - Update the doctest copy with text-file encoding support. - Add logging-level support to the ``loggingsuppport`` module. - At verbosity-level 1, dots are not output continuously, without any line breaks. - Improve output when the inability to tear down a layer causes tests to be run in a subprocess. - Make ``zope.exception`` required only if the ``zope_tracebacks`` extra is requested. - Fix the test coverage. If a module, for example `interfaces`, was in an ignored directory/package, then if a module of the same name existed in a covered directory/package, then it was also ignored there, because the ignore cache stored the result by module name and not the filename of the module. 2.0 (2006-01-05) ================ - Release a separate project corresponding to the version of ``zope.testing`` shipped as part of the Zope 3.2.0 release.
zope.testing
/zope.testing-5.0.1.tar.gz/zope.testing-5.0.1/CHANGES.rst
CHANGES.rst
================= ``zope.testing`` ================= .. image:: https://img.shields.io/pypi/v/zope.testing.svg :target: https://pypi.python.org/pypi/zope.testing/ :alt: Latest Version .. image:: https://github.com/zopefoundation/zope.testing/actions/workflows/tests.yml/badge.svg :target: https://github.com/zopefoundation/zope.testing/actions/workflows/tests.yml .. image:: https://readthedocs.org/projects/zopetesting/badge/?version=latest :target: http://zopetesting.readthedocs.org/en/latest/ :alt: Documentation Status This package provides a number of testing frameworks. For complete documentation, see https://zopetesting.readthedocs.io cleanup Provides a mixin class for cleaning up after tests that make global changes. See `zope.testing.cleanup` formparser An HTML parser that extracts form information. This is intended to support functional tests that need to extract information from HTML forms returned by the publisher. See `zope.testing.formparser` loggingsupport Support for testing logging code If you want to test that your code generates proper log output, you can create and install a handler that collects output. See `zope.testing.loggingsupport` loghandler Logging handler for tests that check logging output. See `zope.testing.loghandler` module Lets a doctest pretend to be a Python module. See `zope.testing.module` renormalizing Regular expression pattern normalizing output checker. Useful for doctests. See `zope.testing.renormalizing` server Provides a simple HTTP server compatible with the zope.app.testing functional testing API. Lets you interactively play with the system under test. Helpful in debugging functional doctest failures. **Python 2 only** See `zope.testing.server` setupstack A simple framework for automating doctest set-up and tear-down. See `zope.testing.setupstack` wait A small utility for dealing with timing non-determinism See `zope.testing.wait` doctestcase Support for defining doctests as methods of `unittest.TestCase` classes so that they can be more easily found by test runners, like nose, that ignore test suites. See `zope.testing.doctestcase` Getting started developing zope.testing ======================================= ``zope.testing`` uses ``tox``. To start, install ``tox`` using ``pip install tox``. Now, run ``tox`` to run the ``zope.testing`` test suite.
zope.testing
/zope.testing-5.0.1.tar.gz/zope.testing-5.0.1/README.rst
README.rst
import os import stat import tempfile import unittest key = '__' + __name__ def globs(test): """ Return the globals for *test*, which can be a `doctest` or a regular `unittest.TestCase`. """ try: return test.globs except AttributeError: return test.__dict__ def register(test, function, *args, **kw): """ Add a clean up *function* to be called with *args* and *kw* when *test* is torn down. Clean up functions are called in the reverse order of registration. """ tglobs = globs(test) stack = tglobs.get(key) if stack is None: stack = tglobs[key] = [] stack.append((function, args, kw)) def tearDown(test): """ Call all the clean up functions registered for *test*, in the reverse of their registration order. """ tglobs = globs(test) stack = tglobs.get(key) while stack: f, p, k = stack.pop() f(*p, **k) def setUpDirectory(test): """ Create and change to a temporary directory, and `register` `rmtree` to clean it up. Returns to the starting directory when finished. """ tmp = tempfile.mkdtemp() register(test, rmtree, tmp) here = os.getcwd() register(test, os.chdir, here) os.chdir(tmp) def rmtree(path): """ Remove all the files and directories found in *path*. Intended to be used as a clean up function with *register*. """ for path, dirs, files in os.walk(path, False): for fname in files: fname = os.path.join(path, fname) if not os.path.islink(fname): os.chmod(fname, stat.S_IWUSR) os.remove(fname) for dname in dirs: dname = os.path.join(path, dname) os.rmdir(dname) os.rmdir(path) def context_manager(test, manager): """ A stack-based version of the **with** statement. The context manager *manager* is entered when this method is called, and it is exited when the *test* is torn down. """ result = manager.__enter__() register(test, manager.__exit__, None, None, None) return result def _get_mock(): # A hook for the setupstack.txt doctest : from unittest import mock as mock_module return mock_module def mock(test, *args, **kw): """ Patch an object by calling `unittest.mock.patch` with the *args* and *kw* given, and returns the result. This will be torn down when the *test* is torn down. """ mock_module = _get_mock() return context_manager(test, mock_module.patch(*args, **kw)) class TestCase(unittest.TestCase): """ A ``TestCase`` base class that overrides `tearDown` to use the function from this module. In addition, it provides other methods using the functions in this module: - `register` - `setUpDirectory` - `context_manager` - `mock` """ tearDown = tearDown register = register setUpDirectory = setUpDirectory context_manager = context_manager mock = mock
zope.testing
/zope.testing-5.0.1.tar.gz/zope.testing-5.0.1/src/zope/testing/setupstack.py
setupstack.py
import logging class Handler(logging.Handler): """ A `logging.Handler` that collects logging records that are emitted by the loggers named in *names*. You must call `install` to begin collecting records, and before destroying this object you must call `uninstall`. """ def __init__(self, *names, **kw): logging.Handler.__init__(self) self.names = names self.records = [] self.setLoggerLevel(**kw) def setLoggerLevel(self, level=1): self.level = level self.oldlevels = {} def emit(self, record): """ Save the given record in ``self.records``. """ self.records.append(record) def clear(self): """ Delete all records collecting by this object. """ del self.records[:] def install(self): """ Begin collecting logging records for all the logger names given to the constructor. """ for name in self.names: logger = logging.getLogger(name) self.oldlevels[name] = logger.level logger.setLevel(self.level) logger.addHandler(self) def uninstall(self): """ Stop collecting logging records. """ for name in self.names: logger = logging.getLogger(name) logger.setLevel(self.oldlevels[name]) logger.removeHandler(self) def __str__(self): return '\n'.join( "{} {}\n {}".format( record.name, record.levelname, '\n'.join( line for line in record.getMessage().split('\n') if line.strip() ), ) for record in self.records ) class InstalledHandler(Handler): """ A `Handler` that automatically calls `install` when constructed. You must still manually call `uninstall`. """ def __init__(self, *names, **kw): Handler.__init__(self, *names, **kw) self.install()
zope.testing
/zope.testing-5.0.1.tar.gz/zope.testing-5.0.1/src/zope/testing/loggingsupport.py
loggingsupport.py
__docformat__ = "reStructuredText" import html.parser as HTMLParser import urllib.parse as urlparse def parse(data, base=None): """Return a form collection parsed from *data*. *base* should be the URL from which *data* was retrieved. """ parser = FormParser(data, base) return parser.parse() class FormParser: """ The parser. """ def __init__(self, data, base=None): self.data = data self.base = base self._parser = HTMLParser.HTMLParser() self._parser.handle_data = self._handle_data self._parser.handle_endtag = self._handle_endtag self._parser.handle_starttag = self._handle_starttag self._parser.handle_startendtag = self._handle_starttag self._buffer = [] self.current = None # current form self.forms = FormCollection() def parse(self): """Parse the document, returning the collection of forms.""" self._parser.feed(self.data) self._parser.close() return self.forms # HTMLParser handlers def _handle_data(self, data): self._buffer.append(data) def _handle_endtag(self, tag): if tag == "textarea": self.textarea.value = "".join(self._buffer) self.textarea = None elif tag == "select": self.select = None elif tag == "option": option = self.select.options[-1] label = "".join(self._buffer) if not option.label: option.label = label if not option.value: option.value = label if option.selected: if self.select.multiple: self.select.value.append(option.value) else: self.select.value = option.value def _handle_starttag(self, tag, attrs): del self._buffer[:] d = {} for name, value in attrs: d[name] = value name = d.get("name") id = d.get("id") or d.get("xml:id") if tag == "form": method = kwattr(d, "method", "get") action = d.get("action", "").strip() or None if self.base and action: action = urlparse.urljoin(self.base, action) enctype = kwattr(d, "enctype", "application/x-www-form-urlencoded") self.current = Form(name, id, method, action, enctype) self.forms.append(self.current) elif tag == "input": type = kwattr(d, "type", "text") checked = "checked" in d disabled = "disabled" in d readonly = "readonly" in d src = d.get("src", "").strip() or None if self.base and src: src = urlparse.urljoin(self.base, src) value = d.get("value") size = intattr(d, "size") maxlength = intattr(d, "maxlength") self._add_field( Input(name, id, type, value, checked, disabled, readonly, src, size, maxlength)) elif tag == "button": pass elif tag == "textarea": disabled = "disabled" in d readonly = "readonly" in d self.textarea = Input(name, id, "textarea", None, None, disabled, readonly, None, None, None) self.textarea.rows = intattr(d, "rows") self.textarea.cols = intattr(d, "cols") self._add_field(self.textarea) # The value will be set when the </textarea> is seen. elif tag == "base": href = d.get("href", "").strip() if href and self.base: href = urlparse.urljoin(self.base, href) self.base = href elif tag == "select": disabled = "disabled" in d multiple = "multiple" in d size = intattr(d, "size") self.select = Select(name, id, disabled, multiple, size) self._add_field(self.select) elif tag == "option": disabled = "disabled" in d selected = "selected" in d value = d.get("value") label = d.get("label") option = Option(id, value, selected, label, disabled) self.select.options.append(option) # Helpers: def _add_field(self, field): if field.name in self.current: ob = self.current[field.name] if isinstance(ob, list): ob.append(field) else: self.current[field.name] = [ob, field] else: self.current[field.name] = field def kwattr(d, name, default=None): """Return attribute, converted to lowercase.""" v = d.get(name, default) if v != default and v is not None: v = v.strip().lower() v = v or default return v def intattr(d, name): """Return attribute as an integer, or None.""" if name in d: v = d[name].strip() return int(v) else: return None class FormCollection(list): """Collection of all forms from a page.""" def __getattr__(self, name): for form in self: if form.name == name: return form raise AttributeError(name) class Form(dict): """A specific form within a page.""" # This object should provide some method to prepare a dictionary # that can be passed directly as the value of the `form` argument # to the `http()` function of the Zope functional test. # # This is probably a low priority given the availability of the # `zope.testbrowser` package. def __init__(self, name, id, method, action, enctype): super().__init__() self.name = name self.id = id self.method = method self.action = action self.enctype = enctype class Input: """Input element.""" rows = None cols = None def __init__(self, name, id, type, value, checked, disabled, readonly, src, size, maxlength): super().__init__() self.name = name self.id = id self.type = type self.value = value self.checked = checked self.disabled = disabled self.readonly = readonly self.src = src self.size = size self.maxlength = maxlength class Select(Input): """Select element.""" def __init__(self, name, id, disabled, multiple, size): super().__init__(name, id, "select", None, None, disabled, None, None, size, None) self.options = [] self.multiple = multiple if multiple: self.value = [] class Option: """Individual value representation for a select element.""" def __init__(self, id, value, selected, label, disabled): super().__init__() self.id = id self.value = value self.selected = selected self.label = label self.disabled = disabled
zope.testing
/zope.testing-5.0.1.tar.gz/zope.testing-5.0.1/src/zope/testing/formparser.py
formparser.py
=============== API Reference =============== zope.testing.cleanup ==================== .. automodule:: zope.testing.cleanup zope.testing.doctestcase ======================== .. automodule:: zope.testing.doctestcase zope.testing.exceptions ======================= .. automodule:: zope.testing.exceptions zope.testing.formparser ======================= .. automodule:: zope.testing.formparser zope.testing.loggingsupport =========================== .. automodule:: zope.testing.loggingsupport zope.testing.module =================== .. automodule:: zope.testing.module zope.testing.renormalizing ========================== .. automodule:: zope.testing.renormalizing zope.testing.setupstack ======================= .. automodule:: zope.testing.setupstack .. zope.testing.testrunner is deprecated, do not document zope.testing.wait ================= .. automodule:: zope.testing.wait
zope.testing
/zope.testing-5.0.1.tar.gz/zope.testing-5.0.1/docs/api/index.rst
index.rst
============= Test Recorder ============= The testrecorder is a browser-based tool to support the rapid development of functional tests for Web-based systems and applications. The idea is to "record" tests by exercising whatever is to be tested within the browser. The test recorder will turn a recorded session into a functional test. Output ------ Test recorder supports two output modes: Selenium In this mode, the testrecorder spits out HTML markup that lets you recreate the browser test using the Selenium_ functional testing framework. Test browser In this mode, the testrecorder spits out a Python doctest_ that exercises a functional test using the Zope testbrowser_. The Zope testbrowser allows you to programmatically simulate a browser from Python code. Its main use is to make functional tests easy and runnable without a browser at hand. It is used in Zope, but is not tied to Zope at all. .. _Selenium: http://www.openqa.org/selenium/ .. _doctest: http://docs.python.org/lib/module-doctest.html .. _testbrowser: http://cheeseshop.python.org/pypi/ZopeTestbrowser Usage ----- Like Selenium and the Zope test browser, the test recorder can very well be used to test any web application, be it Zope-based or not. Of course, it was developed by folks from the Zope community for use with Zope.
zope.testrecorder
/zope.testrecorder-0.4.tar.gz/zope.testrecorder-0.4/README.txt
README.txt
if (typeof(TestRecorder) == "undefined") { TestRecorder = {}; } // --------------------------------------------------------------------------- // Browser -- a singleton that provides a cross-browser API for managing event // handlers and miscellaneous browser functions. // // Methods: // // captureEvent(window, name, handler) -- capture the named event occurring // in the given window, setting the function handler as the event handler. // The event name should be of the form "click", "blur", "change", etc. // // releaseEvent(window, name, handler) -- release the named event occurring // in the given window. The event name should be of the form "click", "blur", // "change", etc. // // getSelection(window) -- return the text currently selected, or the empty // string if no text is currently selected in the browser. // // --------------------------------------------------------------------------- if (typeof(TestRecorder.Browser) == "undefined") { TestRecorder.Browser = {}; } TestRecorder.Browser.captureEvent = function(wnd, name, func) { var lname = name.toLowerCase(); var doc = wnd.document; if (doc.layers && wnd.captureEvents) { wnd.captureEvents(Event[name.toUpperCase()]); wnd["on" + lname] = func; } else if (doc.all && !doc.getElementById) { doc["on" + lname] = func; } else if (doc.all && doc.attachEvent) { doc.attachEvent("on" + lname, func); } else if (doc.addEventListener) { doc.addEventListener(lname, func, true); } } TestRecorder.Browser.releaseEvent = function(wnd, name, func) { var lname = name.toLowerCase(); var doc = wnd.document; if (doc.layers && wnd.releaseEvents) { wnd.releaseEvents(Event[name.toUpperCase()]); wnd["on" + lname] = null; } else if (doc.all && !doc.getElementById) { doc["on" + lname] = null; } else if (doc.all && doc.attachEvent) { doc.detachEvent("on" + lname, func); } else if (doc.addEventListener) { doc.removeEventListener(lname, func, true); } } TestRecorder.Browser.getSelection = function(wnd) { var doc = wnd.document; if (wnd.getSelection) { return wnd.getSelection() + ""; } else if (doc.getSelection) { return doc.getSelection() + ""; } else if (doc.selection && doc.selection.createRange) { return doc.selection.createRange().text + ""; } return ""; } TestRecorder.Browser.windowHeight = function(wnd) { var doc = wnd.document; if (wnd.innerHeight) { return wnd.innerHeight; } else if (doc.documentElement && doc.documentElement.clientHeight) { return doc.documentElement.clientHeight; } else if (document.body) { return document.body.clientHeight; } return -1; } TestRecorder.Browser.windowWidth = function(wnd) { var doc = wnd.document; if (wnd.innerWidth) { return wnd.innerWidth; } else if (doc.documentElement && doc.documentElement.clientWidth) { return doc.documentElement.clientWidth; } else if (document.body) { return document.body.clientWidth; } return -1; } // --------------------------------------------------------------------------- // Event -- a class that provides a cross-browser API dealing with most of the // interesting information about events. // // Methods: // // type() -- returns the string type of the event (e.g. "click") // // target() -- returns the target of the event // // button() -- returns the mouse button pressed during the event. Because // it is not possible to reliably detect a middle button press, this method // only recognized the left and right mouse buttons. Returns one of the // constants Event.LeftButton, Event.RightButton or Event.UnknownButton for // a left click, right click, or indeterminate (or no mouse click). // // keycode() -- returns the index code of the key pressed. Note that this // value may differ across browsers because of character set differences. // Whenever possible, it is suggested to use keychar() instead. // // keychar() -- returns the char version of the key pressed rather than a // raw numeric code. The resulting value is subject to all of the vagaries // of browsers, character encodings in use, etc. // // shiftkey() -- returns true if the shift key was pressed. // // posX() -- return the X coordinate of the mouse relative to the document. // // posY() -- return the y coordinate of the mouse relative to the document. // // stopPropagation() -- stop event propagation (if supported) // // preventDefault() -- prevent the default action (if supported) // // --------------------------------------------------------------------------- TestRecorder.Event = function(e) { this.event = (e) ? e : window.event; } TestRecorder.Event.LeftButton = 0; TestRecorder.Event.MiddleButton = 1; TestRecorder.Event.RightButton = 2; TestRecorder.Event.UnknownButton = 3; TestRecorder.Event.prototype.stopPropagation = function() { if (this.event.stopPropagation) this.event.stopPropagation(); } TestRecorder.Event.prototype.preventDefault = function() { if (this.event.preventDefault) this.event.preventDefault(); } TestRecorder.Event.prototype.type = function() { return this.event.type; } TestRecorder.Event.prototype.button = function() { if (this.event.button) { if (this.event.button == 2) { return TestRecorder.Event.RightButton; } return TestRecorder.Event.LeftButton; } else if (this.event.which) { if (this.event.which > 1) { return TestRecorder.Event.RightButton; } return TestRecorder.Event.LeftButton; } return TestRecorder.Event.UnknownButton; } TestRecorder.Event.prototype.target = function() { var t = (this.event.target) ? this.event.target : this.event.srcElement; if (t && t.nodeType == 3) // safari bug return t.parentNode; return t; } TestRecorder.Event.prototype.keycode = function() { return (this.event.keyCode) ? this.event.keyCode : this.event.which; } TestRecorder.Event.prototype.keychar = function() { return String.fromCharCode(this.keycode()); } TestRecorder.Event.prototype.shiftkey = function() { if (this.event.shiftKey) return true; return false; } TestRecorder.Event.prototype.posX = function() { if (this.event.pageX) return this.event.pageX; else if (this.event.clientX) { return this.event.clientX + document.body.scrollLeft; } return 0; } TestRecorder.Event.prototype.posY = function() { if (this.event.pageY) return this.event.pageY; else if (this.event.clientY) { return this.event.clientY + document.body.scrollTop; } return 0; } // --------------------------------------------------------------------------- // TestCase -- this class contains the interesting events that happen in // the course of a test recording and provides some testcase metadata. // // Attributes: // // title -- the title of the test case. // // items -- an array of objects representing test actions and checks // // // --------------------------------------------------------------------------- TestRecorder.TestCase = function() { this.title = "Test Case"; this.items = new Array(); } TestRecorder.TestCase.prototype.append = function(o) { this.items[this.items.length] = o; } TestRecorder.TestCase.prototype.peek = function() { return this.items[this.items.length - 1]; } // --------------------------------------------------------------------------- // Event types -- whenever an interesting event happens (an action or a check) // it is recorded as one of the object types defined below. All events have a // 'type' attribute that marks the type of the event (one of the values in the // EventTypes enumeration) and different attributes to capture the pertinent // information at the time of the event. // --------------------------------------------------------------------------- if (typeof(TestRecorder.EventTypes) == "undefined") { TestRecorder.EventTypes = {}; } TestRecorder.EventTypes.OpenUrl = 0; TestRecorder.EventTypes.Click = 1; TestRecorder.EventTypes.Change = 2; TestRecorder.EventTypes.Comment = 3; TestRecorder.EventTypes.Submit = 4; TestRecorder.EventTypes.CheckPageTitle = 5; TestRecorder.EventTypes.CheckPageLocation = 6; TestRecorder.EventTypes.CheckTextPresent = 7; TestRecorder.EventTypes.CheckValue = 8; TestRecorder.EventTypes.CheckValueContains = 9; TestRecorder.EventTypes.CheckText = 10; TestRecorder.EventTypes.CheckHref = 11; TestRecorder.EventTypes.CheckEnabled = 12; TestRecorder.EventTypes.CheckDisabled = 13; TestRecorder.EventTypes.CheckSelectValue = 14; TestRecorder.EventTypes.CheckSelectOptions = 15; TestRecorder.EventTypes.CheckImageSrc = 16; TestRecorder.EventTypes.PageLoad = 17; TestRecorder.ElementInfo = function(element) { this.action = element.action; this.method = element.method; this.href = element.href; this.tagName = element.tagName; this.value = element.value; this.checked = element.checked; this.name = element.name; this.type = element.type; if (this.type) this.type = this.type.toLowerCase(); this.src = element.src; this.id = element.id; this.options = []; if (element.selectedIndex) { for (var i=0; i < element.options.length; i++) { var o = element.options[i]; this.options[i] = {text:o.text, value:o.value}; } } this.label = this.findLabelText(element); } TestRecorder.ElementInfo.prototype.findLabelText = function(element) { var label = this.findContainingLabel(element) var text; if (!label) { label = this.findReferencingLabel(element); } if (label) { text = label.innerHTML; // remove newlines text = text.replace('\n', ' '); // remove tags text = text.replace(/<[^>]*>/g, ' '); // remove non-alphanumeric prefixes or suffixes text = text.replace(/^\W*/mg, '') text = text.replace(/\W*$/mg, '') // remove extra whitespace text = text.replace(/^\s*/, '').replace(/\s*$/, '').replace(/\s+/g, ' '); } return text; } TestRecorder.ElementInfo.prototype.findReferencingLabel = function(element) { var labels = top.frames[1].document.getElementsByTagName('label') for (var i = 0; i < labels.length; i++) { if (labels[i].attributes['for'] && labels[i].attributes['for'].value == element.id) return labels[i] } } TestRecorder.ElementInfo.prototype.findContainingLabel = function(element) { var parent = element.parentNode; if (!parent) return undefined; if (parent.tagName && parent.tagName.toLowerCase() == 'label') return parent; else return this.findContainingLabel(parent); } TestRecorder.DocumentEvent = function(type, target) { this.type = type; this.url = target.URL; this.title = target.title; } TestRecorder.ElementEvent = function(type, target, text) { this.type = type; this.info = new TestRecorder.ElementInfo(target); this.text = text ? text : recorder.strip(contextmenu.innertext(target)); } TestRecorder.CommentEvent = function(text) { this.type = TestRecorder.EventTypes.Comment; this.text = text; } TestRecorder.OpenURLEvent = function(url) { this.type = TestRecorder.EventTypes.OpenUrl; this.url = url; } TestRecorder.PageLoadEvent = function(url) { this.type = TestRecorder.EventTypes.OpenUrl; this.url = url; this.viaBack = back } // --------------------------------------------------------------------------- // ContextMenu -- this class is responsible for managing the right-click // context menu that shows appropriate checks for targeted elements. // // All methods and attributes are private to this implementation. // --------------------------------------------------------------------------- TestRecorder.ContextMenu = function() { this.selected = null; this.target = null; this.window = null; this.visible = false; this.over = false; this.menu = null; } contextmenu = new TestRecorder.ContextMenu(); TestRecorder.ContextMenu.prototype.build = function(t, x, y) { var d = recorder.window.document; var b = d.getElementsByTagName("body").item(0); var menu = d.createElement("div"); // Needed to deal with various cross-browser insanities... menu.setAttribute("style", "backgroundColor:#ffffff;color:#000000;border:1px solid #000000;padding:2px;position:absolute;display:none;top:" + y + "px;left:" + x + "px;border:1px;z-index:10000;"); menu.style.backgroundColor="#ffffff"; menu.style.color="#000000"; menu.style.border = "1px solid #000000"; menu.style.padding="2px"; menu.style.position = "absolute"; menu.style.display = "none"; menu.style.zIndex = "10000"; menu.style.top = y.toString(); menu.style.left = x.toString(); menu.onmouseover=contextmenu.onmouseover; menu.onmouseout=contextmenu.onmouseout; var selected = TestRecorder.Browser.getSelection(recorder.window).toString(); if (t.width && t.height) { menu.appendChild(this.item("Check Image Src", this.checkImgSrc)); } else if (t.type == "text" || t.type == "textarea") { if (selected && (selected != "")) { this.selected = recorder.strip(selected); menu.appendChild(this.item("Check Selected Text", this.checkValueContains) ); } menu.appendChild(this.item("Check Text Value", this.checkValue)); menu.appendChild(this.item("Check Enabled", this.checkEnabled)); menu.appendChild(this.item("Check Disabled", this.checkDisabled)); } else if (selected && (selected != "")) { this.selected = recorder.strip(selected); menu.appendChild(this.item("Check Text Appears On Page", this.checkTextPresent)); } else if (t.href) { menu.appendChild(this.item("Check Link Text", this.checkText)); menu.appendChild(this.item("Check Link Href", this.checkHref)); } else if (t.selectedIndex || t.type == "option") { var name = "Check Selected Value"; if (t.type != "select-one") { name = name + "s"; } menu.appendChild(this.item(name, this.checkSelectValue)); menu.appendChild(this.item("Check Select Options", this.checkSelectOptions)); menu.appendChild(this.item("Check Enabled", this.checkEnabled)); menu.appendChild(this.item("Check Disabled", this.checkDisabled)); } else if (t.type == "button" || t.type == "submit") { menu.appendChild(this.item("Check Button Text", this.checkText)); menu.appendChild(this.item("Check Button Value", this.checkValue)); menu.appendChild(this.item("Check Enabled", this.checkEnabled)); menu.appendChild(this.item("Check Disabled", this.checkDisabled)); } else if (t.value) { menu.appendChild(this.item("Check Value", this.checkValue)); menu.appendChild(this.item("Check Enabled", this.checkEnabled)); menu.appendChild(this.item("Check Disabled", this.checkDisabled)); } else { menu.appendChild(this.item("Check Page Location", this.checkPageLocation)); menu.appendChild(this.item("Check Page Title", this.checkPageTitle)); } menu.appendChild(this.item("Cancel", this.cancel)); b.insertBefore(menu, b.firstChild); return menu; } TestRecorder.ContextMenu.prototype.item = function(text, func) { var doc = recorder.window.document; var div = doc.createElement("div"); var txt = doc.createTextNode(text); div.setAttribute("style", "padding:6px;border:1px solid #ffffff;"); div.style.border = "1px solid #ffffff"; div.style.padding = "6px"; div.appendChild(txt); div.onmouseover = this.onitemmouseover; div.onmouseout = this.onitemmouseout; div.onclick = func; return div; } TestRecorder.ContextMenu.prototype.show = function(e) { if (this.menu) { this.hide(); } var wnd = recorder.window; var doc = wnd.document; this.target = e.target(); TestRecorder.Browser.captureEvent(wnd, "mousedown", this.onmousedown); var wh = TestRecorder.Browser.windowHeight(wnd); var ww = TestRecorder.Browser.windowWidth(wnd); var x = e.posX(); var y = e.posY(); if ((ww >= 0) && ((ww - x) < 100)) { x = x - 100; } if ((wh >= 0) && ((wh - y) < 100)) { y = y - 100; } var menu = this.build(e.target(), x, y); this.menu = menu; menu.style.display = ""; this.visible = true; return; } TestRecorder.ContextMenu.prototype.hide = function() { var wnd = recorder.window; TestRecorder.Browser.releaseEvent(wnd, "mousedown", this.onmousedown); var d = wnd.document; var b = d.getElementsByTagName("body").item(0); this.menu.style.display = "none" ; b.removeChild(this.menu); this.target = null; this.visible = false; this.over = false; this.menu = null; } TestRecorder.ContextMenu.prototype.onitemmouseover = function(e) { this.style.backgroundColor = "#efefef"; this.style.border = "1px solid #c0c0c0"; return true; } TestRecorder.ContextMenu.prototype.onitemmouseout = function(e) { this.style.backgroundColor = "#ffffff"; this.style.border = "1px solid #ffffff"; return true; } TestRecorder.ContextMenu.prototype.onmouseover = function(e) { contextmenu.over = true; } TestRecorder.ContextMenu.prototype.onmouseout = function(e) { contextmenu.over = false; } TestRecorder.ContextMenu.prototype.onmousedown = function(e) { if(contextmenu.visible) { if (contextmenu.over == false) { contextmenu.hide(); return true; } return true ; } return false; } TestRecorder.ContextMenu.prototype.record = function(o) { recorder.testcase.append(o); recorder.log(o.type); contextmenu.hide(); } TestRecorder.ContextMenu.prototype.checkPageTitle = function() { var doc = recorder.window.document; var et = TestRecorder.EventTypes; var e = new TestRecorder.DocumentEvent(et.CheckPageTitle, doc); contextmenu.record(e); } TestRecorder.ContextMenu.prototype.checkPageLocation = function() { var doc = recorder.window.document; var et = TestRecorder.EventTypes; var e = new TestRecorder.DocumentEvent(et.CheckPageLocation, doc); contextmenu.record(e); } TestRecorder.ContextMenu.prototype.checkValue = function() { var t = contextmenu.target; var et = TestRecorder.EventTypes; var e = new TestRecorder.ElementEvent(et.CheckValue, t); contextmenu.record(e); } TestRecorder.ContextMenu.prototype.checkValueContains = function() { var s = contextmenu.selected; var t = contextmenu.target; var et = TestRecorder.EventTypes; var e = new TestRecorder.ElementEvent(et.CheckValueContains, t, s); contextmenu.selected = null; contextmenu.record(e); } TestRecorder.ContextMenu.prototype.innertext = function(e) { var doc = recorder.window.document; if (document.createRange) { var r = recorder.window.document.createRange(); r.selectNodeContents(e); return r.toString(); } else { return e.innerText; } } TestRecorder.ContextMenu.prototype.checkText = function() { var t = contextmenu.target; var s = ""; if (t.type == "button" || t.type == "submit") { s = t.value; } else { s = contextmenu.innertext(t); } s = recorder.strip(s); var et = TestRecorder.EventTypes; var e = new TestRecorder.ElementEvent(et.CheckText, t, s); contextmenu.record(e); } TestRecorder.ContextMenu.prototype.checkTextPresent = function() { var t = contextmenu.target; var s = contextmenu.selected; var et = TestRecorder.EventTypes; var e = new TestRecorder.ElementEvent(et.CheckTextPresent, t, s); contextmenu.selected = null; contextmenu.record(e); } TestRecorder.ContextMenu.prototype.checkHref = function() { var t = contextmenu.target; var et = TestRecorder.EventTypes; var e = new TestRecorder.ElementEvent(et.CheckHref, t); contextmenu.record(e); } TestRecorder.ContextMenu.prototype.checkEnabled = function() { var t = contextmenu.target; var et = TestRecorder.EventTypes; var e = new TestRecorder.ElementEvent(et.CheckEnabled, t); contextmenu.record(e); } TestRecorder.ContextMenu.prototype.checkDisabled = function() { var t = contextmenu.target; var et = TestRecorder.EventTypes; var e = new TestRecorder.ElementEvent(et.CheckDisabled, t); contextmenu.record(e); } TestRecorder.ContextMenu.prototype.checkSelectValue = function() { var t = contextmenu.target; var et = TestRecorder.EventTypes; var e = new TestRecorder.ElementEvent(et.CheckSelectValue, t); contextmenu.record(e); } TestRecorder.ContextMenu.prototype.checkSelectOptions = function() { var t = contextmenu.target; var et = TestRecorder.EventTypes; var e = new TestRecorder.ElementEvent(et.CheckSelectOptions, t); contextmenu.record(e); } TestRecorder.ContextMenu.prototype.checkImgSrc = function() { var t = contextmenu.target; var et = TestRecorder.EventTypes; var e = new TestRecorder.ElementEvent(et.CheckImageSrc, t); contextmenu.record(e); } TestRecorder.ContextMenu.prototype.cancel = function() { contextmenu.hide(); } // --------------------------------------------------------------------------- // Recorder -- a controller class that manages the recording of web browser // activities to produce a test case. // // Instance Methods: // // start() -- start recording browser events. // // stop() -- stop recording browser events. // // reset() -- reset the recorder and initialize a new test case. // // --------------------------------------------------------------------------- TestRecorder.Recorder = function() { this.testcase = new TestRecorder.TestCase(); this.logfunc = null; this.window = null; this.active = false; } // The recorder is a singleton -- there is no real reason to have more than // one instance, and many of its methods are event handlers which need a // stable reference to the instance. recorder = new TestRecorder.Recorder(); TestRecorder.Recorder.prototype.start = function(wnd) { this.window = wnd; this.captureEvents(); this.active = true; this.log("recorder started"); } TestRecorder.Recorder.prototype.stop = function() { this.releaseEvents(); this.active = false; this.log("recorder stopped"); return; } TestRecorder.Recorder.prototype.open = function(url) { var e = new TestRecorder.OpenURLEvent(url); this.testcase.append(e); this.log("open url: " + url); } TestRecorder.Recorder.prototype.pageLoad = function() { var doc = recorder.window.document; var et = TestRecorder.EventTypes; var e = new TestRecorder.DocumentEvent(et.PageLoad, doc); this.testcase.append(e); this.log("page loaded url: " + e.url); } TestRecorder.Recorder.prototype.captureEvents = function() { var wnd = this.window; TestRecorder.Browser.captureEvent(wnd, "contextmenu", this.oncontextmenu); TestRecorder.Browser.captureEvent(wnd, "click", this.onclick); TestRecorder.Browser.captureEvent(wnd, "change", this.onchange); TestRecorder.Browser.captureEvent(wnd, "keypress", this.onkeypress); TestRecorder.Browser.captureEvent(wnd, "select", this.onselect); TestRecorder.Browser.captureEvent(wnd, "submit", this.onsubmit); } TestRecorder.Recorder.prototype.releaseEvents = function() { var wnd = this.window; TestRecorder.Browser.releaseEvent(wnd, "contextmenu", this.oncontextmenu); TestRecorder.Browser.releaseEvent(wnd, "click", this.onclick); TestRecorder.Browser.releaseEvent(wnd, "change", this.onchange); TestRecorder.Browser.releaseEvent(wnd, "keypress", this.onkeypress); TestRecorder.Browser.releaseEvent(wnd, "select", this.onselect); TestRecorder.Browser.releaseEvent(wnd, "submit", this.onsubmit); } TestRecorder.Recorder.prototype.clickaction = function(e) { // This method is called by our low-level event handler when the mouse // is clicked in normal mode. Its job is decide whether the click is // something we care about. If so, we record the event in the test case. // // If the context menu is visible, then the click is either over the // menu (selecting a check) or out of the menu (cancelling it) so we // always discard clicks that happen when the menu is visible. if (!contextmenu.visible) { var et = TestRecorder.EventTypes; var t = e.target(); if (t.href || (t.type && t.type == "submit") || (t.type && t.type == "submit")) { this.testcase.append(new TestRecorder.ElementEvent(et.Click,e.target())); } } } TestRecorder.Recorder.prototype.addComment = function(text) { this.testcase.append(new TestRecorder.CommentEvent(text)); } TestRecorder.Recorder.prototype.check = function(e) { // This method is called by our low-level event handler when the mouse // is clicked in check mode. Its job is decide whether the click is // something we care about. If so, we record the check in the test case. contextmenu.show(e); var target = e.target(); if (target.type) { var type = target.type.toLowerCase(); if (type == "submit" || type == "button" || type == "image") { recorder.log('check button == "' + target.value + '"'); } } else if (target.href) { if (target.innerText) { var text = recorder.strip(target.innerText); recorder.log('check link == "' + target.text + '"'); } } } TestRecorder.Recorder.prototype.onpageload = function() { if (this.active) { // This must be called each time a new document is fully loaded into the // testing target frame to ensure that events are captured for the page. recorder.captureEvents(); // if a new page has loaded, but there doesn't seem to be a reason why, // then we need to record the fact or the information will be lost if (this.testcase.peek()) { var last_event_type = this.testcase.peek().type; if (last_event_type != TestRecorder.EventTypes.OpenUrl && last_event_type != TestRecorder.EventTypes.Click && last_event_type != TestRecorder.EventTypes.Submit) { this.open(this.window.location.toString()); } } // record the fact that a page load happened if (this.window) this.pageLoad(); } } TestRecorder.Recorder.prototype.onchange = function(e) { var e = new TestRecorder.Event(e); var et = TestRecorder.EventTypes; var v = new TestRecorder.ElementEvent(et.Change, e.target()); recorder.testcase.append(v); recorder.log("value changed: " + e.target()); } TestRecorder.Recorder.prototype.onselect = function(e) { var e = new TestRecorder.Event(e); recorder.log("select: " + e.target()); } TestRecorder.Recorder.prototype.onsubmit = function(e) { var e = new TestRecorder.Event(e); var et = TestRecorder.EventTypes; // We want to save the form element as the event target var t = e.target(); while (t.parentNode && t.tagName != "FORM") { t = t.parentNode; } var v = new TestRecorder.ElementEvent(et.Submit, t); recorder.testcase.append(v); recorder.log("submit: " + e.target()); } // The dance here between onclick and oncontextmenu requires a bit of // explanation. IE and Moz/Firefox have wildly different behaviors when // a right-click occurs. IE6 fires only an oncontextmenu event; Firefox // gets an onclick event first followed by an oncontextment event. So // to do the right thing here, we need to silently consume oncontextmenu // on Firefox, and reroute oncontextmenu to look like a click event for // IE. In both cases, we need to prevent the default action for cmenu. TestRecorder.Recorder.prototype.onclick = function(e) { var e = new TestRecorder.Event(e); if (e.shiftkey()) { recorder.check(e); e.stopPropagation(); e.preventDefault(); return false; } if (!top.document.all) { if (e.button() == TestRecorder.Event.RightButton) { recorder.check(e); return true; } else if (e.button() == TestRecorder.Event.LeftButton) { recorder.clickaction(e); return true; } e.stopPropagation(); e.preventDefault(); return false; } else { recorder.clickaction(e); return true; } } TestRecorder.Recorder.prototype.oncontextmenu = function(e) { var e = new TestRecorder.Event(e); if (top.document.all) { recorder.check(e); } e.stopPropagation(); e.preventDefault(); return false; } TestRecorder.Recorder.prototype.onkeypress = function(e) { var e = new TestRecorder.Event(e); if (e.shiftkey() && (e.keychar() == 'C')) { // TODO show comment box here } return true; } TestRecorder.Recorder.prototype.strip = function(s) { return s.replace('\n', ' ').replace(/^\s*/, "").replace(/\s*$/, ""); } TestRecorder.Recorder.prototype.log = function(text) { top.window.status = text; if (this.logfunc) { this.logfunc(text); } }
zope.testrecorder
/zope.testrecorder-0.4.tar.gz/zope.testrecorder-0.4/src/zope/testrecorder/html/recorder.js
recorder.js
=========================== zope.testrunner Changelog =========================== 6.1 (2023-08-26) ================ - Add preliminary support for Python 3.12b4. (`#149 <https://github.com/zopefoundation/zope.testrunner/issues/149>`_) 6.0 (2023-03-28) ================ - Drop support for Python 2.7, 3.5, 3.6. 5.6 (2022-12-09) ================ - Add support for Python 3.11. - Inline a small part of ``random.Random.shuffle`` which was deprecated in Python 3.9 and removed in 3.11 (`#119 <https://github.com/zopefoundation/zope.testrunner/issues/119>`_). - Don't trigger post mortem debugger for skipped tests. ( `#141 <https://github.com/zopefoundation/zope.testrunner/issues/141>`_). 5.5.1 (2022-09-07) ================== - Fix: let ``--at-level=level`` with ``level <= 0`` run the tests at all levels (rather than at no level) `#138 <https://github.com/zopefoundation/zope.testrunner/issues/138>`_. 5.5 (2022-06-24) ================ - Use ``sys._current_frames`` (rather than ``threading.enumerate``) as base for new thread detection, fixes `#130 <https://github.com/zopefoundation/zope.testrunner/issues/130>`_. - New option ``--gc-after-test``. It calls for a garbage collection after each test and can be used to track down ``ResourceWarning``s and cyclic garbage. With ``rv = gc.collect()``, ``!`` is output on verbosity level 1 when ``rv`` is non zero (i.e. when cyclic structures have been released), ``[``*rv*``]`` on higher verbosity levels and a detailed cyclic garbage analysis on verbosity level 4+. For details, see `#133 <https://github.com/zopefoundation/zope.testrunner/pull/133>`_. - Allow the filename for the logging configuration to be specified via the envvar ``ZOPE_TESTRUNNER_LOG_INI``. If not defined, the configuration continues to be locked for in file ``log.ini`` of the current working directory. Remember the logging configuration file in envvar ``ZOPE_TESTRUNNER_LOG_INI`` to allow spawned child processes to recreate the logging configuration. For details, see `#134 <https://github.com/zopefoundation/zope.testrunner/pull/134>`_. 5.4.0 (2021-11-19) ================== - Improve ``--help`` documentation for ``--package-path`` option (`#121 <https://github.com/zopefoundation/zope.testrunner/pull/121>`_). - Do not disable existing loggers during logsupport initialization (`#120 <https://github.com/zopefoundation/zope.testrunner/pull/120>`_). - Fix tests with testtools >= 2.5.0 (`#125 <https://github.com/zopefoundation/zope.testrunner/issues/125>`_). - Add support for Python 3.10. 5.3.0 (2021-03-17) ================== - Add support for Python 3.9. - Fix `package init file missing` warning (`#112 <https://github.com/zopefoundation/zope.testrunner/pull/112>`_). - Make standard streams provide a `buffer` attribute on Python 3 when using `--buffer` or testing under subunit. 5.2 (2020-06-29) ================ - Add support for Python 3.8. - When a layer is run in a subprocess, read its stderr in a thread to avoid a deadlock if its stderr output (containing failing and erroring test IDs) overflows the capacity of a pipe (`#105 <https://github.com/zopefoundation/zope.testrunner/issues/105>`_). 5.1 (2019-10-19) ================ - Recover more gracefully when layer setUp or tearDown fails, producing useful subunit output. - Prevent a spurious warning from the ``--require-unique`` option if the ``--module`` option was not used. - Add optional buffering of standard output and standard error during tests, requested via the ``--buffer`` option or enabled by default for subunit. - Fix incorrect failure counts in per-layer summary output, broken in 4.0.1. 5.0 (2019-03-19) ================ - Fix test failures and deprecation warnings occurring when using Python 3.8a1. (`#89 <https://github.com/zopefoundation/zope.testrunner/pull/89>`_) - Drop support for Python 3.4. 4.9.2 (2018-11-24) ================== - Fix ``TypeError: a bytes-like object is required, not 'str'`` running tests in parallel on Python 3. See `issue 80 <https://github.com/zopefoundation/zope.testrunner/issues/80>`_. 4.9.1 (2018-11-21) ================== - Fix AssertionError in _DummyThread.isAlive on Python 3 (`#81 <https://github.com/zopefoundation/zope.testrunner/issues/81>`_). 4.9 (2018-10-05) ================ - Drop support for Python 3.3. - Add support for Python 3.7. - Enable test coverage reporting on coveralls.io and in tox.ini. - Host documentation at https://zopetestrunner.readthedocs.io - Remove untested support for the ``--pychecker`` option. See `issue 63 <https://github.com/zopefoundation/zope.testrunner/issues/63>`_. - Update the command line interface to use ``argparse`` instead of ``optparse``. See `issue 61 <https://github.com/zopefoundation/zope.testrunner/issues/61>`_. - Use ipdb instead of pdb for post-mortem debugging if available (`#10 <https://github.com/zopefoundation/zope.testrunner/issues/10>`_). - Add a --require-unique option to check for duplicate test IDs. See `LP #682771 <https://bugs.launchpad.net/launchpad/+bug/682771>`_. - Reintroduce optional support for ``subunit``, now with support for both version 1 and version 2 of its protocol. - Handle string in exception values when formatting chained exceptions. (`#74 <https://github.com/zopefoundation/zope.testrunner/pull/74>`_) 4.8.1 (2017-11-12) ================== - Enable ``DeprecationWarning`` earlier, when discovering test modules. This lets warnings that are raised on import (such as those produced by ``zope.deprecation.moved``) be reported. See `issue 57 <https://github.com/zopefoundation/zope.testrunner/issues/57>`_. 4.8.0 (2017-11-10) ================== - Automatically enable ``DeprecationWarning`` when running tests. This is recommended by the Python core developers and matches the behaviour of the ``unittest`` module. This can be overridden with Python command-line options (``-W``) or environment variables (``PYTHONWARNINGS``). See `issue 54 <https://github.com/zopefoundation/zope.testrunner/issues/54>`_. 4.7.0 (2017-05-30) ================== - Drop all support for ``subunit``. 4.6.0 (2016-12-28) ================== - Make the ``subunit`` support purely optional: applications which have been getting the dependencies via ``zope.testrunner`` should either add ``zope.testrunner[subunit]`` to their ``install_requires`` or else depend directly on ``python-subunit``. - New option ``--ignore-new-thread=<regexp>`` to suppress "New thread(s)" warnings. - Support Python 3.6. 4.5.1 (2016-06-20) ================== - Fixed: Using the ``-j`` option to run tests in multiple processes caused tests that used the ``multiprocessing`` package to hang (because the testrunner replaced ``sys.stdin`` with an unclosable object). - Drop conditional dependency on ``unittest2`` (redundant after dropping support for Python 2.6). 4.5.0 (2016-05-02) ================== - Stop tests for all layers when test fails/errors when started with -x/--stop-on-error (`#37 <https://github.com/zopefoundation/zope.testrunner/pull/37>`_). - Drop support for Python 2.6 and 3.2. 4.4.10 (2015-11-10) =================== - Add support for Python 3.5 (`#31 <https://github.com/zopefoundation/zope.testrunner/pull/31>`_). - Insert extra paths (from ``--path``) to the front of sys.argv (`#32 <https://github.com/zopefoundation/zope.testrunner/issues/32>`_). 4.4.9 (2015-05-21) ================== - When using ``-j``, parallelize all the tests, including the first test layer (`#28 <https://github.com/zopefoundation/zope.testrunner/issues/28>`_). 4.4.8 (2015-05-01) ================== - Support skipped tests in subunit output (`#25 <https://github.com/zopefoundation/zope.testrunner/pull/25>`_). - More efficient test filtering (`#26 <https://github.com/zopefoundation/zope.testrunner/pull/26>`_). 4.4.7 (2015-04-02) ================== - Work around a bug in PyPy3's curses module (`#24 <https://github.com/zopefoundation/zope.testrunner/issues/24>`_). 4.4.6 (2015-01-21) ================== - Restore support for instance-based test layers that regressed in 4.4.5 (`#20 <https://github.com/zopefoundation/zope.testrunner/pull/20>`_). 4.4.5 (2015-01-06) ================== - Sort related layers close to each other to reduce the number of unnecessary teardowns (fixes `#14 <https://github.com/zopefoundation/zope.testrunner/issues/14>`_). - Run the unit test layer first (fixes `LP #497871 <https://bugs.launchpad.net/zope.testrunner/+bug/497871>`__). 4.4.4 (2014-12-27) ================== - When looking for the right location of test code, start with longest location paths first. This fixes problems with nested code locations. 4.4.3 (2014-03-19) ================== - Added support for Python 3.4. 4.4.2 (2014-02-22) ================== - Drop support for Python 3.1. - Fix post-mortem debugging when a non-printable exception happens (https://github.com/zopefoundation/zope.testrunner/issues/8). 4.4.1 (2013-07-10) ================== - Updated ``boostrap.py`` to version 2.2. - Fix nondeterministic test failures on Python 3.3 - Tear down layers after ``post_mortem`` debugging is finished. - Fix tests that write to source directory, it might be read-only. 4.4.0 (2013-06-06) ================== - Fix tests selection when the negative "!" pattern is used several times (LP #1160965) - Moved tests into a 'tests' subpackage. - Made ``python -m zope.testrunner`` work again. - Support 'skip' feature of unittest2 (which became the new unittest in Python 2.7). - Better diagnostics when communication with subprocess fails (https://github.com/zopefoundation/zope.testrunner/issues/5). - Do not break subprocess execution when the test suite changes the working directory (https://github.com/zopefoundation/zope.testrunner/issues/6). - Count test module import errors as errors (LP #1026576). 4.3.3 (2013-03-03) ================== - Running layers in sub-processes did not use to work when run via ``python setup.py ftest`` since it tried to run setup.py with all the command line options. It now detects ``setup.py`` runs and we run the test runner directly. 4.3.2 (2013-03-03) ================== - Fix ``SkipLayers`` class in cases where the distribution specifies a ``test_suite`` value. 4.3.1 (2013-03-02) ================== - Fixed a bug in the `ftest` command and added a test. - Fixed a trivial test failure with Python 3 of the previous release. 4.3.0 (2013-03-02) ================== - Expose `ftest` distutils command via an entry point. - Added tests for ``zope.testrunner.eggsupport``. 4.2.0 (2013-02-12) ================== - Dropped use of 2to3, rewrote source code to be compatible with all Python versions. Introduced a dependency on `six`_. 4.1.1 (2013-02-08) ================== - Dropped use of zope.fixers (LP: #1118877). - Fixed tox test error reporting; fixed tests on Pythons 2.6, 3.1, 3.2, 3.3 and PyPy 1.9. - Fix --shuffle ordering on Python 3.2 to be the same as it was on older Python versions. - Fix --shuffle nondeterminism when multiple test layers are present. Note: this will likely change the order of tests for the same --shuffle-seed. - New option: --profile-directory. Use it in the test suite so that tests executed by detox in parallel don't conflict. - Use a temporary coverage directory in the test suite so that tests executed by detox in parallel don't conflict. - Fix --post-mortem (aka -D, --pdb) when a test module cannot be imported or is invalid (LP #1119363). 4.1.0 (2013-02-07) ================== - Replaced deprecated ``zope.interface.implements`` usage with equivalent ``zope.interface.implementer`` decorator. - Dropped support for Python 2.4 and 2.5. - Made StartUpFailure compatible with unittest.TextTestRunner() (LP #1118344). 4.0.4 (2011-10-25) ================== - Work around sporadic timing-related issues in the subprocess buffering tests. Thanks to Jonathan Ballet for the patch! 4.0.3 (2011-03-17) ================== - Added back support for Python <= 2.6 which was broken in 4.0.2. 4.0.2 (2011-03-16) ================== - Added back Python 3 support which was broken in 4.0.1. - Fixed `Unexpected success`_ support by implementing the whole concept. - Added support for the new __pycache__ directories in Python 3.2. 4.0.1 (2011-02-21) ================== - LP #719369: An `Unexpected success`_ (concept introduced in Python 2.7) is no longer handled as success but as failure. This is a workaround. The whole unexpected success concept might be implemented later. .. _`Unexpected success`: http://www.voidspace.org.uk/python/articles/unittest2.shtml#more-skipping 4.0.0 (2010-10-19) ================== - Show more information about layers whose setup fails (LP #638153). 4.0.0b5 (2010-07-20) ==================== - Update fix for LP #221151 to a spelling compatible with Python 2.4. - Timestamps are now always included in subunit output (r114849). - LP #591309: fix a crash when subunit reports test failures containing UTF8-encoded data. 4.0.0b4 (2010-06-23) ==================== - Package as a zipfile to work around Python 2.4 distutils bug (no feature changes or bugfixes in ``zope.testrunner`` itself). 4.0.0b3 (2010-06-16) ==================== - LP #221151: keep ``unittest.TestCase.shortDescription`` happy by supplying a ``_testMethodDoc`` attribute. - LP #595052: keep the distribution installable under Python 2.4: its distutils appears to munge the empty ``__init__.py`` file in the ``foo.bar`` egg used for testing into a directory. - LP #580083: fix the ``bin/test`` script to run only tests from ``zope.testrunner``. - LP #579019: When layers were run in parallel, their tearDown was not called. Additionally, the first layer which was run in the main thread did not have its tearDown called either. 4.0.0b2 (2010-05-03) ==================== - Having 'sampletests' in the MANIFEST.in gave warnings, but doesn't actually seem to include any more files, so I removed it. - Moved zope.testing.exceptions to zope.testrunner.exceptions. Now zope.testrunner no longer requires zope.testing except for when running its own tests. 4.0.0b1 (2010-04-29) ==================== - Initial release of the testrunner from zope.testrunner as its own module. (Previously it was part of zope.testing.) .. _six: http://pypi.python.org/pypi/six
zope.testrunner
/zope.testrunner-6.1.tar.gz/zope.testrunner-6.1/CHANGES.rst
CHANGES.rst
================= zope.testrunner ================= .. image:: https://img.shields.io/pypi/v/zope.testrunner.svg :target: https://pypi.org/project/zope.testrunner/ :alt: Latest release .. image:: https://img.shields.io/pypi/pyversions/zope.testrunner.svg :target: https://pypi.org/project/zope.testrunner/ :alt: Supported Python versions .. image:: https://github.com/zopefoundation/zope.testrunner/actions/workflows/tests.yml/badge.svg :target: https://github.com/zopefoundation/zope.testrunner/actions/workflows/tests.yml .. image:: https://coveralls.io/repos/github/zopefoundation/zope.testrunner/badge.svg?branch=master :target: https://coveralls.io/github/zopefoundation/zope.testrunner?branch=master .. image:: https://readthedocs.org/projects/zopetestrunner/badge/?version=latest :target: https://zopetestrunner.readthedocs.io/en/latest/?badge=latest :alt: Documentation Status .. contents:: This package provides a flexible test runner with layer support. Detailed documentation is hosted at https://zopetestrunner.readthedocs.io
zope.testrunner
/zope.testrunner-6.1.tar.gz/zope.testrunner-6.1/README.rst
README.rst
Zope Public License (ZPL) Version 2.1 A copyright notice accompanies this license document that identifies the copyright holders. This license has been certified as open source. It has also been designated as GPL compatible by the Free Software Foundation (FSF). Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions in source code must retain the accompanying copyright notice, this list of conditions, and the following disclaimer. 2. Redistributions in binary form must reproduce the accompanying copyright notice, this list of conditions, and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Names of the copyright holders must not be used to endorse or promote products derived from this software without prior written permission from the copyright holders. 4. The right to distribute this software or to use it for any purpose does not give you the right to use Servicemarks (sm) or Trademarks (tm) of the copyright holders. Use of them is covered by separate agreement with the copyright holders. 5. If any files are modified, you must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. Disclaimer THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
zope.testrunner
/zope.testrunner-6.1.tar.gz/zope.testrunner-6.1/LICENSE.md
LICENSE.md
************************** developing zope.testrunner ************************** Zope testrunner needs itself to run its own tests. There are two ways to do that. Using zc.buildout ----------------- The standard way to set up a testrunner to test zope.testrunner with, is to use buildout:: $ python bootstrap.py $ bin/buildout You can now run the tests:: $ bin/test -pvc Running zope.testrunner.layer.UnitTests tests: Set up zope.testrunner.layer.UnitTests in 0.000 seconds. Ran 28 tests with 0 failures and 0 errors in 17.384 seconds. Tearing down left over layers: Tear down zope.testrunner.layer.UnitTests in 0.000 seconds. Using setup.py -------------- You may run the tests without buildout as well, as the setup.py has a custom test command that will run the tests:: $ python setup.py test running test running egg_info writing requirements to src/zope.testrunner.egg-info/requires.txt writing src/zope.testrunner.egg-info/PKG-INFO writing namespace_packages to src/zope.testrunner.egg-info/namespace_packages.txt writing top-level names to src/zope.testrunner.egg-info/top_level.txt writing dependency_links to src/zope.testrunner.egg-info/dependency_links.txt writing entry points to src/zope.testrunner.egg-info/entry_points.txt reading manifest template 'MANIFEST.in' warning: no files found matching 'sampletests' under directory 'src' writing manifest file 'src/zope.testrunner.egg-info/SOURCES.txt' running build_ext Running zope.testrunner.layer.UnitTests tests: Set up zope.testrunner.layer.UnitTests in 0.000 seconds. Ran 27 tests with 0 failures and 0 errors in 17.600 seconds. Tearing down left over layers: Tear down zope.testrunner.layer.UnitTests in 0.000 seconds. Using tox/detox --------------- This is a convenient way to run the test suite for all supported Python versions, either sequentially (`tox`_) or in parallel (`detox`_):: $ detox GLOB sdist-make: /home/mg/src/zope.testrunner/setup.py py33 sdist-reinst: .../.tox/dist/zope.testrunner-4.1.2.dev0.zip py27 sdist-reinst: .../.tox/dist/zope.testrunner-4.1.2.dev0.zip pypy sdist-reinst: .../.tox/dist/zope.testrunner-4.1.2.dev0.zip py31 sdist-reinst: .../.tox/dist/zope.testrunner-4.1.2.dev0.zip py32 sdist-reinst: .../.tox/dist/zope.testrunner-4.1.2.dev0.zip py26 sdist-reinst: .../.tox/dist/zope.testrunner-4.1.2.dev0.zip py27 runtests: commands[0] py26 runtests: commands[0] pypy runtests: commands[0] py32 runtests: commands[0] py33 runtests: commands[0] py31 runtests: commands[0] ______________________________ summary _______________________________ py26: commands succeeded py27: commands succeeded py31: commands succeeded py32: commands succeeded py33: commands succeeded pypy: commands succeeded congratulations :) .. _tox: http://pypi.python.org/pypi/tox .. _detox: http://pypi.python.org/pypi/detox
zope.testrunner
/zope.testrunner-6.1.tar.gz/zope.testrunner-6.1/DEVELOPING.rst
DEVELOPING.rst
import doctest import io import pdb import sys import threading import traceback try: import ipdb _ipdb_state = threading.local() except ImportError: ipdb = None import zope.testrunner.interfaces def _use_ipdb(): """Check whether ipdb is usable.""" global _ipdb_ok if ipdb is None: return False if getattr(_ipdb_state, 'ok', None) is None: _ipdb_state.ok = False if hasattr(sys.stdin, 'isatty') and sys.stdin.isatty(): try: sys.stdin.fileno() except (AttributeError, io.UnsupportedOperation): pass else: _ipdb_state.ok = True return _ipdb_state.ok def post_mortem(exc_info): err = exc_info[1] if isinstance(err, (doctest.UnexpectedException, doctest.DocTestFailure)): if isinstance(err, doctest.UnexpectedException): exc_info = err.exc_info # Print out location info if the error was in a doctest if exc_info[2].tb_frame.f_code.co_filename == '<string>': print_doctest_location(err) else: print_doctest_location(err) # Hm, we have a DocTestFailure exception. We need to # generate our own traceback try: exec(('raise ValueError' '("Expected and actual output are different")' ), err.test.globs) except BaseException: exc_info = sys.exc_info() print(''.join(traceback.format_exception_only(exc_info[0], exc_info[1]))) if _use_ipdb(): ipdb.post_mortem(exc_info[2]) else: pdb.post_mortem(exc_info[2]) raise zope.testrunner.interfaces.EndRun() def print_doctest_location(err): # This mimics pdb's output, which gives way cool results in emacs :) filename = err.test.filename if filename.endswith('.pyc'): filename = filename[:-1] print("> {}({})_()".format(filename, err.test.lineno+err.example.lineno+1))
zope.testrunner
/zope.testrunner-6.1.tar.gz/zope.testrunner-6.1/src/zope/testrunner/debug.py
debug.py
import gc import sys import types class TrackRefs: """Object to track reference counts across test runs.""" def __init__(self): self.type2count = {} self.type2all = {} self.delta = None self.n = 0 self.update() self.delta = None def update(self): gc.collect() obs = sys.getobjects(0) type2count = {} type2all = {} n = 0 for o in obs: if type(o) is str and o == '<dummy key>': # avoid dictionary madness continue all = sys.getrefcount(o) - 3 n += all t = type(o) if issubclass(t, types.InstanceType): t = o.__class__ if t in type2count: type2count[t] += 1 type2all[t] += all else: type2count[t] = 1 type2all[t] = all ct = [( type_or_class_title(t), type2count[t] - self.type2count.get(t, 0), type2all[t] - self.type2all.get(t, 0), ) for t in type2count] ct += [( type_or_class_title(t), - self.type2count[t], - self.type2all[t], ) for t in self.type2count if t not in type2count] ct.sort() self.delta = ct self.type2count = type2count self.type2all = type2all self.n = n def output(self): printed = False s1 = s2 = 0 for t, delta1, delta2 in self.delta: if delta1 or delta2: if not printed: print( ' Leak details, changes in instances and refcounts' ' by type/class:') print( " %-55s %6s %6s" % ('type/class', 'insts', 'refs')) print(" %-55s %6s %6s" % ('-' * 55, '-----', '----')) printed = True print(" %-55s %6d %6d" % (t, delta1, delta2)) s1 += delta1 s2 += delta2 if printed: print(" %-55s %6s %6s" % ('-' * 55, '-----', '----')) print(" %-55s %6s %6s" % ('total', s1, s2)) self.delta = None def type_or_class_title(t): module = getattr(t, '__module__', '__builtin__') if module == '__builtin__': return t.__name__ return "{}.{}".format(module, t.__name__)
zope.testrunner
/zope.testrunner-6.1.tar.gz/zope.testrunner-6.1/src/zope/testrunner/refcount.py
refcount.py
"""Output formatting. """ import doctest import io import os import re import sys import tempfile import traceback from collections.abc import MutableMapping from contextlib import contextmanager from datetime import datetime from datetime import timedelta from zope.testrunner.exceptions import DocTestFailureException doctest_template = """ File "%s", line %s, in %s %s Want: %s Got: %s """ class OutputFormatter: """Test runner output formatter.""" # Implementation note: be careful about printing stuff to sys.stderr. # It is used for interprocess communication between the parent and the # child test runner, when you run some test layers in a subprocess. # resume_layer() reasigns sys.stderr for this reason, but be careful # and don't store the original one in __init__ or something. max_width = 80 def __init__(self, options): self.options = options self.last_width = 0 self.compute_max_width() progress = property(lambda self: self.options.progress) verbose = property(lambda self: self.options.verbose) in_subprocess = property( lambda self: ( self.options.resume_layer is not None and self.options.processes > 1)) def compute_max_width(self): """Try to determine the terminal width.""" # Note that doing this every time is more test friendly. self.max_width = tigetnum('cols', self.max_width) def getShortDescription(self, test, room): """Return a description of a test that fits in ``room`` characters.""" room -= 1 s = str(test) if len(s) > room: pos = s.find(" (") if pos >= 0: w = room - (pos + 5) if w < 1: # first portion (test method name) is too long s = s[:room-3] + "..." else: pre = s[:pos+2] post = s[-w:] s = "{}...{}".format(pre, post) else: w = room - 4 s = '... ' + s[-w:] return ' ' + s[:room] def info(self, message): """Print an informative message.""" print(message) def info_suboptimal(self, message): """Print an informative message about losing some of the features. For example, when you run some tests in a subprocess, you lose the ability to use the debugger. """ print(message) def error(self, message): """Report an error.""" print(message) def error_with_banner(self, message): """Report an error with a big ASCII banner.""" print() print('*'*70) self.error(message) print('*'*70) print() def profiler_stats(self, stats): """Report profiler stats.""" stats.print_stats(50) def import_errors(self, import_errors): """Report test-module import errors (if any).""" if import_errors: print("Test-module import failures:") for error in import_errors: self.print_traceback("Module: %s\n" % error.module, error.exc_info), print() def tests_with_errors(self, errors): """Report names of tests with errors (if any).""" if errors: print() print("Tests with errors:") for test, exc_info in errors: print(" ", test) def tests_with_failures(self, failures): """Report names of tests with failures (if any).""" if failures: print() print("Tests with failures:") for test, exc_info in failures: print(" ", test) def modules_with_import_problems(self, import_errors): """Report names of modules with import problems (if any).""" if import_errors: print() print("Test-modules with import problems:") for test in import_errors: print(" " + test.module) def format_seconds(self, n_seconds): """Format a time in seconds.""" if n_seconds >= 60: n_minutes, n_seconds = divmod(n_seconds, 60) return "%d minutes %.3f seconds" % (n_minutes, n_seconds) else: return "%.3f seconds" % n_seconds def format_seconds_short(self, n_seconds): """Format a time in seconds (short version).""" return "%.3f s" % n_seconds def summary(self, n_tests, n_failures, n_errors, n_seconds, n_skipped=0): """Summarize the results of a single test layer.""" print(" Ran %s tests with %s failures, %s errors and " "%s skipped in %s." % (n_tests, n_failures, n_errors, n_skipped, self.format_seconds(n_seconds))) def totals(self, n_tests, n_failures, n_errors, n_seconds, n_skipped=0): """Summarize the results of all layers.""" print("Total: %s tests, %s failures, %s errors and %s skipped in %s." % (n_tests, n_failures, n_errors, n_skipped, self.format_seconds(n_seconds))) def list_of_tests(self, tests, layer_name): """Report a list of test names.""" print("Listing %s tests:" % layer_name) for test in tests: print(' ', test) def garbage(self, garbage): """Report garbage generated by tests.""" if garbage: print("Tests generated new (%d) garbage:" % len(garbage)) print(garbage) def test_garbage(self, test, garbage): """Report garbage generated by a test.""" if garbage: print("The following test left garbage:") print(test) print(garbage) def test_threads(self, test, new_threads): """Report threads left behind by a test.""" if new_threads: print("The following test left new threads behind:") print(test) print("New thread(s):", new_threads) def test_cycles(self, test, cycles): """Report cyclic garbage left behind by a test.""" if cycles: print("The following test left cyclic garbage behind:") print(test) for i, cy in enumerate(cycles): print("Cycle", i + 1) for oi in cy: print(" * ", "\n ".join(oi)) def refcounts(self, rc, prev): """Report a change in reference counts.""" print(" sys refcount=%-8d change=%-6d" % (rc, rc - prev)) def detailed_refcounts(self, track, rc, prev): """Report a change in reference counts, with extra detail.""" print(" sum detail refcount=%-8d" " sys refcount=%-8d" " change=%-6d" % (track.n, rc, rc - prev)) track.output() def start_set_up(self, layer_name): """Report that we're setting up a layer. The next output operation should be stop_set_up(). """ print(" Set up %s" % layer_name, end=' ') sys.stdout.flush() def stop_set_up(self, seconds): """Report that we've set up a layer. Should be called right after start_set_up(). """ print("in %s." % self.format_seconds(seconds)) def start_tear_down(self, layer_name): """Report that we're tearing down a layer. The next output operation should be stop_tear_down() or tear_down_not_supported(). """ print(" Tear down %s" % layer_name, end=' ') sys.stdout.flush() def stop_tear_down(self, seconds): """Report that we've tore down a layer. Should be called right after start_tear_down(). """ print("in %s." % self.format_seconds(seconds)) def tear_down_not_supported(self): """Report that we could not tear down a layer. Should be called right after start_tear_down(). """ print("... not supported") def start_test(self, test, tests_run, total_tests): """Report that we're about to run a test. The next output operation should be test_success(), test_error(), or test_failure(). """ self.test_width = 0 if self.progress: if self.last_width: sys.stdout.write('\r' + (' ' * self.last_width) + '\r') s = " %d/%d (%.1f%%)" % (tests_run, total_tests, tests_run * 100.0 / total_tests) sys.stdout.write(s) self.test_width += len(s) if self.verbose == 1: room = self.max_width - self.test_width - 1 s = self.getShortDescription(test, room) sys.stdout.write(s) self.test_width += len(s) elif self.verbose == 1: sys.stdout.write('.' * test.countTestCases()) elif self.in_subprocess: sys.stdout.write('.' * test.countTestCases()) # Give the parent process a new line so it sees the progress # in a timely manner. sys.stdout.write('\n') if self.verbose > 1: s = str(test) sys.stdout.write(' ') sys.stdout.write(s) self.test_width += len(s) + 1 sys.stdout.flush() def test_success(self, test, seconds): """Report that a test was successful. Should be called right after start_test(). The next output operation should be stop_test(). """ if self.verbose > 2: s = " (%s)" % self.format_seconds_short(seconds) sys.stdout.write(s) self.test_width += len(s) + 1 def test_skipped(self, test, reason): """Report that a test was skipped. Should be called right after start_test(). The next output operation should be stop_test(). """ if self.verbose > 2: s = " (skipped: %s)" % reason elif self.verbose > 1: s = " (skipped)" else: return sys.stdout.write(s) self.test_width += len(s) + 1 def test_error(self, test, seconds, exc_info, stdout=None, stderr=None): """Report that an error occurred while running a test. Should be called right after start_test(). The next output operation should be stop_test(). """ if self.verbose > 2: print(" (%s)" % self.format_seconds_short(seconds)) print() self.print_traceback("Error in test %s" % test, exc_info) self.print_std_streams(stdout, stderr) self.test_width = self.last_width = 0 def test_failure(self, test, seconds, exc_info, stdout=None, stderr=None): """Report that a test failed. Should be called right after start_test(). The next output operation should be stop_test(). """ if self.verbose > 2: print(" (%s)" % self.format_seconds_short(seconds)) print() self.print_traceback("Failure in test %s" % test, exc_info) self.print_std_streams(stdout, stderr) self.test_width = self.last_width = 0 def print_traceback(self, msg, exc_info): """Report an error with a traceback.""" print() print(msg) print(self.format_traceback(exc_info)) def print_std_streams(self, stdout, stderr): """Emit contents of buffered standard streams.""" if stdout: sys.stdout.write("Stdout:\n") sys.stdout.write(stdout) if not stdout.endswith("\n"): sys.stdout.write("\n") sys.stdout.write("\n") if stderr: sys.stderr.write("Stderr:\n") sys.stderr.write(stderr) if not stderr.endswith("\n"): sys.stderr.write("\n") sys.stderr.write("\n") def format_traceback(self, exc_info): """Format the traceback.""" v = exc_info[1] if isinstance(v, DocTestFailureException): tb = v.args[0] elif isinstance(v, doctest.DocTestFailure): tb = doctest_template % ( v.test.filename, v.test.lineno + v.example.lineno + 1, v.test.name, v.example.source, v.example.want, v.got, ) else: tb = "".join(traceback.format_exception(*exc_info)) return tb def stop_test(self, test, gccount): """Clean up the output state after a test.""" if gccount and self.verbose: s = "!" if self.verbose == 1 else " [%d]" % gccount self.test_width += len(s) print(s, end="") if self.progress: self.last_width = self.test_width elif self.verbose > 1: print() sys.stdout.flush() def stop_tests(self): """Clean up the output state after a collection of tests.""" if self.progress and self.last_width: sys.stdout.write('\r' + (' ' * self.last_width) + '\r') if self.verbose == 1 or self.progress: print() def tigetnum(attr, default=None): """Return a value from the terminfo database. Terminfo is used on Unix-like systems to report various terminal attributes (such as width, height or the number of supported colors). Returns ``default`` when the ``curses`` module is not available, or when sys.stdout is not a terminal. """ try: import curses except ImportError: # avoid reimporting a broken module sys.modules['curses'] = None else: # If sys.stdout is not a real file object (e.g. in unit tests that # use various wrappers), you get an error, different depending on # Python version: expected_exceptions = ( curses.error, TypeError, AttributeError, io.UnsupportedOperation) try: curses.setupterm() except expected_exceptions: # You get curses.error when $TERM is set to an unknown name pass else: try: return curses.tigetnum(attr) except expected_exceptions: # You get TypeError on PyPy3 due to a bug: # https://bitbucket.org/pypy/pypy/issue/2016/pypy3-cursestigetnum-raises-ctype pass return default def terminal_has_colors(): """Determine whether the terminal supports colors. Some terminals (e.g. the emacs built-in one) don't. """ return tigetnum('colors', -1) >= 8 class ColorfulOutputFormatter(OutputFormatter): """Output formatter that uses ANSI color codes. Like syntax highlighting in your text editor, colorizing test failures helps the developer. """ # These colors are carefully chosen to have enough contrast # on terminals with both black and white background. colorscheme = {'normal': 'normal', 'default': 'default', 'info': 'normal', 'suboptimal-behaviour': 'magenta', 'error': 'brightred', 'number': 'green', 'slow-test': 'brightmagenta', 'ok-number': 'green', 'error-number': 'brightred', 'filename': 'lightblue', 'lineno': 'lightred', 'testname': 'lightcyan', 'failed-example': 'cyan', 'expected-output': 'green', 'actual-output': 'red', 'character-diffs': 'magenta', 'diff-chunk': 'magenta', 'exception': 'red', 'skipped': 'brightyellow', } # Map prefix character to color in diff output. This handles ndiff and # udiff correctly, but not cdiff. In cdiff we ought to highlight '!' as # expected-output until we see a '-', then highlight '!' as actual-output, # until we see a '*', then switch back to highlighting '!' as # expected-output. Nevertheless, coloried cdiffs are reasonably readable, # so I'm not going to fix this. # -- mgedmin diff_color = {'-': 'expected-output', '+': 'actual-output', '?': 'character-diffs', '@': 'diff-chunk', '*': 'diff-chunk', '!': 'actual-output', } prefixes = [('dark', '0;'), ('light', '1;'), ('bright', '1;'), ('bold', '1;'), ] colorcodes = {'default': 0, 'normal': 0, 'black': 30, 'red': 31, 'green': 32, 'brown': 33, 'yellow': 33, 'blue': 34, 'magenta': 35, 'cyan': 36, 'grey': 37, 'gray': 37, 'white': 37} slow_test_threshold = 10.0 # seconds def color_code(self, color): """Convert a color description (e.g. 'lightred') to a terminal code.""" prefix_code = '' for prefix, code in self.prefixes: if color.startswith(prefix): color = color[len(prefix):] prefix_code = code break color_code = self.colorcodes[color] return '\033[{}{}m'.format(prefix_code, color_code) def color(self, what): """Pick a named color from the color scheme""" return self.color_code(self.colorscheme[what]) def colorize(self, what, message, normal='normal'): """Wrap message in color.""" return self.color(what) + message + self.color(normal) def error_count_color(self, n): """Choose a color for the number of errors.""" if n: return self.color('error-number') else: return self.color('ok-number') def skip_count_color(self, n): """Choose a color for the number of skipped tests.""" if n: return self.color('skipped') else: return self.color('ok-number') def test_skipped(self, test, reason): """Report that a test was skipped. Should be called right after start_test(). The next output operation should be stop_test(). """ if self.verbose > 2: s = " ({}skipped: {}{})".format( self.color('skipped'), reason, self.color('info')) elif self.verbose > 1: s = " ({}skipped{})".format( self.color('skipped'), self.color('info')) else: return sys.stdout.write(s) self.test_width += len(s) + 1 def info(self, message): """Print an informative message.""" print(self.colorize('info', message)) def info_suboptimal(self, message): """Print an informative message about losing some of the features. For example, when you run some tests in a subprocess, you lose the ability to use the debugger. """ print(self.colorize('suboptimal-behaviour', message)) def error(self, message): """Report an error.""" print(self.colorize('error', message)) def error_with_banner(self, message): """Report an error with a big ASCII banner.""" print() print(self.colorize('error', '*'*70)) self.error(message) print(self.colorize('error', '*'*70)) print() def tear_down_not_supported(self): """Report that we could not tear down a layer. Should be called right after start_tear_down(). """ print("...", self.colorize('suboptimal-behaviour', "not supported")) def format_seconds(self, n_seconds, normal='normal'): """Format a time in seconds.""" if n_seconds >= 60: n_minutes, n_seconds = divmod(n_seconds, 60) return "{} minutes {} seconds".format( self.colorize('number', '%d' % n_minutes, normal), self.colorize('number', '%.3f' % n_seconds, normal)) else: return "%s seconds" % ( self.colorize('number', '%.3f' % n_seconds, normal)) def format_seconds_short(self, n_seconds): """Format a time in seconds (short version).""" if n_seconds >= self.slow_test_threshold: color = 'slow-test' else: color = 'number' return self.colorize(color, "%.3f s" % n_seconds) def summary(self, n_tests, n_failures, n_errors, n_seconds, n_skipped=0): """Summarize the results.""" sys.stdout.writelines([ self.color('info'), ' Ran ', self.color('number'), str(n_tests), self.color('info'), ' tests with ', self.error_count_color(n_failures), str(n_failures), self.color('info'), ' failures, ', self.error_count_color(n_errors), str(n_errors), self.color('info'), ' errors, ', self.skip_count_color(n_skipped), str(n_skipped), self.color('info'), ' skipped in ', self.format_seconds(n_seconds, 'info'), '.', self.color('normal'), '\n', ]) def totals(self, n_tests, n_failures, n_errors, n_seconds, n_skipped=0): """Report totals (number of tests, failures, and errors).""" sys.stdout.writelines([ self.color('info'), 'Total: ', self.color('number'), str(n_tests), self.color('info'), ' tests, ', self.error_count_color(n_failures), str(n_failures), self.color('info'), ' failures, ', self.error_count_color(n_errors), str(n_errors), self.color('info'), ' errors, ', self.skip_count_color(n_skipped), str(n_skipped), self.color('info'), ' skipped in ', self.format_seconds(n_seconds, 'info'), '.', self.color('normal'), '\n']) def print_traceback(self, msg, exc_info): """Report an error with a traceback.""" print() print(self.colorize('error', msg)) v = exc_info[1] if isinstance(v, DocTestFailureException): self.print_doctest_failure(v.args[0]) elif isinstance(v, doctest.DocTestFailure): # I don't think these are ever used... -- mgedmin tb = self.format_traceback(exc_info) print(tb) else: tb = self.format_traceback(exc_info) self.print_colorized_traceback(tb) def print_doctest_failure(self, formatted_failure): """Report a doctest failure. ``formatted_failure`` is a string -- that's what DocTestSuite/DocFileSuite gives us. """ color_of_indented_text = 'normal' colorize_diff = False for line in formatted_failure.splitlines(): if line.startswith('File '): m = re.match(r'File "(.*)", line (\d*), in (.*)$', line) if m: filename, lineno, test = m.groups() sys.stdout.writelines([ self.color('normal'), 'File "', self.color('filename'), filename, self.color('normal'), '", line ', self.color('lineno'), lineno, self.color('normal'), ', in ', self.color('testname'), test, self.color('normal'), '\n']) else: print(line) elif line.startswith(' ') or line.strip() == '': if colorize_diff and len(line) > 4: color = self.diff_color.get( line[4], color_of_indented_text) print(self.colorize(color, line)) else: if line.strip() != '': print(self.colorize(color_of_indented_text, line)) else: print(line) else: colorize_diff = False if line.startswith('Failed example'): color_of_indented_text = 'failed-example' elif line.startswith('Expected:'): color_of_indented_text = 'expected-output' elif line.startswith('Got:'): color_of_indented_text = 'actual-output' elif line.startswith('Exception raised:'): color_of_indented_text = 'exception' elif line.startswith('Differences '): color_of_indented_text = 'normal' colorize_diff = True else: color_of_indented_text = 'normal' print(line) print() def print_colorized_traceback(self, formatted_traceback): """Report a test failure. ``formatted_traceback`` is a string. """ for line in formatted_traceback.splitlines(): if line.startswith(' File'): m = re.match(r' File "(.*)", line (\d*), in (.*)$', line) if m: filename, lineno, test = m.groups() sys.stdout.writelines([ self.color('normal'), ' File "', self.color('filename'), filename, self.color('normal'), '", line ', self.color('lineno'), lineno, self.color('normal'), ', in ', self.color('testname'), test, self.color('normal'), '\n']) else: print(line) elif line.startswith(' '): print(self.colorize('failed-example', line)) elif line.startswith('Traceback (most recent call last)'): print(line) else: print(self.colorize('exception', line)) print() class FakeTest: """A fake test object that only has an id.""" failureException = None def __init__(self, test_id): self._id = test_id def id(self): return self._id # Conditional imports: we don't want zope.testrunner to have a hard # dependency on subunit. try: import subunit from subunit.iso8601 import Utc subunit.StreamResultToBytes except (ImportError, AttributeError): subunit = None # testtools is a hard dependency of subunit itself, but we guard it # separately for richer error messages. try: import testtools from testtools.content import Content from testtools.content import ContentType from testtools.content import content_from_file from testtools.content import text_content testtools.StreamToExtendedDecorator except (ImportError, AttributeError): testtools = None class _RunnableDecorator: """Permit controlling the runnable annotation on tests. This decorates a StreamResult, adding a setRunnable context manager to indicate whether a test is runnable. (A context manager is unidiomatic here, but it's just about the simplest way to stuff the relevant state through the various layers of decorators involved without accidentally affecting later test results.) """ def __init__(self, decorated): self.decorated = decorated self._runnable = True def __getattr__(self, name): return getattr(self.decorated, name) @contextmanager def setRunnable(self, runnable): orig_runnable = self._runnable try: self._runnable = runnable yield finally: self._runnable = orig_runnable def status(self, **kwargs): kwargs = dict(kwargs) kwargs['runnable'] = self._runnable self.decorated.status(**kwargs) class _SortedDict(MutableMapping): """A dict that always returns items in sorted order. This differs from collections.OrderedDict in that it returns items in *sorted* order, not in insertion order. We use this as a workaround for the fact that testtools.ExtendedToStreamDecorator doesn't sort the details dict when encoding it, which makes it difficult to write stable doctests for subunit v2 output. """ def __init__(self, items): self._dict = dict(items) def __getitem__(self, key): return self._dict[key] def __setitem__(self, key, value): self._dict[key] = value def __delitem__(self, key): del self._dict[key] def __iter__(self): return iter(sorted(self._dict)) def __len__(self): return len(self._dict) class SubunitOutputFormatter: """A subunit output formatter. This output formatter generates subunit-compatible output (see https://launchpad.net/subunit). Subunit output is essentially a stream of results of unit tests. In this formatter, non-test events (such as layer set up) are encoded as specially-tagged tests. In particular, for a layer 'foo', the fake tests related to layer setup and teardown are tagged with 'zope:layer' and are called 'foo:setUp' and 'foo:tearDown'. Any tests within layer 'foo' are tagged with 'zope:layer:foo'. Note that all tags specific to this formatter begin with 'zope:'. """ # subunit output is designed for computers, so displaying a progress bar # isn't helpful. progress = False verbose = property(lambda self: self.options.verbose) TAG_INFO_SUBOPTIMAL = 'zope:info_suboptimal' TAG_ERROR_WITH_BANNER = 'zope:error_with_banner' TAG_LAYER = 'zope:layer' TAG_IMPORT_ERROR = 'zope:import_error' TAG_PROFILER_STATS = 'zope:profiler_stats' TAG_GARBAGE = 'zope:garbage' TAG_THREADS = 'zope:threads' TAG_REFCOUNTS = 'zope:refcounts' def __init__(self, options, stream=None): if subunit is None: raise Exception('Requires subunit 0.0.11 or better') if testtools is None: raise Exception('Requires testtools 0.9.30 or better') self.options = options if stream is None: stream = sys.stdout self._stream = stream self._subunit = self._subunit_factory(self._stream) # Used to track the last layer that was set up or torn down. Either # None or (layer_name, last_touched_time). self._last_layer = None self.UTC = Utc() # Content types used in the output. self.TRACEBACK_CONTENT_TYPE = ContentType( 'text', 'x-traceback', {'language': 'python', 'charset': 'utf8'}) self.PROFILE_CONTENT_TYPE = ContentType( 'application', 'x-binary-profile') self.PLAIN_TEXT = ContentType('text', 'plain', {'charset': 'utf8'}) @classmethod def _subunit_factory(cls, stream): """Return a TestResult attached to the given stream.""" return _RunnableDecorator(subunit.TestProtocolClient(stream)) def _emit_timestamp(self, now=None): """Emit a timestamp to the subunit stream. If 'now' is not specified, use the current time on the system clock. """ if now is None: now = datetime.now(self.UTC) self._subunit.time(now) return now def _emit_fake_test(self, message, tag, details=None): """Emit a successful fake test to the subunit stream. Use this to print tagged informative messages. """ test = FakeTest(message) with self._subunit.setRunnable(False): self._subunit.startTest(test) self._subunit.tags([tag], []) self._subunit.addSuccess(test, details=details) self._subunit.stopTest(test) def _emit_error(self, error_id, tag, exc_info, runnable=False): """Emit an error to the subunit stream. Use this to pass on information about errors that occur outside of tests. """ test = FakeTest(error_id) with self._subunit.setRunnable(runnable): self._subunit.startTest(test) self._subunit.tags([tag], []) self._subunit.addError(test, exc_info) self._subunit.stopTest(test) def _emit_failure(self, failure_id, tag, exc_info): """Emit an failure to the subunit stream. Use this to pass on information about failures that occur outside of tests. """ test = FakeTest(failure_id) self._subunit.addFailure(test, exc_info) def _enter_layer(self, layer_name): """Tell subunit that we are entering a layer.""" self._subunit.tags(['zope:layer:{}'.format(layer_name)], []) def _exit_layer(self, layer_name): """Tell subunit that we are exiting a layer.""" self._subunit.tags([], ['zope:layer:{}'.format(layer_name)]) def info(self, message): """Print an informative message.""" # info() output is not relevant to actual test results. It only # says things like "Running tests" or "Tearing down left over # layers", things that are communicated already by the subunit # stream. Just suppress the info() output. pass def info_suboptimal(self, message): """Print an informative message about losing some of the features. For example, when you run some tests in a subprocess, you lose the ability to use the debugger. """ # Used _only_ to indicate running in a subprocess. self._emit_fake_test(message.strip(), self.TAG_INFO_SUBOPTIMAL) def error(self, message): """Report an error.""" # XXX: Mostly used for user errors, sometimes used for errors in the # test framework, sometimes used to record layer setUp failure (!!!). self._stream.write('{}\n'.format(message)) def error_with_banner(self, message): """Report an error with a big ASCII banner.""" # Either "Could not communicate with subprocess" # Or "Can't post-mortem debug when running a layer as a subprocess!" self._emit_fake_test(message, self.TAG_ERROR_WITH_BANNER) def profiler_stats(self, stats): """Report profiler stats.""" fd, filename = tempfile.mkstemp(prefix='zope.testrunner-') os.close(fd) try: stats.dump_stats(filename) profile_content = content_from_file( filename, content_type=self.PROFILE_CONTENT_TYPE) details = {'profiler-stats': profile_content} # Name the test 'zope:profiler_stats' just like its tag. self._emit_fake_test( self.TAG_PROFILER_STATS, self.TAG_PROFILER_STATS, details) finally: os.unlink(filename) def import_errors(self, import_errors): """Report test-module import errors (if any).""" if import_errors: for error in import_errors: self._emit_error( error.module, self.TAG_IMPORT_ERROR, error.exc_info, runnable=True) def tests_with_errors(self, errors): """Report names of tests with errors (if any). Simply not supported by the subunit formatter. Fancy summary output doesn't make sense. """ pass def tests_with_failures(self, failures): """Report names of tests with failures (if any). Simply not supported by the subunit formatter. Fancy summary output doesn't make sense. """ pass def modules_with_import_problems(self, import_errors): """Report names of modules with import problems (if any).""" # This is simply a summary method, and subunit output doesn't # benefit from summaries. pass def summary(self, n_tests, n_failures, n_errors, n_seconds, n_skipped=0): """Summarize the results of a single test layer. Since subunit is a stream protocol format, it has no need for a summary. When the stream is finished other tools can generate a summary if so desired. """ pass def totals(self, n_tests, n_failures, n_errors, n_seconds, n_skipped=0): """Summarize the results of all layers. Simply not supported by the subunit formatter. Fancy summary output doesn't make sense. """ pass def _emit_exists(self, test): """Emit an indication that a test exists. With the v1 protocol, we just emit a fake success line. """ self._subunit.addSuccess(test) def list_of_tests(self, tests, layer_name): """Report a list of test names.""" self._enter_layer(layer_name) for test in tests: self._subunit.startTest(test) self._emit_exists(test) self._subunit.stopTest(test) self._exit_layer(layer_name) def garbage(self, garbage): """Report garbage generated by tests.""" # XXX: Really, 'garbage', 'profiler_stats' and the 'refcounts' twins # ought to add extra details to a fake test that represents the # summary information for the whole suite. However, there's no event # on output formatters for "everything is really finished, honest". -- # jml, 2010-02-14 details = {'garbage': text_content(str(garbage))} self._emit_fake_test(self.TAG_GARBAGE, self.TAG_GARBAGE, details) def test_garbage(self, test, garbage): """Report garbage generated by a test. Encoded in the subunit stream as a test error. Clients can filter out these tests based on the tag if they don't think garbage should fail the test run. """ # XXX: Perhaps 'test_garbage' and 'test_threads' ought to be within # the output for the actual test, appended as details to whatever # result the test gets. Not an option with the present API, as there's # no event for "no more output for this test". -- jml, 2010-02-14 self._subunit.startTest(test) self._subunit.tags([self.TAG_GARBAGE], []) self._subunit.addError( test, details={'garbage': text_content(str(garbage))}) self._subunit.stopTest(test) def test_threads(self, test, new_threads): """Report threads left behind by a test. Encoded in the subunit stream as a test error. Clients can filter out these tests based on the tag if they don't think left-over threads should fail the test run. """ self._subunit.startTest(test) self._subunit.tags([self.TAG_THREADS], []) self._subunit.addError( test, details={'threads': text_content(str(new_threads))}) self._subunit.stopTest(test) def test_cycles(self, test, cycles): """Report cycles left behind by a test.""" pass # not implemented def refcounts(self, rc, prev): """Report a change in reference counts.""" details = _SortedDict({ 'sys-refcounts': text_content(str(rc)), 'changes': text_content(str(rc - prev)), }) # XXX: Emit the details dict as JSON? self._emit_fake_test(self.TAG_REFCOUNTS, self.TAG_REFCOUNTS, details) def detailed_refcounts(self, track, rc, prev): """Report a change in reference counts, with extra detail.""" details = _SortedDict({ 'sys-refcounts': text_content(str(rc)), 'changes': text_content(str(rc - prev)), 'track': text_content(str(track.delta)), }) self._emit_fake_test(self.TAG_REFCOUNTS, self.TAG_REFCOUNTS, details) def start_set_up(self, layer_name): """Report that we're setting up a layer. We do this by emitting a fake test of the form '$LAYER_NAME:setUp' and adding a tag of the form 'zope:layer:$LAYER_NAME' to the current tag context. The next output operation should be stop_set_up(). """ test = FakeTest('{}:setUp'.format(layer_name)) now = self._emit_timestamp() with self._subunit.setRunnable(False): self._subunit.startTest(test) self._subunit.tags([self.TAG_LAYER], []) self._last_layer = (layer_name, now) def stop_set_up(self, seconds): """Report that we've set up a layer. Should be called right after start_set_up(). """ layer_name, start_time = self._last_layer self._last_layer = None test = FakeTest('{}:setUp'.format(layer_name)) self._emit_timestamp(start_time + timedelta(seconds=seconds)) with self._subunit.setRunnable(False): self._subunit.addSuccess(test) self._subunit.stopTest(test) self._enter_layer(layer_name) def layer_failure(self, failure_type, exc_info): layer_name, start_time = self._last_layer self._emit_failure( '{}:{}'.format(layer_name, failure_type), self.TAG_LAYER, exc_info) def start_tear_down(self, layer_name): """Report that we're tearing down a layer. We do this by emitting a fake test of the form '$LAYER_NAME:tearDown' and removing a tag of the form 'layer:$LAYER_NAME' from the current tag context. The next output operation should be stop_tear_down() or tear_down_not_supported(). """ test = FakeTest('{}:tearDown'.format(layer_name)) self._exit_layer(layer_name) now = self._emit_timestamp() with self._subunit.setRunnable(False): self._subunit.startTest(test) self._subunit.tags([self.TAG_LAYER], []) self._last_layer = (layer_name, now) def stop_tear_down(self, seconds): """Report that we've torn down a layer. Should be called right after start_tear_down(). """ layer_name, start_time = self._last_layer self._last_layer = None test = FakeTest('{}:tearDown'.format(layer_name)) self._emit_timestamp(start_time + timedelta(seconds=seconds)) with self._subunit.setRunnable(False): self._subunit.addSuccess(test) self._subunit.stopTest(test) def tear_down_not_supported(self): """Report that we could not tear down a layer. Should be called right after start_tear_down(). """ layer_name, start_time = self._last_layer self._last_layer = None test = FakeTest('{}:tearDown'.format(layer_name)) self._emit_timestamp() with self._subunit.setRunnable(False): self._subunit.addSkip(test, 'tearDown not supported') self._subunit.stopTest(test) def start_test(self, test, tests_run, total_tests): """Report that we're about to run a test. The next output operation should be test_success(), test_error(), or test_failure(). """ self._emit_timestamp() self._subunit.startTest(test) def test_success(self, test, seconds): """Report that a test was successful. Should be called right after start_test(). The next output operation should be stop_test(). """ self._emit_timestamp() self._subunit.addSuccess(test) def test_skipped(self, test, reason): """Report that a test was skipped. Should be called right after start_test(). The next output operation should be stop_test(). """ self._subunit.addSkip(test, reason) def _exc_info_to_details(self, exc_info): """Translate 'exc_info' into a details dict usable with subunit.""" # In an ideal world, we'd use the pre-bundled 'TracebackContent' # class from testtools. However, 'OutputFormatter' contains special # logic to handle errors from doctests, so we have to use that and # manually create an object equivalent to an instance of # 'TracebackContent'. formatter = OutputFormatter(None) traceback = formatter.format_traceback(exc_info) # We have no idea if the traceback is a str object or a # bytestring with non-ASCII characters. We had best be careful when # handling it. if isinstance(traceback, bytes): # Assume the traceback was UTF-8-encoded, but still be careful. str_tb = traceback.decode('utf-8', 'replace') else: str_tb = traceback return _SortedDict({ 'traceback': Content( self.TRACEBACK_CONTENT_TYPE, lambda: [str_tb.encode('utf8')]), }) def _add_std_streams_to_details(self, details, stdout, stderr): """Add buffered standard stream contents to a subunit details dict.""" if stdout: if isinstance(stdout, bytes): stdout = stdout.decode('utf-8', 'replace') details['test-stdout'] = Content( self.PLAIN_TEXT, lambda: [stdout.encode('utf-8')]) if stderr: if isinstance(stderr, bytes): stderr = stderr.decode('utf-8', 'replace') details['test-stderr'] = Content( self.PLAIN_TEXT, lambda: [stderr.encode('utf-8')]) def test_error(self, test, seconds, exc_info, stdout=None, stderr=None): """Report that an error occurred while running a test. Should be called right after start_test(). The next output operation should be stop_test(). """ self._emit_timestamp() details = self._exc_info_to_details(exc_info) self._add_std_streams_to_details(details, stdout, stderr) self._subunit.addError(test, details=details) def test_failure(self, test, seconds, exc_info, stdout=None, stderr=None): """Report that a test failed. Should be called right after start_test(). The next output operation should be stop_test(). """ self._emit_timestamp() details = self._exc_info_to_details(exc_info) self._add_std_streams_to_details(details, stdout, stderr) self._subunit.addFailure(test, details=details) def stop_test(self, test, gccount): """Clean up the output state after a test.""" self._subunit.stopTest(test) def stop_tests(self): """Clean up the output state after a collection of tests.""" # subunit handles all of this itself. pass class SubunitV2OutputFormatter(SubunitOutputFormatter): """A subunit v2 output formatter.""" @classmethod def _subunit_factory(cls, stream): """Return a TestResult attached to the given stream.""" stream_result = _RunnableDecorator(subunit.StreamResultToBytes(stream)) result = testtools.ExtendedToStreamDecorator(stream_result) # Lift our decorating method up so that we can get at it easily. result.setRunnable = stream_result.setRunnable result.startTestRun() return result def error(self, message): """Report an error.""" # XXX: Mostly used for user errors, sometimes used for errors in the # test framework, sometimes used to record layer setUp failure (!!!). self._subunit.status( file_name='error', file_bytes=str(message).encode('utf-8'), eof=True, mime_type=repr(self.PLAIN_TEXT)) def _emit_exists(self, test): """Emit an indication that a test exists.""" now = datetime.now(self.UTC) self._subunit.status( test_id=test.id(), test_status='exists', test_tags=self._subunit.current_tags, timestamp=now)
zope.testrunner
/zope.testrunner-6.1.tar.gz/zope.testrunner-6.1/src/zope/testrunner/formatter.py
formatter.py
import zope.interface class EndRun(Exception): """Indicate that the existing run call should stop Used to prevent additional test output after post-mortem debugging. """ class IFeature(zope.interface.Interface): """Features extend the test runners functionality in a pipe-lined order. """ active = zope.interface.Attribute( "Flag whether this feature is activated. If it is not activated than " "its methods won't be called by the runner.") def global_setup(): """Executed once when the test runner is being set up.""" def late_setup(): """Executed once right before the actual tests get executed and after all global setups have happened. Should do as little work as possible to avoid timing interferences with other features. It is guaranteed that the calling stack frame is not left until early_teardown was called. """ def layer_setup(layer): """Executed once after a layer was set up.""" def layer_teardown(layer): """Executed once after a layer was run.""" def test_setup(test): """Executed once before each test.""" def test_teardown(test): """Executed once after each test.""" def early_teardown(): """Executed once directly after all tests. This method should do as little as possible to avoid timing issues. It is guaranteed to be called directly from the same stack frame that called `late_setup`. """ def global_teardown(): """Executed once after all tests where run and early teardowns have happened. """ def report(): """Executed once after all tests have been run and all setup was torn down. This is the only method that should produce output. """ class ITestRunner(zope.interface.Interface): """The test runner manages test layers and their execution. The functionality of a test runner can be extended by configuring features. """ options = zope.interface.Attribute( "Provides access to configuration options.") class IMinimalTestLayer(zope.interface.Interface): """A test layer. This is the bare minimum that a ``layer`` attribute on a test suite should provide. """ __bases__ = zope.interface.Attribute( "A tuple of base layers.") __name__ = zope.interface.Attribute( "Name of the layer") __module__ = zope.interface.Attribute( "Dotted name of the module that defines this layer") def __hash__(): """A test layer must be hashable. The default identity-based __eq__ and __hash__ that Python provides usually suffice. """ def __eq__(): """A test layer must be hashable. The default identity-based __eq__ and __hash__ that Python provides usually suffice. """ class IFullTestLayer(IMinimalTestLayer): """A test layer. This is the full list of optional methods that a test layer can specify. """ def setUp(): """Shared layer setup. Called once before any of the tests in this layer (or sublayers) are run. """ def tearDown(): """Shared layer teardown. Called once after all the tests in this layer (and sublayers) are run. May raise NotImplementedError. """ def testSetUp(): """Additional test setup. Called once before every of test in this layer (or sublayers) is run. """ def testTearDown(): """Additional test teardown. Called once after every of test in this layer (or sublayers) is run. """
zope.testrunner
/zope.testrunner-6.1.tar.gz/zope.testrunner-6.1/src/zope/testrunner/interfaces.py
interfaces.py
import sys import traceback import zope.exceptions.exceptionformatter import zope.testrunner.feature def _iter_chain(exc, custom_tb=None, seen=None): if seen is None: seen = set() seen.add(exc) its = [] context = exc.__context__ cause = exc.__cause__ if cause is not None and cause not in seen: its.append(_iter_chain(cause, False, seen)) its.append([(traceback._cause_message, None)]) elif (context is not None and not exc.__suppress_context__ and context not in seen): its.append(_iter_chain(context, None, seen)) its.append([(traceback._context_message, None)]) its.append([(exc, custom_tb or exc.__traceback__)]) # itertools.chain is in an extension module and may be unavailable for it in its: yield from it def _parse_value_tb(exc, value, tb): # Taken straight from the traceback module code on Python 3.10, which # introduced the ability to call print_exception with an exception # instance as first parameter if (value is None) != (tb is None): raise ValueError("Both or neither of value and tb must be given") if value is tb is None: if exc is not None: return exc, exc.__traceback__ else: return None, None return value, tb def format_exception(t, v, tb, limit=None, chain=None): if chain: values = _iter_chain(v, tb) else: values = [(v, tb)] fmt = zope.exceptions.exceptionformatter.TextExceptionFormatter( limit=None, with_filenames=True) for v, tb in values: if isinstance(v, str): return v return fmt.formatException(t, v, tb) def print_exception(t, v=None, tb=None, limit=None, file=None, chain=None): v, tb = _parse_value_tb(t, v, tb) if chain: values = _iter_chain(v, tb) else: values = [(v, tb)] if file is None: file = sys.stdout for v, tb in values: file.writelines(format_exception(t, v, tb, limit)) class Traceback(zope.testrunner.feature.Feature): active = True def global_setup(self): self.old_format = traceback.format_exception traceback.format_exception = format_exception self.old_print = traceback.print_exception traceback.print_exception = print_exception def global_teardown(self): traceback.format_exception = self.old_format traceback.print_exception = self.old_print
zope.testrunner
/zope.testrunner-6.1.tar.gz/zope.testrunner-6.1/src/zope/testrunner/tb_format.py
tb_format.py
import errno import gc import io import os import pprint import queue import re import subprocess import sys import threading import time import traceback import unittest import warnings from contextlib import contextmanager from io import StringIO import zope.testrunner import zope.testrunner._doctest import zope.testrunner.coverage import zope.testrunner.debug import zope.testrunner.filter import zope.testrunner.garbagecollection import zope.testrunner.interfaces import zope.testrunner.listing import zope.testrunner.logsupport import zope.testrunner.process import zope.testrunner.profiling import zope.testrunner.selftest import zope.testrunner.shuffle import zope.testrunner.statistics import zope.testrunner.tb_format from zope.testrunner import threadsupport from zope.testrunner.find import _layer_name_cache from zope.testrunner.find import import_name from zope.testrunner.find import name_from_layer from zope.testrunner.layer import EmptyLayer from zope.testrunner.layer import EmptySuite from zope.testrunner.layer import UnitTests from zope.testrunner.options import get_options from zope.testrunner.refcount import TrackRefs from .digraph import DiGraph from .util import is_jython from .util import uses_refcounts class UnexpectedSuccess(Exception): pass PYREFCOUNT_PATTERN = re.compile(r'\[[0-9]+ refs\]') class SubprocessError(Exception): """An error occurred when running a subprocess """ def __init__(self, reason, stderr): self.reason = reason self.stderr = stderr def __str__(self): return '{}: {}'.format(self.reason, self.stderr) class CanNotTearDown(Exception): "Couldn't tear down a test" class Runner: """The test runner. It is the central point of this package and responsible for finding and executing tests as well as configuring itself from the (command-line) options passed into it. .. versionchanged:: 4.8.0 Add the *warnings* keyword argument. If this is ``None`` (the default) and the user hasn't configured Python otherwise with command-line arguments or environment variables, we will enable the default warnings, including ``DeprecationWarning``, when running tests. Otherwise, it can be any string acceptable to :func:`warnings.simplefilter` and that filter will be in effect while running tests. """ def __init__(self, defaults=None, args=None, found_suites=None, options=None, script_parts=None, cwd=None, warnings=None): if defaults is None: self.defaults = [] else: self.defaults = defaults self.args = args self.found_suites = found_suites self.options = options self.script_parts = script_parts self.cwd = cwd self.failed = True if warnings is None and not sys.warnoptions: # even if DeprecationWarnings are ignored by default # print them anyway unless other warnings settings are # specified by the warnings arg or the -W python flag self.warnings = 'default' else: # here self.warnings is set either to the value passed # to the warnings args or to None. # If the user didn't pass a value self.warnings will # be None. This means that the behavior is unchanged # and depends on the values passed to -W. self.warnings = warnings self.ran = 0 self.skipped = [] self.failures = [] self.errors = [] self.import_errors = [] self.show_report = True self.do_run_tests = True self.features = [] self.tests_by_layer_name = {} def ordered_layers(self): if (self.options.processes > 1 and not self.options.resume_layer): # if we want multiple processes, we need a fake layer as first # to start spreading out layers/tests to subprocesses # but only if this is not in the subprocess yield (name_from_layer(EmptyLayer), EmptyLayer, EmptySuite()) layer_names = {layer_from_name(layer_name): layer_name for layer_name in self.tests_by_layer_name} for layer in order_by_bases(layer_names): layer_name = layer_names[layer] yield layer_name, layer, self.tests_by_layer_name[layer_name] def register_tests(self, tests): """Registers tests.""" # XXX To support multiple features that find tests this shouldn't be # an update but merge the various layers individually. self.tests_by_layer_name.update(tests) def run(self): self.configure() if self.options.fail: return True # XXX Hacky to support existing code. self.layer_name_cache = _layer_name_cache self.layer_name_cache.clear() with self._enabled_warnings(): # Enable warnings during setup so that # warnings raised on import (which we do for test # discover) can be reported. # Global setup for feature in self.features: feature.global_setup() # Late setup # # Some system tools like profilers are really bad with stack # frames. E.g. hotshot doesn't like it when we leave the stack # frame that we called start() from. for feature in self.features: feature.late_setup() try: if self.do_run_tests: self.run_tests() finally: # Early teardown for feature in reversed(self.features): feature.early_teardown() # Global teardown for feature in reversed(self.features): feature.global_teardown() if self.show_report: for feature in self.features: feature.report() def configure(self): if self.args is None: self.args = sys.argv[:] # Check to see if we are being run as a subprocess. If we are, # then use the resume-layer and defaults passed in. if len(self.args) > 1 and self.args[1] == '--resume-layer': self.args.pop(1) resume_layer = self.args.pop(1) resume_number = int(self.args.pop(1)) self.defaults = [] while len(self.args) > 1 and self.args[1] == '--default': self.args.pop(1) self.defaults.append(self.args.pop(1)) sys.stdin = FakeInputContinueGenerator() else: resume_layer = resume_number = None options = get_options(self.args, self.defaults) options.testrunner_defaults = self.defaults options.resume_layer = resume_layer options.resume_number = resume_number self.options = options self.features.append(zope.testrunner.selftest.SelfTest(self)) self.features.append(zope.testrunner.logsupport.Logging(self)) self.features.append(zope.testrunner.coverage.Coverage(self)) self.features.append(zope.testrunner._doctest.DocTest(self)) self.features.append(zope.testrunner.profiling.Profiling(self)) if is_jython: # Jython GC support is not yet implemented pass else: self.features.append( zope.testrunner.garbagecollection.Threshold(self)) self.features.append( zope.testrunner.garbagecollection.Debug(self)) self.features.append(zope.testrunner.find.Find(self)) self.features.append(zope.testrunner.shuffle.Shuffle(self)) self.features.append(zope.testrunner.process.SubProcess(self)) self.features.append(zope.testrunner.filter.Filter(self)) self.features.append(zope.testrunner.listing.Listing(self)) self.features.append( zope.testrunner.statistics.Statistics(self)) self.features.append(zope.testrunner.tb_format.Traceback(self)) # Remove all features that aren't activated self.features = [f for f in self.features if f.active] @contextmanager def _enabled_warnings(self): """ A context manager to enable warnings as configured. """ with warnings.catch_warnings(): if self.warnings: # if self.warnings is set, use it to filter all the warnings warnings.simplefilter(self.warnings) # if the filter is 'default' or 'always', special-case the # warnings from the deprecated unittest methods to show them # no more than once per module, because they can be fairly # noisy. The -Wd and -Wa flags can be used to bypass this # only when self.warnings is None. if self.warnings in ['default', 'always']: warnings.filterwarnings( 'module', category=DeprecationWarning, message=r'Please use assert\w+ instead.') yield def run_tests(self): """Run all tests that were registered. Returns True if there where failures or False if all tests passed. """ setup_layers = {} layers_to_run = list(self.ordered_layers()) should_resume = False while layers_to_run: layer_name, layer, tests = layers_to_run[0] for feature in self.features: feature.layer_setup(layer) try: self.ran += run_layer(self.options, layer_name, layer, tests, setup_layers, self.failures, self.errors, self.skipped, self.import_errors) except zope.testrunner.interfaces.EndRun: self.failed = True break except CanNotTearDown: if not self.options.resume_layer: should_resume = True break layers_to_run.pop(0) if self.options.processes > 1: should_resume = True break if self.options.stop_on_error and (self.failures or self.errors): break if should_resume: if layers_to_run: self.ran += resume_tests( self.script_parts, self.options, self.features, layers_to_run, self.failures, self.errors, self.skipped, self.cwd) if setup_layers: if self.options.resume_layer is None: self.options.output.info("Tearing down left over layers:") tear_down_unneeded( self.options, (), setup_layers, self.errors, optional=True) self.failed = bool(self.import_errors or self.failures or self.errors) def handle_layer_failure(failure_type, output, errors): if hasattr(output, 'layer_failure'): output.layer_failure(failure_type.subunit_label, sys.exc_info()) else: f = StringIO() traceback.print_exc(file=f) output.error(f.getvalue()) errors.append((failure_type, sys.exc_info())) def run_tests(options, tests, name, failures, errors, skipped, import_errors): repeat = options.repeat or 1 repeat_range = iter(range(repeat)) ran = 0 output = options.output if is_jython: # Jython has no GC suppport - set count to 0 lgarbage = 0 else: gc.collect() lgarbage = len(gc.garbage) if options.report_refcounts: if options.verbose: # XXX This code path is untested track = TrackRefs() rc = sys.gettotalrefcount() for iteration in repeat_range: if repeat > 1: output.info("Iteration %d" % (iteration + 1)) if options.verbose > 0 or options.progress: output.info(' Running:') result = TestResult(options, tests, layer_name=name) t = time.time() if options.post_mortem: # post-mortem debugging for test in tests: if result.shouldStop: break result.startTest(test) state = test.__dict__.copy() try: try: test.debug() except KeyboardInterrupt: raise except unittest.SkipTest as e: result.addSkip(test, str(e)) except BaseException: result.addError( test, sys.exc_info()[:2] + (sys.exc_info()[2].tb_next, ), ) else: result.addSuccess(test) finally: result.stopTest(test) test.__dict__.clear() test.__dict__.update(state) else: # normal for test in tests: if result.shouldStop: break state = test.__dict__.copy() test(result) test.__dict__.clear() test.__dict__.update(state) t = time.time() - t output.stop_tests() failures.extend(result.failures) n_failures = len(result.failures) failures.extend(result.unexpectedSuccesses) n_failures += len(result.unexpectedSuccesses) skipped.extend(result.skipped) errors.extend(result.errors) output.summary(n_tests=result.testsRun, n_failures=n_failures, n_errors=len(result.errors) + len(import_errors), n_seconds=t, n_skipped=len(result.skipped)) ran = result.testsRun if is_jython: lgarbage = 0 else: gc.collect() if len(gc.garbage) > lgarbage: output.garbage(gc.garbage[lgarbage:]) lgarbage = len(gc.garbage) if options.report_refcounts: # If we are being tested, we don't want stdout itself to # foul up the numbers. :) try: sys.stdout.getvalue() except AttributeError: pass prev = rc rc = sys.gettotalrefcount() if options.verbose: track.update() if iteration > 0: output.detailed_refcounts(track, rc, prev) else: track.delta = None elif iteration > 0: output.refcounts(rc, prev) return ran def run_layer(options, layer_name, layer, tests, setup_layers, failures, errors, skipped, import_errors): output = options.output gathered = [] gather_layers(layer, gathered) needed = {ly: 1 for ly in gathered} if options.resume_number != 0: output.info("Running %s tests:" % layer_name) tear_down_unneeded(options, needed, setup_layers, errors) if options.resume_layer is not None: output.info_suboptimal(" Running in a subprocess.") try: setup_layer(options, layer, setup_layers) except zope.testrunner.interfaces.EndRun: raise except MemoryError: raise except Exception: handle_layer_failure(SetUpLayerFailure(layer), output, errors) return 0 else: return run_tests(options, tests, layer_name, failures, errors, skipped, import_errors) class SetUpLayerFailure(unittest.TestCase): subunit_label = 'setUp' def __init__(self, layer): super().__init__() self.layer = layer def runTest(self): pass def __str__(self): return "Layer: %s.setUp" % (name_from_layer(self.layer)) class TearDownLayerFailure(unittest.TestCase): subunit_label = 'tearDown' def __init__(self, layer): super().__init__() self.layer = layer def runTest(self): pass def __str__(self): return "Layer: %s.tearDown" % (name_from_layer(self.layer)) def spawn_layer_in_subprocess(result, script_parts, options, features, layer_name, layer, failures, errors, skipped, resume_number, cwd=None): output = options.output child = None try: # BBB if script_parts is None: script_parts = zope.testrunner._script_parts() args = [sys.executable] args.extend(script_parts) args.extend(['--resume-layer', layer_name, str(resume_number)]) for d in options.testrunner_defaults: args.extend(['--default', d]) args.extend(options.original_testrunner_args[1:]) debugargs = args # save them before messing up for windows if sys.platform.startswith('win'): args = args[0] + ' ' + ' '.join([ ('"' + a.replace('\\', '\\\\').replace('"', '\\"') + '"') for a in args[1:]]) for feature in features: feature.layer_setup(layer) child = subprocess.Popen( args, shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd, close_fds=not sys.platform.startswith('win')) def reader_thread(f, buf): buf.append(f.read()) # Start reading stderr in a thread. This means we don't hang if the # subprocess writes more to stderr than the pipe capacity. stderr_buf = [] stderr_thread = threading.Thread( target=reader_thread, args=(child.stderr, stderr_buf)) stderr_thread.daemon = True stderr_thread.start() while True: try: while True: # We use readline() instead of iterating over stdout # because it appears that iterating over stdout causes a # lot more buffering to take place (probably so it can # return its lines as a batch). We don't want too much # buffering because this foils automatic and human monitors # trying to verify that the subprocess is still alive. line = child.stdout.readline() if not line: break result.write(line) except OSError as e: if e.errno == errno.EINTR: # If the subprocess dies before we finish reading its # output, a SIGCHLD signal can interrupt the reading. # The correct thing to to in that case is to retry. continue output.error( "Error reading subprocess output for %s" % layer_name) output.info(str(e)) else: break # Now we should be able to finish reading stderr. stderr_thread.join() errlines = stderr_buf[0].splitlines() erriter = iter(errlines) nfail = nerr = 0 for line in erriter: try: result.num_ran, nfail, nerr = map(int, line.strip().split()) except ValueError: continue else: break else: errmsg = "Could not communicate with subprocess!" errors.append(("subprocess for %s" % layer_name, None)) if options.verbose >= 1: errmsg += "\nChild command line: %s" % debugargs if (options.verbose >= 2 or (options.verbose == 1 and len(errlines) < 20)): errmsg += ("\nChild stderr was:\n" + "\n".join(" " + line.decode('utf-8', 'replace') for line in errlines)) elif options.verbose >= 1: errmsg += ("\nChild stderr was:\n" + "\n".join(" " + line.decode('utf-8', 'replace') for line in errlines[:10]) + "\n...\n" + "\n".join(" " + line.decode('utf-8', 'replace') for line in errlines[-10:])) output.error_with_banner(errmsg) while nfail > 0: nfail -= 1 # Doing erriter.next().strip() confuses the 2to3 fixer, so # we need to do it on a separate line. Also, in python 3 this # returns bytes, so we decode it. next_fail = next(erriter) failures.append((next_fail.strip().decode(), None)) while nerr > 0: nerr -= 1 # Doing erriter.next().strip() confuses the 2to3 fixer, so # we need to do it on a separate line. Also, in python 3 this # returns bytes, so we decode it. next_err = next(erriter) errors.append((next_err.strip().decode(), None)) finally: result.done = True if child is not None: # Regardless of whether the process ran to completion, we # must properly cleanup the process to avoid # `ResourceWarning: subprocess XXX is still alive` and # `ResourceWarning: unclosed file` for its stdout and # stderr. child.kill() child.communicate() def _get_output_buffer(stream): """Get a binary-safe version of a stream.""" try: fileno = stream.fileno() except (io.UnsupportedOperation, AttributeError): pass else: # Win32 mangles \r\n to \n and that breaks streams. See # https://bugs.launchpad.net/bugs/505078. if sys.platform == 'win32': import msvcrt msvcrt.setmode(fileno, os.O_BINARY) try: stream.write(b'') except TypeError: return stream.buffer return stream class AbstractSubprocessResult: """A result of a subprocess layer run.""" num_ran = 0 done = False def __init__(self, layer_name, queue): self.layer_name = layer_name self.queue = queue self.stdout = [] def write(self, out): """Receive a line of the subprocess out.""" class DeferredSubprocessResult(AbstractSubprocessResult): """Keeps stdout around for later processing,""" def write(self, out): if not _is_dots(out): self.stdout.append(out) class ImmediateSubprocessResult(AbstractSubprocessResult): """Sends complete output to queue.""" def __init__(self, layer_name, queue): super().__init__(layer_name, queue) self.stream = _get_output_buffer(sys.stdout) def write(self, out): self.stream.write(out) # Help keep-alive monitors (human or automated) keep up-to-date. self.stream.flush() _is_dots = re.compile(br'\.+(\r\n?|\n)').match # Windows sneaks in a \r\n. class KeepaliveSubprocessResult(AbstractSubprocessResult): "Keeps stdout for later processing; sends marks to queue to show activity." _done = False def _set_done(self, value): self._done = value assert value, 'Internal error: unexpectedly setting done to False' self.queue.put((self.layer_name, ' LAYER FINISHED')) done = property(lambda self: self._done, _set_done) def write(self, out): if _is_dots(out): self.queue.put((self.layer_name, out.strip())) else: self.stdout.append(out) def resume_tests(script_parts, options, features, layers, failures, errors, skipped, cwd=None): results = [] stdout_queue = None if options.processes == 1: result_factory = ImmediateSubprocessResult elif (options.verbose > 1 and not options.subunit and not options.subunit_v2): result_factory = KeepaliveSubprocessResult stdout_queue = queue.Queue() else: result_factory = DeferredSubprocessResult resume_number = int(options.processes > 1) ready_threads = [] for layer_name, layer, tests in layers: result = result_factory(layer_name, stdout_queue) results.append(result) ready_threads.append(threading.Thread( target=spawn_layer_in_subprocess, args=(result, script_parts, options, features, layer_name, layer, failures, errors, skipped, resume_number, cwd))) resume_number += 1 # Now start a few threads at a time. running_threads = [] results_iter = iter(results) current_result = next(results_iter) last_layer_intermediate_output = None output = None # Get an object that (only) accepts bytes stdout = _get_output_buffer(sys.stdout) while ready_threads or running_threads: while len(running_threads) < options.processes and ready_threads: thread = ready_threads.pop(0) thread.start() running_threads.append(thread) for index, thread in reversed(list(enumerate(running_threads))): if not thread.is_alive(): del running_threads[index] # Clear out any messages in queue while stdout_queue is not None: previous_output = output try: layer_name, output = stdout_queue.get(False) except queue.Empty: break if layer_name != last_layer_intermediate_output: # Clarify what layer is reporting activity. if previous_output is not None: stdout.write(b']\n') stdout.write( ('[Parallel tests running in ' '%s:\n ' % (layer_name,)).encode('utf-8')) last_layer_intermediate_output = layer_name if not isinstance(output, bytes): output = output.encode('utf-8') stdout.write(output) # Display results in the order they would have been displayed, had the # work not been done in parallel. while current_result and current_result.done: if output is not None: stdout.write(b']\n') output = None stdout.writelines(current_result.stdout) try: current_result = next(results_iter) except StopIteration: current_result = None # Help keep-alive monitors (human or automated) keep up-to-date. stdout.flush() time.sleep(0.01) # Keep the loop from being too tight. # Return the total number of tests run. return sum(r.num_ran for r in results) def tear_down_unneeded(options, needed, setup_layers, errors, optional=False): # Tear down any layers not needed for these tests. The unneeded layers # might interfere. unneeded = [layer for layer in setup_layers if layer not in needed] unneeded = order_by_bases(unneeded) unneeded.reverse() output = options.output for layer in unneeded: output.start_tear_down(name_from_layer(layer)) t = time.time() try: try: if hasattr(layer, 'tearDown'): layer.tearDown() except NotImplementedError: output.tear_down_not_supported() if not optional: raise CanNotTearDown(layer) except MemoryError: raise except Exception: handle_layer_failure( TearDownLayerFailure(layer), output, errors) else: output.stop_tear_down(time.time() - t) finally: del setup_layers[layer] cant_pm_in_subprocess_message = """ Can't post-mortem debug when running a layer as a subprocess! Try running layer %r by itself. """ def setup_layer(options, layer, setup_layers): assert layer is not object output = options.output if layer not in setup_layers: for base in layer.__bases__: if base is not object: setup_layer(options, base, setup_layers) output.start_set_up(name_from_layer(layer)) t = time.time() if hasattr(layer, 'setUp'): try: layer.setUp() except MemoryError: raise except Exception: if options.post_mortem: if options.resume_layer: options.output.error_with_banner( cant_pm_in_subprocess_message % options.resume_layer) raise else: zope.testrunner.debug.post_mortem( sys.exc_info()) else: raise output.stop_set_up(time.time() - t) setup_layers[layer] = 1 class TestResult(unittest.TestResult): def __init__(self, options, tests, layer_name=None): unittest.TestResult.__init__(self) self.options = options # Calculate our list of relevant layers we need to call testSetUp # and testTearDown on. layers = [] gather_layers(layer_from_name(layer_name), layers) self.layers = order_by_bases(layers) count = 0 for test in tests: count += test.countTestCases() self.count = count self._stdout_buffer = None self._stderr_buffer = None self._original_stdout = sys.stdout self._original_stderr = sys.stderr def testSetUp(self): """A layer may define a setup method to be called before each individual test. """ for layer in self.layers: if hasattr(layer, 'testSetUp'): layer.testSetUp() def testTearDown(self): """A layer may define a teardown method to be called after each individual test. This is useful for clearing the state of global resources or resetting external systems such as relational databases or daemons. """ for layer in self.layers[-1::-1]: if hasattr(layer, 'testTearDown'): layer.testTearDown() def _makeBufferedStdStream(self): """Make a buffered stream to replace a standard stream.""" # The returned stream needs to have a 'buffer' attribute, since # some tests may expect that to exist on standard streams, and a # 'getvalue' method for the convenience of _restoreStdStreams. # This requires some care. class BufferedStandardStream(io.TextIOWrapper): def getvalue(self): return self.buffer.getvalue().decode( encoding=self.encoding, errors=self.errors) return BufferedStandardStream( io.BytesIO(), newline='\n', write_through=True) def _setUpStdStreams(self): """Set up buffered standard streams, if requested.""" if self.options.buffer: if self._stdout_buffer is None: self._stdout_buffer = self._makeBufferedStdStream() if self._stderr_buffer is None: self._stderr_buffer = self._makeBufferedStdStream() sys.stdout = self._stdout_buffer sys.stderr = self._stderr_buffer def _restoreStdStreams(self): """Restore the buffered standard streams and return any contents.""" if self.options.buffer: stdout = sys.stdout.getvalue() stderr = sys.stderr.getvalue() sys.stdout = self._original_stdout sys.stderr = self._original_stderr self._stdout_buffer.seek(0) self._stdout_buffer.truncate(0) self._stderr_buffer.seek(0) self._stderr_buffer.truncate(0) return stdout, stderr else: return None, None def startTest(self, test): self._test_state = test.__dict__.copy() self.testSetUp() unittest.TestResult.startTest(self, test) testsRun = self.testsRun - 1 # subtract the one the base class added count = test.countTestCases() self.testsRun = testsRun + count self.options.output.start_test(test, self.testsRun, self.count) self._threads = threadsupport.enumerate() self._start_time = time.time() self._setUpStdStreams() def addSuccess(self, test): self._restoreStdStreams() t = max(time.time() - self._start_time, 0.0) self.options.output.test_success(test, t) def addSkip(self, test, reason): self._restoreStdStreams() unittest.TestResult.addSkip(self, test, reason) self.options.output.test_skipped(test, reason) def addError(self, test, exc_info): stdout, stderr = self._restoreStdStreams() self.options.output.test_error(test, time.time() - self._start_time, exc_info, stdout=stdout, stderr=stderr) unittest.TestResult.addError(self, test, exc_info) if self.options.post_mortem: if self.options.resume_layer: self.options.output.error_with_banner("Can't post-mortem debug" " when running a layer" " as a subprocess!") else: zope.testrunner.debug.post_mortem(exc_info) elif self.options.stop_on_error: self.stop() def addFailure(self, test, exc_info): stdout, stderr = self._restoreStdStreams() self.options.output.test_failure(test, time.time() - self._start_time, exc_info, stdout=stdout, stderr=stderr) unittest.TestResult.addFailure(self, test, exc_info) if self.options.post_mortem: # XXX: mgedmin: why isn't there a resume_layer check here like # in addError? zope.testrunner.debug.post_mortem(exc_info) elif self.options.stop_on_error: self.stop() def addExpectedFailure(self, test, exc_info): self._restoreStdStreams() t = max(time.time() - self._start_time, 0.0) self.options.output.test_success(test, t) unittest.TestResult.addExpectedFailure(self, test, exc_info) def addUnexpectedSuccess(self, test): stdout, stderr = self._restoreStdStreams() self.options.output.test_error( test, time.time() - self._start_time, (UnexpectedSuccess, UnexpectedSuccess(), None), stdout=stdout, stderr=stderr) unittest.TestResult.addUnexpectedSuccess(self, test) if self.options.post_mortem: if self.options.resume_layer: self.options.output.error_with_banner("Can't post-mortem debug" " when running a layer" " as a subprocess!") else: # XXX: what exc_info? there's no exc_info! # flake8 is correct, but keep it quiet for now ... zope.testrunner.debug.post_mortem(exc_info) # noqa: F821 elif self.options.stop_on_error: self.stop() def stopTest(self, test): self.testTearDown() # Without clearing, cyclic garbage referenced by the test # would be reported in the following test. test.__dict__.clear() test.__dict__.update(self._test_state) del self._test_state cycles = None if (uses_refcounts and self.options.gc_after_test and self.options.verbose >= 4): gc_opts = gc.get_debug() gc.set_debug(gc.DEBUG_SAVEALL) gc.collect() if gc.garbage: g = DiGraph(gc.garbage) for obj in gc.garbage: g.add_neighbors(obj, gc.get_referents(obj)) cycles = [[repr_lines(o) for o in c] for c in g.sccs()] del gc.garbage[:] g = obj = None # avoid to hold cyclic garbage gc.set_debug(gc_opts) gccount = gc.collect() \ if uses_refcounts and self.options.gc_after_test else 0 self.options.output.stop_test(test, gccount) if cycles: self.options.output.test_cycles(test, cycles) if is_jython: pass else: if gc.garbage: self.options.output.test_garbage(test, gc.garbage) # TODO: Perhaps eat the garbage here, so that the garbage isn't # printed for every subsequent test. # Did the test leave any new threads behind? new_threads = [] for t in threadsupport.enumerate(): if t.is_alive() and t not in self._threads: if not any([re.match(p, t.name) for p in self.options.ignore_new_threads]): new_threads.append(t) if new_threads: self.options.output.test_threads(test, new_threads) def layer_from_name(layer_name): """Return the layer for the corresponding layer_name by discovering and importing the necessary module if necessary. Note that a name -> layer cache is maintained by name_from_layer to allow locating layers in cases where it would otherwise be impossible. """ if layer_name in _layer_name_cache: return _layer_name_cache[layer_name] layer_names = layer_name.split('.') layer_module, module_layer_name = layer_names[:-1], layer_names[-1] module_name = '.'.join(layer_module) module = import_name(module_name) try: return getattr(module, module_layer_name) except AttributeError: # the default error is very uninformative: # AttributeError: 'module' object has no attribute 'DemoLayer' # it doesn't say *which* module raise AttributeError('module %r has no attribute %r' % (module_name, module_layer_name)) def layer_sort_key(layer): """Compute sort key for layers. Based on the reverse MRO ordering in order to put layers with shared base layers next to each other. """ seen = set() key = [] # Note: we cannot reuse gather_layers() here because it uses a # different traversal order. binding = {} # hack to avoid recursion -- for PY2 def _gather(layer): seen.add(layer) # We make the simplifying assumption that the order of initialization # of base layers does not matter. Given that, traversing the bases # in reverse order here keeps the ordering of layers in # testrunner-layers.rst the same as it was in older versions of # zope.testrunner, so let's use that. for base in layer.__bases__[::-1]: if base is not object and base not in seen: binding["_gather"](base) key.append(layer) binding["_gather"] = _gather _gather(layer) try: return tuple(name_from_layer(ly) for ly in key if ly != UnitTests) finally: binding.clear() # break reference cycle def order_by_bases(layers): """Order the layers from least to most specific (bottom to top). Puts unit tests first. Groups layers with common base layers together. Sorts the rest alphabetically. Removes duplicates. """ layers = sorted(layers, key=layer_sort_key, reverse=True) gathered = [] for layer in layers: gather_layers(layer, gathered) gathered.reverse() seen = {} result = [] for layer in gathered: if layer not in seen: seen[layer] = 1 if layer in layers: result.append(layer) return result def gather_layers(layer, result): if layer is not object: result.append(layer) for b in layer.__bases__: gather_layers(b, result) class FakeInputContinueGenerator: def readline(self): print('c\n') print('*'*70) print("Can't use pdb.set_trace when running a layer" " as a subprocess!") print('*'*70) print() return 'c\n' def close(self): pass def repr_lines(obj, max_width=75, max_lines=5): """represent *obj* by a sequence of text lines. Use at most *max_lines*, each with at most *max_width* chars. """ try: oi = pprint.pformat(obj) except Exception: # unprintable oi = "{} instance at 0x{:x}".format(obj.__class__, id(obj)) # limit cmps = oi.split("\n", max_lines) if len(cmps) > max_lines: cmps[-1] = "..." for i, li in enumerate(cmps): if len(li) > max_width: cmps[i] = li[:max_width - 3] + "..." return cmps
zope.testrunner
/zope.testrunner-6.1.tar.gz/zope.testrunner-6.1/src/zope/testrunner/runner.py
runner.py
import re import zope.testrunner.feature UNITTEST_LAYER = 'zope.testrunner.layer.UnitTests' class Filter(zope.testrunner.feature.Feature): """Filters and orders all tests registered until now.""" active = True def global_setup(self): layers = self.runner.tests_by_layer_name options = self.runner.options if UNITTEST_LAYER in layers: # We start out assuming unit tests should run and look for reasons # why they shouldn't be run. should_run = True if (not options.non_unit): if options.layer: accept = build_filtering_func(options.layer) should_run = accept(UNITTEST_LAYER) else: should_run = True else: should_run = False if not should_run: layers.pop(UNITTEST_LAYER) if self.runner.options.resume_layer is not None: for name in list(layers): if name != self.runner.options.resume_layer: layers.pop(name) if not layers: self.runner.options.output.error_with_banner( "Cannot find layer %s" % self.runner.options.resume_layer) self.runner.errors.append( ("subprocess failed for %s" % self.runner.options.resume_layer, None)) elif self.runner.options.layer: accept = build_filtering_func(self.runner.options.layer) for name in list(layers): if not accept(name): # No pattern matched this name so we remove it layers.pop(name) if (self.runner.options.verbose and not self.runner.options.resume_layer): if self.runner.options.all: msg = "Running tests at all levels" else: msg = ( "Running tests at level %d" % self.runner.options.at_level) self.runner.options.output.info(msg) def report(self): if not self.runner.do_run_tests: return if self.runner.options.resume_layer: return if self.runner.options.verbose: self.runner.options.output.tests_with_errors(self.runner.errors) self.runner.options.output.tests_with_failures( self.runner.failures) def build_filtering_func(patterns): """Build a filtering function from a set of patterns Patterns are understood as regular expressions, with the additional feature that, prefixed by "!", they create a "don't match" rule. This returns a function which returns True if a string matches the set of patterns, or False if it doesn't match. """ selected = [] unselected = [] for pattern in patterns: if pattern.startswith('!'): store = unselected.append pattern = pattern[1:] else: store = selected.append store(re.compile(pattern).search) if not selected and unselected: # If there's no selection patterns but some un-selection patterns, # suppose we want everything (that is, everything that matches '.'), # minus the un-selection ones. selected.append(re.compile('.').search) def accept(value): return (any(search(value) for search in selected) and not any(search(value) for search in unselected)) return accept
zope.testrunner
/zope.testrunner-6.1.tar.gz/zope.testrunner-6.1/src/zope/testrunner/filter.py
filter.py
from setuptools.command.test import ScanningLoader from setuptools.command.test import test as BaseCommand def skipLayers(suite, _result=None): """ Walk the suite returned by setuptools' testloader. o Skip any tests which have a 'layer' defined. """ from unittest import TestSuite if _result is None: _result = TestSuite() # Sometimes test suites do not have tests, like DocFileSuite. if not suite._tests: _result.addTest(suite) return _result for test in suite._tests: layer = getattr(test, 'layer', None) if layer is not None: continue if isinstance(test, TestSuite): skipLayers(test, _result) else: _result.addTest(test) return _result class SkipLayers(ScanningLoader): """ Load only unit tests (those which have no layer associated with them). * Running the tests using 'setup.py test' cannot, by default, drive the full testrunner, with its support for layers (in functional tests). This loader allows the command to work, by running only those tests which don't need the layer support. * To run layer-dependent tests, use 'setup.py ftest' (see below for adding the command to your setup.py). * To use this loader your package add the following your 'setup()' call:: setup( ... setup_requires=[ 'eggtestinfo' # captures testing metadata in EGG-INFO ], tests_require=['zope.testrunner', ], ... test_loader='zope.testrunner.eggsupport:SkipLayers', ... ) """ def loadTestsFromModule(self, module): return skipLayers( ScanningLoader.loadTestsFromModule(self, module)) def loadTestsFromNames(self, testNames, module): return skipLayers( ScanningLoader.loadTestsFromNames(self, testNames, module)) def print_usage(): print('python setup.py ftest') print() print(ftest.__doc__) class ftest(BaseCommand): """ Run unit and functional tests after an in-place build. * Note that this command runs *all* tests (unit *and* functional). * This command does not provide any of the configuration options which the usual testrunner provided by 'zope.testrunner' offers: it is intended to allow easy verification that a package has been installed correctly via setuptools, but is not likely to be useful for developers working on the package. * Developers working on the package will likely prefer to work with the stock testrunner, e.g., by using buildout with a recipe which configures the testrunner as a standalone script. * To use this in your package add the following to the 'entry_points' section:: setup( ... setup_requires=[ 'zope.testrunner', 'eggtestinfo' # captures testing metadata in EGG-INFO ], ... ) """ description = "Run all functional and unit tests after in-place build" user_options = [] help_options = [('usage', '?', 'Show usage', print_usage)] def initialize_options(self): pass # suppress normal handling def finalize_options(self): pass # suppress normal handling def run(self): from zope.testrunner import run args = ['IGNORE_ME'] dist = self.distribution for src_loc in (dist.package_dir.values() or ['.']): args += ['--test-path', src_loc] if dist.install_requires: dist.fetch_build_eggs(dist.install_requires) if dist.tests_require: dist.fetch_build_eggs(dist.tests_require) def _run(): run(args=args) self.with_project_on_sys_path(_run)
zope.testrunner
/zope.testrunner-6.1.tar.gz/zope.testrunner-6.1/src/zope/testrunner/eggsupport.py
eggsupport.py
import os import re import sys import unittest import zope.testrunner.debug import zope.testrunner.feature import zope.testrunner.layer from zope.testrunner.filter import build_filtering_func identifier = re.compile(r'[_a-zA-Z]\w*$').match class DuplicateTestIDError(Exception): """Raised whenever a test ID is encountered twice during loading.""" class StartUpFailure(unittest.TestCase): """Empty test case added to the test suite to indicate import failures. >>> class Options(object): ... post_mortem = False >>> options = Options() Normally the StartUpFailure just acts as an empty test suite to satisfy the test runner and statistics: >>> s = StartUpFailure(options, 'fauxmodule', None) >>> s <StartUpFailure module=fauxmodule> >>> isinstance(s,unittest.TestCase) True >>> s.shortDescription() 'StartUpFailure: import errors in fauxmodule.' Sometimes test suited collected by zope.testrunner end up being run by a regular unittest TestRunner, and it's not hard to make sure StartUpFailure does something sensible in that case >>> r = unittest.TestResult() >>> _ = s.run(r) >>> print(r.failures[0][1].rstrip()) # doctest: +ELLIPSIS Traceback (most recent call last): ... AssertionError: could not import fauxmodule If you'd like more details, be sure to pass the original exc_info:: >>> import sys >>> try: ... raise Exception('something bad happened during import') ... except: ... exc_info = sys.exc_info() >>> s = StartUpFailure(options, 'fauxmodule', exc_info) >>> r = unittest.TestResult() >>> _ = s.run(r) >>> print(r.errors[0][0].shortDescription()) StartUpFailure: import errors in fauxmodule. >>> print(r.errors[0][1].rstrip()) # doctest: +ELLIPSIS Traceback (most recent call last): ... Exception: something bad happened during import However, if the post mortem option is enabled: >>> options.post_mortem = True ...then the the StartUpFailure will start the debugger and stop the test run after the debugger quits. To simulate the user pressing 'c' and hitting return in the debugger, we use a FakeInputContinueGenerator: >>> from zope.testrunner.runner import FakeInputContinueGenerator >>> old_stdin = sys.stdin >>> sys.stdin = FakeInputContinueGenerator() Now we can see the EndRun exception that is raised by the postmortem debugger to indicate that debugging is finished and the test run should be terminated: >>> from zope.testrunner.interfaces import EndRun >>> try: #doctest: +ELLIPSIS ... # Needed to prevent the result from starting with '...' ... print("Result:") ... StartUpFailure(options, None, exc_info) ... except EndRun: ... print("EndRun raised") ... finally: ... sys.stdin = old_stdin Result: Exception: something bad happened during import ... (Pdb) c <BLANKLINE> ********************************************************************** Can't use pdb.set_trace when running a layer as a subprocess! ********************************************************************** <BLANKLINE> EndRun raised Annoyingly, sometimes StartUpFailures occur when postmortem debugging is enabled but no exc_info is passed. In this case, we raise a sensible exception rather than letting the debugger barf with an AttributeError: >>> options.post_mortem = True >>> StartUpFailure(options, None, exc_info[:2]+(None,)) Traceback (most recent call last): ... TypeError: If post_mortem is specified, full exc_info must be passed! """ def __init__(self, options, module, exc_info): if options.post_mortem: for item in exc_info: if item is None: raise TypeError('If post_mortem is specified, ' 'full exc_info must be passed!') zope.testrunner.debug.post_mortem(exc_info) self.module = module self.exc_info = exc_info super().__init__() def shortDescription(self): return 'StartUpFailure: import errors in %s.' % self.module def __repr__(self): return '<StartUpFailure module=%s>' % self.module def runTest(self): if self.exc_info is None or any(x is None for x in self.exc_info): self.fail("could not import %s" % self.module) else: try: _, value, tb = self.exc_info raise value.with_traceback(tb) finally: value = None tb = None def find_tests(options, found_suites=None): """Creates a dictionary mapping layer name to a suite of tests to be run in that layer. Passing a list of suites using the found_suites parameter will cause that list of suites to be used instead of attempting to load them from the filesystem. This is useful for unit testing the test runner. """ remove_stale_bytecode(options) suites = {} dupe_ids = set() test_accept = build_filtering_func(options.test) module_accept = build_filtering_func(options.module) if found_suites is None: found_suites = find_suites(options, accept=module_accept) for suite in found_suites: for test, layer_name in tests_from_suite(suite, options, accept=test_accept, duplicated_test_ids=dupe_ids): if dupe_ids: # If there are any duplicated test IDs, we stop trying to # load tests; we'll raise an error later on with all the # duplicates in it. continue suite = suites.get(layer_name) if not suite: suite = suites[layer_name] = unittest.TestSuite() suite.addTest(test) if dupe_ids: message_lines = ['Duplicate test IDs found:'] + sorted(dupe_ids) message = '\n '.join(message_lines) raise DuplicateTestIDError(message) return suites def find_suites(options, accept=None): for fpath, package in find_test_files(options): for (prefix, prefix_package) in options.prefix: if fpath.startswith(prefix) and package == prefix_package: # strip prefix, strip .py suffix and convert separator to dots noprefix = fpath[len(prefix):] noext = strip_py_ext(options, noprefix) assert noext is not None module_name = noext.replace(os.path.sep, '.') if package: module_name = package + '.' + module_name if accept is not None and not accept(module_name): continue try: module = import_name(module_name) except KeyboardInterrupt: raise except BaseException: exc_info = sys.exc_info() if not options.post_mortem: # Skip a couple of frames exc_info = ( exc_info[:2] + (exc_info[2].tb_next.tb_next,)) suite = StartUpFailure( options, module_name, exc_info) else: try: if hasattr(module, options.suite_name): suite = getattr(module, options.suite_name)() else: loader = unittest.defaultTestLoader suite = loader.loadTestsFromModule(module) if suite.countTestCases() == 0: raise TypeError( "Module %s does not define any tests" % module_name) if not isinstance(suite, unittest.TestSuite): # We extract the error message expression into a # local variable because we want the `raise` # statement to fit on a single line, to make the # testrunner-debugging-import-failure.rst doctest # see the same pdb output on Python 3.8 as on older # Python versions. bad_test_suite_msg = ( "Invalid test_suite, %r, in %s" % (suite, module_name) ) raise TypeError(bad_test_suite_msg) except KeyboardInterrupt: raise except BaseException: exc_info = sys.exc_info() if not options.post_mortem: # Suppress traceback exc_info = exc_info[:2] + (None,) suite = StartUpFailure( options, module_name, exc_info) yield suite break def find_test_files(options): found = {} for f, package in find_test_files_(options): if f not in found: found[f] = 1 yield f, package def find_test_files_(options): tests_pattern = options.tests_pattern test_file_pattern = options.test_file_pattern # If options.usecompiled, we can accept .pyc or .pyo files instead # of .py files. We'd rather use a .py file if one exists. `root2ext` # maps a test file path, sans extension, to the path with the best # extension found (.py if it exists, else .pyc or .pyo). # Note that "py" < "pyc" < "pyo", so if more than one extension is # found, the lexicographically smaller one is best. # Found a new test file, in directory `dirname`. `noext` is the # file name without an extension, and `withext` is the file name # with its extension. def update_root2ext(dirname, noext, withext): key = os.path.join(dirname, noext) new = os.path.join(dirname, withext) if key in root2ext: root2ext[key] = min(root2ext[key], new) else: root2ext[key] = new for (p, package) in test_dirs(options, {}): for dirname, dirs, files in walk_with_symlinks(options, p): if dirname != p and not contains_init_py(options, files): # This is not a plausible test directory. Avoid descending # further. del dirs[:] continue root2ext = {} dirs[:] = [d for d in dirs if identifier(d)] d = os.path.split(dirname)[1] if tests_pattern(d) and contains_init_py(options, files): # tests directory for file in files: noext = strip_py_ext(options, file) if noext and test_file_pattern(noext): update_root2ext(dirname, noext, file) for file in files: noext = strip_py_ext(options, file) if noext and tests_pattern(noext): update_root2ext(dirname, noext, file) winners = sorted(root2ext.values()) for file in winners: yield file, package def strip_py_ext(options, path): """Return path without its .py (or .pyc or .pyo) extension, or None. If options.usecompiled is false: If path ends with ".py", the path without the extension is returned. Else None is returned. If options.usecompiled is true: If Python is running with -O, a .pyo extension is also accepted. If Python is running without -O, a .pyc extension is also accepted. """ if path.endswith(".py"): return path[:-3] if options.usecompiled: if __debug__: # Python is running without -O. ext = ".pyc" else: # Python is running with -O. ext = ".pyo" if path.endswith(ext): return path[:-len(ext)] return None def test_dirs(options, seen): if options.package: for p in options.package: p = import_name(p) for p in p.__path__: p = os.path.abspath(p) if p in seen: continue for (prefix, package) in options.prefix: if p.startswith(prefix) or p == prefix[:-1]: seen[p] = 1 yield p, package break else: yield from options.test_path def walk_with_symlinks(options, dir): # TODO -- really should have test of this that uses symlinks # this is hard on a number of levels ... for dirpath, dirs, files in os.walk(dir): dirs.sort() files.sort() dirs[:] = [d for d in dirs if d not in options.ignore_dir] yield (dirpath, dirs, files) for d in dirs: p = os.path.join(dirpath, d) if os.path.islink(p): yield from walk_with_symlinks(options, p) compiled_suffixes = '.pyc', '.pyo' def remove_stale_bytecode(options): if options.keepbytecode: return for (p, _) in options.test_path: for dirname, dirs, files in walk_with_symlinks(options, p): if '__pycache__' in dirs: # Do not recurse in there: we would end up removing all pyc # files because the main loop checks for py files in the same # directory. Besides, stale pyc files in __pycache__ are # harmless, see PEP-3147 for details (sourceless imports # work only when pyc lives in the source dir directly). dirs.remove('__pycache__') for file in files: if file[-4:] in compiled_suffixes and file[:-1] not in files: fullname = os.path.join(dirname, file) options.output.info("Removing stale bytecode file %s" % fullname) os.unlink(fullname) def contains_init_py(options, fnamelist): """Return true iff fnamelist contains a suitable spelling of __init__.py. If options.usecompiled is false, this is so iff "__init__.py" is in the list. If options.usecompiled is true, then "__init__.pyo" is also acceptable if Python is running with -O, and "__init__.pyc" is also acceptable if Python is running without -O. """ if "__init__.py" in fnamelist: return True if options.usecompiled: if __debug__: # Python is running without -O. return "__init__.pyc" in fnamelist else: # Python is running with -O. return "__init__.pyo" in fnamelist return False def import_name(name): __import__(name) return sys.modules[name] def tests_from_suite(suite, options, dlevel=1, dlayer=zope.testrunner.layer.UnitTests, accept=None, seen_test_ids=None, duplicated_test_ids=None): """Returns a sequence of (test, layer_name) The tree of suites is recursively visited, with the most specific layer taking precedence. So if a TestCase with a layer of 'foo' is contained in a TestSuite with a layer of 'bar', the test case would be returned with 'foo' as the layer. Tests are also filtered out based on the test level and accept predicate. accept is a function, returning boolean for given test name (see also build_filtering_func()). """ # We use this to track the test IDs that have been registered. # tests_from_suite will complain if it encounters the same test ID # twice. if seen_test_ids is None: seen_test_ids = set() if duplicated_test_ids is None: duplicated_test_ids = set() level = getattr(suite, 'level', dlevel) layer = getattr(suite, 'layer', dlayer) if not isinstance(layer, str): layer = name_from_layer(layer) if isinstance(suite, unittest.TestSuite): for possible_suite in suite: yield from tests_from_suite( possible_suite, options, level, layer, accept=accept, seen_test_ids=seen_test_ids, duplicated_test_ids=duplicated_test_ids) elif isinstance(suite, StartUpFailure): yield (suite, None) else: if options.require_unique_ids: suite_id = str(suite) if suite_id in seen_test_ids: duplicated_test_ids.add(suite_id) else: seen_test_ids.add(suite_id) if options.at_level <= 0 or level <= options.at_level: if accept is None or accept(str(suite)): yield (suite, layer) _layer_name_cache = {} def name_from_layer(layer): """Determine a name for the Layer using the namespace to avoid conflicts. We also cache a name -> layer mapping to enable layer_from_name to work in cases where the layer cannot be imported (such as layers defined in doctests) """ if layer.__module__ == '__builtin__': name = layer.__name__ else: name = layer.__module__ + '.' + layer.__name__ _layer_name_cache[name] = layer return name class Find(zope.testrunner.feature.Feature): """Finds tests and registers them with the test runner.""" active = True def global_setup(self): # Add directories to the path for path in reversed(self.runner.options.path): if path not in sys.path: sys.path.insert(0, path) tests = find_tests(self.runner.options, self.runner.found_suites) self.import_errors = tests.pop(None, None) self.runner.register_tests(tests) # XXX move to reporting ??? self.runner.options.output.import_errors(self.import_errors) self.runner.import_errors = list(self.import_errors or []) def report(self): self.runner.options.output.modules_with_import_problems( self.import_errors)
zope.testrunner
/zope.testrunner-6.1.tar.gz/zope.testrunner-6.1/src/zope/testrunner/find.py
find.py
import os.path import sys import threading import trace import zope.testrunner.feature from zope.testrunner.find import test_dirs # For some reason, the doctest module resets the trace callable randomly, thus # disabling the coverage. Simply disallow the code from doing this. A real # trace can be set, so that debugging still works. osettrace = sys.settrace def settrace(trace): if trace is None: # pragma: no cover return osettrace(trace) class TestTrace(trace.Trace): """Simple tracer. >>> tracer = TestTrace([], count=False, trace=False) Simple rules for use: you can't stop the tracer if it not started and you can't start the tracer if it already started: >>> tracer.stop() Traceback (most recent call last): File 'testrunner.py' AssertionError: can't stop if not started >>> tracer.start() >>> tracer.start() Traceback (most recent call last): File 'testrunner.py' AssertionError: can't start if already started >>> tracer.stop() >>> tracer.stop() Traceback (most recent call last): File 'testrunner.py' AssertionError: can't stop if not started """ def __init__(self, directories, **kw): trace.Trace.__init__(self, **kw) self.ignore = TestIgnore(directories) self.started = False def start(self): assert not self.started, "can't start if already started" if not self.donothing: sys.settrace = settrace sys.settrace(self.globaltrace) threading.settrace(self.globaltrace) self.started = True def stop(self): assert self.started, "can't stop if not started" if not self.donothing: sys.settrace = osettrace sys.settrace(None) threading.settrace(None) self.started = False class TestIgnore: def __init__(self, directories): self._test_dirs = [self._filenameFormat(d[0]) + os.path.sep for d in directories] self._ignore = {} self._ignored = self._ignore.get def names(self, filename, modulename): # Special case: Modules generated from text files; i.e. doctests if modulename == '<string>': return True filename = self._filenameFormat(filename) ignore = self._ignored(filename) if ignore is None: ignore = True if filename is not None: for d in self._test_dirs: if filename.startswith(d): ignore = False break self._ignore[filename] = ignore return ignore def _filenameFormat(self, filename): return os.path.abspath(filename) if sys.platform == 'win32': # on win32 drive name can be passed with different case to `names` # that lets e.g. the coverage profiler skip complete files # _filenameFormat will make sure that all drive and filenames get # lowercased albeit trace coverage has still problems with lowercase # drive letters when determining the dotted module name OldTestIgnore = TestIgnore class TestIgnore(OldTestIgnore): def _filenameFormat(self, filename): return os.path.normcase(os.path.abspath(filename)) class Coverage(zope.testrunner.feature.Feature): tracer = None directory = None def __init__(self, runner): super().__init__(runner) self.active = bool(runner.options.coverage) def global_setup(self): """Executed once when the test runner is being set up.""" self.directory = os.path.join( os.getcwd(), self.runner.options.coverage) # FIXME: This shouldn't rely on the find feature directly. self.tracer = TestTrace(test_dirs(self.runner.options, {}), trace=False, count=True) self.tracer.start() def early_teardown(self): """Executed once directly after all tests.""" self.tracer.stop() def report(self): """Executed once after all tests have been run and all setup was torn down.""" r = self.tracer.results() r.write_results(summary=True, coverdir=self.directory)
zope.testrunner
/zope.testrunner-6.1.tar.gz/zope.testrunner-6.1/src/zope/testrunner/coverage.py
coverage.py
from itertools import count class DiGraph: """Directed graph. A directed graph is a set of nodes together with a neighboring relation. The class makes intensive use of dicts; therefore, hashability is important. Therefore, the class usually does not work with the nodes directly but transforms them via a ``make_hashable`` function, ``id`` by default. This works well for object types where equality is identity. For other types, you may need to deactive the transformation or use a different ``make_hashable``. """ def __init__(self, nodes=None, make_hashable=id): self._nodes = set() # transformed nodes self._neighbors = {} # node --> neighbors -- transformed if make_hashable: tr2n = {} # transform -> node tr_node = make_hashable def utr_node(node): return tr2n[node] def tr_nodes(nodes): ns = set() add = ns.add for n in nodes: trn = make_hashable(n) if trn not in tr2n: tr2n[trn] = n add(trn) return ns else: tr_nodes = lambda nodes: set(nodes) # noqa: E731 utr_node = tr_node = lambda node: node self._transform_node = tr_node self._transform_nodes = tr_nodes self._untransform_node = utr_node if nodes is not None: self.add_nodes(nodes) def add_nodes(self, nodes): """add *nodes* (iterator) to the graph's nodes.""" self._nodes |= self._transform_nodes(nodes) def add_neighbors(self, node, neighbors, ignore_unknown=True): """add *neighbors* (iterator) as neighbors for *node*. if *ignore_unknown*, unknown nodes in *neighbors* are ignored, otherwise a ``KeyError`` is raised. """ tr_n = self._transform_node(node) nodes = self._nodes nbad = tr_n not in nodes if nbad: if ignore_unknown: return else: raise KeyError(node) tr_neighbors = self._transform_nodes(neighbors) known_neighbors = tr_neighbors & nodes if not ignore_unknown and len(known_neighbors) != len(tr_neighbors): raise KeyError(tr_neighbors - known_neighbors) nbs = self._neighbors.get(tr_n) if nbs is None: self._neighbors[tr_n] = known_neighbors else: nbs |= known_neighbors def nodes(self): """iterate of the graph's nodes.""" utr = self._untransform_node for n in self._nodes: yield utr(n) def neighbors(self, node): """iterate over *node*'s neighbors.""" utr = self._untransform_node for n in self._neighbors.get(self._transform_node(node), ()): yield utr(n) def sccs(self, trivial=False): """iteratate over the strongly connected components. If *trivial*, include the trivial components; otherwise only the cycles. This is an implementation of the "Tarjan SCC" algorithm. """ # any node is either in ``unvisited`` or in ``state`` unvisited = self._nodes.copy() state = {} # nodes -> state ancestors = [] # the ancestors of the currently processed node stack = [] # the nodes which might still be on a cycle # the algorithm visits each node twice in a depth first order # In the first visit, visits for the unprocessed neighbors # are scheduled as well as the second visit to this # node after all neighbors have been processed. dfs = count() # depth first search visit order rtn_marker = object() # marks second visit to ``ancestor`` top visits = [] # scheduled visits while unvisited: node = next(iter(unvisited)) # determine the depth first spanning tree rooted in *node* visits.append(node) while visits: visit = visits[-1] # ``rtn_marker`` or node if visit is rtn_marker: # returned to the top of ``ancestors`` visits.pop() node = ancestors.pop() # returned to *node* nstate = state[node] if nstate.low == nstate.dfs: # SCC root scc = [] while True: n = stack.pop() state[n].stacked = False scc.append(n) if n is node: break if len(scc) == 1 and not trivial: # check for triviality n = scc[0] if n not in self._neighbors[n]: continue # tivial -- ignore utr = self._untransform_node yield [utr(n) for n in scc] if not ancestors: # dfs tree determined assert not visits break pstate = state[ancestors[-1]] nstate = state[node] low = nstate.low if low < pstate.low: pstate.low = low else: # scheduled first visit node = visit nstate = state.get(node) if nstate is not None: # we have already been visited if nstate.stacked: # update parent pstate = state[ancestors[-1]] if nstate.dfs < pstate.low: pstate.low = nstate.dfs visits.pop() continue unvisited.remove(node) nstate = state[node] = _TarjanState(dfs) ancestors.append(node) stack.append(node) nstate.stacked = True visits[-1] = rtn_marker # schedule return visit # schedule neighbor visits visits.extend(self._neighbors.get(node, ())) class _TarjanState: """representation of a node's processing state.""" __slots__ = "stacked dfs low".split() def __init__(self, dfs): self.stacked = False self.dfs = self.low = next(dfs) def __repr__(self): return "dfs=%d low=%d stacked=%s" \ % (self.dfs, self.low, self.stacked)
zope.testrunner
/zope.testrunner-6.1.tar.gz/zope.testrunner-6.1/src/zope/testrunner/digraph.py
digraph.py
import os import sys def run(defaults=None, args=None, script_parts=None, cwd=None, warnings=None): """Main runner function which can be and is being used from main programs. Will execute the tests and exit the process according to the test result. .. versionchanged:: 4.8.0 Add the *warnings* keyword argument. See :class:`zope.testrunner.runner.Runner` """ failed = run_internal(defaults, args, script_parts=script_parts, cwd=cwd, warnings=warnings) sys.exit(int(failed)) def run_internal(defaults=None, args=None, script_parts=None, cwd=None, warnings=None): """Execute tests. Returns whether errors or failures occured during testing. .. versionchanged:: 4.8.0 Add the *warnings* keyword argument. See :class:`zope.testrunner.runner.Runner` """ if script_parts is None: script_parts = _script_parts(args) if cwd is None: cwd = os.getcwd() # XXX Bah. Lazy import to avoid circular/early import problems from zope.testrunner.runner import Runner runner = Runner( defaults, args, script_parts=script_parts, cwd=cwd, warnings=warnings) runner.run() return runner.failed def _script_parts(args=None): script_parts = (args or sys.argv)[0:1] # If we are running via setup.py, then we'll have to run the # sub-process differently. if script_parts[0] == 'setup.py': script_parts = ['-c', 'from zope.testrunner import run; run()'] else: # make sure we remember the absolute path early -- the tests might # do an os.chdir() script_parts[0] = os.path.abspath(script_parts[0]) if not os.path.exists(script_parts[0]): # uhh, no wrapper script? this happens on Windows sometimes, # where there are like three wrapper scripts with various suffixes, # and I don't want to go looking up what they might be. script_parts = ['-m', 'zope.testrunner'] return script_parts if __name__ == '__main__': # this used to allow people to try out the test runner with # python -m zope.testrunner --test-path . # on Python 2.5. This broke on 2.6, and 2.7 and newer use __main__.py # for that. But there are some users out there who actually use # python -e zope.testrunner.__init__ --test-path . # so let's keep this for BBB run()
zope.testrunner
/zope.testrunner-6.1.tar.gz/zope.testrunner-6.1/src/zope/testrunner/__init__.py
__init__.py
"""Profiler support for the test runner """ import cProfile import glob import os import pstats import tempfile import zope.testrunner.feature available_profilers = {} class CProfiler: """cProfiler""" def __init__(self, filepath): self.filepath = filepath self.profiler = cProfile.Profile() self.enable = self.profiler.enable self.disable = self.profiler.disable def finish(self): self.profiler.dump_stats(self.filepath) def loadStats(self, prof_glob): stats = None for file_name in glob.glob(prof_glob): if stats is None: stats = pstats.Stats(file_name) else: stats.add(file_name) return stats available_profilers['cProfile'] = CProfiler class Profiling(zope.testrunner.feature.Feature): def __init__(self, runner): super().__init__(runner) self.active = bool(self.runner.options.profile) self.profiler = self.runner.options.profile def global_setup(self): self.prof_prefix = 'tests_profile.' self.prof_suffix = '.prof' self.prof_glob = os.path.join( self.runner.options.prof_dir, self.prof_prefix + '*' + self.prof_suffix) # if we are going to be profiling, and this isn't a subprocess, # clean up any stale results files if not self.runner.options.resume_layer: for file_name in glob.glob(self.prof_glob): os.unlink(file_name) # set up the output file self.oshandle, self.file_path = tempfile.mkstemp( self.prof_suffix, self.prof_prefix, self.runner.options.prof_dir) self.profiler = available_profilers[self.runner.options.profile]( self.file_path) # Need to do this rebinding to support the stack-frame annoyance with # hotshot. self.late_setup = self.profiler.enable self.early_teardown = self.profiler.disable def global_teardown(self): self.profiler.finish() # We must explicitly close the handle mkstemp returned, else on # Windows this dies the next time around just above due to an # attempt to unlink a still-open file. os.close(self.oshandle) if not self.runner.options.resume_layer: self.profiler_stats = self.profiler.loadStats(self.prof_glob) self.profiler_stats.sort_stats('cumulative', 'calls') def report(self): if not self.runner.options.resume_layer: self.runner.options.output.profiler_stats(self.profiler_stats)
zope.testrunner
/zope.testrunner-6.1.tar.gz/zope.testrunner-6.1/src/zope/testrunner/profiling.py
profiling.py
import math import random import time import zope.testrunner.feature class Shuffle(zope.testrunner.feature.Feature): """Take the tests found so far and shuffle them.""" def __init__(self, runner): super().__init__(runner) self.active = runner.options.shuffle self.seed = runner.options.shuffle_seed if self.seed is None: # We can't rely on the random modules seed initialization because # we can't introspect the seed later for reporting. This is a # simple emulation of what random.Random.seed does anyway. self.seed = int(time.time() * 256) # use fractional seconds def global_setup(self): rng = random.Random(self.seed) # in case somebody tries to use a string as the seed rng.seed(self.seed, version=1) # Be careful to shuffle the layers in a deterministic order! for layer, suite in sorted(self.runner.tests_by_layer_name.items()): # Test suites cannot be modified through a public API. We thus # take a mutable copy of the list of tests of that suite, shuffle # that and replace the test suite instance with a new one of the # same class. tests = list(suite) # The standard library guarantees rng.random() will return the # same floats if given the same seed. It makes no guarantees # for rng.randrange, or rng.choice, or rng.shuffle. Experiments # show that Python happily breaks backwards compatibility for # these functions. We used to use `rng.shuffle(tests, # random=rng.random)` to trick it into using the old algorithm, # but even this was deprecated in Python 3.9 and removed in # 3.11. Accordingly, inline equivalent code which we know is # stable across Python versions. floor = math.floor for i in reversed(range(1, len(tests))): # Pick an element in tests[:i+1] with which to exchange # tests[i]. j = floor(rng.random() * (i + 1)) tests[i], tests[j] = tests[j], tests[i] self.runner.tests_by_layer_name[layer] = suite.__class__(tests) def report(self): msg = "Tests were shuffled using seed number %d." % self.seed self.runner.options.output.info(msg)
zope.testrunner
/zope.testrunner-6.1.tar.gz/zope.testrunner-6.1/src/zope/testrunner/shuffle.py
shuffle.py
import argparse import os import re import sys import pkg_resources from zope.testrunner.formatter import ColorfulOutputFormatter from zope.testrunner.formatter import OutputFormatter from zope.testrunner.formatter import SubunitOutputFormatter from zope.testrunner.formatter import SubunitV2OutputFormatter from zope.testrunner.formatter import terminal_has_colors from zope.testrunner.profiling import available_profilers from .util import uses_refcounts def _regex_search(s): return re.compile(s).search parser = argparse.ArgumentParser( description="Discover and run unittest tests") parser.add_argument("legacy_module_filter", nargs="?", help="DEPRECATED: Prefer to use --module.") parser.add_argument("legacy_test_filter", nargs="?", help="DEPRECATED: Prefer to use --test.") ###################################################################### # Searching and filtering searching = parser.add_argument_group("Searching and filtering", """\ Options in this group are used to define which tests to run. """) searching.add_argument( '--package', '--dir', '-s', action="append", dest='package', help="""\ Search the given package's directories for tests. This can be specified more than once to run tests in multiple parts of the source tree. For example, if refactoring interfaces, you don't want to see the way you have broken setups for tests in other packages. You *just* want to run the interface tests. Packages are supplied as dotted names. For compatibility with the old test runner, forward and backward slashed in package names are converted to dots. (In the special case of packages spread over multiple directories, only directories within the test search path are searched. See the --path option.) """) searching.add_argument( '--module', '-m', action="append", dest='module', help="""\ Specify a test-module filter as a regular expression. This is a case-sensitive regular expression, used in search (not match) mode, to limit which test modules are searched for tests. The regular expressions are checked against dotted module names. In an extension of Python regexp notation, a leading "!" is stripped and causes the sense of the remaining regexp to be negated (so "!bc" matches any string that does not match "bc", and vice versa). The option can be specified multiple test-module filters. Test modules matching any of the test filters are searched. If no test-module filter is specified, then all test modules are used. """) searching.add_argument( '--test', '-t', action="append", dest='test', help="""\ Specify a test filter as a regular expression. This is a case-sensitive regular expression, used in search (not match) mode, to limit which tests are run. In an extension of Python regexp notation, a leading "!" is stripped and causes the sense of the remaining regexp to be negated (so "!bc" matches any string that does not match "bc", and vice versa). The option can be specified multiple test filters. Tests matching any of the test filters are included. If no test filter is specified, then all tests are run. """) searching.add_argument( '--unit', '-u', action="store_true", dest='unit', help="""\ Run only unit tests, ignoring any layer options. """) searching.add_argument( '--non-unit', '-f', action="store_true", dest='non_unit', help="""\ Run tests other than unit tests. """) searching.add_argument( '--layer', action="append", dest='layer', help="""\ Specify a test layer to run. The option can be given multiple times to specify more than one layer. If not specified, all layers are run. It is common for the running script to provide default values for this option. Layers are specified regular expressions, used in search mode, for dotted names of objects that define a layer. In an extension of Python regexp notation, a leading "!" is stripped and causes the sense of the remaining regexp to be negated (so "!bc" matches any string that does not match "bc", and vice versa). The layer named 'zope.testrunner.layer.UnitTests' is reserved for unit tests, however, take note of the --unit and non-unit options. """) searching.add_argument( '-a', '--at-level', type=int, dest='at_level', default=1, help="""\ Run the tests at the given level. Any test at a level at or below this is run, any test at a level above this is not run. Level <= 0 runs all tests. """) searching.add_argument( '--all', action="store_true", dest='all', help="Run tests at all levels.") searching.add_argument( '--list-tests', action="store_true", dest='list_tests', default=False, help="List all tests that matched your filters. Do not run any tests.") searching.add_argument( '--require-unique', action="store_true", dest='require_unique_ids', default=False, help="""\ Require that all test IDs be unique and raise an error if duplicates are encountered. """) ###################################################################### # Reporting reporting = parser.add_argument_group("Reporting", """\ Reporting options control basic aspects of test-runner output """) reporting.add_argument( '--verbose', '-v', action="count", dest='verbose', default=0, help="""\ Make output more verbose. Increment the verbosity level. """) reporting.add_argument( '--quiet', '-q', action="store_true", dest='quiet', help="""\ Make the output minimal, overriding any verbosity options. """) reporting.add_argument( '--progress', '-p', action="store_true", dest='progress', help="""\ Output progress status """) reporting.add_argument( '--no-progress', action="store_false", dest='progress', help="""\ Do not output progress status. This is the default, but can be used to counter a previous use of --progress or -p. """) # The actual processing will be done in the get_options function, but # we want argparse to generate appropriate help info for us, so we add # an option anyway. reporting.add_argument( '--auto-progress', action="store_const", const=None, help="""\ Output progress status, but only when stdout is a terminal. """) reporting.add_argument( '--color', '-c', action="store_true", dest='color', help="""\ Colorize the output. """) reporting.add_argument( '--no-color', '-C', action="store_false", dest='color', help="""\ Do not colorize the output. This is the default, but can be used to counter a previous use of --color or -c. """) # The actual processing will be done in the get_options function, but # we want argparse to generate appropriate help info for us, so we add # an option anyway. reporting.add_argument( '--auto-color', action="store_const", const=None, help="""\ Colorize the output, but only when stdout is a terminal. """) reporting.add_argument( '--subunit', action="store_true", dest='subunit', help="""\ Use subunit v1 output. Will not be colorized. """) reporting.add_argument( '--subunit-v2', action="store_true", dest='subunit_v2', help="""\ Use subunit v2 output. Will not be colorized. """) reporting.add_argument( '--slow-test', type=float, dest='slow_test_threshold', metavar='N', default=10, help="""\ With -c and -vvv, highlight tests that take longer than N seconds (default: %(default)s). """) reporting.add_argument( '-1', '--hide-secondary-failures', action="store_true", dest='report_only_first_failure', help="""\ Report only the first failure in a doctest. (Examples after the failure are still executed, in case they do any cleanup.) """) reporting.add_argument( '--show-secondary-failures', action="store_false", dest='report_only_first_failure', help="""\ Report all failures in a doctest. This is the default, but can be used to counter a default use of -1 or --hide-secondary-failures. """) reporting.add_argument( '--ndiff', action="store_true", dest="ndiff", help="""\ When there is a doctest failure, show it as a diff using the ndiff.py utility. """) reporting.add_argument( '--udiff', action="store_true", dest="udiff", help="""\ When there is a doctest failure, show it as a unified diff. """) reporting.add_argument( '--cdiff', action="store_true", dest="cdiff", help="""\ When there is a doctest failure, show it as a context diff. """) reporting.add_argument( '--ignore-new-thread', metavar='REGEXP', action="append", default=[], dest='ignore_new_threads', help="""\ If a thread with this name is left behind, don't report this at the end. This is a case-sensitive regular expression, used in match mode. This option can be used multiple times. If a thread name matches any of them, it will be ignored. """) reporting.add_argument( '--buffer', action="store_true", dest="buffer", help="""\ Buffer the standard output and standard error streams during each test. Output during a passing test is discarded. Output during failing or erroring tests is echoed. This option is enabled by default if --subunit or --subunit-v2 is in use, to avoid corrupting the subunit stream. """) ###################################################################### # Analysis analysis = parser.add_argument_group("Analysis", """\ Analysis options provide tools for analysing test output. """) analysis.add_argument( '--stop-on-error', '--stop', '-x', action="store_true", dest='stop_on_error', help="Stop running tests after first test failure or error." ) analysis.add_argument( '--post-mortem', '--pdb', '-D', action="store_true", dest='post_mortem', help="Enable post-mortem debugging of test failures" ) analysis.add_argument( '--gc', '-g', action="append", dest='gc', type=int, help="""\ Set the garbage collector generation threshold. This can be used to stress memory and gc correctness. Some crashes are only reproducible when the threshold is set to 1 (aggressive garbage collection). Do "--gc 0" to disable garbage collection altogether. The --gc option can be used up to 3 times to specify up to 3 of the 3 Python gc_threshold settings. """) analysis.add_argument( '--gc-option', '-G', action="append", dest='gc_option', choices={'DEBUG_STATS', 'DEBUG_COLLECTABLE', 'DEBUG_UNCOLLECTABLE', 'DEBUG_INSTANCES', 'DEBUG_OBJECTS', 'DEBUG_SAVEALL', 'DEBUG_LEAK'}, help="""\ Set a Python gc-module debug flag. This option can be used more than once to set multiple flags. """) if uses_refcounts: analysis.add_argument( '--gc-after-test', action="store_true", dest='gc_after_test', help="""\ After each test, call 'gc.collect' and record the return value *rv*; when *rv* is non-zero, output '!' on verbosity level 1 and '[*rv*]' on higher verbosity levels.\n On verbosity level 4 or higher output detailed cycle information. """) analysis.add_argument( '--repeat', '-N', action="store", type=int, dest='repeat', default=1, help="""\ Repeat the tests the given number of times. This option is used to make sure that tests leave their environment in the state they found it and, with the --report-refcounts option to look for memory leaks. """) analysis.add_argument( '--report-refcounts', '-r', action="store_true", dest='report_refcounts', help="""\ After each run of the tests, output a report summarizing changes in refcounts by object type. This option that requires that Python was built with the --with-pydebug option to configure. """) analysis.add_argument( '--coverage', action="store", dest='coverage', help="""\ Perform code-coverage analysis, saving trace data to the directory with the given name. A code coverage summary is printed to standard out. """) analysis.add_argument( '--profile', action="store", dest='profile', choices=set(available_profilers), help="""\ Run the tests under cProfiler and display the top 50 stats, sorted by cumulative time and number of calls. """) analysis.add_argument( '--profile-directory', action="store", dest='prof_dir', default='.', help="""\ Directory for temporary profiler files. All files named tests_profile.*.prof in this directory will be removed. If you intend to run multiple instances of the test runner in parallel, be sure to tell them to use different directories, so they won't step on each other's toes. """) ###################################################################### # Setup setup = parser.add_argument_group("Setup", """\ Setup options are normally supplied by the testrunner script, although they can be overridden by users. """) setup.add_argument( '--path', action="append", dest='path', type=os.path.abspath, help="""\ Specify a path to be added to Python's search path. This option can be used multiple times to specify multiple search paths. The path is usually specified by the test-runner script itself, rather than by users of the script, although it can be overridden by users. Only tests found in the path will be run. This option also specifies directories to be searched for tests. See the search_directory. """) setup.add_argument( '--test-path', action="append", dest='test_path', type=os.path.abspath, help="""\ Specify a path to be searched for tests, but not added to the Python search path. This option can be used multiple times to specify multiple search paths. The path is usually specified by the test-runner script itself, rather than by users of the script, although it can be overridden by users. Only tests found in the path will be run. """) setup.add_argument( '--package-path', action="append", dest='package_path', nargs=2, metavar="ARG", help="""\ Specify a path to be searched for tests, but not added to the Python search path. Also specify a package for files found in this path. This is used to deal with directories that are stitched into packages that are not otherwise searched for tests. This option takes 2 arguments specifying the path and the package. This option can be used multiple times to specify multiple search paths. The path is usually specified by the test-runner script itself, rather than by users of the script, although it can be overridden by users. Only tests found in the path will be run. """) setup.add_argument( '--tests-pattern', action="store", dest='tests_pattern', default=_regex_search('^tests$'), type=_regex_search, help="""\ The test runner looks for modules containing tests. It uses this pattern to identify these modules. The modules may be either packages or python files. If a test module is a package, it uses the value given by the test-file-pattern to identify python files within the package containing tests. """) setup.add_argument( '--suite-name', action="store", dest='suite_name', default='test_suite', help="""\ Specify the name of the object in each test_module that contains the module's test suite. """) setup.add_argument( '--test-file-pattern', action="store", dest='test_file_pattern', default=_regex_search('^test'), type=_regex_search, help="""\ Specify a pattern for identifying python files within a tests package. See the documentation for the --tests-pattern option. """) setup.add_argument( '--ignore_dir', action="append", dest='ignore_dir', default=['.git', '.svn', 'CVS', '{arch}', '.arch-ids', '_darcs'], help="""\ Specifies the name of a directory to ignore when looking for tests. """) setup.add_argument( '--shuffle', action="store_true", dest='shuffle', help="""\ Shuffles the order in which tests are ran. """) setup.add_argument( '--shuffle-seed', action="store", dest='shuffle_seed', type=int, help="""\ Value used to initialize the tests shuffler. Specify a value to create repeatable random ordered tests. """) ###################################################################### # Other other = parser.add_argument_group("Other", "Other options") other.add_argument( '--version', action="store_true", dest='showversion', help="Print the version of the testrunner, and exit.") other.add_argument( '-j', action="store", type=int, dest='processes', default=1, help="""\ Use up to given number of parallel processes to execute tests. May decrease test run time substantially. Defaults to %(default)s. """) other.add_argument( '--keepbytecode', '-k', action="store_true", dest='keepbytecode', help="""\ Normally, the test runner scans the test paths and the test directories looking for and deleting pyc or pyo files without corresponding py files. This is to prevent spurious test failures due to finding compiled modules where source modules have been deleted. This scan can be time consuming. Using this option disables this scan. If you know you haven't removed any modules since last running the tests, can make the test run go much faster. """) other.add_argument( '--usecompiled', action="store_true", dest='usecompiled', help="""\ Normally, a package must contain an __init__.py file, and only .py files can contain test code. When this option is specified, compiled Python files (.pyc and .pyo) can be used instead: a directory containing __init__.pyc or __init__.pyo is also considered to be a package, and if file XYZ.py contains tests but is absent while XYZ.pyc or XYZ.pyo exists then the compiled files will be used. This is necessary when running tests against a tree where the .py files have been removed after compilation to .pyc/.pyo. Use of this option implies --keepbytecode. """) other.add_argument( '--exit-with-status', action="store_true", dest='exitwithstatus', help="""DEPRECATED: The test runner will always exit with a status.\ """) ###################################################################### # Command-line processing def merge_options(options, defaults): odict = options.__dict__ for name, value in defaults.__dict__.items(): if (value is not None) and (odict[name] is None): odict[name] = value def get_options(args=None, defaults=None): # Because we want to inspect stdout and decide to colorize or not, we # replace the --auto-color option with the appropriate --color or # --no-color option. That way the subprocess doesn't have to decide (which # it would do incorrectly anyway because stdout would be a pipe). def apply_auto_color(args): if args and '--auto-color' in args: if sys.stdout.isatty() and terminal_has_colors(): colorization = '--color' else: colorization = '--no-color' args[:] = [arg.replace('--auto-color', colorization) for arg in args] # The comment of apply_auto_color applies here as well def apply_auto_progress(args): if args and '--auto-progress' in args: if sys.stdout.isatty(): progress = '--progress' else: progress = '--no-progress' args[:] = [arg.replace('--auto-progress', progress) for arg in args] apply_auto_color(args) apply_auto_color(defaults) apply_auto_progress(args) apply_auto_progress(defaults) if defaults: defaults = parser.parse_args(defaults) else: defaults = None if args is None: args = sys.argv options = parser.parse_args(args[1:], defaults) options.original_testrunner_args = args if options.showversion: dist = pkg_resources.require('zope.testrunner')[0] print('zope.testrunner version %s' % dist.version) options.fail = True return options if options.subunit or options.subunit_v2: try: import subunit subunit except ImportError: print("""\ Subunit is not installed. Please install Subunit to generate subunit output. """) options.fail = True return options options.buffer = True if options.subunit and options.subunit_v2: print("""\ You may only use one of --subunit and --subunit-v2. """) options.fail = True return options if options.subunit: options.output = SubunitOutputFormatter(options) elif options.subunit_v2: options.output = SubunitV2OutputFormatter(options) elif options.color: options.output = ColorfulOutputFormatter(options) options.output.slow_test_threshold = options.slow_test_threshold else: options.output = OutputFormatter(options) options.fail = False if options.legacy_module_filter: module_filter = options.legacy_module_filter if module_filter != '.': if options.module: options.module.append(module_filter) else: options.module = [module_filter] if options.legacy_test_filter: test_filter = options.legacy_test_filter if options.test: options.test.append(test_filter) else: options.test = [test_filter] options.ignore_dir = set(options.ignore_dir) options.test = options.test or ['.'] module_set = bool(options.module) options.module = options.module or ['.'] options.path = options.path or [] options.test_path = options.test_path or [] options.test_path += options.path options.test_path = ([(path, '') for path in options.test_path] + [(os.path.abspath(path), package) for (path, package) in options.package_path or () ]) if options.package: pkgmap = dict(options.test_path) options.package = [normalize_package(p, pkgmap) for p in options.package] options.prefix = [(path + os.path.sep, package) for (path, package) in options.test_path] # Sort prefixes so that longest prefixes come first. # That is because only first match is evaluated which # can be a problem with nested source packages. options.prefix.sort(key=lambda p: len(p[0]), reverse=True) if options.all: options.at_level = sys.maxsize if options.unit and options.non_unit: # The test runner interprets this as "run only those tests that are # both unit and non-unit at the same time". The user, however, wants # to run both unit and non-unit tests. Disable the filtering so that # the user will get what she wants: options.unit = options.non_unit = False if options.unit: # XXX Argh. options.layer = ['zope.testrunner.layer.UnitTests'] options.layer = options.layer and {layer: 1 for layer in options.layer} if options.usecompiled: options.keepbytecode = options.usecompiled if options.quiet: options.verbose = 0 if options.report_refcounts and options.repeat < 2: print("""\ You must use the --repeat (-N) option to specify a repeat count greater than 1 when using the --report_refcounts (-r) option. """) options.fail = True return options if options.report_refcounts and not hasattr(sys, "gettotalrefcount"): print("""\ The Python you are running was not configured with --with-pydebug. This is required to use the --report-refcounts option. """) options.fail = True return options if module_set and options.require_unique_ids: # We warn if --module and --require-unique are specified at the same # time, though we don't exit. print("""\ You specified a module along with --require-unique; --require-unique will not try to enforce test ID uniqueness when working with a specific module. """) return options def normalize_package(package, package_map=None): r"""Normalize package name passed to the --package option. >>> normalize_package('zope.testrunner') 'zope.testrunner' Converts path names into package names for compatibility with the old test runner. >>> normalize_package('zope/testrunner') 'zope.testrunner' >>> normalize_package('zope/testrunner/') 'zope.testrunner' >>> normalize_package('zope\\testrunner') 'zope.testrunner' Can use a map of absolute pathnames to package names >>> a = os.path.abspath >>> normalize_package('src/zope/testrunner/', ... {a('src'): ''}) 'zope.testrunner' >>> normalize_package('src/zope_testrunner/', ... {a('src/zope_testrunner'): 'zope.testrunner'}) 'zope.testrunner' >>> normalize_package('src/zope_something/tests', ... {a('src/zope_something'): 'zope.something', ... a('src'): ''}) 'zope.something.tests' """ package_map = {} if package_map is None else package_map package = package.replace('\\', '/') if package.endswith('/'): package = package[:-1] bits = package.split('/') for n in range(len(bits), 0, -1): pkg = package_map.get(os.path.abspath('/'.join(bits[:n]))) if pkg is not None: bits = bits[n:] if pkg: bits = [pkg] + bits return '.'.join(bits) return package.replace('/', '.')
zope.testrunner
/zope.testrunner-6.1.tar.gz/zope.testrunner-6.1/src/zope/testrunner/options.py
options.py
======================= Using zope.testrunner ======================= .. IMPORTANT: This document is included in the long_description for rendering on PyPI, so it cannot use Sphinx-only features. Installation ============ Buildout-based projects ----------------------- zope.testrunner is often used for projects that use buildout_:: [buildout] develop = . parts = ... test ... [test] recipe = zc.recipe.testrunner eggs = mypackage The usual buildout process :: python bootstrap.py bin/buildout creates a ``bin/test`` script that will run the tests for *mypackage*. .. tip:: zc.recipe.testrunner_ takes care to specify the right ``--test-path`` option in the generated script. You can add other options (such as ``--tests-pattern``) too; check zc.recipe.testrunner_'s documentation for details. Virtualenv-based projects ------------------------- ``pip install zope.testrunner`` and you'll get a ``zope-testrunner`` script. Run your tests with :: zope-testrunner --test-path=path/to/your/source/tree Your source code needs to be available for the testrunner to import, so you need to run ``python setup.py install`` or ``pip install -e .`` into the same virtualenv_. Some useful command-line options to get you started =================================================== -p show a progress indicator -v increase verbosity -c colorize the output -t test specify test names (one or more regexes) -m module specify test modules (one or more regexes) -s package specify test packages (one or more regexes) --list-tests show names of tests instead of running them -x stop on first error or failure -D, --pdb enable post-mortem debugging of test failures --help show *all* command-line options (there are many more!) For example :: bin/test -pvc -m test_foo -t TestBar runs all TestBar tests from a module called test_foo.py. Writing tests ============= ``zope.testrunner`` expects to find your tests inside your package directory, in a subpackage or module named ``tests``. Test modules in a test subpackage should be named ``test*.py``. .. tip:: You can change these assumptions with ``--tests-pattern`` and ``--test-file-pattern`` test runner options. Tests themselves should be classes inheriting from ``unittest.TestCase``, and if you wish to use doctests, please tell the test runner where to find them and what options to use for them in by supplying a function named ``test_suite``. Example:: import unittest import doctest class TestArithmetic(unittest.TestCase): def test_two_plus_two(self): self.assertEqual(2 + 2, 4) def doctest_string_formatting(): """Test Python string formatting >>> print('{} + {}'.format(2, 2)) 2 + 2 """ def test_suite(): return unittest.TestSuite([ unittest.defaultTestLoader.loadTestsFromName(__name__), doctest.DocTestSuite(), doctest.DocFileSuite('../README.txt', optionflags=doctest.ELLIPSIS), ]) Test grouping ============= In addition to per-package and per-module filtering, zope.testrunner has other mechanisms for grouping tests: * **layers** allow you to have shared setup/teardown code to be used by a group of tests, that is executed only once, and not for each test. Layers are orthogonal to the usual package/module structure and are specified by setting the ``layer`` attribute on test suites. * **levels** allow you to group slow-running tests and not run them by default. They're specified by setting the ``level`` attribute on test suites to an int. Other features ============== zope.testrunner can profile your tests, measure test coverage, check for memory leaks, integrate with subunit_, shuffle the test execution order, and run multiple tests in parallel. .. _buildout: https://buildout.readthedocs.io .. _virtualenv: https://virtualenv.pypa.io/ .. _zc.recipe.testrunner: https://pypi.python.org/pypi/zc.recipe.testrunner .. _subunit: https://pypi.python.org/pypi/python-subunit
zope.testrunner
/zope.testrunner-6.1.tar.gz/zope.testrunner-6.1/docs/getting-started.rst
getting-started.rst
======================================== zope.testrunner Detailed Documentation ======================================== .. image:: https://img.shields.io/pypi/v/zope.testrunner.svg :target: https://pypi.python.org/pypi/zope.testrunner/ :alt: Latest release .. image:: https://img.shields.io/pypi/pyversions/zope.testrunner.svg :target: https://pypi.org/project/zope.testrunner/ :alt: Supported Python versions .. image:: https://travis-ci.org/zopefoundation/zope.testrunner.svg?branch=master :target: https://travis-ci.org/zopefoundation/zope.testrunner .. image:: https://coveralls.io/repos/github/zopefoundation/zope.testrunner/badge.svg?branch=master :target: https://coveralls.io/github/zopefoundation/zope.testrunner?branch=master For an overview of features, see :doc:`testrunner`. To get started testing right away, see :doc:`getting-started` .. toctree:: :maxdepth: 2 :caption: Usage testrunner getting-started cli .. toctree:: :maxdepth: 2 :caption: Writing Tests testrunner-layers-api testrunner-layers-ntd testrunner-layers-instances .. toctree:: :maxdepth: 2 :caption: Running Tests testrunner-discovery testrunner-layers testrunner-test-selection testrunner-shuffle testrunner-debugging testrunner-coverage testrunner-profiling testrunner-wo-source testrunner-repeat testrunner-gc testrunner-leaks testrunner-new-threads .. toctree:: :maxdepth: 2 :caption: Output Control testrunner-verbose testrunner-progress testrunner-colors testrunner-errors .. toctree:: :maxdepth: 2 :caption: Advanced testrunner-knit testrunner-edge-cases .. toctree:: :maxdepth: 2 :caption: zope.testrunner API testrunner-simple testrunner-arguments testrunner-eggsupport api .. toctree:: :maxdepth: 2 changelog Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search`
zope.testrunner
/zope.testrunner-6.1.tar.gz/zope.testrunner-6.1/docs/index.rst
index.rst
__docformat__ = 'restructuredtext' import re import zope.component import zope.interface from zope.i18n.interfaces import IModifiableUserPreferredLanguages from zope.interface import alsoProvides from zope.interface.interfaces import ComponentLookupError from zope.location.interfaces import LocationError from zope.publisher.interfaces.browser import IBrowserSkinType from zope.publisher.skinnable import applySkin from zope.security.proxy import removeSecurityProxy from zope.traversing.interfaces import IEtcNamespace from zope.traversing.interfaces import IPathAdapter from zope.traversing.interfaces import ITraversable class UnexpectedParameters(LocationError): "Unexpected namespace parameters were provided." class ExcessiveDepth(LocationError): "Too many levels of containment. We don't believe them." def namespaceLookup(ns, name, object, request=None): """Lookup a value from a namespace. We look up a value by getting an adapter from the *object* to :class:`~zope.traversing.interfaces.ITraversable` named *ns*. If the *request* is passed, we get a multi-adapter on the *object* and *request* (sometimes this is called a "view"). Let's start with adapter-based traversal:: >>> class I(zope.interface.Interface): ... 'Test interface' >>> @zope.interface.implementer(I) ... class C(object): ... pass We'll register a simple testing adapter:: >>> class Adapter(object): ... def __init__(self, context): ... self.context = context ... def traverse(self, name, remaining): ... return name+'42' >>> zope.component.provideAdapter(Adapter, (I,), ITraversable, 'foo') Then given an object, we can traverse it with a namespace-qualified name:: >>> namespaceLookup('foo', 'bar', C()) 'bar42' If we give an invalid namespace, we'll get a not found error:: >>> namespaceLookup('fiz', 'bar', C()) # doctest: +ELLIPSIS Traceback (most recent call last): ... zope.location.interfaces.LocationError: (<zope.traversing.namespace.C object at 0x...>, '++fiz++bar') We'll get the same thing if we provide a request:: >>> from zope.publisher.browser import TestRequest >>> request = TestRequest() >>> namespaceLookup('foo', 'bar', C(), request) # doctest: +ELLIPSIS Traceback (most recent call last): ... zope.location.interfaces.LocationError: (<zope.traversing.namespace.C object at 0x...>, '++foo++bar') We need to provide a view:: >>> class View(object): ... def __init__(self, context, request): ... pass ... def traverse(self, name, remaining): ... return name+'fromview' >>> from zope.traversing.testing import browserView >>> browserView(I, 'foo', View, providing=ITraversable) >>> namespaceLookup('foo', 'bar', C(), request) 'barfromview' Clean up:: >>> from zope.testing.cleanup import cleanUp >>> cleanUp() """ # noqa: E501 line too long if request is not None: traverser = zope.component.queryMultiAdapter((object, request), ITraversable, ns) else: traverser = zope.component.queryAdapter(object, ITraversable, ns) if traverser is None: raise LocationError(object, "++{}++{}".format(ns, name)) return traverser.traverse(name, ()) namespace_pattern = re.compile('[+][+]([a-zA-Z0-9_]+)[+][+]') def nsParse(name): """ Parse a namespace-qualified name into a namespace name and a name. Returns the namespace name and a name. A namespace-qualified name is usually of the form ++ns++name, as in:: >>> nsParse('++acquire++foo') ('acquire', 'foo') The part inside the +s must be an identifier, so:: >>> nsParse('++hello world++foo') ('', '++hello world++foo') >>> nsParse('+++acquire+++foo') ('', '+++acquire+++foo') But it may also be a @@foo, which implies the view namespace:: >>> nsParse('@@foo') ('view', 'foo') >>> nsParse('@@@foo') ('view', '@foo') >>> nsParse('@foo') ('', '@foo') """ ns = '' if name.startswith('@@'): ns = 'view' name = name[2:] else: match = namespace_pattern.match(name) if match: prefix, ns = match.group(0, 1) name = name[len(prefix):] return ns, name def getResource(context, name, request): result = queryResource(context, name, request) if result is None: raise LocationError(context, name) return result def queryResource(context, name, request, default=None): result = zope.component.queryAdapter(request, name=name) if result is None: return default # We need to set the __parent__ and __name__. We need the unproxied # resource to do this. We still return the proxied resource. unproxied = removeSecurityProxy(result) unproxied.__parent__ = context unproxied.__name__ = name return result # ---- namespace processors below ---- @zope.interface.implementer(ITraversable) class SimpleHandler: def __init__(self, context, request=None): """ It ignores its second constructor arg and stores the first one in its ``context`` attr. """ self.context = context class acquire(SimpleHandler): """ Traversal adapter for the ``acquire`` namespace. This namespace tries to traverse to the given *name* starting with the context object. If it cannot be found, it proceeds to look at each ``__parent__`` all the way up the tree until it is found. """ def traverse(self, name, remaining): """ Acquire a name Let's set up some example data:: >>> @zope.interface.implementer(ITraversable) ... class testcontent(object): ... def traverse(self, name, remaining): ... v = getattr(self, name, None) ... if v is None: ... raise LocationError(self, name) ... return v ... def __repr__(self): ... return 'splat' >>> ob = testcontent() >>> ob.a = 1 >>> ob.__parent__ = testcontent() >>> ob.__parent__.b = 2 >>> ob.__parent__.__parent__ = testcontent() >>> ob.__parent__.__parent__.c = 3 And acquire some names: >>> adapter = acquire(ob) >>> adapter.traverse('a', ()) 1 >>> adapter.traverse('b', ()) 2 >>> adapter.traverse('c', ()) 3 >>> adapter.traverse('d', ()) Traceback (most recent call last): ... zope.location.interfaces.LocationError: (splat, 'd') """ i = 0 ob = self.context while i < 200: i += 1 traversable = ITraversable(ob, None) if traversable is not None: try: # ??? what do we do if the path gets bigger? path = [] after = traversable.traverse(name, path) if path: continue except LocationError: pass else: return after ob = getattr(ob, '__parent__', None) if ob is None: raise LocationError(self.context, name) raise ExcessiveDepth(self.context, name) class attr(SimpleHandler): """ Traversal adapter for the ``attribute`` namespace. This namespace simply looks for an attribute of the given *name*. """ def traverse(self, name, ignored): """Attribute traversal adapter This adapter just provides traversal to attributes: >>> ob = {'x': 1} >>> adapter = attr(ob) >>> list(adapter.traverse('keys', ())()) ['x'] """ return getattr(self.context, name) class item(SimpleHandler): """ Traversal adapter for the ``item`` namespace. This namespace simply uses ``__getitem__`` to find a value of the given *name*. """ def traverse(self, name, ignored): """Item traversal adapter This adapter just provides traversal to items: >>> ob = {'x': 42} >>> adapter = item(ob) >>> adapter.traverse('x', ()) 42 """ return self.context[name] class etc(SimpleHandler): """ Traversal adapter for the ``etc`` namespace. This namespace provides for a layer of indirection. The given **name** is used to find a utility of that name that implements `zope.traversing.interfaces.IEtcNamespace`. As a special case, if there is no such utility, and the name is "site", then we will attempt to call a method named ``getSiteManager`` on the *context* object. """ def traverse(self, name, ignored): utility = zope.component.queryUtility(IEtcNamespace, name) if utility is not None: return utility ob = self.context if name not in ('site',): raise LocationError(ob, name) method_name = "getSiteManager" method = getattr(ob, method_name, None) if method is None: raise LocationError(ob, name) try: return method() except ComponentLookupError: raise LocationError(ob, name) @zope.interface.implementer(ITraversable) class view: """ Traversal adapter for the ``view`` (``@@``) namespace. This looks for the default multi-adapter from the *context* and *request* of the given *name*. :raises zope.location.interfaces.LocationError: If no such adapter can be found. """ def __init__(self, context, request): self.context = context self.request = request def traverse(self, name, ignored): result = zope.component.queryMultiAdapter((self.context, self.request), name=name) if result is None: raise LocationError(self.context, name) return result class resource(view): """ Traversal adapter for the ``resource`` namespace. Resources are default adapters of the given *name* for the *request* (**not** the *context*). The returned object will have its ``__parent__`` set to the *context* and its ``__name__`` will match the *name* we traversed. """ def traverse(self, name, ignored): # The context is important here, since it becomes the parent of the # resource, which is needed to generate the absolute URL. return getResource(self.context, name, self.request) class lang(view): """ Traversal adapter for the ``lang`` namespace. Traversing to *name* means to adapt the request to :class:`zope.i18n.interfaces.IModifiableUserPreferredLanguages` and set the *name* as the only preferred language. This needs the *request* to support :class:`zope.publisher.interfaces.http.IVirtualHostRequest` because it shifts the language name to the application. """ def traverse(self, name, ignored): self.request.shiftNameToApplication() languages = IModifiableUserPreferredLanguages(self.request) languages.setPreferredLanguages([name]) return self.context class skin(view): """ Traversal adapter for the ``skin`` namespace. Traversing to *name* looks for the :class:`zope.publisher.interfaces.browser.IBrowserSkinType` utility having the given name, and then applies it to the *request* with :func:`.applySkin`. This needs the *request* to support :class:`zope.publisher.interfaces.http.IVirtualHostRequest` because it shifts the skin name to the application. """ def traverse(self, name, ignored): self.request.shiftNameToApplication() try: the_skin = zope.component.getUtility(IBrowserSkinType, name) except ComponentLookupError: raise LocationError("++skin++%s" % name) applySkin(self.request, the_skin) return self.context class vh(view): """ Traversal adapter for the ``vh`` namespace. Traversing to *name*, which must be of the form ``protocol:host:port`` causes a call to :meth:`zope.publisher.interfaces.http.IVirtualHostRequest.setApplicationServer`. Segments in the request's traversal stack up to a prior ``++`` are collected and become the application names given to :meth:`zope.publisher.interfaces.http.IVirtualHostRequest.setVirtualHostRoot`. """ def traverse(self, name, ignored): request = self.request if name: try: proto, host, port = name.split(":") except ValueError: raise ValueError("Vhost directive should have the form " "++vh++protocol:host:port") request.setApplicationServer(host, proto, port) traversal_stack = request.getTraversalStack() app_names = [] if '++' in traversal_stack: segment = traversal_stack.pop() while segment != '++': app_names.append(segment) segment = traversal_stack.pop() request.setTraversalStack(traversal_stack) else: raise ValueError( "Must have a path element '++' after a virtual host " "directive.") request.setVirtualHostRoot(app_names) return self.context class adapter(SimpleHandler): """ Traversal adapter for the ``adapter`` namespace. This adapter provides traversal to named adapters for the *context* registered to provide `zope.traversing.interfaces.IPathAdapter`. """"" def traverse(self, name, ignored): """ To demonstrate this, we need to register some adapters: >>> def adapter1(ob): ... return 1 >>> def adapter2(ob): ... return 2 >>> zope.component.provideAdapter( ... adapter1, (None,), IPathAdapter, 'a1') >>> zope.component.provideAdapter( ... adapter2, (None,), IPathAdapter, 'a2') Now, with these adapters in place, we can use the traversal adapter: >>> ob = object() >>> adapter = adapter(ob) >>> adapter.traverse('a1', ()) 1 >>> adapter.traverse('a2', ()) 2 >>> try: ... adapter.traverse('bob', ()) ... except LocationError: ... print('no adapter') no adapter Clean up: >>> from zope.testing.cleanup import cleanUp >>> cleanUp() """ try: return zope.component.getAdapter(self.context, IPathAdapter, name) except ComponentLookupError: raise LocationError(self.context, name) class debug(view): """ Traversal adapter for the ``debug`` namespace. This adapter allows debugging flags to be set in the request. .. seealso:: :class:`zope.publisher.interfaces.IDebugFlags` """ enable_debug = __debug__ def traverse(self, name, ignored): """ Setup for demonstration: >>> from zope.publisher.browser import TestRequest >>> request = TestRequest() >>> ob = object() >>> adapter = debug(ob, request) in debug mode, ``++debug++source`` enables source annotations >>> request.debug.sourceAnnotations False >>> adapter.traverse('source', ()) is ob True >>> request.debug.sourceAnnotations True ``++debug++tal`` enables TAL markup in output >>> request.debug.showTAL False >>> adapter.traverse('tal', ()) is ob True >>> request.debug.showTAL True ``++debug++errors`` enables tracebacks (by switching to debug skin) >>> from zope.publisher.interfaces.browser import IBrowserRequest >>> from zope.interface import directlyProvides >>> from zope.interface import Interface >>> class Debug(IBrowserRequest): ... pass >>> directlyProvides(Debug, IBrowserSkinType) >>> zope.component.provideUtility( ... Debug, IBrowserSkinType, name='Debug') >>> Debug.providedBy(request) False >>> adapter.traverse('errors', ()) is ob True >>> Debug.providedBy(request) True Interfaces already directly provided by the request are still provided by it once the debug skin is applied. >>> request = TestRequest() >>> class IFoo(Interface): ... pass >>> directlyProvides(request, IFoo) >>> adapter = debug(ob, request) >>> adapter.traverse('errors', ()) is ob True >>> Debug.providedBy(request) True >>> IFoo.providedBy(request) True You can specify several flags separated by commas >>> adapter.traverse('source,tal', ()) is ob True Unknown flag names cause exceptions >>> try: ... adapter.traverse('badflag', ()) ... except ValueError: ... print('unknown debugging flag') unknown debugging flag Of course, if Python was started with the ``-O`` flag to disable debugging, none of this is allowed (we simulate this with a private setting on the instance): >>> adapter.enable_debug = False >>> adapter.traverse('source', ()) Traceback (most recent call last): ... ValueError: Debug flags only allowed in debug mode """ if not self.enable_debug or not __debug__: raise ValueError("Debug flags only allowed in debug mode") request = self.request for flag in name.split(','): if flag == 'source': request.debug.sourceAnnotations = True elif flag == 'tal': request.debug.showTAL = True elif flag == 'errors': # Note that we don't use applySkin(), because it removes all # existing skins. We may want to get tracebacks while trying to # debug a different skin. debug_skin = zope.component.getUtility( IBrowserSkinType, 'Debug') alsoProvides(request, debug_skin) else: raise ValueError("Unknown debug flag: %s" % flag) return self.context if not __debug__: # pragma: no cover # If not in debug mode, we should get an error: traverse.__doc__ = """Disabled debug traversal adapter This adapter allows debugging flags to be set in the request, but it is disabled because Python was run with -O. Setup for demonstration: >>> from zope.publisher.browser import TestRequest >>> request = TestRequest() >>> ob = object() >>> adapter = debug(ob, request) in debug mode, ++debug++source enables source annotations >>> request.debug.sourceAnnotations False >>> adapter.traverse('source', ()) is ob Traceback (most recent call last): ... ValueError: Debug flags only allowed in debug mode ++debug++tal enables TAL markup in output >>> request.debug.showTAL False >>> adapter.traverse('tal', ()) is ob Traceback (most recent call last): ... ValueError: Debug flags only allowed in debug mode ++debug++errors enables tracebacks (by switching to debug skin) >>> Debug.providedBy(request) False >>> adapter.traverse('errors', ()) is ob Traceback (most recent call last): ... ValueError: Debug flags only allowed in debug mode You can specify several flags separated by commas >>> adapter.traverse('source,tal', ()) is ob Traceback (most recent call last): ... ValueError: Debug flags only allowed in debug mode """
zope.traversing
/zope.traversing-5.0-py3-none-any.whl/zope/traversing/namespace.py
namespace.py
from zope.interface import Attribute from zope.interface import Interface from zope.interface import implementer from zope.interface.interfaces import IObjectEvent from zope.interface.interfaces import ObjectEvent # BBB: Re-import symbols to their old location. from zope.location.interfaces import ILocationInfo as IPhysicallyLocatable from zope.location.interfaces import IRoot as IContainmentRoot from zope.location.interfaces import LocationError as TraversalError _RAISE_KEYERROR = object() class ITraversable(Interface): """To traverse an object, this interface must be provided""" def traverse(name, furtherPath): """Get the next item on the path Should return the item corresponding to 'name' or raise :exc:`~zope.location.interfaces.LocationError` where appropriate. :param str name: an ASCII string or Unicode object. :param list furtherPath: is a list of names still to be traversed. This method is allowed to change the contents of furtherPath. """ class ITraverser(Interface): """Provide traverse features""" # XXX This is used like a utility but implemented as an adapter: The # traversal policy is only implemented once and repeated for all objects # along the path. def traverse(path, default=_RAISE_KEYERROR): """Return an object given a path. Path is either an immutable sequence of strings or a slash ('/') delimited string. If the first string in the path sequence is an empty string, or the path begins with a '/', start at the root. Otherwise the path is relative to the current context. If the object is not found, return *default* argument. """ class ITraversalAPI(Interface): """ Common API functions to ease traversal computations. This is provided by :mod:`zope.traversing.api`. """ def joinPath(path, *args): """Join the given relative paths to the given *path*. Returns a text (`unicode`) path. The path should be well-formed, and not end in a '/' unless it is the root path. It can be either a string (ascii only) or unicode. The positional arguments are relative paths to be added to the path as new path segments. The path may be absolute or relative. A segment may not start with a '/' because that would be confused with an absolute path. A segment may not end with a '/' because we do not allow '/' at the end of relative paths. A segment may consist of '.' or '..' to mean "the same place", or "the parent path" respectively. A '.' should be removed and a '..' should cause the segment to the left to be removed. ``joinPath('/', '..')`` should raise an exception. """ def getPath(obj): """Returns a string representing the physical path to the object. """ def getRoot(obj): """Returns the root of the traversal for the given object. """ def traverse(object, path, default=None, request=None): """ Traverse *path* relative to the given object. :param str path: a string with path segments separated by '/'. :keyword request: Passed in when traversing from presentation code. This allows paths like "@@foo" to work. :raises zope.location.interfaces.LocationError: if *path* cannot be found .. note:: Calling `traverse` with a path argument taken from an untrusted source, such as an HTTP request form variable, is a bad idea. It could allow a maliciously constructed request to call code unexpectedly. Consider using `traverseName` instead. """ def traverseName(obj, name, default=None, traversable=None, request=None): """ Traverse a single step *name* relative to the given object. *name* must be a string. '.' and '..' are treated specially, as well as names starting with '@' or '+'. Otherwise *name* will be treated as a single path segment. You can explicitly pass in an `ITraversable` as the *traversable* argument. If you do not, the given object will be adapted to `ITraversable`. *request* is passed in when traversing from presentation code. This allows paths like "@@foo" to work. :raises zope.location.interfaces.LocationError: if *path* cannot be found and *default* was not provided. """ def getName(obj): """ Get the name an object was traversed via. """ def getParent(obj): """ Returns the container the object was traversed via. Returns `None` if the object is a containment root. :raises TypeError: if the object doesn't have enough context to get the parent. """ def getParents(obj): """ Returns a list starting with the given object's parent followed by each of its parents. :raises TypeError: if the context doesn't go all the way down to a containment root. """ def canonicalPath(path_or_object): """ Returns a canonical absolute unicode path for the path or object. Resolves segments that are '.' or '..'. :raises ValueError: if a badly formed path is given. """ class IPathAdapter(Interface): """ Marker interface for adapters to be used in paths. .. seealso:: :class:`.namespace.adapter`. """ class IEtcNamespace(Interface): """ Marker for utility registrations in the ``++etc++`` namespace. .. seealso:: :class:`.namespace.etc` """ class IBeforeTraverseEvent(IObjectEvent): """ An event which gets sent on publication traverse. """ request = Attribute("The current request") @implementer(IBeforeTraverseEvent) class BeforeTraverseEvent(ObjectEvent): """ An event which gets sent on publication traverse. Default implementation of `IBeforeTraverseEvent`. """ def __init__(self, ob, request): ObjectEvent.__init__(self, ob) self.request = request
zope.traversing
/zope.traversing-5.0-py3-none-any.whl/zope/traversing/interfaces.py
interfaces.py
import zope.interface from zope.location.interfaces import ILocationInfo from zope.location.interfaces import LocationError from zope.location.traversing import RootPhysicallyLocatable # BBB from zope.traversing.interfaces import ITraversable from zope.traversing.interfaces import ITraverser from zope.traversing.namespace import namespaceLookup from zope.traversing.namespace import nsParse _marker = object() # opaque marker that doesn't get security proxied @zope.interface.implementer(ITraversable) class DefaultTraversable: """ Traverses objects via attribute and item lookup. Implements `~zope.traversing.interfaces.ITraversable`. """ def __init__(self, subject): self._subject = subject def traverse(self, name, furtherPath): subject = self._subject __traceback_info__ = (subject, name, furtherPath) attr = getattr(subject, name, _marker) if attr is not _marker: return attr if hasattr(subject, '__getitem__'): try: return subject[name] except (KeyError, TypeError): pass raise LocationError(subject, name) @zope.interface.implementer(ITraverser) class Traverser: """ Provide traverse features. Implements `~zope.traversing.interfaces.ITraverser`. """ # This adapter can be used for any object. def __init__(self, wrapper): self.context = wrapper def traverse(self, path, default=_marker, request=None): if not path: return self.context if isinstance(path, str): path = path.split('/') if len(path) > 1 and not path[-1]: # Remove trailing slash path.pop() else: path = list(path) path.reverse() pop = path.pop curr = self.context if not path[-1]: # Start at the root pop() curr = ILocationInfo(self.context).getRoot() try: while path: name = pop() curr = traversePathElement(curr, name, path, request=request) return curr except LocationError: if default == _marker: raise return default def traversePathElement(obj, name, further_path, default=_marker, traversable=None, request=None): """ Traverse a single step *name* relative to the given object. This is used to implement :meth:`zope.traversing.interfaces.ITraversalAPI.traverseName`. :param str name: must be a string. '.' and '..' are treated specially, as well as names starting with '@' or '+'. Otherwise *name* will be treated as a single path segment. :param list further_path: a list of names still to be traversed. This method is allowed to change the contents of *further_path*. :keyword ITraversable traversable: You can explicitly pass in an `~zope.traversing.interfaces.ITraversable` as the *traversable* argument. If you do not, the given object will be adapted to ``ITraversable``. :keyword request: assed in when traversing from presentation code. This allows paths like ``@@foo`` to work. :raises zope.location.interfaces.LocationError: if *path* cannot be found and '*default* was not provided. """ __traceback_info__ = (obj, name) if name == '.': return obj if name == '..': return obj.__parent__ if name and name[:1] in '@+': ns, nm = nsParse(name) if ns: return namespaceLookup(ns, nm, obj, request) else: nm = name if traversable is None: traversable = ITraversable(obj, None) if traversable is None: raise LocationError('No traversable adapter found', obj) try: return traversable.traverse(nm, further_path) except LocationError: if default is not _marker: return default raise
zope.traversing
/zope.traversing-5.0-py3-none-any.whl/zope/traversing/adapters.py
adapters.py
"""Publication Traverser """ __docformat__ = 'restructuredtext' from zope.component import queryMultiAdapter from zope.publisher.interfaces import IPublishTraverse from zope.publisher.interfaces import NotFound from zope.publisher.interfaces.browser import IBrowserPublisher from zope.security.checker import ProxyFactory from zope.traversing.interfaces import TraversalError from zope.traversing.namespace import namespaceLookup from zope.traversing.namespace import nsParse class PublicationTraverser: """Traversal used for publication. The significant differences from `zope.traversing.adapters.traversePathElement` are: - Instead of adapting each traversed object to ITraversable, this version multi-adapts (ob, request) to `zope.publisher.interfaces.IPublishTraverse`. - This version wraps a security proxy around each traversed object. - This version raises `zope.publisher.interfaces.NotFound` rather than `zope.location.interfaces.LocationError`. - This version has a method, :meth:`traverseRelativeURL`, that supports "browserDefault" traversal. """ def proxy(self, ob): return ProxyFactory(ob) def traverseName(self, request, ob, name): nm = name # the name to look up the object with if name and name[:1] in '@+': # Process URI segment parameters. ns, nm = nsParse(name) if ns: try: ob2 = namespaceLookup(ns, nm, ob, request) except TraversalError: raise NotFound(ob, name) return self.proxy(ob2) if nm == '.': return ob if IPublishTraverse.providedBy(ob): ob2 = ob.publishTraverse(request, nm) else: # self is marker adapter = queryMultiAdapter((ob, request), IPublishTraverse, default=self) if adapter is not self: ob2 = adapter.publishTraverse(request, nm) else: raise NotFound(ob, name, request) return self.proxy(ob2) def traversePath(self, request, ob, path): if isinstance(path, str): path = path.split('/') if len(path) > 1 and not path[-1]: # Remove trailing slash path.pop() else: path = list(path) # Remove single dots path = [x for x in path if x != '.'] path.reverse() # Remove double dots if possible while '..' in path: parent_index = path.index('..') if parent_index + 2 > len(path): break del path[parent_index:parent_index + 2] pop = path.pop while path: name = pop() ob = self.traverseName(request, ob, name) return ob def traverseRelativeURL(self, request, ob, path): """Path traversal that includes browserDefault paths""" ob = self.traversePath(request, ob, path) while True: adapter = IBrowserPublisher(ob, None) if adapter is None: return ob ob, path = adapter.browserDefault(request) ob = self.proxy(ob) if not path: return ob ob = self.traversePath(request, ob, path) # alternate spelling PublicationTraverse = PublicationTraverser class PublicationTraverserWithoutProxy(PublicationTraverse): """ A `PublicationTraverse` that does not add security proxies. """ def proxy(self, ob): return ob
zope.traversing
/zope.traversing-5.0-py3-none-any.whl/zope/traversing/publicationtraverse.py
publicationtraverse.py
from zope.interface import moduleProvides from zope.location.interfaces import ILocationInfo from zope.location.interfaces import IRoot from zope.traversing.adapters import traversePathElement from zope.traversing.interfaces import ITraversalAPI from zope.traversing.interfaces import ITraverser # The authoritative documentation for these functions # is in this interface. Later, we replace all our docstrings # with those defined in the interface. moduleProvides(ITraversalAPI) __all__ = tuple(ITraversalAPI) _marker = object() def joinPath(path, *args): """ Join the given relative paths to the given path. See `ITraversalAPI` for details. """ if not args: return path if path != '/' and path.endswith('/'): raise ValueError('path must not end with a "/": %s' % path) if path != '/': path += '/' for arg in args: if arg.startswith('/') or arg.endswith('/'): raise ValueError("Leading or trailing slashes in path elements") return _normalizePath(path + '/'.join(args)) def getPath(obj): """ Returns a string representing the physical path to the object. See `ITraversalAPI` for details. """ return ILocationInfo(obj).getPath() def getRoot(obj): """ Returns the root of the traversal for the given object. See `ITraversalAPI` for details. """ return ILocationInfo(obj).getRoot() def traverse(object, path, default=_marker, request=None): """ Traverse *path* relative to the given object. See `ITraversalAPI` for details. """ traverser = ITraverser(object) if default is _marker: return traverser.traverse(path, request=request) return traverser.traverse(path, default=default, request=request) def traverseName(obj, name, default=_marker, traversable=None, request=None): """ Traverse a single step 'name' relative to the given object. See `ITraversalAPI` for details. """ further_path = [] if default is _marker: obj = traversePathElement(obj, name, further_path, traversable=traversable, request=request) else: obj = traversePathElement(obj, name, further_path, default=default, traversable=traversable, request=request) if further_path: raise NotImplementedError('further_path returned from traverse') return obj def getName(obj): """ Get the name an object was traversed via. See `ITraversalAPI` for details. """ return ILocationInfo(obj).getName() def getParent(obj): """ Returns the container the object was traversed via. See `ITraversalAPI` for details. """ try: location_info = ILocationInfo(obj) except TypeError: pass else: return location_info.getParent() # XXX Keep the old implementation as the fallback behaviour in the case # that obj doesn't have a location parent. This seems advisable as the # 'parent' is sometimes taken to mean the traversal parent, and the # __parent__ attribute is used for both. if IRoot.providedBy(obj): return None parent = getattr(obj, '__parent__', None) if parent is not None: return parent raise TypeError("Not enough context information to get parent", obj) def getParents(obj): """ Returns a list starting with the given object's parent followed by each of its parents. See `ITraversalAPI` for details. """ return ILocationInfo(obj).getParents() def _normalizePath(path): """Normalize a path by resolving '.' and '..' path elements.""" # Special case for the root path. if path == '/': return path new_segments = [] prefix = '' if path.startswith('/'): prefix = '/' path = path[1:] for segment in path.split('/'): if segment == '.': continue if segment == '..': new_segments.pop() # raises IndexError if there is nothing to pop continue if not segment: raise ValueError('path must not contain empty segments: %s' % path) new_segments.append(segment) return prefix + '/'.join(new_segments) def canonicalPath(path_or_object): """ Returns a canonical absolute unicode path for the given path or object. See `ITraversalAPI` for details. """ if isinstance(path_or_object, str): path = path_or_object if not path: raise ValueError("path must be non-empty: %s" % path) else: path = getPath(path_or_object) path = '' + path # Special case for the root path. if path == '/': return path if path[0] != '/': raise ValueError('canonical path must start with a "/": %s' % path) if path[-1] == '/': raise ValueError('path must not end with a "/": %s' % path) # Break path into segments. Process '.' and '..' segments. return _normalizePath(path) # Synchronize the documentation. for name in ITraversalAPI.names(): if name in globals(): globals()[name].__doc__ = ITraversalAPI[name].__doc__ del name
zope.traversing
/zope.traversing-5.0-py3-none-any.whl/zope/traversing/api.py
api.py
from urllib.parse import quote_from_bytes as quote from urllib.parse import unquote_to_bytes as unquote import zope.component from zope.i18nmessageid import MessageFactory from zope.interface import implementer from zope.location.interfaces import ILocation from zope.proxy import sameProxiedObjects from zope.publisher.browser import BrowserView from zope.traversing.browser.interfaces import IAbsoluteURL _ = MessageFactory('zope') _insufficientContext = _( "There isn't enough context to get URL information. " "This is probably due to a bug in setting up location " "information.") _safe = '@+' # Characters that we don't want to have quoted def absoluteURL(ob, request): return zope.component.getMultiAdapter((ob, request), IAbsoluteURL)() class _EncodedUnicode(object): def __unicode__(self): return unquote(self.__str__()).decode('utf-8') @implementer(IAbsoluteURL) class AbsoluteURL(_EncodedUnicode, BrowserView): """ The default implementation of :class:`zope.traversing.browser.interfaces.IAbsoluteURL`. """ def __str__(self): context = self.context request = self.request # The application URL contains all the namespaces that are at the # beginning of the URL, such as skins, virtual host specifications and # so on. if (context is None or sameProxiedObjects(context, request.getVirtualHostRoot())): return request.getApplicationURL() # first try to get the __parent__ of the object, no matter whether # it provides ILocation or not. If this fails, look up an ILocation # adapter. This will always work, as a general ILocation adapter # is registered for interface in zope.location (a LocationProxy) # This proxy will return a parent of None, causing this to fail # More specific ILocation adapters can be provided however. try: container = context.__parent__ except AttributeError: # we need to assign to context here so we can get # __name__ from it below context = ILocation(context) container = context.__parent__ if container is None: raise TypeError(_insufficientContext) url = str(zope.component.getMultiAdapter((container, request), IAbsoluteURL)) name = getattr(context, '__name__', None) if name is None: raise TypeError(_insufficientContext) if name: url += '/' + quote(name.encode('utf-8'), _safe) return url def __call__(self): return self.__str__() def breadcrumbs(self): context = self.context request = self.request # We do this here do maintain the rule that we must be wrapped context = ILocation(context, context) container = getattr(context, '__parent__', None) if container is None: raise TypeError(_insufficientContext) if sameProxiedObjects(context, request.getVirtualHostRoot()) or \ isinstance(context, Exception): return ({'name': '', 'url': self.request.getApplicationURL()}, ) base = tuple(zope.component.getMultiAdapter( (container, request), IAbsoluteURL).breadcrumbs()) name = getattr(context, '__name__', None) if name is None: raise TypeError(_insufficientContext) if name: base += ( { 'name': name, 'url': ("{}/{}".format(base[-1]['url'], quote(name.encode('utf-8'), _safe))) }, ) return base @implementer(IAbsoluteURL) class SiteAbsoluteURL(_EncodedUnicode, BrowserView): """ An implementation of :class:`zope.traversing.browser.interfaces.IAbsoluteURL` for site root objects (:class:`zope.location.interfaces.IRoot`). """ def __str__(self): context = self.context request = self.request if sameProxiedObjects(context, request.getVirtualHostRoot()): return request.getApplicationURL() url = request.getApplicationURL() name = getattr(context, '__name__', None) if name: url += '/' + quote(name.encode('utf-8'), _safe) return url def __call__(self): return self.__str__() def breadcrumbs(self): context = self.context request = self.request if sameProxiedObjects(context, request.getVirtualHostRoot()): return ({'name': '', 'url': self.request.getApplicationURL()}, ) base = ({'name': '', 'url': self.request.getApplicationURL()}, ) name = getattr(context, '__name__', None) if name: base += ( { 'name': name, 'url': ("{}/{}".format(base[-1]['url'], quote(name.encode('utf-8'), _safe))) }, ) return base
zope.traversing
/zope.traversing-5.0-py3-none-any.whl/zope/traversing/browser/absoluteurl.py
absoluteurl.py
************************************* Locale-based text collation using ICU ************************************* This package provides a Python interface to the `International Component for Unicode (ICU) <http://www-306.ibm.com/software/globalization/icu/index.jsp>`_. .. contents:: Change History ************** 1.0.2 (2006-10-16) ================== Fixed setup file problems. 1.0.1 (2006-10-16) ================== Added missing import to setup.py. 1.0 (2006-10-16) ================ Initial version.
zope.ucol
/zope.ucol-1.0.2.tar.gz/zope.ucol-1.0.2/README.txt
README.txt
Locale-based text collation using ICU ===================================== The zope.ucol package provides a minimal Pythonic wrapper around the u_col C API of the International Components for Unicode (ICU) library. It provides locale-based text collation. To perform collation, you need to create a collator key factory for your locale. We'll use the special "root" locale in this example: >>> import zope.ucol >>> collator = zope.ucol.Collator("root") The collator has a key method for creating collation keys from unicode strings. The method can be passed as the key argument to list.sort or to the built-in sorted function. >>> sorted([u'Sam', u'sally', u'Abe', u'alice', u'Terry', u'tim', ... u'\U00023119', u'\u62d5'], key=collator.key) [u'Abe', u'alice', u'sally', u'Sam', u'Terry', u'tim', u'\u62d5', u'\U00023119'] There is a cmp method for comparing 2 unicode strings, which can also be used when sorting: >>> sorted([u'Sam', u'sally', u'Abe', u'alice', u'Terry', u'tim', ... u'\U00023119', u'\u62d5'], collator.cmp) [u'Abe', u'alice', u'sally', u'Sam', u'Terry', u'tim', u'\u62d5', u'\U00023119'] Note that it is almost always more efficient to pass the key method to sorting functions, rather than the cmp method. The cmp method is more efficient in the special case that strings are long and few and when they tend to differ at their beginnings. This is because computing the entire key can be much more expensive than comparison when the order can be determined based on analyzing a small portion of the original strings. Collator attributes ------------------- You can ask a collator for it's locale: >>> collator.locale 'root' and you can find out whether default collation information was used: >>> collator.used_default_information 0 >>> collator = zope.ucol.Collator("eek") >>> collator.used_default_information 1
zope.ucol
/zope.ucol-1.0.2.tar.gz/zope.ucol-1.0.2/src/zope/ucol/README.txt
README.txt
import os, sys, shutil, tempfile, urllib2 import setuptools.archive_util class Recipe: def __init__(self, buildout, name, options): self.name = name self.options = options self.location = os.path.join( buildout['buildout']['parts-directory'], self.name) options['location'] = self.location if sys.platform.startswith('linux'): platform = 'LinuxRedHat' elif sys.platform.startswith('darwin'): platform = 'MacOSX' elif sys.platform.startswith('win32'): platform = 'win32' else: raise SystemError("Can't guess an ICU platform") options['platform'] = platform def install(self): options = self.options dest = options['location'] if os.path.exists(dest): return dest if options['platform'] == 'win32': return self.install_win32(options, dest) here = os.getcwd() tmp = tempfile.mkdtemp() try: f = urllib2.urlopen( 'ftp://ftp.software.ibm.com/software/globalization/icu/' '%(version)s/icu-%(version)s.tgz' % dict(version=options['version']) ) open(os.path.join(tmp, 'arch'), 'w').write(f.read()) f.close() setuptools.archive_util.unpack_archive( os.path.join(tmp, 'arch'), tmp, ) os.chdir(os.path.join(tmp, 'icu', 'source')) assert os.spawnl( os.P_WAIT, os.path.join(tmp, 'icu', 'source', 'runConfigureICU'), os.path.join(tmp, 'icu', 'source', 'runConfigureICU'), options['platform'], '--prefix='+dest, ) == 0 assert os.spawnlp(os.P_WAIT, 'make', 'make', 'install') == 0 finally: os.chdir(here) shutil.rmtree(tmp) return dest def update(self): pass def install_win32(self, options, dest): tmp = tempfile.mkstemp() try: f = urllib2.urlopen( 'ftp://ftp.software.ibm.com/software/globalization/icu/' '%(version)s/icu-%(version)s-Win32-msvc7.1.zip' % dict(version=options['version']) ) open(tmp, 'w').write(f.read()) f.close() setuptools.archive_util.unpack_archive(tmp, dest) finally: shutil.rmfile(tmp) return dest
zope.ucol
/zope.ucol-1.0.2.tar.gz/zope.ucol-1.0.2/icu/src/zc/recipe/icu/__init__.py
__init__.py
======= CHANGES ======= 5.0 (2022-11-29) ---------------- Backwards incompatible changes ++++++++++++++++++++++++++++++ - Require ``RestrictedPython >= 4``. - Drop support for writing output of ``print`` calls to a variable named ``untrusted_output``. It is now done the same way ``RestrictedPython`` handles printing, i. e. access it trough the variable ``printed``. ``.interpreter.CompiledProgram`` still supports output to a file like object by implementing accessing the printed data. - The following names are no longer available via ``__builtins__`` as they are either potentially harmful, not accessible at all or meaningless: + ``__debug__`` + ``__name__`` + ``__doc__`` + ``copyright`` + ``credits`` + ``license`` + ``quit`` - Drop support to run the tests using ``python setup.py test``. - Drop support for Python 2.6. Features ++++++++ - Add support for Python 3.5, 3.6, 3.7, 3.8, 3.9, 3.10, 3.11. 4.0.0 (2013-02-12) ------------------ - Test coverage at 100%. - Package extracted from zope.security, preserving revision history
zope.untrustedpython
/zope.untrustedpython-5.0.tar.gz/zope.untrustedpython-5.0/CHANGES.rst
CHANGES.rst
"""Protection of built-in objects. """ from types import ModuleType import six from zope.security.checker import NamesChecker from zope.security.proxy import ProxyFactory def SafeBuiltins(): safe_builtins = {} if six.PY2: import __builtin__ as builtins # pragma: PY2 else: import builtins # pragma: PY3 _builtinTypeChecker = NamesChecker( ['__str__', '__repr__', '__name__', '__module__', '__bases__', '__call__']) # It's better to say what is safe than it say what is not safe safe_names = [ # Names of safe objects. See untrustedinterpreter.txt for a # definition of safe objects. 'ArithmeticError', 'AssertionError', 'AttributeError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'FloatingPointError', 'IOError', 'ImportError', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'OverflowWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TypeError', 'UnboundLocalError', 'UnicodeError', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', 'abs', 'bool', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'complex', 'delattr', 'dict', 'divmod', 'filter', 'float', 'frozenset', 'getattr', 'hasattr', 'hash', 'hex', 'id', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'list', 'long', 'map', 'max', 'min', 'object', 'oct', 'ord', 'pow', 'property', 'range', 'reduce', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'zip', 'True', 'False', # TODO: dir segfaults with a seg fault due to a bad tuple # check in merge_class_dict in object.c. The assert macro # seems to be doing the wrong think. Basically, if an object # has bases, then bases is assumed to be a tuple. # dir, ] if six.PY2: safe_names.extend([ 'apply', 'buffer', 'xrange', ]) # pragma: PY2 for name in safe_names: try: value = getattr(builtins, name) except AttributeError: pass else: if isinstance(value, type): value = ProxyFactory(value, _builtinTypeChecker) else: value = ProxyFactory(value) safe_builtins[name] = value from sys import modules def _imp(name, fromlist, prefix=''): module = modules.get(prefix + name) if module is not None: if fromlist or ('.' not in name): return module return modules[prefix + name.split('.')[0]] def __import__(name, globals=None, locals=None, fromlist=()): # Waaa, we have to emulate __import__'s weird semantics. if globals: __name__ = globals.get('__name__') if __name__: # Maybe do a relative import if '__path__' not in globals: # We have an ordinary module, not a package, # so remove last name segment: __name__ = '.'.join(__name__.split('.')[:-1]) if __name__: module = _imp(name, fromlist, __name__ + '.') if module is not None: return module module = _imp(name, fromlist) if module is not None: return module raise ImportError(name) safe_builtins['__import__'] = ProxyFactory(__import__) return safe_builtins class ImmutableModule(ModuleType): def __init__(self, name='__builtins__', **kw): ModuleType.__init__(self, name) self.__dict__.update(kw) def __setattr__(self, name, v): raise AttributeError(name) def __delattr__(self, name): raise AttributeError(name) SafeBuiltins = ImmutableModule(**SafeBuiltins())
zope.untrustedpython
/zope.untrustedpython-5.0.tar.gz/zope.untrustedpython-5.0/src/zope/untrustedpython/builtins.py
builtins.py
Untrusted interpreters ====================== Untrusted programs are executed by untrusted interpreters. Untrusted interpreters make use of security proxies to prevent un-mediated access to assets. An untrusted interpreter defines an environment for running untrusted programs. All objects within the environment are either: - "safe" objects created internally by the environment or created in the course of executing the untrusted program, or - "basic" objects - security-proxied non-basic objects The environment includes proxied functions for accessing objects outside of the environment. These proxied functions provide the only way to access information outside the environment. Because these functions are proxied, as described below, any access to objects outside the environment is mediated by the target security functions. Safe objects are objects whose operations, except for attribute retrieval, and methods access only information stored within the objects or passed as arguments. Safe objects contained within the interpreter environment can contain only information that is already in the environment or computed directly from information that is included in the environment. For this reason, safe objects created within the environment cannot be used to directly access information outside the environment. Safe objects have some attributes that could (very) indirectly be used to access assets. For this reason, an untrusted interpreter always proxies the results of attribute accesses on a safe objects. Basic objects are safe objects that are used to represent elemental data values such as strings and numbers. Basic objects require a lower level of protection than non-basic objects, as will be described detail in a later section. Security proxies mediate all object operations. Any operation access is checked to see whether a subject is authorized to perform the operation. All operation results other than basic objects are, in turn, security proxied. Security proxies will be described in greater detail in a later section. Any operation on a security proxy that results in a non-basic object is also security proxied. All external resources needed to perform an operation are security proxied. Let's consider the trusted interpreter for evaluating URLs. In operation 1 of the example, the interpreter uses a proxied method for getting the system root object. Because the method is proxied, the result of calling the method and the operation is also proxied. The interpreter has a function for traversing objects. This function is proxied. When traversing an object, the function is passed an object and a name. In operation 2, the function is passed the result of operation 1, which is the proxied root object and the name 'A'. We may traverse an object by invoking an operation on it. For example, we may use an operation to get a sub-object. Because any operation on a proxied object returns a proxied object or a basic object, the result is either a proxied object or a basic object. Traversal may also look up a component. For example, in operation 1, we might look up a presentation component named "A" for the root object. In this case, the external object is not proxied, but, when it is returned from the traversal function, it is proxied (unless it is a a basic object) because the traversal function is proxied, and the result of calling a proxied function is proxied (unless the result is a basic object). Operation 3 proceeds in the same way. When we get to operation 4, we use a function for computing the default presentation of the result of operation 3. As with traversal, the result of getting the default presentation is either a proxied object or a basic object because the function for getting the default presentation is proxied. When we get to the last operation, we have either a proxied object or a basic object. If the result of operation 4 is a basic object, we simply convert it to a string and return it as the result page. If the result of operation 4 is a non-basic object, we invoke a render operation on it and return the result as a string. Note that an untrusted interpreter may or may not provide protection against excessive resource usage. Different interpreters will provide different levels of service with respect to limitations on resource usage. If an untrusted interpreter performs an attribute access, the trusted interpreter must proxy the result unless the result is a basic object. In summary, an untrusted interpreter assures that any access to assets is mediated through security proxies by creating an environment to run untrusted code and making sure that: - The only way to access anything from outside of the environment is to call functions that are proxied in the environment. - Results of any attribute access in the environment are proxied unless the results are basic objects. Security proxies ---------------- Security proxies are objects that wrap and mediate access to objects. The Python programming language used by Zope defines a set of specific named low-level operations. In addition to operations, Python objects can have attributes, used to represent data and methods. Attributes are accessed using a dot notation. Applications can, and usually do, define methods to provide extended object behaviors. Methods are accessed as attributes through the low-level operation named "__getattribute__". The Python code:: a.b() invokes 2 operations: 1. Use the low-level `__getattribute__` operation with the name "b". 2. Use the low-level '__call__' operation on the result of the first operation. For all operations except the ``__getattribute__`` and ``__setattribute__`` operations, security proxies have a permission value defined by the permission-declaration subsystem. Two special permission values indicate that access is either forbidden (never allowed) or public (always allowed). For all other permission values, the authorization subsystem is used to decide whether the subject has the permission for the proxied object. If the subject has the permission, then access to the operation is allowed. Otherwise, access is denied. For getting or setting attributes, a proxy has permissions for getting and a permission for setting attribute values for a given attribute name. As described above, these permissions may be one of the two special permission values indicating forbidden or public access, or another permission value that must be checked with the authorization system. For all objects, Zope defines the following operations to be always public: comparison "__lt__", "__le__", "__eq__", "__gt__", "__ge__", "__ne__" hash "__hash__" boolean value "__nonzero__" class introspection "__class__" interface introspection "__providedBy__", "__implements__" adaptation "__conform__" low-level string representation "__repr__" The result of an operation on a proxied object is a security proxy unless the result is a basic value. Basic objects ------------- Basic objects are safe immutable objects that contain only immutable subobjects. Examples of basic objects include: - Strings, - Integers (long and normal), - Floating-point objects, - Date-time objects, - Boolean objects (True and False), and - The special (nil) object, None. Basic objects are safe, so, as described earlier, operations on basic objects, other than attribute access, use only information contained within the objects or information passed to them. For this reason, basic objects cannot be used to access information outside of the untrusted interpreter environment. The decision not to proxy basic objects is largely an optimization. It allows low-level safe computation to be performed without unnecessary overhead, Note that a basic object could contain sensitive information, but such a basic object would need to be obtained by making a call on a proxied object. Therefore, the access to the basic object in the first place is mediated by the security functions. Rationale for mutable safe objects ---------------------------------- Some safe objects are not basic. For these objects, we proxy the objects if they originate from outside of the environment. We do this for two reasons: 1. Non-basic objects from outside the environment need to be proxied to prevent unauthorized access to information. 2. We need to prevent un-mediated change of information from outside of the environment. We don't proxy safe objects created within the environment. This is safe to do because such safe objects can contain and provide access to information already in the environment. Sometimes the interpreter or the interpreted program needs to be able to create simple data containers to hold information computed in the course of the program execution. Several safe container types are provided for this purpose. Safe Builtins ============= When executing untrusted Python code, we need to make sure that we only give the code access to safe, basic or proxied objects. This included the builtin objects provided to Python code through a special __builtins__ module in globals. The `builtins` module provides a suitable module object: .. doctest:: >>> from zope.untrustedpython.builtins import SafeBuiltins >>> d = {'__builtins__': SafeBuiltins} >>> exec('x = str(1)', d) >>> d['x'] '1' The object is immutable: .. doctest:: >>> SafeBuiltins.foo = 1 Traceback (most recent call last): ... AttributeError: foo >>> del SafeBuiltins['getattr'] Traceback (most recent call last): ... TypeError: object does not support item deletion It contains items with keys that are all strings and values that are either proxied or are basic types: .. doctest:: >>> from zope.security.proxy import Proxy >>> for key, value in SafeBuiltins.__dict__.items(): ... if not isinstance(key, str): ... raise TypeError(key) ... if value is not None and not isinstance(value, (Proxy, int, str)): ... raise TypeError(value, key) It doesn't contain unsafe items, such as eval, globals, quit, ...: .. doctest:: >>> SafeBuiltins.eval Traceback (most recent call last): ... AttributeError: 'ImmutableModule' object has no attribute 'eval' >>> SafeBuiltins.globals Traceback (most recent call last): ... AttributeError: 'ImmutableModule' object has no attribute 'globals' >>> SafeBuiltins.quit Traceback (most recent call last): ... AttributeError: 'ImmutableModule' object has no attribute 'quit' The safe builtins also contains a custom __import__ function. .. doctest:: >>> imp = SafeBuiltins.__import__ As with regular import, it only returns the top-level package if no fromlist is specified: .. doctest:: >>> import zope.security >>> imp('zope.security') == zope True >>> imp('zope.security', {}, {}, ['*']) == zope.security True Note that the values returned are proxied: .. doctest:: >>> type(imp('zope.security')) is Proxy True This means that, having imported a module, you will only be able to access attributes for which you are authorized. Unlike regular __import__, you can only import modules that have been previously imported. This is to prevent unauthorized execution of module-initialization code: .. doctest:: >>> security = zope.security >>> import sys >>> del sys.modules['zope.security'] >>> imp('zope.security') Traceback (most recent call last): ... ImportError: zope.security >>> sys.modules['zope.security'] = security Package-relative imports are supported (for now): .. doctest:: >>> imp('security', {'__name__': 'zope', '__path__': []}) == security True >>> imp('security', {'__name__': 'zope.foo'}) == zope.security True Untrusted Python interpreter ============================ The interpreter module provides very basic Python interpreter support. It combined untrusted code compilation with safe builtins and an exec-like API. The exec_src function can be used to execute Python source: .. doctest:: >>> from zope.untrustedpython.interpreter import exec_src >>> d = {} >>> exec_src("x=1", d) >>> d['x'] 1 >>> exec_src("x=getattr", d) Note that the safe builtins dictionary is inserted into the dictionary: .. doctest:: >>> from zope.untrustedpython.builtins import SafeBuiltins >>> d['__builtins__'] == SafeBuiltins True All of the non-basic items in the safe builtins are proxied: .. doctest:: >>> exec_src('str=str', d) >>> from zope.security.proxy import Proxy >>> type(d['str']) is Proxy True Note that you cannot get access to `__builtins__`: .. doctest:: >>> exec_src('__builtins__.__dict__["x"] = 1', d) Traceback (most recent call last): ... SyntaxError: ('Line 1: "__dict__" is an invalid attribute name because it starts with "_".', 'Line 1: "__builtins__" is an invalid variable name because it starts with "_"') Because the untrusted code compiler is used, you can't use exec, raise, or try/except statements: .. doctest:: >>> exec_src("exec('x=1'"), d) Traceback (most recent call last): ... SyntaxError: Line 1: exec calls are not supported Any attribute-access results will be proxied: .. doctest:: >>> exec_src("data = {}\nupdate = data.update\nupdate({'x': 'y'})", d) >>> type(d['update']) is Proxy True In this case, we were able to get to and use the update method because the data dictionary itself was created by the untrusted code and was, thus, unproxied. You can compile code yourself and call exec_code instead: .. doctest:: >>> from zope.untrustedpython.rcompile import compile >>> code = compile('x=2', '<mycode>', 'exec') >>> d = {} >>> from zope.untrustedpython.interpreter import exec_code >>> exec_code(code, d) >>> d['x'] 2 This is useful if you are going to be executing the same expression many times, as you can avoid the cost of repeated compilation. Compiled Programs ----------------- A slightly higher-level interface is provided by compiled programs. These make it easier to safely safe the results of compilation: .. doctest:: >>> from zope.untrustedpython.interpreter import CompiledProgram >>> p = CompiledProgram('x=2') >>> d = {} >>> p.exec_(d) >>> d['x'] 2 When you execute a compiled program, you can supply an object with a write method to get print output. (Assigning ``printed`` to ``res`` is only done to prevent a ``SyntaxWarning`` of ``RestrictedPython``.) .. doctest:: >>> p = CompiledProgram('print("Hello world!"); res=printed') >>> import io >>> f = io.StringIO() >>> p.exec_({}, output=f) >>> f.getvalue() 'Hello world!\n' Compiled Expressions -------------------- You can also pre-compile expressions: .. doctest:: >>> from zope.untrustedpython.interpreter import CompiledExpression >>> p = CompiledExpression('x*2') >>> p.eval({'x': 2}) 4 Support for Restricted Python Code ================================== This package provides a way to compile untrusted Python code so that it can be executed safely. This form of restricted Python assumes that security proxies will be used to protect assets. Given this, the only thing that actually needs to be done differently by the generated code is to: - Ensure that all attribute lookups go through a safe version of the getattr() function that's been provided in the built-in functions used in the execution environment. - Prevent exec statements. (Later, we could possibly make exec safe.) - Print statements always go to an output that is provided as a global, rather than having an implicit sys.output. - Prevent try/except and raise statements. This is mainly because they don't work properly in the presence of security proxies. Try/except statements will be made to work in the future. No other special treatment is needed to support safe expression evaluation. The implementation makes use of the `RestrictedPython` package, originally written for Zope 2. There is a new AST re-writer in `zope.untrustedpython.transformer` which performs the tree-transformation, and a top-level `compile()` function in `zope.untrustedpython.rcompile`; the later is what client applications are expected to use. The signature of the `compile()` function is very similar to that of Python's built-in `compile()` function:: compile(source, filename, mode) Using it is equally simple: .. doctest:: >>> from zope.untrustedpython.rcompile import compile >>> code = compile("21 * 2", "<string>", "eval") >>> eval(code) 42 What's interesting about the restricted code is that all attribute lookups go through the ``_getattr_`` function. (This is not a typo, the name * actually single underscore getattr single underscore, see https://restrictedpython.readthedocs.io/en/latest/usage/policy.html?highlight=_getattr_#implementing-a-policy for details.) It is generally provided as a built-in function in the restricted environment: .. doctest:: >>> def mygetattr(object, name, default="Yahoo!"): ... marker = [] ... print("Looking up", name) ... if getattr(object, name, marker) is marker: ... return default ... else: ... return "Yeehaw!" >>> import builtins >>> builtins = builtins.__dict__.copy() >>> def reval(source): ... code = compile(source, "README.txt", "eval") ... globals = {"__builtins__": builtins, ... "_getattr_": mygetattr} ... return eval(code, globals, {}) >>> reval("(42).real") Looking up real 'Yeehaw!' >>> reval("(42).not_really_there") Looking up not_really_there 'Yahoo!' >>> reval("(42).foo.not_really_there") Looking up foo Looking up not_really_there 'Yahoo!' This allows a `getattr()` to be used that ensures the result of evaluation is a security proxy. To compile code with statements, use exec or single: .. doctest:: >>> exec(compile("x = 1", "<string>", "exec"), globals()) >>> x 1 Trying to compile exec, raise or try/except statements gives syntax errors: .. doctest:: >>> compile("exec('x = 2')", "<string>", "exec") Traceback (most recent call last): ... SyntaxError: Line 1: exec statements are not supported >>> compile("raise KeyError('x')", "<string>", "exec") Traceback (most recent call last): ... SyntaxError: Line 1: raise statements are not supported >>> compile("try: pass\nexcept: pass", "<string>", "exec") Traceback (most recent call last): ... SyntaxError: Line 1: try/except statements are not supported
zope.untrustedpython
/zope.untrustedpython-5.0.tar.gz/zope.untrustedpython-5.0/docs/narr.rst
narr.rst
=============================== Viewlets and Viewlet Managers =============================== Let's start with some motivation. Using content providers allows us to insert one piece of HTML content. In most Web development, however, you are often interested in defining some sort of region and then allow developers to register content for those regions. >>> from zope.viewlet import interfaces Design Notes ============ As mentioned above, besides inserting snippets of HTML at places, we more frequently want to define a region in our page and allow specialized content providers to be inserted based on configuration. Those specialized content providers are known as viewlets and are only available inside viewlet managers, which are just a more complex example of content providers. Unfortunately, the Java world does not implement this layer separately. The viewlet manager is most similar to a Java "channel", but we decided against using this name, since it is very generic and not very meaningful. The viewlet has no Java counterpart, since Java does not implement content providers using a component architecture and thus does not register content providers specifically for viewlet managers, which I believe makes the Java implementation less useful as a generic concept. In fact, the main design goal in the Java world is the implementation of reusable and shareable portlets. The scope for Zope 3 is larger, since we want to provide a generic framework for building pluggable user interfaces. The Viewlet Manager =================== In this implementation of viewlets, those regions are just :class:`content providers <zope.contentprovider.interfaces.IContentProvider>` called :class:`viewlet managers <zope.viewlet.interfaces.IViewletManager>` that manage a special type of content providers known as :class:`viewlets <zope.viewlet.interfaces.IViewlet>`. Every viewlet manager handles the viewlets registered for it: >>> class ILeftColumn(interfaces.IViewletManager): ... """Viewlet manager located in the left column.""" You can then create :obj:`a viewlet manager <.ViewletManager>` using this interface now: >>> from zope.viewlet import manager >>> LeftColumn = manager.ViewletManager('left', ILeftColumn) Now we have to instantiate it: >>> import zope.interface >>> @zope.interface.implementer(zope.interface.Interface) ... class Content(object): ... pass >>> content = Content() >>> from zope.publisher.browser import TestRequest >>> request = TestRequest() >>> from zope.publisher.interfaces.browser import IBrowserView >>> @zope.interface.implementer(IBrowserView) ... class View(object): ... def __init__(self, context, request): ... pass >>> view = View(content, request) >>> leftColumn = LeftColumn(content, request, view) So initially nothing gets rendered: >>> leftColumn.update() >>> leftColumn.render() '' But now we register some :class:`viewlets <zope.viewlet.interfaces.IViewlet>` for the manager: >>> import zope.component >>> from zope.publisher.interfaces.browser import IDefaultBrowserLayer >>> @zope.interface.implementer(interfaces.IViewlet) ... class WeatherBox(object): ... ... def __init__(self, context, request, view, manager): ... self.__parent__ = view ... ... def update(self): ... pass ... ... def render(self): ... return '<div class="box">It is sunny today!</div>' ... ... def __repr__(self): ... return '<WeatherBox object at %x>' % id(self) >>> # Create a security checker for viewlets. >>> from zope.security.checker import NamesChecker, defineChecker >>> viewletChecker = NamesChecker(('update', 'render')) >>> defineChecker(WeatherBox, viewletChecker) >>> zope.component.provideAdapter( ... WeatherBox, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, ILeftColumn), ... interfaces.IViewlet, name='weather') >>> from zope.location.interfaces import ILocation >>> @zope.interface.implementer(interfaces.IViewlet, ... ILocation) ... class SportBox(object): ... ... def __init__(self, context, request, view, manager): ... self.__parent__ = view ... ... def update(self): ... pass ... ... def render(self): ... return '<div class="box">Patriots (23) : Steelers (7)</div>' >>> defineChecker(SportBox, viewletChecker) >>> zope.component.provideAdapter( ... SportBox, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, ILeftColumn), ... interfaces.IViewlet, name='sport') and thus the left column is filled. Note that also events get fired before viewlets are updated. We register a simple handler to demonstrate this behaviour. >>> from zope.contentprovider.interfaces import IBeforeUpdateEvent >>> events = [] >>> def handler(ev): ... events.append(ev) >>> zope.component.provideHandler(handler, (IBeforeUpdateEvent,)) >>> leftColumn.update() >>> sorted([(ev, ev.object.__class__.__name__) for ev in events], ... key=lambda x: x[1]) [(<zope.contentprovider.interfaces.BeforeUpdateEvent...>, 'SportBox'), (<zope.contentprovider.interfaces.BeforeUpdateEvent...>, 'WeatherBox')] >>> print(leftColumn.render()) <div class="box">Patriots (23) : Steelers (7)</div> <div class="box">It is sunny today!</div> But this is of course pretty lame, since there is no way of specifying how the viewlets are put together. But we have a solution. The second argument of the :obj:`.ViewletManager` function is a template in which we can specify how the viewlets are put together: >>> import os, tempfile >>> temp_dir = tempfile.mkdtemp() >>> leftColTemplate = os.path.join(temp_dir, 'leftCol.pt') >>> with open(leftColTemplate, 'w') as file: ... _ = file.write(''' ... <div class="left-column"> ... <tal:block repeat="viewlet options/viewlets" ... replace="structure viewlet/render" /> ... </div> ... ''') >>> LeftColumn = manager.ViewletManager('left', ILeftColumn, ... template=leftColTemplate) >>> leftColumn = LeftColumn(content, request, view) .. TODO: Fix this silly thing; viewlets should be directly available. As you can see, the viewlet manager provides a global ``options/viewlets`` variable that is an iterable of all the available viewlets in the correct order: >>> leftColumn.update() >>> print(leftColumn.render().strip()) <div class="left-column"> <div class="box">Patriots (23) : Steelers (7)</div> <div class="box">It is sunny today!</div> </div> If a viewlet provides :class:`zope.location.interfaces.ILocation` the ``__name__`` attribute of the viewlet is set to the name under which the viewlet is registered. >>> [getattr(viewlet, '__name__', None) for viewlet in leftColumn.viewlets] ['sport', None] You can also lookup the viewlets directly for management purposes: >>> leftColumn['weather'] <WeatherBox ...> >>> leftColumn.get('weather') <WeatherBox ...> The viewlet manager also provides the ``__contains__`` method defined in :class:`zope.interface.common.mapping.IReadMapping`: >>> 'weather' in leftColumn True >>> 'unknown' in leftColumn False If the viewlet is not found, then the expected behavior is provided: >>> leftColumn['stock'] Traceback (most recent call last): ... ComponentLookupError: No provider with name `stock` found. >>> leftColumn.get('stock') is None True Customizing the default Viewlet Manager ======================================= One important feature of any viewlet manager is to be able to filter and sort the viewlets it is displaying. The default viewlet manager that we have been using in the tests above, supports filtering by access availability and sorting via the viewlet's ``__cmp__()`` method (default). You can easily override this default policy by providing a base viewlet manager class. In our case we will manage the viewlets using a global list: >>> shown = ['weather', 'sport'] The viewlet manager base class now uses this list: >>> class ListViewletManager(object): ... ... def filter(self, viewlets): ... viewlets = super(ListViewletManager, self).filter(viewlets) ... return [(name, viewlet) ... for name, viewlet in viewlets ... if name in shown] ... ... def sort(self, viewlets): ... viewlets = dict(viewlets) ... return [(name, viewlets[name]) for name in shown] Let's now create a new viewlet manager: >>> LeftColumn = manager.ViewletManager( ... 'left', ILeftColumn, bases=(ListViewletManager,), ... template=leftColTemplate) >>> leftColumn = LeftColumn(content, request, view) So we get the weather box first and the sport box second: >>> leftColumn.update() >>> print(leftColumn.render().strip()) <div class="left-column"> <div class="box">It is sunny today!</div> <div class="box">Patriots (23) : Steelers (7)</div> </div> Now let's change the order... >>> shown.reverse() and the order should switch as well: >>> leftColumn.update() >>> print(leftColumn.render().strip()) <div class="left-column"> <div class="box">Patriots (23) : Steelers (7)</div> <div class="box">It is sunny today!</div> </div> Of course, we also can remove a shown viewlet: >>> weather = shown.pop() >>> leftColumn.update() >>> print(leftColumn.render().strip()) <div class="left-column"> <div class="box">Patriots (23) : Steelers (7)</div> </div> WeightOrderedViewletManager =========================== The :class:`weight ordered viewlet manager <.WeightOrderedViewletManager>` offers ordering viewlets by a additional weight argument. Viewlets which doesn't provide a weight attribute will get a weight of 0 (zero). Let's define a new column: >>> class IWeightedColumn(interfaces.IViewletManager): ... """Column with weighted viewlet manager.""" First register a template for the weight ordered viewlet manager: >>> weightedColTemplate = os.path.join(temp_dir, 'weightedColTemplate.pt') >>> with open(weightedColTemplate, 'w') as file: ... _ = file.write(''' ... <div class="weighted-column"> ... <tal:block repeat="viewlet options/viewlets" ... replace="structure viewlet/render" /> ... </div> ... ''') And create a new weight ordered viewlet manager: >>> from zope.viewlet.manager import WeightOrderedViewletManager >>> WeightedColumn = manager.ViewletManager( ... 'left', IWeightedColumn, bases=(WeightOrderedViewletManager,), ... template=weightedColTemplate) >>> weightedColumn = WeightedColumn(content, request, view) Let's create some viewlets: >>> from zope.viewlet import viewlet >>> class FirstViewlet(viewlet.ViewletBase): ... ... weight = 1 ... ... def render(self): ... return '<div>first</div>' >>> class SecondViewlet(viewlet.ViewletBase): ... ... weight = 2 ... ... def render(self): ... return '<div>second</div>' >>> class ThirdViewlet(viewlet.ViewletBase): ... ... weight = 3 ... ... def render(self): ... return '<div>third</div>' >>> class UnWeightedViewlet(viewlet.ViewletBase): ... ... def render(self): ... return '<div>unweighted</div>' >>> defineChecker(FirstViewlet, viewletChecker) >>> defineChecker(SecondViewlet, viewletChecker) >>> defineChecker(ThirdViewlet, viewletChecker) >>> defineChecker(UnWeightedViewlet, viewletChecker) >>> zope.component.provideAdapter( ... ThirdViewlet, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, IWeightedColumn), ... interfaces.IViewlet, name='third') >>> zope.component.provideAdapter( ... FirstViewlet, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, IWeightedColumn), ... interfaces.IViewlet, name='first') >>> zope.component.provideAdapter( ... SecondViewlet, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, IWeightedColumn), ... interfaces.IViewlet, name='second') >>> zope.component.provideAdapter( ... UnWeightedViewlet, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, IWeightedColumn), ... interfaces.IViewlet, name='unweighted') And check the order: >>> weightedColumn.update() >>> print(weightedColumn.render().strip()) <div class="weighted-column"> <div>unweighted</div> <div>first</div> <div>second</div> <div>third</div> </div> ConditionalViewletManager ========================= The :class:`conditional ordered viewlet manager <.ConditionalViewletManager>` offers ordering viewlets by a additional weight argument and filters by the available attribute if a supported by the viewlet. Viewlets which doesn't provide a available attribute will not get skipped. The default weight value for viewlets which doesn't provide a weight attribute is 0 (zero). Let's define a new column: >>> class IConditionalColumn(interfaces.IViewletManager): ... """Column with weighted viewlet manager.""" First register a template for the weight ordered viewlet manager: >>> conditionalColTemplate = os.path.join(temp_dir, ... 'conditionalColTemplate.pt') >>> with open(conditionalColTemplate, 'w') as file: ... _ = file.write(''' ... <div class="conditional-column"> ... <tal:block repeat="viewlet options/viewlets" ... replace="structure viewlet/render" /> ... </div> ... ''') And create a new conditional viewlet manager: >>> from zope.viewlet.manager import ConditionalViewletManager >>> ConditionalColumn = manager.ViewletManager( ... 'left', IConditionalColumn, bases=(ConditionalViewletManager,), ... template=conditionalColTemplate) >>> conditionalColumn = ConditionalColumn(content, request, view) Let's create some viewlets. We also use the previous viewlets supporting no weight and or no available attribute: >>> from zope.viewlet import viewlet >>> class AvailableViewlet(viewlet.ViewletBase): ... ... weight = 4 ... ... available = True ... ... def render(self): ... return '<div>available</div>' >>> class UnAvailableViewlet(viewlet.ViewletBase): ... ... weight = 5 ... ... available = False ... ... def render(self): ... return '<div>not available</div>' >>> defineChecker(AvailableViewlet, viewletChecker) >>> defineChecker(UnAvailableViewlet, viewletChecker) >>> zope.component.provideAdapter( ... ThirdViewlet, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, IConditionalColumn), ... interfaces.IViewlet, name='third') >>> zope.component.provideAdapter( ... FirstViewlet, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, IConditionalColumn), ... interfaces.IViewlet, name='first') >>> zope.component.provideAdapter( ... SecondViewlet, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, IConditionalColumn), ... interfaces.IViewlet, name='second') >>> zope.component.provideAdapter( ... UnWeightedViewlet, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, IConditionalColumn), ... interfaces.IViewlet, name='unweighted') >>> zope.component.provideAdapter( ... AvailableViewlet, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, IConditionalColumn), ... interfaces.IViewlet, name='available') >>> zope.component.provideAdapter( ... UnAvailableViewlet, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, IConditionalColumn), ... interfaces.IViewlet, name='unavailable') And check the order: >>> conditionalColumn.update() >>> print(conditionalColumn.render().strip()) <div class="conditional-column"> <div>unweighted</div> <div>first</div> <div>second</div> <div>third</div> <div>available</div> </div> Viewlet Base Classes ==================== To make the creation of viewlets simpler, a set of useful base classes and helper functions are provided. The first class is :class:`a base class <.ViewletBase>` that simply defines the constructor: >>> base = viewlet.ViewletBase('context', 'request', 'view', 'manager') >>> base.context 'context' >>> base.request 'request' >>> base.__parent__ 'view' >>> base.manager 'manager' But a default ``render()`` method implementation is not provided: >>> base.render() Traceback (most recent call last): ... NotImplementedError: `render` method must be implemented by subclass. If you have already an existing class that produces the HTML content in some method, then :class:`.SimpleAttributeViewlet` might be for you, since it can be used to convert any class quickly into a viewlet: >>> class FooViewlet(viewlet.SimpleAttributeViewlet): ... __page_attribute__ = 'foo' ... ... def foo(self): ... return 'output' The ``__page_attribute__`` attribute provides the name of the function to call for rendering. >>> foo = FooViewlet('context', 'request', 'view', 'manager') >>> foo.foo() 'output' >>> foo.render() 'output' If you specify ``render`` as the attribute an error is raised to prevent infinite recursion: >>> foo.__page_attribute__ = 'render' >>> foo.render() Traceback (most recent call last): ... AttributeError: render The same is true if the specified attribute does not exist: >>> foo.__page_attribute__ = 'bar' >>> foo.render() Traceback (most recent call last): ... AttributeError: 'FooViewlet' object has no attribute 'bar' To create simple template-based viewlets you can use the :func:`.SimpleViewletClass` function. This function is very similar to its view equivalent and is used by the ZCML directives to create viewlets. The result of this function call will be a fully functional viewlet class. Let's start by simply specifying a template only: >>> template = os.path.join(temp_dir, 'demoTemplate.pt') >>> with open(template, 'w') as file: ... _ = file.write('''<div>contents</div>''') >>> Demo = viewlet.SimpleViewletClass(template) >>> print(Demo(content, request, view, manager).render()) <div>contents</div> Now let's additionally specify a class that can provide additional features: >>> class MyViewlet(object): ... myAttribute = 8 >>> Demo = viewlet.SimpleViewletClass(template, bases=(MyViewlet,)) >>> MyViewlet in Demo.__bases__ True >>> Demo(content, request, view, manager).myAttribute 8 The final important feature is the ability to pass in further attributes to the class: >>> Demo = viewlet.SimpleViewletClass( ... template, attributes={'here': 'now', 'lucky': 3}) >>> demo = Demo(content, request, view, manager) >>> demo.here 'now' >>> demo.lucky 3 As for all views, they must provide a name that can also be passed to the function: >>> Demo = viewlet.SimpleViewletClass(template, name='demoViewlet') >>> demo = Demo(content, request, view, manager) >>> demo.__name__ 'demoViewlet' CSS and JavaScript ------------------ In addition to the the generic viewlet code above, the package comes with two viewlet base classes and helper functions for inserting :obj:`CSS <.CSSViewlet>` and :obj:`Javascript links <.JavaScriptViewlet>` into HTML headers, since those two are so very common. I am only going to demonstrate the helper functions here, since those demonstrations will fully demonstrate the functionality of the base classes as well. The viewlet will look up the resource it was given and tries to produce the absolute URL for it: >>> class JSResource(object): ... def __init__(self, request): ... self.request = request ... ... def __call__(self): ... return '/@@/resource.js' >>> zope.component.provideAdapter( ... JSResource, ... (IDefaultBrowserLayer,), ... zope.interface.Interface, name='resource.js') >>> JSViewlet = viewlet.JavaScriptViewlet('resource.js') >>> print(JSViewlet(content, request, view, manager).render().strip()) <script type="text/javascript" src="/@@/resource.js"></script> There is also a :obj:`javascript viewlet base class <.JavaScriptBundleViewlet>` which knows how to render more than one javascript resource file: >>> class JSSecondResource(object): ... def __init__(self, request): ... self.request = request ... ... def __call__(self): ... return '/@@/second-resource.js' >>> zope.component.provideAdapter( ... JSSecondResource, ... (IDefaultBrowserLayer,), ... zope.interface.Interface, name='second-resource.js') >>> JSBundleViewlet = viewlet.JavaScriptBundleViewlet(('resource.js', ... 'second-resource.js')) >>> print(JSBundleViewlet(content, request, view, manager).render().strip()) <script type="text/javascript" src="/@@/resource.js"> </script> <script type="text/javascript" src="/@@/second-resource.js"> </script> The same works for the :obj:`CSS resource viewlet <.CSSViewlet>`: >>> class CSSResource(object): ... def __init__(self, request): ... self.request = request ... ... def __call__(self): ... return '/@@/resource.css' >>> zope.component.provideAdapter( ... CSSResource, ... (IDefaultBrowserLayer,), ... zope.interface.Interface, name='resource.css') >>> CSSViewlet = viewlet.CSSViewlet('resource.css') >>> print(CSSViewlet(content, request, view, manager).render().strip()) <link type="text/css" rel="stylesheet" href="/@@/resource.css" media="all" /> You can also change the media type and the rel attribute: >>> CSSViewlet = viewlet.CSSViewlet('resource.css', media='print', rel='css') >>> print(CSSViewlet(content, request, view, manager).render().strip()) <link type="text/css" rel="css" href="/@@/resource.css" media="print" /> There is also :class:`a bundle viewlet for CSS links <.CSSBundleViewlet>`: >>> class CSSPrintResource(object): ... def __init__(self, request): ... self.request = request ... ... def __call__(self): ... return '/@@/print-resource.css' >>> zope.component.provideAdapter( ... CSSPrintResource, ... (IDefaultBrowserLayer,), ... zope.interface.Interface, name='print-resource.css') >>> items = [] >>> items.append({'path':'resource.css', 'rel':'stylesheet', 'media':'all'}) >>> items.append({'path':'print-resource.css', 'media':'print'}) >>> CSSBundleViewlet = viewlet.CSSBundleViewlet(items) >>> print(CSSBundleViewlet(content, request, view, manager).render().strip()) <link type="text/css" rel="stylesheet" href="/@@/resource.css" media="all" /> <link type="text/css" rel="stylesheet" href="/@@/print-resource.css" media="print" /> A Complex Example ================= The Data -------- So far we have only demonstrated simple (maybe overly trivial) use cases of the viewlet system. In the following example, we are going to develop a generic contents view for files. The step is to create a file component: >>> class IFile(zope.interface.Interface): ... data = zope.interface.Attribute('Data of file.') >>> @zope.interface.implementer(IFile) ... class File(object): ... def __init__(self, data=''): ... self.__name__ = '' ... self.data = data Since we want to also provide the size of a file, here a simple implementation of the ``ISized`` interface: >>> from zope import size >>> @zope.interface.implementer(size.interfaces.ISized) ... @zope.component.adapter(IFile) ... class FileSized(object): ... ... def __init__(self, file): ... self.file = file ... ... def sizeForSorting(self): ... return 'byte', len(self.file.data) ... ... def sizeForDisplay(self): ... return '%i bytes' %len(self.file.data) >>> zope.component.provideAdapter(FileSized) We also need a container to which we can add files: >>> class Container(dict): ... def __setitem__(self, name, value): ... value.__name__ = name ... super(Container, self).__setitem__(name, value) Here is some sample data: >>> container = Container() >>> container['test.txt'] = File('Hello World!') >>> container['mypage.html'] = File('<html><body>Hello World!</body></html>') >>> container['data.xml'] = File('<message>Hello World!</message>') The View -------- The contents view of the container should iterate through the container and represent the files in a table: >>> contentsTemplate = os.path.join(temp_dir, 'contents.pt') >>> with open(contentsTemplate, 'w') as file: ... _ = file.write(''' ... <html> ... <body> ... <h1>Contents</h1> ... <div tal:content="structure provider:contents" /> ... </body> ... </html> ... ''') >>> from zope.browserpage.simpleviewclass import SimpleViewClass >>> Contents = SimpleViewClass(contentsTemplate, name='contents.html') The Viewlet Manager ------------------- Now we have to write our own viewlet manager. In this case we cannot use the default implementation, since the viewlets will be looked up for each different item: >>> shownColumns = [] >>> @zope.interface.implementer(interfaces.IViewletManager) ... class ContentsViewletManager(object): ... index = None ... ... def __init__(self, context, request, view): ... self.context = context ... self.request = request ... self.__parent__ = view ... ... def update(self): ... rows = [] ... for name, value in sorted(self.context.items()): ... rows.append( ... [zope.component.getMultiAdapter( ... (value, self.request, self.__parent__, self), ... interfaces.IViewlet, name=colname) ... for colname in shownColumns]) ... [entry.update() for entry in rows[-1]] ... self.rows = rows ... ... def render(self, *args, **kw): ... return self.index(*args, **kw) Now we need a template to produce the contents table: >>> tableTemplate = os.path.join(temp_dir, 'table.pt') >>> with open(tableTemplate, 'w') as file: ... _ = file.write(''' ... <table> ... <tr tal:repeat="row view/rows"> ... <td tal:repeat="column row"> ... <tal:block replace="structure column/render" /> ... </td> ... </tr> ... </table> ... ''') From the two pieces above, we can generate the final viewlet manager class and register it (it's a bit tedious, I know): >>> from zope.browserpage import ViewPageTemplateFile >>> ContentsViewletManager = type( ... 'ContentsViewletManager', (ContentsViewletManager,), ... {'index': ViewPageTemplateFile(tableTemplate)}) >>> zope.component.provideAdapter( ... ContentsViewletManager, ... (Container, IDefaultBrowserLayer, zope.interface.Interface), ... interfaces.IViewletManager, name='contents') Since we have not defined any viewlets yet, the table is totally empty: >>> contents = Contents(container, request) >>> print(contents().strip()) <html> <body> <h1>Contents</h1> <div> <table> <tr> </tr> <tr> </tr> <tr> </tr> </table> </div> </body> </html> The Viewlets and the Final Result --------------------------------- Now let's create a first viewlet for the manager... >>> class NameViewlet(object): ... ... def __init__(self, context, request, view, manager): ... self.__parent__ = view ... self.context = context ... ... def update(self): ... pass ... ... def render(self): ... return self.context.__name__ and register it: >>> zope.component.provideAdapter( ... NameViewlet, ... (IFile, IDefaultBrowserLayer, ... zope.interface.Interface, interfaces.IViewletManager), ... interfaces.IViewlet, name='name') Note how you register the viewlet on ``IFile`` and not on the container. Now we should be able to see the name for each file in the container: >>> print(contents().strip()) <html> <body> <h1>Contents</h1> <div> <table> <tr> </tr> <tr> </tr> <tr> </tr> </table> </div> </body> </html> Waaa, nothing there! What happened? Well, we have to tell our user preferences that we want to see the name as a column in the table: >>> shownColumns = ['name'] >>> print(contents().strip()) <html> <body> <h1>Contents</h1> <div> <table> <tr> <td> data.xml </td> </tr> <tr> <td> mypage.html </td> </tr> <tr> <td> test.txt </td> </tr> </table> </div> </body> </html> Let's now write a second viewlet that will display the size of the object for us: >>> class SizeViewlet(object): ... ... def __init__(self, context, request, view, manager): ... self.__parent__ = view ... self.context = context ... ... def update(self): ... pass ... ... def render(self): ... return size.interfaces.ISized(self.context).sizeForDisplay() >>> zope.component.provideAdapter( ... SizeViewlet, ... (IFile, IDefaultBrowserLayer, ... zope.interface.Interface, interfaces.IViewletManager), ... interfaces.IViewlet, name='size') After we added it to the list of shown columns, >>> shownColumns = ['name', 'size'] we can see an entry for it: >>> print(contents().strip()) <html> <body> <h1>Contents</h1> <div> <table> <tr> <td> data.xml </td> <td> 31 bytes </td> </tr> <tr> <td> mypage.html </td> <td> 38 bytes </td> </tr> <tr> <td> test.txt </td> <td> 12 bytes </td> </tr> </table> </div> </body> </html> If we switch the two columns around, >>> shownColumns = ['size', 'name'] the result will be >>> print(contents().strip()) <html> <body> <h1>Contents</h1> <div> <table> <tr> <td> 31 bytes </td> <td> data.xml </td> </tr> <tr> <td> 38 bytes </td> <td> mypage.html </td> </tr> <tr> <td> 12 bytes </td> <td> test.txt </td> </tr> </table> </div> </body> </html> Supporting Sorting ------------------ Oftentimes you also want to batch and sort the entries in a table. Since those two features are not part of the view logic, they should be treated with independent components. In this example, we are going to only implement sorting using a simple utility: >>> class ISorter(zope.interface.Interface): ... ... def sort(values): ... """Sort the values.""" >>> @zope.interface.implementer(ISorter) ... class SortByName(object): ... ... def sort(self, values): ... return sorted(values, key=lambda x: x.__name__) >>> zope.component.provideUtility(SortByName(), name='name') >>> @zope.interface.implementer(ISorter) ... class SortBySize(object): ... ... def sort(self, values): ... return sorted( ... values, ... key=lambda x: size.interfaces.ISized(x).sizeForSorting()) >>> zope.component.provideUtility(SortBySize(), name='size') Note that we decided to give the sorter utilities the same name as the corresponding viewlet. This convention will make our implementation of the viewlet manager much simpler: >>> sortByColumn = '' >>> @zope.interface.implementer(interfaces.IViewletManager) ... class SortedContentsViewletManager(object): ... index = None ... ... def __init__(self, context, request, view): ... self.context = context ... self.request = request ... self.__parent__ = view ... ... def update(self): ... values = self.context.values() ... ... if sortByColumn: ... sorter = zope.component.queryUtility(ISorter, sortByColumn) ... if sorter: ... values = sorter.sort(values) ... ... rows = [] ... for value in values: ... rows.append( ... [zope.component.getMultiAdapter( ... (value, self.request, self.__parent__, self), ... interfaces.IViewlet, name=colname) ... for colname in shownColumns]) ... [entry.update() for entry in rows[-1]] ... self.rows = rows ... ... def render(self, *args, **kw): ... return self.index(*args, **kw) As you can see, the concern of sorting is cleanly separated from generating the view code. In MVC terms that means that the controller (sort) is logically separated from the view (viewlets). Let's now do the registration dance for the new viewlet manager. We simply override the existing registration: >>> SortedContentsViewletManager = type( ... 'SortedContentsViewletManager', (SortedContentsViewletManager,), ... {'index': ViewPageTemplateFile(tableTemplate)}) >>> zope.component.provideAdapter( ... SortedContentsViewletManager, ... (Container, IDefaultBrowserLayer, zope.interface.Interface), ... interfaces.IViewletManager, name='contents') Finally we sort the contents by name: >>> shownColumns = ['name', 'size'] >>> sortByColumn = 'name' >>> print(contents().strip()) <html> <body> <h1>Contents</h1> <div> <table> <tr> <td> data.xml </td> <td> 31 bytes </td> </tr> <tr> <td> mypage.html </td> <td> 38 bytes </td> </tr> <tr> <td> test.txt </td> <td> 12 bytes </td> </tr> </table> </div> </body> </html> Now let's sort by size: >>> sortByColumn = 'size' >>> print(contents().strip()) <html> <body> <h1>Contents</h1> <div> <table> <tr> <td> test.txt </td> <td> 12 bytes </td> </tr> <tr> <td> data.xml </td> <td> 31 bytes </td> </tr> <tr> <td> mypage.html </td> <td> 38 bytes </td> </tr> </table> </div> </body> </html> That's it! As you can see, in a few steps we have built a pretty flexible contents view with selectable columns and sorting. However, there is a lot of room for extending this example: - Table Header: The table header cell for each column should be a different type of viewlet, but registered under the same name. The column header viewlet also adapts the container not the item. The header column should also be able to control the sorting. - Batching: A simple implementation of batching should work very similar to the sorting feature. Of course, efficient implementations should somehow combine batching and sorting more effectively. - Sorting in ascending and descending order: Currently, you can only sort from the smallest to the highest value; however, this limitation is almost superficial and can easily be removed by making the sorters a bit more flexible. - Further Columns: For a real application, you would want to implement other columns, of course. You would also probably want some sort of fallback for the case that a viewlet is not found for a particular container item and column. Cleanup ======= >>> import shutil >>> shutil.rmtree(temp_dir)
zope.viewlet
/zope.viewlet-5.0-py3-none-any.whl/zope/viewlet/README.rst
README.rst
================================= Viewlet-related ZCML Directives ================================= The ``viewletManager`` Directive ================================ The ``viewletManager`` directive allows you to quickly register a new viewlet manager without worrying about the details of the ``adapter`` directive. Before we can use the directives, we have to register their handlers by executing the package's meta configuration: >>> from zope.configuration import xmlconfig >>> context = xmlconfig.string(''' ... <configure i18n_domain="zope"> ... <include package="zope.viewlet" file="meta.zcml" /> ... </configure> ... ''') Now we can register a viewlet manager: >>> context = xmlconfig.string(''' ... <configure xmlns="http://namespaces.zope.org/browser" i18n_domain="zope"> ... <viewletManager ... name="defaultmanager" ... permission="zope.Public" ... /> ... </configure> ... ''', context=context) Let's make sure the directive has really issued a sensible adapter registration; to do that, we create some dummy content, request and view objects: >>> import zope.interface >>> @zope.interface.implementer(zope.interface.Interface) ... class Content(object): ... pass >>> content = Content() >>> from zope.publisher.browser import TestRequest >>> request = TestRequest() >>> from zope.publisher.browser import BrowserView >>> view = BrowserView(content, request) Now let's lookup the manager. This particular registration is pretty boring: >>> import zope.component >>> from zope.viewlet import interfaces >>> manager = zope.component.getMultiAdapter( ... (content, request, view), ... interfaces.IViewletManager, name='defaultmanager') >>> manager <zope.viewlet.manager.<ViewletManager providing IViewletManager> object ...> >>> interfaces.IViewletManager.providedBy(manager) True >>> manager.template is None True >>> manager.update() >>> manager.render() '' However, this registration is not very useful, since we did specify a specific viewlet manager interface, a specific content interface, specific view or specific layer. This means that all viewlets registered will be found. The first step to effectively using the viewlet manager directive is to define a special viewlet manager interface: >>> class ILeftColumn(interfaces.IViewletManager): ... """Left column of my page.""" Now we can register register a manager providing this interface: >>> context = xmlconfig.string(''' ... <configure xmlns="http://namespaces.zope.org/browser" i18n_domain="zope"> ... <viewletManager ... name="leftcolumn" ... permission="zope.Public" ... provides="zope.viewlet.directives.ILeftColumn" ... /> ... </configure> ... ''', context=context) >>> manager = zope.component.getMultiAdapter( ... (content, request, view), ILeftColumn, name='leftcolumn') >>> manager <zope.viewlet.manager.<ViewletManager providing ILeftColumn> object ...> >>> ILeftColumn.providedBy(manager) True >>> manager.template is None True >>> manager.update() >>> manager.render() '' Next let's see what happens, if we specify a template for the viewlet manager: >>> import os, tempfile >>> temp_dir = tempfile.mkdtemp() >>> leftColumnTemplate = os.path.join(temp_dir, 'leftcolumn.pt') >>> with open(leftColumnTemplate, 'w') as file: ... _ = file.write(''' ... <div class="column"> ... <div class="entry" ... tal:repeat="viewlet options/viewlets" ... tal:content="structure viewlet" /> ... </div> ... ''') >>> context = xmlconfig.string(''' ... <configure xmlns="http://namespaces.zope.org/browser" i18n_domain="zope"> ... <viewletManager ... name="leftcolumn" ... permission="zope.Public" ... provides="zope.viewlet.directives.ILeftColumn" ... template="%s" ... /> ... </configure> ... ''' %leftColumnTemplate, context=context) >>> manager = zope.component.getMultiAdapter( ... (content, request, view), ILeftColumn, name='leftcolumn') >>> manager <zope.viewlet.manager.<ViewletManager providing ILeftColumn> object ...> >>> ILeftColumn.providedBy(manager) True >>> manager.template <BoundPageTemplateFile of ...<ViewletManager providing ILeftColumn> ...>> >>> manager.update() >>> print(manager.render().strip()) <div class="column"> </div> Additionally you can specify a class that will serve as a base to the default viewlet manager or be a viewlet manager in its own right. In our case we will provide a custom implementation of the ``sort()`` method, which will sort by a weight attribute in the viewlet: >>> class WeightBasedSorting(object): ... def sort(self, viewlets): ... return sorted(viewlets, key=lambda x: getattr(x[1], 'weight', 0)) >>> context = xmlconfig.string(''' ... <configure xmlns="http://namespaces.zope.org/browser" i18n_domain="zope"> ... <viewletManager ... name="leftcolumn" ... permission="zope.Public" ... provides="zope.viewlet.directives.ILeftColumn" ... template="%s" ... class="zope.viewlet.directives.WeightBasedSorting" ... /> ... </configure> ... ''' %leftColumnTemplate, context=context) >>> manager = zope.component.getMultiAdapter( ... (content, request, view), ILeftColumn, name='leftcolumn') >>> manager <zope.viewlet.manager.<ViewletManager providing ILeftColumn> object ...> >>> manager.__class__.__bases__ (<class 'zope.viewlet.directives.WeightBasedSorting'>, <class 'zope.viewlet.manager.ViewletManagerBase'>) >>> ILeftColumn.providedBy(manager) True >>> manager.template <BoundPageTemplateFile of ...<ViewletManager providing ILeftColumn> ...>> >>> manager.update() >>> print(manager.render().strip()) <div class="column"> </div> Finally, if a non-existent template is specified, an error is raised: >>> context = xmlconfig.string(''' ... <configure xmlns="http://namespaces.zope.org/browser" i18n_domain="zope"> ... <viewletManager ... name="leftcolumn" ... permission="zope.Public" ... template="foo.pt" ... /> ... </configure> ... ''', context=context) Traceback (most recent call last): ... ConfigurationError: ('No such file', '...foo.pt') File "<string>", line 3.2-7.8 The ``viewlet`` Directive ========================= Now that we have a viewlet manager, we have to register some viewlets for it. The ``viewlet`` directive is similar to the ``viewletManager`` directive, except that the viewlet is also registered for a particular manager interface, as seen below: >>> weatherTemplate = os.path.join(temp_dir, 'weather.pt') >>> with open(weatherTemplate, 'w') as file: ... _ = file.write(''' ... <div>sunny</div> ... ''') >>> context = xmlconfig.string(''' ... <configure xmlns="http://namespaces.zope.org/browser" i18n_domain="zope"> ... <viewlet ... name="weather" ... manager="zope.viewlet.directives.ILeftColumn" ... template="%s" ... permission="zope.Public" ... extra_string_attributes="can be specified" ... /> ... </configure> ... ''' % weatherTemplate, context=context) If we look into the adapter registry, we will find the viewlet: >>> viewlet = zope.component.getMultiAdapter( ... (content, request, view, manager), interfaces.IViewlet, ... name='weather') >>> viewlet.render().strip() '<div>sunny</div>' >>> viewlet.extra_string_attributes 'can be specified' The manager now also gives us the output of the one and only viewlet: >>> manager.update() >>> print(manager.render().strip()) <div class="column"> <div class="entry"> <div>sunny</div> </div> </div> Let's now ensure that we can also specify a viewlet class: >>> class Weather(object): ... weight = 0 >>> context = xmlconfig.string(''' ... <configure xmlns="http://namespaces.zope.org/browser" i18n_domain="zope"> ... <viewlet ... name="weather2" ... for="*" ... manager="zope.viewlet.directives.ILeftColumn" ... template="%s" ... class="zope.viewlet.directives.Weather" ... permission="zope.Public" ... /> ... </configure> ... ''' % weatherTemplate, context=context) >>> viewlet = zope.component.getMultiAdapter( ... (content, request, view, manager), interfaces.IViewlet, ... name='weather2') >>> viewlet().strip() '<div>sunny</div>' Okay, so the template-driven cases work. But just specifying a class should also work: >>> class Sport(object): ... weight = 0 ... def __call__(self): ... return 'Red Sox vs. White Sox' >>> context = xmlconfig.string(''' ... <configure xmlns="http://namespaces.zope.org/browser" i18n_domain="zope"> ... <viewlet ... name="sport" ... for="*" ... manager="zope.viewlet.directives.ILeftColumn" ... class="zope.viewlet.directives.Sport" ... permission="zope.Public" ... /> ... </configure> ... ''', context=context) >>> viewlet = zope.component.getMultiAdapter( ... (content, request, view, manager), interfaces.IViewlet, name='sport') >>> viewlet() 'Red Sox vs. White Sox' It should also be possible to specify an alternative attribute of the class to be rendered upon calling the viewlet: >>> class Stock(object): ... weight = 0 ... def getStockTicker(self): ... return 'SRC $5.19' >>> context = xmlconfig.string(''' ... <configure xmlns="http://namespaces.zope.org/browser" i18n_domain="zope"> ... <viewlet ... name="stock" ... for="*" ... manager="zope.viewlet.directives.ILeftColumn" ... class="zope.viewlet.directives.Stock" ... attribute="getStockTicker" ... permission="zope.Public" ... /> ... </configure> ... ''', context=context) >>> viewlet = zope.component.getMultiAdapter( ... (content, request, view, manager), interfaces.IViewlet, ... name='stock') >>> viewlet.render() 'SRC $5.19' If the class mentions that it implements any interfaces using the old-fashioned style, the resulting viewlet will implement ``IBrowserPublisher``: >>> from zope.publisher.interfaces.browser import IBrowserPublisher >>> from zope.interface import classImplements >>> Stock.__implements__ = () >>> context = xmlconfig.string(''' ... <configure xmlns="http://namespaces.zope.org/browser" i18n_domain="zope"> ... <viewlet ... name="stock" ... for="*" ... manager="zope.viewlet.directives.ILeftColumn" ... class="zope.viewlet.directives.Stock" ... attribute="getStockTicker" ... permission="zope.Public" ... /> ... </configure> ... ''', context=context) >>> viewlet = zope.component.getMultiAdapter( ... (content, request, view, manager), interfaces.IViewlet, ... name='stock') >>> IBrowserPublisher.providedBy(viewlet) True A final feature the ``viewlet`` directive is that it supports the specification of any number of keyword arguments: >>> context = xmlconfig.string(''' ... <configure xmlns="http://namespaces.zope.org/browser" i18n_domain="zope"> ... <viewlet ... name="stock2" ... permission="zope.Public" ... class="zope.viewlet.directives.Stock" ... weight="8" ... /> ... </configure> ... ''', context=context) >>> viewlet = zope.component.getMultiAdapter( ... (content, request, view, manager), interfaces.IViewlet, ... name='stock2') >>> viewlet.weight '8' Error Scenarios --------------- Neither the class or template have been specified: >>> context = xmlconfig.string(''' ... <configure xmlns="http://namespaces.zope.org/browser" i18n_domain="zope"> ... <viewlet ... name="testviewlet" ... manager="zope.viewlet.directives.ILeftColumn" ... permission="zope.Public" ... /> ... </configure> ... ''', context=context) Traceback (most recent call last): ... ConfigurationError: Must specify a class or template File "<string>", line 3.2-7.8 The specified attribute is not ``__call__``, but also a template has been specified: >>> context = xmlconfig.string(''' ... <configure xmlns="http://namespaces.zope.org/browser" i18n_domain="zope"> ... <viewlet ... name="testviewlet" ... manager="zope.viewlet.directives.ILeftColumn" ... template="test_viewlet.pt" ... attribute="faux" ... permission="zope.Public" ... /> ... </configure> ... ''', context=context) Traceback (most recent call last): ... ConfigurationError: Attribute and template cannot be used together. File "<string>", line 3.2-9.8 Now, we are not specifying a template, but a class that does not have the specified attribute: >>> context = xmlconfig.string(''' ... <configure xmlns="http://namespaces.zope.org/browser" i18n_domain="zope"> ... <viewlet ... name="testviewlet" ... manager="zope.viewlet.directives.ILeftColumn" ... class="zope.viewlet.directives.Sport" ... attribute="faux" ... permission="zope.Public" ... /> ... </configure> ... ''', context=context) Traceback (most recent call last): ... ConfigurationError: The provided class doesn't have the specified attribute File "<string>", line 3.2-9.8 Now for a template that doesn't exist: >>> context = xmlconfig.string(''' ... <configure xmlns="http://namespaces.zope.org/browser" i18n_domain="zope"> ... <viewlet ... name="weather2" ... for="*" ... manager="zope.viewlet.directives.ILeftColumn" ... template="this template is not here" ... class="zope.viewlet.directives.Weather" ... permission="zope.Public" ... /> ... </configure> ... ''', context=context) Traceback (most recent call last): ... ConfigurationError: ('No such file', '...this template is not here') File "<string>", line 3.2-10.8 Cleanup ------- >>> import shutil >>> shutil.rmtree(temp_dir)
zope.viewlet
/zope.viewlet-5.0-py3-none-any.whl/zope/viewlet/directives.rst
directives.rst
============================================== A technique for communication between viewlets ============================================== Sometimes one wants viewlets to communicate with each other to supplement a more generic viewlet's behaviour with another viewlet. One example would be a viewlet that contains a search form created by a library such as z3c.form, plus a second viewlet that provides a list of search results. This is very simple to accomplish with zope.viewlet but has turned out not to be obvious, so here is an explicit example. It is not written as a doc test since it uses z3c.form which should not become a dependency of zope.viewlet. The viewlets ============ For the purpose of this example, we simulate a search form. Our search results are simply the characters of the search term and are stored on the viewlet as an attribute:: class ISearchForm(zope.interface.Interface): searchterm = zope.schema.TextLine(title=u"Search term") class SearchForm(z3c.form.form.Form): ignoreContext = True fields = z3c.form.field.Fields(ISearchForm) results = "" @z3c.form.button.buttonAndHandler(u"Search") def search(self, action): data, errors = self.extractData() self.results = list(data["searchterm"]) (Notice that this example is minimized to point out communication between viewlets, and no care is taken to handle the form itself in the best way possible. In particular, one will probably want to make sure that the actual search is not performed more than once, which may happen with the above code.) The result list viewlet needs to display the results stored on the search form. Therefore, the result list viewlet needs to access that viewlet, which is probably the only tricky part (if there is any at all) in this example: Since viewlets know their viewlet manager which lets viewlets be looked up by ID, it is all a matter of the result list viewlet knowing the ID of the search form. We'll store the search form viewlet's ID as an attribute of the result list viewlet. Let's hard-code the ID for a start, then the result list looks like this:: class ResultList(zope.viewlet.viewlet.ViewletBase): searchform_id = "searchform" def update(self): super(ResultList, self).update() searchform = self.manager[self.searchform_id] searchform.update() self.results = searchform.results def render(self): return "<ul>%s</ul>" % "\n".join(u"<li>%s</li>" % x for x in self.results) Registering the viewlets ======================== As long as we treat the ID of the search form as hard-coded, we have to use the correct name when registering the two viewlets: .. code-block:: xml <viewlet name="searchform" class="...SearchForm" permission="zope.Public" /> <viewlet name="resultlist" class="...ResultList" permission="zope.Public" /> Making the ID of the search form more flexible now doesn't even require changing any code: the viewlet directive may be passed arbitrary attributes which will be available as attributes of the ResultList objects. The attribute that holds our search form's ID is searchform_id, so we might register the viewlets like this: .. code-block:: xml <viewlet name="sitesearch" class="...SearchForm" permission="zope.Public" /> <viewlet name="resultlist" class="...ResultList" permission="zope.Public" searchform_id="sitesearch" />
zope.viewlet
/zope.viewlet-5.0-py3-none-any.whl/zope/viewlet/communicating-viewlets.rst
communicating-viewlets.rst
__docformat__ = 'restructuredtext' import os import sys import zope.interface from zope.browserpage import ViewPageTemplateFile from zope.browserpage import simpleviewclass from zope.publisher.browser import BrowserView from zope.traversing import api from zope.viewlet import interfaces @zope.interface.implementer(interfaces.IViewlet) class ViewletBase(BrowserView): """Viewlet adapter class used in meta directive as a mixin class.""" def __init__(self, context, request, view, manager): super().__init__(context, request) self.__parent__ = view self.context = context self.request = request self.manager = manager def update(self): pass def render(self): raise NotImplementedError( '`render` method must be implemented by subclass.') class SimpleAttributeViewlet(ViewletBase): """ A viewlet that uses a method named in :attr:`__page_attribute__` to produce its content. """ #: The name of the attribute of this object that will be used #: in `render` to produce our content. Must not be set to ``"render"``. __page_attribute__ = None def render(self, *args, **kw): # If a class doesn't provide it's own call, then get the attribute # given by the browser default. attr = self.__page_attribute__ if attr == 'render': raise AttributeError("render") meth = getattr(self, attr) return meth(*args, **kw) class simple(simpleviewclass.simple): """Simple viewlet class supporting the ``render()`` method.""" render = simpleviewclass.simple.__call__ def SimpleViewletClass(template, offering=None, bases=(), attributes=None, name=''): """A function that can be used to generate a viewlet from a set of information. """ # Get the current frame if offering is None: offering = sys._getframe(1).f_globals # Create the base class hierarchy bases += (simple, ViewletBase) attrs = {'index': ViewPageTemplateFile(template, offering), '__name__': name} if attributes: attrs.update(attributes) # Generate a derived view class. class_ = type("SimpleViewletClass from %s" % template, bases, attrs) return class_ class ResourceViewletBase: """A simple viewlet for inserting references to resources. This is an abstract class that is expected to be used as a base only. """ _path = None def getURL(self): """ Retrieve the resource for our path using the :class:`++resource++ namespace <zope.traversing.namespace.resource>` and call it, returning the results. Commonly, the found resource will be an :class:`zope.browserresource.interfaces.IResource`, which, when called, will adapt itself to :class:`zope.traversing.browser.interfaces.IAbsoluteURL` and return the string value of the absolute URL. """ resource = api.traverse(self.context, '++resource++' + self._path, request=self.request) return resource() def render(self, *args, **kw): return self.index(*args, **kw) def JavaScriptViewlet(path): """Create a viewlet that can simply insert a javascript link.""" src = os.path.join(os.path.dirname(__file__), 'javascript_viewlet.pt') klass = type('JavaScriptViewlet', (ResourceViewletBase, ViewletBase), {'index': ViewPageTemplateFile(src), '_path': path}) return klass class CSSResourceViewletBase(ResourceViewletBase): _media = 'all' _rel = 'stylesheet' def getMedia(self): return self._media def getRel(self): return self._rel def CSSViewlet(path, media="all", rel="stylesheet"): """Create a viewlet that can simply insert a CSS link.""" src = os.path.join(os.path.dirname(__file__), 'css_viewlet.pt') klass = type('CSSViewlet', (CSSResourceViewletBase, ViewletBase), {'index': ViewPageTemplateFile(src), '_path': path, '_media': media, '_rel': rel}) return klass class ResourceBundleViewletBase: """A simple viewlet for inserting references to different resources. This is an abstract class that is expected to be used as a base only. """ _paths = None #: A callable (usually a template) that is used to implement #: the `render` method. index = None def getResources(self): """ Retrieve all the resources in our desired paths using the :class:`++resource++ namespace <zope.traversing.namespace.resource>` """ resources = [] append = resources.append for path in self._paths: append(api.traverse(self.context, '++resource++' + path, request=self.request)) return resources def render(self, *args, **kw): return self.index(*args, **kw) def JavaScriptBundleViewlet(paths): """Create a viewlet that can simply insert javascript links.""" src = os.path.join( os.path.dirname(__file__), 'javascript_bundle_viewlet.pt') klass = type('JavaScriptBundleViewlet', (ResourceBundleViewletBase, ViewletBase), {'index': ViewPageTemplateFile(src), '_paths': paths}) return klass class CSSResourceBundleViewletBase: """A simple viewlet for inserting css references to different resources. There is a sequence of dict used for the different resource descriptions. The sequence uses the following format: ({path:'the path', media:'all', rel:'stylesheet'},...) The default values for media is ``all`` and the default value for rel is ``stylesheet``. The path must be set there is no default value for the path attribute. This is an abstract class that is expected to be used as a base only. """ _items = None def getResources(self): """ Retrieve all the resources for our desired items' paths using the :class:`++resource++ namespace <zope.traversing.namespace.resource>` and return a list of dictionaries. The dictionaries are like those passed to the constructor with the defaults filled in, except that ``path`` has been replaced with ``url``. The ``url`` object is as described for `ResourceViewletBase.getURL`. """ resources = [] append = resources.append for item in self._items: info = {} info['url'] = api.traverse(self.context, '++resource++' + item.get('path'), request=self.request) info['media'] = item.get('media', 'all') info['rel'] = item.get('rel', 'stylesheet') append(info) return resources def render(self, *args, **kw): return self.index(*args, **kw) def CSSBundleViewlet(items): """ Create a viewlet that can simply insert css links. :param items: A sequence of dictionaries as described in `CSSResourceBundleViewletBase`. """ src = os.path.join(os.path.dirname(__file__), 'css_bundle_viewlet.pt') klass = type('CSSBundleViewlet', (CSSResourceBundleViewletBase, ViewletBase), {'index': ViewPageTemplateFile(src), '_items': items}) return klass
zope.viewlet
/zope.viewlet-5.0-py3-none-any.whl/zope/viewlet/viewlet.py
viewlet.py
"""Viewlet metadirective """ from zope.viewlet import interfaces __docformat__ = 'restructuredtext' import zope.configuration.fields import zope.schema from zope.i18nmessageid import MessageFactory from zope.interface import Interface from zope.publisher.interfaces import browser from zope.security.zcml import Permission _ = MessageFactory('zope') class IContentProvider(Interface): """A directive to register a simple content provider. Content providers are registered by their context (`for` attribute), the request (`layer` attribute) and the view (`view` attribute). They also must provide a name, so that they can be found using the TALES ``provider`` namespace. Other than that, content providers are just like any other views. """ view = zope.configuration.fields.GlobalObject( title=_("The view the content provider is registered for."), description=_("The view can either be an interface or a class. By " "default the provider is registered for all views, " "the most common case."), required=False, default=browser.IBrowserView) name = zope.schema.TextLine( title=_("The name of the content provider."), description=_("The name of the content provider is used in the TALES " "``provider`` namespace to look up the content " "provider."), required=True) for_ = zope.configuration.fields.GlobalObject( title="The interface or class this view is for.", required=False ) permission = Permission( title="Permission", description="The permission needed to use the view.", required=True ) class_ = zope.configuration.fields.GlobalObject( title=_("Class"), description=_("A class that provides attributes used by the view."), required=False, ) layer = zope.configuration.fields.GlobalInterface( title=_("The layer the view is in."), description=_(""" A skin is composed of layers. It is common to put skin specific views in a layer named after the skin. If the 'layer' attribute is not supplied, it defaults to 'default'."""), required=False, ) allowed_interface = zope.configuration.fields.Tokens( title=_("Interface that is also allowed if user has permission."), description=_(""" By default, 'permission' only applies to viewing the view and any possible sub views. By specifying this attribute, you can make the permission also apply to everything described in the supplied interface. Multiple interfaces can be provided, separated by whitespace."""), required=False, value_type=zope.configuration.fields.GlobalInterface(), ) allowed_attributes = zope.configuration.fields.Tokens( title=_("View attributes that are also allowed if the user" " has permission."), description=_(""" By default, 'permission' only applies to viewing the view and any possible sub views. By specifying 'allowed_attributes', you can make the permission also apply to the extra attributes on the view object."""), required=False, value_type=zope.configuration.fields.PythonIdentifier(), ) class ITemplatedContentProvider(IContentProvider): """A directive for registering a content provider that uses a page template to provide its content.""" template = zope.configuration.fields.Path( title=_("Content-generating template."), description=_("Refers to a file containing a page template (should " "end in extension ``.pt`` or ``.html``)."), required=False) class IViewletManagerDirective(ITemplatedContentProvider): """A directive to register a new viewlet manager. Viewlet manager registrations are very similar to content provider registrations, since they are just a simple extension of content providers. However, viewlet managers commonly have a specific provided interface, which is used to discriminate the viewlets they are providing. """ provides = zope.configuration.fields.GlobalInterface( title=_("The interface this viewlet manager provides."), description=_("A viewlet manager can provide an interface, which " "is used to lookup its contained viewlets."), required=False, default=interfaces.IViewletManager, ) class IViewletDirective(ITemplatedContentProvider): """A directive to register a new viewlet. Viewlets are content providers that can only be displayed inside a viewlet manager. Thus they are additionally discriminated by the manager. Viewlets can rely on the specified viewlet manager interface to provide their content. The viewlet directive also supports an undefined set of keyword arguments that are set as attributes on the viewlet after creation. Those attributes can then be used to implement sorting and filtering, for example. """ manager = zope.configuration.fields.GlobalObject( title=_("view"), description="The interface of the view this viewlet is for. " "(default IBrowserView)", required=False, default=interfaces.IViewletManager) # Arbitrary keys and values are allowed to be passed to the viewlet. IViewletDirective.setTaggedValue('keyword_arguments', True)
zope.viewlet
/zope.viewlet-5.0-py3-none-any.whl/zope/viewlet/metadirectives.py
metadirectives.py
"""Content Provider Manager implementation """ __docformat__ = 'restructuredtext' import zope.component import zope.event import zope.interface import zope.security from zope.browserpage import ViewPageTemplateFile from zope.contentprovider.interfaces import BeforeUpdateEvent from zope.location.interfaces import ILocation from zope.viewlet import interfaces @zope.interface.implementer(interfaces.IViewletManager) class ViewletManagerBase: """The Viewlet Manager Base A generic manager class which can be instantiated. """ #: A callable that will be used by `render`, if present, #: to produce the output. It will be passed the list of viewlets #: in the *viewlets* keyword argument. template = None #: A list of active viewlets for the current manager. #: Populated by `update`. viewlets = None def __init__(self, context, request, view): self.__updated = False self.__parent__ = view self.context = context self.request = request def __getitem__(self, name): """ Return a viewlet for this object having the given name. This takes into account security. """ # Find the viewlet viewlet = zope.component.queryMultiAdapter( (self.context, self.request, self.__parent__, self), interfaces.IViewlet, name=name) # If the viewlet was not found, then raise a lookup error if viewlet is None: raise zope.interface.interfaces.ComponentLookupError( 'No provider with name `%s` found.' % name) # If the viewlet cannot be accessed, then raise an # unauthorized error if not zope.security.canAccess(viewlet, 'render'): raise zope.security.interfaces.Unauthorized( 'You are not authorized to access the provider ' 'called `%s`.' % name) # Return the viewlet. return viewlet def get(self, name, default=None): """ Return a viewlet registered for this object having the given name. This takes into account security. If no such viewlet can be found, returns *default*. """ try: return self[name] except (zope.interface.interfaces.ComponentLookupError, zope.security.interfaces.Unauthorized): return default def __contains__(self, name): """See zope.interface.common.mapping.IReadMapping""" return bool(self.get(name, False)) def filter(self, viewlets): """ Filter *viewlets* down from all available viewlets to just the currently desired set. :param list viewlets: a list of tuples of the form ``(name, viewlet)``. :return: A list of the available viewlets in the form ``(name, viewlet)``. By default, this method checks with `zope.security.checker.canAccess` to see if the ``render`` method of a viewlet can be used to determine availability. """ # Only return viewlets accessible to the principal return [(name, viewlet) for name, viewlet in viewlets if zope.security.canAccess(viewlet, 'render')] def sort(self, viewlets): """Sort the viewlets. ``viewlets`` is a list of tuples of the form (name, viewlet). """ # By default, we are not sorting by viewlet name. return sorted(viewlets, key=lambda x: x[0]) def update(self): """ Update the viewlet manager for rendering. This method is part of the protocol of a content provider, called before :meth:`render`. This implementation will use it to: 1. Find the total set of available viewlets by querying for viewlet adapters. 2. Filter the total set down to the active set by using :meth:`filter`. 3. Sort the active set using :meth:`sort`. 4. Provide viewlets that implement :class:`~zope.location.interfaces.ILocation` with a name. 5. Set :attr:`viewlets` to the found set of active viewlets. 6. Fire :class:`.BeforeUpdateEvent` for each active viewlet before calling ``update()`` on it. .. seealso:: :class:`zope.contentprovider.interfaces.IContentProvider` """ self.__updated = True # Find all content providers for the region viewlets = zope.component.getAdapters( (self.context, self.request, self.__parent__, self), interfaces.IViewlet) viewlets = self.filter(viewlets) viewlets = self.sort(viewlets) # Just use the viewlets from now on self.viewlets = [] for name, viewlet in viewlets: if ILocation.providedBy(viewlet): viewlet.__name__ = name self.viewlets.append(viewlet) self._updateViewlets() def _updateViewlets(self): """Calls update on all viewlets and fires events""" for viewlet in self.viewlets: zope.event.notify(BeforeUpdateEvent(viewlet, self.request)) viewlet.update() def render(self): """ Render the active viewlets. If a :attr:`template` has been provided, call the template to render. Otherwise, call each viewlet in order to render. .. note:: If a :attr:`template` is provided, it will be called even if there are no :attr:`viewlets`. .. seealso:: :class:`zope.contentprovider.interfaces.IContentProvider` """ # Now render the view if self.template: return self.template(viewlets=self.viewlets) return '\n'.join([viewlet.render() for viewlet in self.viewlets]) def ViewletManager(name, interface, template=None, bases=()): """ Create and return a new viewlet manager class that implements :class:`zope.viewlet.interfaces.IViewletManager`. :param str name: The name of the generated class. :param interface: The additional interface the class will implement. :keyword tuple bases: The base classes to extend. """ attrDict = {'__name__': name} if template is not None: attrDict['template'] = ViewPageTemplateFile(template) if ViewletManagerBase not in bases: # Make sure that we do not get a default viewlet manager mixin, if the # provided base is already a full viewlet manager implementation. if not (len(bases) == 1 and interfaces.IViewletManager.implementedBy(bases[0])): bases = bases + (ViewletManagerBase,) ViewletManagerCls = type( '<ViewletManager providing %s>' % interface.getName(), bases, attrDict) zope.interface.classImplements(ViewletManagerCls, interface) return ViewletManagerCls def getWeight(item): _name, viewlet = item try: return int(viewlet.weight) except AttributeError: return 0 class WeightOrderedViewletManager(ViewletManagerBase): """Weight ordered viewlet managers.""" def sort(self, viewlets): """ Sort the viewlets based on their ``weight`` attribute (if present; viewlets without a ``weight`` are sorted at the beginning but are otherwise unordered). """ return sorted(viewlets, key=getWeight) def render(self): """ Just like :meth:`ViewletManagerBase`, except that if there are no active viewlets in :attr:`viewlets`, we will not attempt to render the template. """ # do not render a manager template if no viewlets are avaiable if not self.viewlets: return '' return ViewletManagerBase.render(self) def isAvailable(viewlet): try: return zope.security.canAccess(viewlet, 'render') and viewlet.available except AttributeError: return True class ConditionalViewletManager(WeightOrderedViewletManager): """Conditional weight ordered viewlet managers.""" def filter(self, viewlets): """ Sort out all viewlets which are explicity not available based on the value of their ``available`` attribute (viewlets without this attribute are considered available). """ return [(name, viewlet) for name, viewlet in viewlets if isAvailable(viewlet)]
zope.viewlet
/zope.viewlet-5.0-py3-none-any.whl/zope/viewlet/manager.py
manager.py
"""Viewlet metadconfigure """ import os from zope.component import zcml from zope.component.interface import provideInterface from zope.configuration.exceptions import ConfigurationError from zope.interface import Interface from zope.interface import classImplements from zope.publisher.interfaces.browser import IBrowserPublisher from zope.publisher.interfaces.browser import IBrowserView from zope.publisher.interfaces.browser import IDefaultBrowserLayer from zope.security import checker from zope.viewlet import interfaces from zope.viewlet import manager from zope.viewlet import viewlet def viewletManagerDirective( _context, name, permission, for_=Interface, layer=IDefaultBrowserLayer, view=IBrowserView, provides=interfaces.IViewletManager, class_=None, template=None, allowed_interface=None, allowed_attributes=None): # A list of attributes available under the provided permission required = {} # Get the permission; mainly to correctly handle CheckerPublic. permission = _handle_permission(_context, permission) # If class is not given we use the basic viewlet manager. if class_ is None: class_ = manager.ViewletManagerBase # Make sure that the template exists and that all low-level API methods # have the right permission. if template: template = os.path.abspath(str(_context.path(template))) if not os.path.isfile(template): raise ConfigurationError("No such file", template) required['__getitem__'] = permission # Create a new class based on the template and class. new_class = manager.ViewletManager( name, provides, template=template, bases=(class_, )) else: # Create a new class based on the class. new_class = manager.ViewletManager(name, provides, bases=(class_, )) # Register some generic attributes with the security dictionary for attr_name in ('browserDefault', 'update', 'render', 'publishTraverse'): required[attr_name] = permission # Register the ``provides`` interface and register fields in the security # dictionary _handle_allowed_interface( _context, (provides,), permission, required) # Register the allowed interface and add the field's security entries _handle_allowed_interface( _context, allowed_interface, permission, required) # Register single allowed attributes in the security dictionary _handle_allowed_attributes( _context, allowed_attributes, permission, required) # Register interfaces _handle_for(_context, for_) zcml.interface(_context, view) # Create a checker for the viewlet manager checker.defineChecker(new_class, checker.Checker(required)) # register a viewlet manager _context.action( discriminator=('viewletManager', for_, layer, view, name), callable=zcml.handler, args=('registerAdapter', new_class, (for_, layer, view), provides, name, _context.info),) def viewletDirective( _context, name, permission, for_=Interface, layer=IDefaultBrowserLayer, view=IBrowserView, manager=interfaces.IViewletManager, class_=None, template=None, attribute='render', allowed_interface=None, allowed_attributes=None, **kwargs): # Security map dictionary required = {} # Get the permission; mainly to correctly handle CheckerPublic. permission = _handle_permission(_context, permission) # Either the class or template must be specified. if not (class_ or template): raise ConfigurationError("Must specify a class or template") # Make sure that all the non-default attribute specifications are correct. if attribute != 'render': if template: raise ConfigurationError( "Attribute and template cannot be used together.") # Note: The previous logic forbids this condition from occurring. assert class_, "A class must be provided if attribute is used" # Make sure that the template exists and that all low-level API methods # have the right permission. if template: template = os.path.abspath(str(_context.path(template))) if not os.path.isfile(template): raise ConfigurationError("No such file", template) required['__getitem__'] = permission # Make sure the has the right form, if specified. if class_: if attribute != 'render': if not hasattr(class_, attribute): raise ConfigurationError( "The provided class doesn't have the specified attribute " ) if template: # Create a new class for the viewlet template and class. new_class = viewlet.SimpleViewletClass( template, bases=(class_, ), attributes=kwargs, name=name) else: cdict = {} if not hasattr(class_, 'browserDefault'): cdict = { 'browserDefault': lambda self, request: ( getattr(self, attribute), ()) } cdict['__name__'] = name cdict['__page_attribute__'] = attribute cdict.update(kwargs) new_class = type(class_.__name__, (class_, viewlet.SimpleAttributeViewlet), cdict) if hasattr(class_, '__implements__'): classImplements(new_class, IBrowserPublisher) else: # Create a new class for the viewlet template alone. new_class = viewlet.SimpleViewletClass(template, name=name, attributes=kwargs) # Set up permission mapping for various accessible attributes _handle_allowed_interface( _context, allowed_interface, permission, required) _handle_allowed_attributes( _context, allowed_attributes, permission, required) _handle_allowed_attributes( _context, kwargs.keys(), permission, required) _handle_allowed_attributes( _context, (attribute, 'browserDefault', 'update', 'render', 'publishTraverse'), permission, required) # Register the interfaces. _handle_for(_context, for_) zcml.interface(_context, view) # Create the security checker for the new class checker.defineChecker(new_class, checker.Checker(required)) # register viewlet _context.action( discriminator=('viewlet', for_, layer, view, manager, name), callable=zcml.handler, args=('registerAdapter', new_class, (for_, layer, view, manager), interfaces.IViewlet, name, _context.info),) def _handle_permission(_context, permission): if permission == 'zope.Public': permission = checker.CheckerPublic return permission def _handle_allowed_interface(_context, allowed_interface, permission, required): # Allow access for all names defined by named interfaces if allowed_interface: for i in allowed_interface: _context.action( discriminator=None, callable=provideInterface, args=(None, i) ) for name in i: required[name] = permission def _handle_allowed_attributes(_context, allowed_attributes, permission, required): # Allow access for all named attributes if allowed_attributes: for name in allowed_attributes: required[name] = permission def _handle_for(_context, for_): if for_ is not None: _context.action( discriminator=None, callable=provideInterface, args=('', for_) )
zope.viewlet
/zope.viewlet-5.0-py3-none-any.whl/zope/viewlet/metaconfigure.py
metaconfigure.py
========= CHANGES ========= 1.2.0 (2021-11-26) ================== - Add support for Python 3.8, 3.9, and 3.10. 1.1.1 (2018-12-03) ================== - Important bugfix for the new feature introduced in 1.1.0: Fall back to active site manager if no local site manager can be looked up for provided context. 1.1.0 (2018-11-30) ================== - Ensure that a context is provided when looking up the vocabulary factory. - Drop support for Python 2.6 and 3.3. - Add support for Python 3.5, 3.6, 3.7, PyPy and PyPy3. 1.0.0 (2013-03-01) ================== - Added support for Python 3.3. - Replaced deprecated ``zope.interface.implements`` usage with equivalent ``zope.interface.implementer`` decorator. - Dropped support for Python 2.4 and 2.5. - Initial release independent of ``zope.app.schema``.
zope.vocabularyregistry
/zope.vocabularyregistry-1.2.0.tar.gz/zope.vocabularyregistry-1.2.0/CHANGES.rst
CHANGES.rst
========================= zope.vocabularyregistry ========================= .. image:: https://img.shields.io/pypi/v/zope.vocabularyregistry.svg :target: https://pypi.python.org/pypi/zope.vocabularyregistry/ :alt: Latest release .. image:: https://img.shields.io/pypi/pyversions/zope.vocabularyregistry.svg :target: https://pypi.org/project/zope.vocabularyregistry/ :alt: Supported Python versions .. image:: https://github.com/zopefoundation/zope.vocabularyregistry/actions/workflows/tests.yml/badge.svg :target: https://github.com/zopefoundation/zope.vocabularyregistry/actions/workflows/tests.yml .. image:: https://coveralls.io/repos/github/zopefoundation/zope.vocabularyregistry/badge.svg?branch=master :target: https://coveralls.io/github/zopefoundation/zope.vocabularyregistry?branch=master This Zope 3 package provides a ``zope.schema`` vocabulary registry that uses utilities to look up vocabularies.
zope.vocabularyregistry
/zope.vocabularyregistry-1.2.0.tar.gz/zope.vocabularyregistry-1.2.0/README.rst
README.rst
===================================== Component-based Vocabulary Registry ===================================== This package provides a vocabulary registry for zope.schema, based on the component architecture. It replaces the zope.schema's simple vocabulary registry when ``zope.vocabularyregistry`` package is imported, so it's done automatically. All we need is provide vocabulary factory utilities: >>> import zope.vocabularyregistry >>> from zope.component import provideUtility >>> from zope.schema.interfaces import IVocabularyFactory >>> from zope.schema.vocabulary import SimpleTerm >>> from zope.schema.vocabulary import SimpleVocabulary >>> def makeVocabularyFactory(*values): ... def vocabularyFactory(context=None): ... terms = [SimpleTerm(v) for v in values] ... return SimpleVocabulary(terms) ... return vocabularyFactory >>> zope.component.provideUtility( ... makeVocabularyFactory(1, 2), IVocabularyFactory, ... name='SomeVocabulary') Now we can get the vocabulary using standard zope.schema way: >>> from zope.schema.vocabulary import getVocabularyRegistry >>> vr = getVocabularyRegistry() >>> voc = vr.get(None, 'SomeVocabulary') >>> [term.value for term in voc] [1, 2] If vocabulary is not found, VocabularyRegistryError is raised. >>> try: ... vr.get(None, 'NotAvailable') ... except LookupError as error: ... print("%s.%s: %s" % (error.__module__, error.__class__.__name__, error)) zope.schema.vocabulary.VocabularyRegistryError: unknown vocabulary: 'NotAvailable' We can also use vocabularies defined in local component registries. Let's define some local sites with a vocabulary. >>> import zope.component.hooks >>> from zope.component import globalregistry >>> from zope.component.globalregistry import getGlobalSiteManager >>> from zope.interface.registry import Components >>> class LocalSite(object): ... def __init__(self, name): ... self.sm = Components( ... name=name, bases=(globalregistry.getGlobalSiteManager(), )) ... ... def getSiteManager(self): ... return self.sm >>> local_site_even = LocalSite('local_site_even') >>> local_site_even.sm.registerUtility( ... makeVocabularyFactory(4, 6, 8), IVocabularyFactory, ... name='SomeVocabulary', event=False) >>> local_site_odd = LocalSite('local_site_odd') >>> local_site_odd.sm.registerUtility( ... makeVocabularyFactory(3, 5, 7), IVocabularyFactory, ... name='SomeVocabulary', event=False) Vocabularies defined in local component registries can be accessed in two ways. 1. Using the registry from within a site. >>> with zope.component.hooks.site(local_site_even): ... voc = getVocabularyRegistry().get(None, 'SomeVocabulary') ... [term.value for term in voc] [4, 6, 8] 2. Binding to a context that can be used to look up a local site manager. >>> from zope.interface.interfaces import IComponentLookup >>> zope.component.provideAdapter( ... lambda number: ((local_site_even, local_site_odd)[number % 2]).sm, ... adapts=(int, ), provides=IComponentLookup) >>> context = 4 >>> voc = getVocabularyRegistry().get(context, 'SomeVocabulary') >>> [term.value for term in voc] [4, 6, 8] Binding to a context takes precedence over active site, so we can look up vocabularies from other sites. >>> context = 7 >>> with zope.component.hooks.site(local_site_even): ... voc = getVocabularyRegistry().get(context, 'SomeVocabulary') ... [term.value for term in voc] [3, 5, 7] If we cannot find a local site for given context, currently active site is used. >>> from zope.interface.interfaces import ComponentLookupError >>> def raisingGetSiteManager(context=None): ... if context == 42: ... raise ComponentLookupError(context) ... return zope.component.hooks.getSiteManager(context) >>> hook = zope.component.getSiteManager.sethook(raisingGetSiteManager) >>> context = 42 >>> with zope.component.hooks.site(local_site_odd): ... voc = getVocabularyRegistry().get(context, 'SomeVocabulary') ... [term.value for term in voc] [3, 5, 7] Configuration ============= This package provides configuration that ensures the vocabulary registry is established: >>> from zope.configuration import xmlconfig >>> _ = xmlconfig.string(r""" ... <configure xmlns="http://namespaces.zope.org/zope" i18n_domain="zope"> ... <include package="zope.vocabularyregistry" /> ... </configure> ... """)
zope.vocabularyregistry
/zope.vocabularyregistry-1.2.0.tar.gz/zope.vocabularyregistry-1.2.0/src/zope/vocabularyregistry/README.rst
README.rst
"""Implementation of Utility-baed Vocabulary Registry """ import zope.component from zope.interface import implementer from zope.interface.interfaces import ComponentLookupError from zope.schema.interfaces import IVocabularyRegistry from zope.schema import vocabulary from zope.schema.interfaces import IVocabularyFactory @implementer(IVocabularyRegistry) class ZopeVocabularyRegistry(object): """IVocabularyRegistry that supports global and local utilities. For contexts that have associated local site manager (component registry), vocabularies are looked up there. For all other contexts, vocabularies are looked up in the currently active local or global site manager. """ __slots__ = () def get(self, context, name): """See zope.schema.interfaces.IVocabularyRegistry""" # Find component registry for the context globalSiteManager = zope.component.getGlobalSiteManager() try: contextSiteManager = zope.component.getSiteManager(context) except ComponentLookupError: contextSiteManager = globalSiteManager if contextSiteManager is not globalSiteManager: # Context has an associated component registry, let's search # for vocabularies defined there. sm = contextSiteManager else: # Component registry for the context is either globalSiteManager, # or it is not found. # # Revert to default getUtility() behaviour - pick manager # for the active site, or fall back to global registry. sm = zope.component.getSiteManager() # Find the vocabulary factory factory = sm.queryUtility(IVocabularyFactory, name, None) if factory is None: raise vocabulary.VocabularyRegistryError(name) return factory(context) vocabularyRegistry = None def _clear(): """Re-initialize the vocabulary registry.""" # This should normally only be needed by the testing framework, # but is also used for module initialization. global vocabularyRegistry # The net effect of these two lines is to have this modules # vocabularyRegistry set to zope.schema.vocabulary.VocabularyRegistry() vocabulary._clear() vocabularyRegistry = vocabulary.getVocabularyRegistry() vocabulary._clear() # Which we immediately replace vocabulary.setVocabularyRegistry(ZopeVocabularyRegistry()) _clear() try: from zope.testing import cleanup except ImportError: # pragma: no cover pass else: cleanup.addCleanUp(_clear)
zope.vocabularyregistry
/zope.vocabularyregistry-1.2.0.tar.gz/zope.vocabularyregistry-1.2.0/src/zope/vocabularyregistry/registry.py
registry.py
Overview ======== This is the "WeakSet" implementation used by ZODB 3.6+. It provides a WeakSet class that implements enough of the Python set API to allow for sets that have weakly-referenced values. Installing This Package ======================= Prerequisites ------------- The installation steps below assume that you have the cool new 'setuptools' package installed in your Python. Here is where to get it: $ wget http://peak.telecommunity.com/dist/ez_setup.py $ /path/to/your/python ez_setup.py # req. write access to 'site-packages' - Docs for EasyInstall: http://peak.telecommunity.com/DevCenter/EasyInstall - Docs for setuptools: http://peak.telecommunity.com/DevCenter/setuptools - Docs for eggs: http://peak.telecommunity.com/DevCenter/PythonEggs Installing a Development Checkout --------------------------------- Check out the package from subversion: $ svn co svn+ssh://svn.zope.org/repos/main/Sandbox/chrism/zodb/3.6.0/zope.weakset \ src/zope.weakset $ cd src/zope.weakset Install it as a "devlopment egg": $ /path/to/your/python setup.py devel Running the Tests ----------------- Eventually, you should be able to type: $ /path/to/your/python setup.py test and have it run the tests. Today, the workaround is run the tests from the checkout's 'weakset' directory: $ /path/to/your/python tests.py Running: ............. Ran 5 tests with 0 failures and 0 errors in 0.094 seconds. Installing a Source Distribution -------------------------------- You can also install it from a source distribution: $ /path/to/easy_install --find-links="...." -eb src zope-weakset $ cd src/zope.weakset $ /path/to/your/python setup.py devel Installing a Binary Egg ----------------------- Install the package as a "binary egg" (which also installs its "hard" dependencies): $ /path/to/easy_install --find-links="...." zope-weakset
zope.weakset
/zope.weakset-3.6.0.tar.gz/zope.weakset-3.6.0/README.txt
README.txt
import weakref # A simple implementation of weak sets, supplying just enough of Python's # sets.Set interface for our needs. class WeakSet(object): """A set of objects that doesn't keep its elements alive. The objects in the set must be weakly referencable. The objects need not be hashable, and need not support comparison. Two objects are considered to be the same iff their id()s are equal. When the only references to an object are weak references (including those from WeakSets), the object can be garbage-collected, and will vanish from any WeakSets it may be a member of at that time. """ def __init__(self): # Map id(obj) to obj. By using ids as keys, we avoid requiring # that the elements be hashable or comparable. self.data = weakref.WeakValueDictionary() def __len__(self): return len(self.data) def __contains__(self, obj): return id(obj) in self.data # Same as a Set, add obj to the collection. def add(self, obj): self.data[id(obj)] = obj # Same as a Set, remove obj from the collection, and raise # KeyError if obj not in the collection. def remove(self, obj): del self.data[id(obj)] # f is a one-argument function. Execute f(elt) for each elt in the # set. f's return value is ignored. def map(self, f): for wr in self.as_weakref_list(): elt = wr() if elt is not None: f(elt) # Return a list of weakrefs to all the objects in the collection. # Because a weak dict is used internally, iteration is dicey (the # underlying dict may change size during iteration, due to gc or # activity from other threads). as_weakef_list() is safe. # # Something like this should really be a method of Python's weak dicts. # If we invoke self.data.values() instead, we get back a list of live # objects instead of weakrefs. If gc occurs while this list is alive, # all the objects move to an older generation (because they're strongly # referenced by the list!). They can't get collected then, until a # less frequent collection of the older generation. Before then, if we # invoke self.data.values() again, they're still alive, and if gc occurs # while that list is alive they're all moved to yet an older generation. # And so on. Stress tests showed that it was easy to get into a state # where a WeakSet grows without bounds, despite that almost all its # elements are actually trash. By returning a list of weakrefs instead, # we avoid that, although the decision to use weakrefs is now# very # visible to our clients. def as_weakref_list(self): # We're cheating by breaking into the internals of Python's # WeakValueDictionary here (accessing its .data attribute). return self.data.data.values()
zope.weakset
/zope.weakset-3.6.0.tar.gz/zope.weakset-3.6.0/src/zope/weakset/__init__.py
__init__.py
__docformat__ = "reStructuredText" from zope import interface class IIntegration(interface.Interface): """Integration of a workflow definition with an application environment ``IIntegration`` objects provide methods for integrating workflow process definition with an application environment. """ def createParticipant(activity, process_definition_identifier, performer): """Create a participant for an activity The process id and especially the performer (id) are used to select an appropriate participant type. """ def createWorkItem(participant, process_definition_identifier, application): """Create a work item for the given participant The process id and especially the application (id) are used to select an appropriate work-item type. """ class IProcessDefinition(interface.Interface): """Process definition A process definition defines a particular workflow and define the control and flow of the work. You can think of them as the workflow blueprint. """ id = interface.Attribute("Process-definition identifier") __name__ = interface.Attribute("Name") description = interface.Attribute("Description") integration = interface.Attribute( """Environment-integration component The integration component is used to hook up a process definition with an application environment. This is an ``IIntegration``. """ ) participants = interface.Attribute( """Process participants This is a mapping from participant id to participant definition """ ) activities = interface.Attribute( """Process activities This is a mapping from activity id to activity definition """ ) applications = interface.Attribute( """Process applications This is a mapping from application id to participant definitions """ ) def defineActivities(**activities): """Add activity definitions to the collection of defined activities Activity definitions are supplied as keyword arguments. The keywords provide activity identifiers. The values are IActivityDefinition objects. """ def defineTransitions(*transitions): """Add transition definitions The transitions are ITransition objects. """ def defineParticipants(**participants): """Declare participants The participants are provided as keyword arguments. Participant identifiers are supplied as the keywords and the definitions are supplied as values. The definitions are IParticipantDefinition objects. """ def defineApplications(**applications): """Declare applications The applications are provided as keyword arguments. Application identifiers are supplied as the keywords and the definitions are supplied as values. The definitions are IApplicationDefinition objects. """ def defineParameters(*parameters): """Declate process parameters Input parameters are set as workflow-relevant data. Output parameters are passed from workflow-relevant data to the processFinished method of process-instances process contexts. """ class IActivityDefinition(interface.Interface): """Activity definition """ id = interface.Attribute("Activity identifier") __name__ = interface.Attribute("Activity Name") description = interface.Attribute("Description") def addApplication(id, *parameters): """Declare that the activity uses the identified activity The application identifier must match an application declared for the process. Parameter definitions can be given as positional arguments. The parameter definition directions must match those given in the application definition. """ def definePerformer(performer): """Set the activity performer The argument must be the identifier of a participant defined for the enclosing process. """ def setAndSplit(setting): """Provide an and-split setting If the setting is true, then the activity will use an "and" split. """ def setAndJoin(setting): """Provide an and-join setting If the setting is true, then the activity will use an "and" join. """ class ITransitionDefinition(interface.Interface): """Transition definition """ id = interface.Attribute("Transition identifier") __name__ = interface.Attribute( "Transition name, Text used to identify the Transition.") description = interface.Attribute("Description") from_ = interface.Attribute( "Determines the FROM source of a Transition. (Activity Identifier)") to = interface.Attribute( "Determines the TO target of a Transition (Activity Identifier)") condition = interface.Attribute( "A Transition condition expression based on relevant data field.") class IProcess(interface.Interface): """Process instance """ definition = interface.Attribute("Process definition") workflowRelevantData = interface.Attribute( """Workflow-relevant data Object with attributes containing data used in conditions and to pass data as parameters between applications """ ) applicationRelevantData = interface.Attribute( """Application-relevant data Object with attributes containing data used to pass data as shared data for applications """ ) class IProcessContext(interface.Interface): """Object that can receive process results. """ def processFinished(process, *results): """Receive notification of process completion, with results """ class IActivity(interface.Interface): """Activity instance """ id = interface.Attribute( """Activity identifier This identifier is set by the process instance """) definition = interface.Attribute("Activity definition") def workItemFinished(work_item, *results): """Notify the activity that the work item has been completed. """ class IApplicationDefinition(interface.Interface): """Application definition """ __name__ = interface.Attribute("Name") description = interface.Attribute("Description") parameters = interface.Attribute( "A sequence of parameter definitions") class IParameterDefinition(interface.Interface): """Parameter definition """ name = interface.Attribute("Parameter name") input = interface.Attribute("Is this an input parameter?") output = interface.Attribute("Is this an output parameter?") class IParticipantDefinition(interface.Interface): """Participant definition """ class IParticipant(interface.Interface): """Workflow participant """ __name__ = interface.Attribute("Name") description = interface.Attribute("Description") class IWorkItem(interface.Interface): """Work items """ id = interface.Attribute( """Item identifier This identifier is set by the activity instance """) def start(*arguments): """Start the work """ class InvalidProcessDefinition(Exception): """A process definition isn't valid in some way. """ class ProcessError(Exception): """An error occurred in execution of a process. """ class IProcessStarted(interface.Interface): """A process has begun executing """ process = interface.Attribute("The process") class IProcessFinished(interface.Interface): """A process has finished executing """ process = interface.Attribute("The process")
zope.wfmc
/zope.wfmc-3.5.0.tar.gz/zope.wfmc-3.5.0/src/zope/wfmc/interfaces.py
interfaces.py
Workflow-Management Coalition Workflow Engine ============================================= This package provides an implementation of a Workflow-Management Coalition (WFMC) workflow engine. The engine is provided as a collection of workflow process components. Workflow processes can be defined in Python or via the XML Process-Definition Language, XPDL. In this document, we'll look at Python-defined process definitions: >>> from zope.wfmc import process >>> pd = process.ProcessDefinition('sample') The argument to the process is a process id. A process has a number of parts. Let's look at a sample review process:: ----------- -->| Publish | ---------- ---------- / ----------- | Author |-->| Review |- ---------- ---------- ---------- \-->| Reject | ---------- Here we have a single start activity and 2 end activities. We could have modeled this with a single end activity, but that is not required. A single start activity *is* required. A process definition has a set of activities, with transitions between them. Let's define the activities for our process definition: >>> pd.defineActivities( ... author = process.ActivityDefinition(), ... review = process.ActivityDefinition(), ... publish = process.ActivityDefinition(), ... reject = process.ActivityDefinition(), ... ) We supply activities as keyword arguments. The argument names provide activity ids that we'll use when defining transitions: >>> pd.defineTransitions( ... process.TransitionDefinition('author', 'review'), ... process.TransitionDefinition('review', 'publish'), ... process.TransitionDefinition('review', 'reject'), ... ) Each transition is constructed with an identifier for a starting activity, and an identifier for an ending activity. Before we can use a workflow definition, we have to register it as a utility. This is necessary so that process instances can find their definitions. In addition, the utility name must match the process id: >>> import zope.component >>> zope.component.provideUtility(pd, name=pd.id) Now, with this definition, we can execute our workflow. We haven't defined any work yet, but we can see the workflow execute. We'll see the workflow executing by registering a subscriber that logs workflow events: >>> def log_workflow(event): ... print event >>> import zope.event >>> zope.event.subscribers.append(log_workflow) To use the workflow definition, we need to create an instance: >>> proc = pd() Now, if we start the workflow: >>> proc.start() ProcessStarted(Process('sample')) Transition(None, Activity('sample.author')) ActivityStarted(Activity('sample.author')) ActivityFinished(Activity('sample.author')) Transition(Activity('sample.author'), Activity('sample.review')) ActivityStarted(Activity('sample.review')) ActivityFinished(Activity('sample.review')) Transition(Activity('sample.review'), Activity('sample.publish')) ActivityStarted(Activity('sample.publish')) ActivityFinished(Activity('sample.publish')) ProcessFinished(Process('sample')) we see that we transition immediately into the author activity, then into review and publish. Normally, we'd need to do some work in each activity, and transitions would continue only after work had been done, however, in this case, we didn't define any work, so each activity completed immediately. Note that we didn't transition into the rejected activity. By default, when an activity is completed, the first transition for which its condition evaluates to `True` is used. By default, transitions have boolean conditions [1]_ that evaluate to `True`, so the transition to `publish` is used because it was defined before the transition to `reject`. What we want is to transition to `publish` if a reviewer approves the content for publication, but to `reject` if the reviewer rejects the content for publication. We can use a condition for this: >>> pd = process.ProcessDefinition('sample') >>> zope.component.provideUtility(pd, name=pd.id) Unregistered event: UtilityRegistration(<BaseGlobalComponents base>, IProcessDefinition, 'sample', ProcessDefinition('sample'), None, u'') >>> pd.defineActivities( ... author = process.ActivityDefinition(), ... review = process.ActivityDefinition(), ... publish = process.ActivityDefinition(), ... reject = process.ActivityDefinition(), ... ) >>> pd.defineTransitions( ... process.TransitionDefinition('author', 'review'), ... process.TransitionDefinition( ... 'review', 'publish', condition=lambda data: data.publish), ... process.TransitionDefinition('review', 'reject'), ... ) We redefined the workflow process, specifying a condition for the transition to `publish`. Boolean conditions are just callable objects that take a data object and return a boolean value. The data object is called "workflow-relevant data". A process instance has a data object containing this data. In the example, above, the condition simply returned the value of the `publish` attribute. How does this attribute get set? It needs to be set by the review activity. To do that, we need to arrange for the activity to set the data. This brings us to applications. Process definitions are meant to be used with different applications. For this reason, process definitions don't include application logic. What they do include is a specifications of the applications to be invoked and the flow of work-flow-relevant data to and from the application. Now, we can define our applications: >>> pd.defineApplications( ... author = process.Application(), ... review = process.Application( ... process.OutputParameter('publish')), ... publish = process.Application(), ... reject = process.Application(), ... ) We used the same names for the applications that we used for our activities. This isn't required, but is a common practice. Note that the `review` application includes a specification of an output parameter. Now that we've defined our applications, we need to modify our activities to use them: >>> pd.activities['author'].addApplication('author') >>> pd.activities['review'].addApplication('review', ['publish']) >>> pd.activities['publish'].addApplication('publish') >>> pd.activities['reject'].addApplication('reject') An activity can use many applications, so we call `addApplication`. In the application definition for the 'review' application, we provided the name of a workflow-relevent data variable corresponding to the output parameter defined for the application. When using an application in an activity, a workflow-relevent data variable name must be provided for each of the parameters in the identified applications's signature. When an application is used in an activity, workflow-relevent data are passed for each of the input parameters and are set by each of the output parameters. In this example, the output parameter, will be used to add a `publish` attribute to the workflow relevant data. Participants ------------ We've declared some applications, and we've wired them up to activities, but we still haven't specified any application code. Before we can specify application code, we need to consider who will be performing the application. Workflow applications are normally executed by people, or other external actors. As with applications, process definitions allow participants in the workflow to be declared and identified with activities. We declare participants much as we declare applications, except without parameters: >>> pd.defineParticipants( ... author = process.Participant(), ... reviewer = process.Participant(), ... ) In this case, we happened to reuse an activity name for one, but not both of the participants. Having defined these participants, we can associate them with activities: >>> pd.activities['author'].definePerformer('author') >>> pd.activities['review'].definePerformer('reviewer') Application Integration ----------------------- To use a process definition to control application logic, we need to associate it with an "integration" object. When a process needs to get a participant, it calls createParticipant on its integration attribute, passing the process id and the performer id. If an activity doesn't have a performer, then the procedure above is used with an empty performer id. Similarly, when a process needs a work item, it calls createWorkItem on its integration attribute, passing the process id and the application id. Work items provide a `start` method, which is used to start the work and pass input arguments. It is the responsibility of the work item, at some later time, to call the `workItemFinished` method on the activity, to notify the activity that the work item was completed. Output parameters are passed to the `workItemFinished` method. A simple way to create integration objects is with `zope.wfmc.attributeintegration.AttributeIntegration`. >>> from zope.wfmc.attributeintegration import AttributeIntegration >>> integration = AttributeIntegration() >>> pd.integration = integration We'll start by defining a simple Participant class: >>> import zope.interface >>> from zope.wfmc import interfaces >>> class Participant(object): ... zope.component.adapts(interfaces.IActivity) ... zope.interface.implements(interfaces.IParticipant) ... ... def __init__(self, activity): ... self.activity = activity We set attributes on the integration for each participant: >>> integration.authorParticipant = Participant >>> integration.reviewerParticipant = Participant We also define an attribute for participants for activities that don't have performers: >>> integration.Participant = Participant Now we'll define our work-items. First we'll define some classes: >>> work_list = [] >>> class ApplicationBase: ... zope.component.adapts(interfaces.IParticipant) ... zope.interface.implements(interfaces.IWorkItem) ... ... def __init__(self, participant): ... self.participant = participant ... work_list.append(self) ... ... def start(self): ... pass ... ... def finish(self): ... self.participant.activity.workItemFinished(self) >>> class Review(ApplicationBase): ... def finish(self, publish): ... self.participant.activity.workItemFinished(self, publish) >>> class Publish(ApplicationBase): ... def start(self): ... print "Published" ... self.finish() >>> class Reject(ApplicationBase): ... def start(self): ... print "Rejected" ... self.finish() and then we'll hook them up with the integration object: >>> integration.authorWorkItem = ApplicationBase >>> integration.reviewWorkItem = Review >>> integration.publishWorkItem = Publish >>> integration.rejectWorkItem = Reject Using workflow processes ------------------------ To use a process definition, instantiate it and call its start method to start execution: >>> proc = pd() >>> proc.start() ... # doctest: +NORMALIZE_WHITESPACE ProcessStarted(Process('sample')) Transition(None, Activity('sample.author')) ActivityStarted(Activity('sample.author')) We transition into the author activity and wait for work to get done. To move forward, we need to get at the authoring work item, so we can finish it. Our work items add themselves to a work list, so we can get the item from the list. >>> item = work_list.pop() Now we can finish the work item, by calling its finish method: >>> item.finish() WorkItemFinished('author') ActivityFinished(Activity('sample.author')) Transition(Activity('sample.author'), Activity('sample.review')) ActivityStarted(Activity('sample.review')) We see that we transitioned to the review activity. Note that the `finish` method isn't a part of the workflow APIs. It was defined by our sample classes. Other applications could use different mechanisms. Now, we'll finish the review process by calling the review work item's `finish`. We'll pass `False`, indicating that the content should not be published: >>> work_list.pop().finish(False) WorkItemFinished('review') ActivityFinished(Activity('sample.review')) Transition(Activity('sample.review'), Activity('sample.reject')) ActivityStarted(Activity('sample.reject')) Rejected WorkItemFinished('reject') ActivityFinished(Activity('sample.reject')) ProcessFinished(Process('sample')) Ordering output transitions --------------------------- Normally, outgoing transitions are ordered in the order of transition definition and all transitions from a given activity are used. If transitions are defined in an inconvenient order, then the workflow might not work as expected. For example, let's modify the above process by switching the order of definition of some of the transitions. We'll reuse our integration object from the previous example by passing it to the definition constructor: >>> pd = process.ProcessDefinition('sample', integration) >>> zope.component.provideUtility(pd, name=pd.id) Unregistered event: UtilityRegistration(<BaseGlobalComponents base>, IProcessDefinition, 'sample', ProcessDefinition('sample'), None, u'') >>> pd.defineActivities( ... author = process.ActivityDefinition(), ... review = process.ActivityDefinition(), ... publish = process.ActivityDefinition(), ... reject = process.ActivityDefinition(), ... ) >>> pd.defineTransitions( ... process.TransitionDefinition('author', 'review'), ... process.TransitionDefinition('review', 'reject'), ... process.TransitionDefinition( ... 'review', 'publish', condition=lambda data: data.publish), ... ) >>> pd.defineApplications( ... author = process.Application(), ... review = process.Application( ... process.OutputParameter('publish')), ... publish = process.Application(), ... reject = process.Application(), ... ) >>> pd.activities['author'].addApplication('author') >>> pd.activities['review'].addApplication('review', ['publish']) >>> pd.activities['publish'].addApplication('publish') >>> pd.activities['reject'].addApplication('reject') >>> pd.defineParticipants( ... author = process.Participant(), ... reviewer = process.Participant(), ... ) >>> pd.activities['author'].definePerformer('author') >>> pd.activities['review'].definePerformer('reviewer') and run our process: >>> proc = pd() >>> proc.start() ... # doctest: +NORMALIZE_WHITESPACE ProcessStarted(Process('sample')) Transition(None, Activity('sample.author')) ActivityStarted(Activity('sample.author')) >>> work_list.pop().finish() WorkItemFinished('author') ActivityFinished(Activity('sample.author')) Transition(Activity('sample.author'), Activity('sample.review')) ActivityStarted(Activity('sample.review')) This time, we'll say that we should publish: >>> work_list.pop().finish(True) WorkItemFinished('review') ActivityFinished(Activity('sample.review')) Transition(Activity('sample.review'), Activity('sample.reject')) ActivityStarted(Activity('sample.reject')) Rejected WorkItemFinished('reject') ActivityFinished(Activity('sample.reject')) ProcessFinished(Process('sample')) But we went to the reject activity anyway. Why? Because transitions are tested in order. Because the transition to the reject activity was tested first and had no condition, we followed it without checking the condition for the transition to the publish activity. We can fix this by specifying outgoing transitions on the reviewer activity directly. To do this, we'll also need to specify ids in our transitions. Let's redefine the process: >>> pd = process.ProcessDefinition('sample', integration) >>> zope.component.provideUtility(pd, name=pd.id) Unregistered event: UtilityRegistration(<BaseGlobalComponents base>, IProcessDefinition, 'sample', ProcessDefinition('sample'), None, u'') >>> pd.defineActivities( ... author = process.ActivityDefinition(), ... review = process.ActivityDefinition(), ... publish = process.ActivityDefinition(), ... reject = process.ActivityDefinition(), ... ) >>> pd.defineTransitions( ... process.TransitionDefinition('author', 'review'), ... process.TransitionDefinition('review', 'reject', id='reject'), ... process.TransitionDefinition( ... 'review', 'publish', id='publish', ... condition=lambda data: data.publish), ... ) >>> pd.defineApplications( ... author = process.Application(), ... review = process.Application( ... process.OutputParameter('publish')), ... publish = process.Application(), ... reject = process.Application(), ... ) >>> pd.activities['author'].addApplication('author') >>> pd.activities['review'].addApplication('review', ['publish']) >>> pd.activities['publish'].addApplication('publish') >>> pd.activities['reject'].addApplication('reject') >>> pd.defineParticipants( ... author = process.Participant(), ... reviewer = process.Participant(), ... ) >>> pd.activities['author'].definePerformer('author') >>> pd.activities['review'].definePerformer('reviewer') >>> pd.activities['review'].addOutgoing('publish') >>> pd.activities['review'].addOutgoing('reject') Now, when we run the process, we'll go to the publish activity as expected: >>> proc = pd() >>> proc.start() ... # doctest: +NORMALIZE_WHITESPACE ProcessStarted(Process('sample')) Transition(None, Activity('sample.author')) ActivityStarted(Activity('sample.author')) >>> work_list.pop().finish() WorkItemFinished('author') ActivityFinished(Activity('sample.author')) Transition(Activity('sample.author'), Activity('sample.review')) ActivityStarted(Activity('sample.review')) >>> work_list.pop().finish(True) WorkItemFinished('review') ActivityFinished(Activity('sample.review')) Transition(Activity('sample.review'), Activity('sample.publish')) ActivityStarted(Activity('sample.publish')) Published WorkItemFinished('publish') ActivityFinished(Activity('sample.publish')) ProcessFinished(Process('sample')) Let's see the other way also, where we should transition to reject: >>> proc = pd() >>> proc.start() ... # doctest: +NORMALIZE_WHITESPACE ProcessStarted(Process('sample')) Transition(None, Activity('sample.author')) ActivityStarted(Activity('sample.author')) >>> work_list.pop().finish() WorkItemFinished('author') ActivityFinished(Activity('sample.author')) Transition(Activity('sample.author'), Activity('sample.review')) ActivityStarted(Activity('sample.review')) >>> work_list.pop().finish(False) WorkItemFinished('review') ActivityFinished(Activity('sample.review')) Transition(Activity('sample.review'), Activity('sample.reject')) ActivityStarted(Activity('sample.reject')) Rejected WorkItemFinished('reject') ActivityFinished(Activity('sample.reject')) ProcessFinished(Process('sample')) Complex Flows ------------- Lets look at a more complex example. In this example, we'll extend the process to work with multiple reviewers. We'll also make the work-list handling a bit more sophisticated. We'll also introduce some new concepts: - splits and joins - process arguments Consider the publication process shown below:: Author: Tech Tech Editorial Reviewer 1: Reviewer 2: Reviewer: =========== =========== =========== ============== --------- ----------------------------------------------------| Start | / --------- | V ----------- | Prepare |<------------------------------\ ----------- \ | ------------ \ | | Tech |--------------- \ \ |------->| Review 1 | V | | ------------ ---------- ------------- \ | Tech | | Editorial | ---------- ------------------->| Review |--->| Review |-->| Reject | | 2 | ------------- ---------- ---------- | | ----------- / \ | Prepare | / \--------\ | Final |<----------------------------/ | ----------- | ^ | ---------- V | \------------------------------->| Review | ----------- \ | Final |----->| Publish | ------------------------------------| | ----------- ---------- Here we've arranged the process diagram into columns, with the activities for each participant. We have four participants, the author, two technical reviewers, and an editorial reviewer. The author prepares a draft. The author sends the draft to *both* technical reviewers for review. When the technical reviews have completed, the editorial review does an initial editorial review. Based on the technical reviews, the editor may choose to: - Reject the document - Publish the document as is - Request technical changes (based on the technical reviewers' comments), or - Request editorial changes. If technical changes are required, the work flows back to the "Prepare" activity. If editorial changes are necessary, then work flows to the "Prepare Final" activity. When the author has made the editorial changes, work flows to "Review Final". The editor may request additional changes, in which case, work flows back to "Prepare Final", otherwise, the work flows to "Publish". This example illustrates different kinds of "joins" and "splits". The term "join" refers to the way incoming transitions to an activity are handled. There are two kinds of joins: "and" and "xor". With an "and" join, the activity waits for each of the incoming transitions. In this example, the inputs to the "Editorial Review" activity form an "and" join. Editorial review waits until each of the technical reviews are completed. The rest of the joins in this example are "xor" joins. The activity starts on any transition into the activity. The term "split" refers to way outgoing transitions from an activity are handled. Normally, exactly one transition out of an activity is used. This is called an "xor" split. With an "and" split, all transitions with boolean conditions that evaluate to `True` are used. In this example, the "Prepare" activity has an "and" split. Work flows simultaneously to the two technical review activities. The rest of the splits in this example are "xor" splits. Lets create our new workflow process. We'll reuse our existing integration object: >>> Publication = process.ProcessDefinition('Publication') >>> Publication.integration = integration >>> zope.component.provideUtility(Publication, name=Publication.id) >>> Publication.defineActivities( ... start = process.ActivityDefinition("Start"), ... prepare = process.ActivityDefinition("Prepare"), ... tech1 = process.ActivityDefinition("Technical Review 1"), ... tech2 = process.ActivityDefinition("Technical Review 2"), ... review = process.ActivityDefinition("Editorial Review"), ... final = process.ActivityDefinition("Final Preparation"), ... rfinal = process.ActivityDefinition("Review Final"), ... publish = process.ActivityDefinition("Publish"), ... reject = process.ActivityDefinition("Reject"), ... ) Here, we've passed strings to the activity definitions providing names. Names must be either unicode or ASCII strings. We define our transitions: >>> Publication.defineTransitions( ... process.TransitionDefinition('start', 'prepare'), ... process.TransitionDefinition('prepare', 'tech1'), ... process.TransitionDefinition('prepare', 'tech2'), ... process.TransitionDefinition('tech1', 'review'), ... process.TransitionDefinition('tech2', 'review'), ... ... process.TransitionDefinition( ... 'review', 'reject', ... condition=lambda data: not data.publish ... ), ... process.TransitionDefinition( ... 'review', 'prepare', ... condition=lambda data: data.tech_changes ... ), ... process.TransitionDefinition( ... 'review', 'final', ... condition=lambda data: data.ed_changes ... ), ... process.TransitionDefinition('review', 'publish'), ... ... process.TransitionDefinition('final', 'rfinal'), ... process.TransitionDefinition( ... 'rfinal', 'final', ... condition=lambda data: data.ed_changes ... ), ... process.TransitionDefinition('rfinal', 'publish'), ... ) We specify our "and" split and join: >>> Publication.activities['prepare'].andSplit(True) >>> Publication.activities['review'].andJoin(True) We define our participants and applications: >>> Publication.defineParticipants( ... author = process.Participant("Author"), ... tech1 = process.Participant("Technical Reviewer 1"), ... tech2 = process.Participant("Technical Reviewer 2"), ... reviewer = process.Participant("Editorial Reviewer"), ... ) >>> Publication.defineApplications( ... prepare = process.Application(), ... tech_review = process.Application( ... process.OutputParameter('publish'), ... process.OutputParameter('tech_changes'), ... ), ... ed_review = process.Application( ... process.InputParameter('publish1'), ... process.InputParameter('tech_changes1'), ... process.InputParameter('publish2'), ... process.InputParameter('tech_changes2'), ... process.OutputParameter('publish'), ... process.OutputParameter('tech_changes'), ... process.OutputParameter('ed_changes'), ... ), ... publish = process.Application(), ... reject = process.Application(), ... final = process.Application(), ... rfinal = process.Application( ... process.OutputParameter('ed_changes'), ... ), ... ) >>> Publication.activities['prepare'].definePerformer('author') >>> Publication.activities['prepare'].addApplication('prepare') >>> Publication.activities['tech1'].definePerformer('tech1') >>> Publication.activities['tech1'].addApplication( ... 'tech_review', ['publish1', 'tech_changes1']) >>> Publication.activities['tech2'].definePerformer('tech2') >>> Publication.activities['tech2'].addApplication( ... 'tech_review', ['publish2', 'tech_changes2']) >>> Publication.activities['review'].definePerformer('reviewer') >>> Publication.activities['review'].addApplication( ... 'ed_review', ... ['publish1', 'tech_changes1', 'publish2', 'tech_changes2', ... 'publish', 'tech_changes', 'ed_changes'], ... ) >>> Publication.activities['final'].definePerformer('author') >>> Publication.activities['final'].addApplication('final') >>> Publication.activities['rfinal'].definePerformer('reviewer') >>> Publication.activities['rfinal'].addApplication( ... 'rfinal', ['ed_changes'], ... ) >>> Publication.activities['publish'].addApplication('publish') >>> Publication.activities['reject'].addApplication('reject') We want to be able to specify an author when we start the process. We'd also like to be told the final disposition of the process. To accomplish this, we'll define parameters for our process: >>> Publication.defineParameters( ... process.InputParameter('author'), ... process.OutputParameter('publish'), ... ) Now that we've defined the process, we need to provide participant and application components. Let's start with our participants. Rather than sharing a single work list, we'll give each user their own work list. We'll also create preexisting participants and return them. Finally, we'll create multiple authors and use the selected one: >>> class User: ... def __init__(self): ... self.work_list = [] >>> authors = {'bob': User(), 'ted': User(), 'sally': User()} >>> reviewer = User() >>> tech1 = User() >>> tech2 = User() >>> class Author(Participant): ... def __init__(self, activity): ... Participant.__init__(self, activity) ... author_name = activity.process.workflowRelevantData.author ... print "Author `%s` selected" % author_name ... self.user = authors[author_name] In this example, we need to define a separate attribute for each participant: >>> integration.authorParticipant = Author When the process is created, the author name will be passed in and assigned to the workflow-relevant data. Our author class uses this information to select the named user. >>> class Reviewer(Participant): ... user = reviewer >>> integration.reviewerParticipant = Reviewer >>> class Tech1(Participant): ... user = tech1 >>> integration.tech1Participant = Tech1 >>> class Tech2(Participant): ... user = tech2 >>> integration.tech2Participant = Tech2 We'll use our orginal participation class for activities without performers: >>> integration.Participant = Participant Now we'll create our applications. Let's start with our author: >>> class ApplicationBase(object): ... zope.component.adapts(interfaces.IParticipant) ... zope.interface.implements(interfaces.IWorkItem) ... ... def __init__(self, participant): ... self.participant = participant ... self.activity = participant.activity ... participant.user.work_list.append(self) ... ... def start(self): ... pass ... ... def finish(self): ... self.participant.activity.workItemFinished(self) >>> class Prepare(ApplicationBase): ... ... def summary(self): ... process = self.activity.process ... doc = getattr(process.applicationRelevantData, 'doc', '') ... if doc: ... print 'Previous draft:' ... print doc ... print 'Changes we need to make:' ... for change in process.workflowRelevantData.tech_changes: ... print change ... else: ... print 'Please write the initial draft' ... ... def finish(self, doc): ... self.activity.process.applicationRelevantData.doc = doc ... super(Prepare, self).finish() >>> integration.prepareWorkItem = Prepare Since we used the prepare application for revisions as well as initial preparation, we provide a summary method to show us what we have to do. Here we get the document created by the author passed in as an argument to the finish method. In a more realistic implementation, the author task would create the document at the start of the task and provide a user interface for the user to edit it. We store the document as application-relevant data, since we'll want reviewers to be able to access it, but we don't need it directly for workflow control. >>> class TechReview(ApplicationBase): ... ... def getDoc(self): ... return self.activity.process.applicationRelevantData.doc ... ... def finish(self, decision, changes): ... self.activity.workItemFinished(self, decision, changes) >>> integration.tech_reviewWorkItem = TechReview Here, we provided a method to access the original document. >>> class Review(TechReview): ... ... def start(self, publish1, changes1, publish2, changes2): ... if not (publish1 and publish2): ... # Reject if either tech reviewer rejects ... self.activity.workItemFinished( ... self, False, changes1 + changes2, ()) ... ... if changes1 or changes2: ... # we won't do anything if there are tech changes ... self.activity.workItemFinished( ... self, True, changes1 + changes2, ()) ... ... def finish(self, ed_changes): ... self.activity.workItemFinished(self, True, (), ed_changes) >>> integration.ed_reviewWorkItem = Review In this implementation, we decided to reject outright if either technical editor recommended rejection and to send work back to preparation if there are any technical changes. We also subclassed `TechReview` to get the `getDoc` method. We'll reuse the `publish` and `reject` application from the previous example. >>> class Final(ApplicationBase): ... ... def summary(self): ... process = self.activity.process ... doc = getattr(process.applicationRelevantData, 'doc', '') ... print 'Previous draft:' ... print self.activity.process.applicationRelevantData.doc ... print 'Changes we need to make:' ... for change in process.workflowRelevantData.ed_changes: ... print change ... ... def finish(self, doc): ... self.activity.process.applicationRelevantData.doc = doc ... super(Final, self).finish() >>> integration.finalWorkItem = Final In our this application, we simply update the document to reflect changes. >>> class ReviewFinal(TechReview): ... ... def finish(self, ed_changes): ... self.activity.workItemFinished(self, ed_changes) >>> integration.rfinalWorkItem = ReviewFinal Our process now returns data. When we create a process, we need to supply an object that it can call back to: >>> class PublicationContext: ... zope.interface.implements(interfaces.IProcessContext) ... ... def processFinished(self, process, decision): ... self.decision = decision Now, let's try out our process: >>> context = PublicationContext() >>> proc = Publication(context) >>> proc.start('bob') ProcessStarted(Process('Publication')) Transition(None, Activity('Publication.start')) ActivityStarted(Activity('Publication.start')) ActivityFinished(Activity('Publication.start')) Author `bob` selected Transition(Activity('Publication.start'), Activity('Publication.prepare')) ActivityStarted(Activity('Publication.prepare')) We should have added an item to bob's work list. Let's get it and finish it, submitting a document: >>> item = authors['bob'].work_list.pop() >>> item.finish("I give my pledge, as an American\n" ... "to save, and faithfully to defend from waste\n" ... "the natural resources of my Country.") WorkItemFinished('prepare') ActivityFinished(Activity('Publication.prepare')) Transition(Activity('Publication.prepare'), Activity('Publication.tech1')) ActivityStarted(Activity('Publication.tech1')) Transition(Activity('Publication.prepare'), Activity('Publication.tech2')) ActivityStarted(Activity('Publication.tech2')) Notice that we transitioned to *two* activities, `tech1` and `tech2`. This is because the prepare activity has an "and" split. Now we'll do a tech review. Let's see what tech1 has: >>> item = tech1.work_list.pop() >>> print item.getDoc() I give my pledge, as an American to save, and faithfully to defend from waste the natural resources of my Country. Let's tell the author to change "American" to "Earthling": >>> item.finish(True, ['Change "American" to "Earthling"']) WorkItemFinished('tech_review') ActivityFinished(Activity('Publication.tech1')) Transition(Activity('Publication.tech1'), Activity('Publication.review')) Here we transitioned to the editorial review activity, but we didn't start it. This is because the editorial review activity has an "and" join, meaning that it won't start until both transitions have occurred. Now we'll do the other technical review: >>> item = tech2.work_list.pop() >>> item.finish(True, ['Change "Country" to "planet"']) WorkItemFinished('tech_review') ActivityFinished(Activity('Publication.tech2')) Transition(Activity('Publication.tech2'), Activity('Publication.review')) ActivityStarted(Activity('Publication.review')) WorkItemFinished('ed_review') ActivityFinished(Activity('Publication.review')) Author `bob` selected Transition(Activity('Publication.review'), Activity('Publication.prepare')) ActivityStarted(Activity('Publication.prepare')) Now when we transitioned to the editorial review activity, we started it, because each of the input transitions had happened. Our editorial review application automatically sent the work back to preparation, because there were technical comments. Of course the author is still `bob`. Let's address the comments: >>> item = authors['bob'].work_list.pop() >>> item.summary() Previous draft: I give my pledge, as an American to save, and faithfully to defend from waste the natural resources of my Country. Changes we need to make: Change "American" to "Earthling" Change "Country" to "planet" >>> item.finish("I give my pledge, as an Earthling\n" ... "to save, and faithfully to defend from waste\n" ... "the natural resources of my planet.") WorkItemFinished('prepare') ActivityFinished(Activity('Publication.prepare')) Transition(Activity('Publication.prepare'), Activity('Publication.tech1')) ActivityStarted(Activity('Publication.tech1')) Transition(Activity('Publication.prepare'), Activity('Publication.tech2')) ActivityStarted(Activity('Publication.tech2')) As before, after completing the initial edits, we start the technical review activities again. We'll review it again. This time, we have no comments, because the author applied our requested changes: >>> item = tech1.work_list.pop() >>> item.finish(True, []) WorkItemFinished('tech_review') ActivityFinished(Activity('Publication.tech1')) Transition(Activity('Publication.tech1'), Activity('Publication.review')) >>> item = tech2.work_list.pop() >>> item.finish(True, []) WorkItemFinished('tech_review') ActivityFinished(Activity('Publication.tech2')) Transition(Activity('Publication.tech2'), Activity('Publication.review')) ActivityStarted(Activity('Publication.review')) This time, we are left in the technical review activity because there weren't any technical changes. We're ready to do our editorial review. We'll request an editorial change: >>> item = reviewer.work_list.pop() >>> print item.getDoc() I give my pledge, as an Earthling to save, and faithfully to defend from waste the natural resources of my planet. >>> item.finish(['change "an" to "a"']) WorkItemFinished('ed_review') ActivityFinished(Activity('Publication.review')) Author `bob` selected Transition(Activity('Publication.review'), Activity('Publication.final')) ActivityStarted(Activity('Publication.final')) Because we requested editorial changes, we transitioned to the final editing activity, so that the author (still bob) can make the changes: >>> item = authors['bob'].work_list.pop() >>> item.summary() Previous draft: I give my pledge, as an Earthling to save, and faithfully to defend from waste the natural resources of my planet. Changes we need to make: change "an" to "a" >>> item.finish("I give my pledge, as a Earthling\n" ... "to save, and faithfully to defend from waste\n" ... "the natural resources of my planet.") WorkItemFinished('final') ActivityFinished(Activity('Publication.final')) Transition(Activity('Publication.final'), Activity('Publication.rfinal')) ActivityStarted(Activity('Publication.rfinal')) We transition to the activity for reviewing the final edits. We review the document and approve it for publication: >>> item = reviewer.work_list.pop() >>> print item.getDoc() I give my pledge, as a Earthling to save, and faithfully to defend from waste the natural resources of my planet. >>> item.finish([]) WorkItemFinished('rfinal') ActivityFinished(Activity('Publication.rfinal')) Transition(Activity('Publication.rfinal'), Activity('Publication.publish')) ActivityStarted(Activity('Publication.publish')) Published WorkItemFinished('publish') ActivityFinished(Activity('Publication.publish')) ProcessFinished(Process('Publication')) At this point, the rest of the process finished automatically. In addition, the decision was recorded in the process context object: >>> context.decision True Coming Soon ------------ - XPDL support - Timeouts/exceptions - "otherwise" conditions .. [1] There are other kinds of conditions, namely "otherwise" and "exception" conditions. See also --------- http://www.wfmc.org http://www.wfmc.org/standards/standards.htm
zope.wfmc
/zope.wfmc-3.5.0.tar.gz/zope.wfmc-3.5.0/src/zope/wfmc/README.txt
README.txt
import persistent import zope.cachedescriptors.property from zope import component, interface import zope.event from zope.wfmc import interfaces def always_true(data): return True class TransitionDefinition(object): interface.implements(interfaces.ITransitionDefinition) def __init__(self, from_, to, condition=always_true, id=None, __name__=None): self.id = id self.from_ = from_ self.to = to self.condition = condition self.__name__ = __name__ self.description = None def __repr__(self): return "TransitionDefinition(from=%r, to=%r)" %(self.from_, self.to) class ProcessDefinition(object): interface.implements(interfaces.IProcessDefinition) TransitionDefinitionFactory = TransitionDefinition def __init__(self, id, integration=None): self.id = id self.integration = integration self.activities = {} self.transitions = [] self.applications = {} self.participants = {} self.parameters = () self.description = None def __repr__(self): return "ProcessDefinition(%r)" % self.id def defineActivities(self, **activities): self._dirty() for id, activity in activities.items(): activity.id = id if activity.__name__ is None: activity.__name__ = self.id + '.' + id activity.process = self self.activities[id] = activity def defineTransitions(self, *transitions): self._dirty() self.transitions.extend(transitions) # Compute activity transitions based on transition data: activities = self.activities for transition in transitions: activities[transition.from_].transitionOutgoing(transition) activities[transition.to].incoming += (transition, ) def defineApplications(self, **applications): for id, application in applications.items(): application.id = id self.applications[id] = application def defineParticipants(self, **participants): for id, participant in participants.items(): participant.id = id self.participants[id] = participant def defineParameters(self, *parameters): self.parameters += parameters def _start(self): # Return an initial transition activities = self.activities # Find the start, making sure that there is one and that there # aren't any activities with no transitions: start = () for aid, activity in activities.items(): if not activity.incoming: start += ((aid, activity), ) if not activity.outgoing: raise interfaces.InvalidProcessDefinition( "Activity %s has no transitions" %aid) if len(start) != 1: if start: raise interfaces.InvalidProcessDefinition( "Multiple start activities", [id for (id, a) in start] ) else: raise interfaces.InvalidProcessDefinition( "No start activities") return self.TransitionDefinitionFactory(None, start[0][0]) _start = zope.cachedescriptors.property.Lazy(_start) def __call__(self, context=None): return Process(self, self._start, context) def _dirty(self): try: del self._start except AttributeError: pass class ActivityDefinition(object): interface.implements(interfaces.IActivityDefinition) performer = '' process = None def __init__(self, __name__=None): self.__name__ = __name__ self.incoming = self.outgoing = () self.transition_outgoing = self.explicit_outgoing = () self.applications = () self.andJoinSetting = self.andSplitSetting = False self.description = None def andSplit(self, setting): self.andSplitSetting = setting def andJoin(self, setting): self.andJoinSetting = setting def addApplication(self, application, actual=()): app = self.process.applications[application] formal = app.parameters if len(formal) != len(actual): raise TypeError("Wrong number of parameters => " "Actual=%s, Formal=%s for Application %s with id=%s" %(actual, formal, app, app.id)) self.applications += ((application, formal, tuple(actual)), ) def definePerformer(self, performer): self.performer = performer def addOutgoing(self, transition_id): self.explicit_outgoing += (transition_id,) self.computeOutgoing() def transitionOutgoing(self, transition): self.transition_outgoing += (transition,) self.computeOutgoing() def computeOutgoing(self): if self.explicit_outgoing: transitions = dict([(t.id, t) for t in self.transition_outgoing]) self.outgoing = () for tid in self.explicit_outgoing: transition = transitions.get(tid) if transition is not None: self.outgoing += (transition,) else: self.outgoing = self.transition_outgoing def __repr__(self): return "<ActivityDefinition %r>" %self.__name__ class Process(persistent.Persistent): interface.implements(interfaces.IProcess) def __init__(self, definition, start, context=None): self.process_definition_identifier = definition.id self.startTransition = start self.context = context self.activities = {} self.nextActivityId = 0 self.workflowRelevantData = WorkflowData() self.applicationRelevantData = WorkflowData() def definition(self): return component.getUtility( interfaces.IProcessDefinition, self.process_definition_identifier, ) definition = property(definition) def start(self, *arguments): if self.activities: raise TypeError("Already started") definition = self.definition data = self.workflowRelevantData args = arguments for parameter in definition.parameters: if parameter.input: arg, args = args[0], args[1:] setattr(data, parameter.__name__, arg) if args: raise TypeError("Too many arguments. Expected %s. got %s" % (len(definition.parameters), len(arguments))) zope.event.notify(ProcessStarted(self)) self.transition(None, (self.startTransition, )) def outputs(self): outputs = [] for parameter in self.definition.parameters: if parameter.output: outputs.append( getattr(self.workflowRelevantData, parameter.__name__)) return outputs def _finish(self): if self.context is not None: self.context.processFinished(self, *self.outputs()) zope.event.notify(ProcessFinished(self)) def transition(self, activity, transitions): if transitions: definition = self.definition for transition in transitions: activity_definition = definition.activities[transition.to] next = None if activity_definition.andJoinSetting: # If it's an and-join, we want only one. for i, a in self.activities.items(): if a.activity_definition_identifier == transition.to: # we already have the activity -- use it next = a break if next is None: next = Activity(self, activity_definition) self.nextActivityId += 1 next.id = self.nextActivityId zope.event.notify(Transition(activity, next)) self.activities[next.id] = next next.start(transition) if activity is not None: del self.activities[activity.id] if not self.activities: self._finish() self._p_changed = True def __repr__(self): return "Process(%r)" % self.process_definition_identifier class WorkflowData(persistent.Persistent): """Container for workflow-relevant and application-relevant data """ class ProcessStarted: interface.implements(interfaces.IProcessStarted) def __init__(self, process): self.process = process def __repr__(self): return "ProcessStarted(%r)" % self.process class ProcessFinished: interface.implements(interfaces.IProcessFinished) def __init__(self, process): self.process = process def __repr__(self): return "ProcessFinished(%r)" % self.process class Activity(persistent.Persistent): interface.implements(interfaces.IActivity) def __init__(self, process, definition): self.process = process self.activity_definition_identifier = definition.id integration = process.definition.integration workitems = {} if definition.applications: participant = integration.createParticipant( self, process.process_definition_identifier, definition.performer, ) i = 0 for application, formal, actual in definition.applications: workitem = integration.createWorkItem( participant, process.process_definition_identifier, application, ) i += 1 workitem.id = i workitems[i] = workitem, application, formal, actual self.workitems = workitems def definition(self): return self.process.definition.activities[ self.activity_definition_identifier] definition = property(definition) incoming = () def start(self, transition): # Start the activity, if we've had enough incoming transitions definition = self.definition if definition.andJoinSetting: if transition in self.incoming: raise interfaces.ProcessError( "Repeated incoming %s with id='%s' " "while waiting for and completion" %(transition, transition.id)) self.incoming += (transition, ) if len(self.incoming) < len(definition.incoming): return # not enough incoming yet zope.event.notify(ActivityStarted(self)) if self.workitems: for workitem, app, formal, actual in self.workitems.values(): args = [] for parameter, name in zip(formal, actual): if parameter.input: args.append( getattr(self.process.workflowRelevantData, name)) workitem.start(*args) else: # Since we don't have any work items, we're done self.finish() def workItemFinished(self, work_item, *results): unused, app, formal, actual = self.workitems.pop(work_item.id) self._p_changed = True res = results for parameter, name in zip(formal, actual): if parameter.output: v = res[0] res = res[1:] setattr(self.process.workflowRelevantData, name, v) if res: raise TypeError("Too many results") zope.event.notify(WorkItemFinished( work_item, app, actual, results)) if not self.workitems: self.finish() def finish(self): zope.event.notify(ActivityFinished(self)) definition = self.definition transitions = [] for transition in definition.outgoing: if transition.condition(self.process.workflowRelevantData): transitions.append(transition) if not definition.andSplitSetting: break # xor split, want first one self.process.transition(self, transitions) def __repr__(self): return "Activity(%r)" % ( self.process.process_definition_identifier + '.' + self.activity_definition_identifier ) class WorkItemFinished: def __init__(self, workitem, application, parameters, results): self.workitem = workitem self.application = application self.parameters = parameters self.results = results def __repr__(self): return "WorkItemFinished(%r)" % self.application class Transition: def __init__(self, from_, to): self.from_ = from_ self.to = to def __repr__(self): return "Transition(%r, %r)" % (self.from_, self.to) class ActivityFinished: def __init__(self, activity): self.activity = activity def __repr__(self): return "ActivityFinished(%r)" % self.activity class ActivityStarted: def __init__(self, activity): self.activity = activity def __repr__(self): return "ActivityStarted(%r)" % self.activity class Parameter(object): interface.implements(interfaces.IParameterDefinition) input = output = False def __init__(self, name): self.__name__ = name class OutputParameter(Parameter): output = True class InputParameter(Parameter): input = True class InputOutputParameter(InputParameter, OutputParameter): pass class Application: interface.implements(interfaces.IApplicationDefinition) def __init__(self, *parameters): self.parameters = parameters def defineParameters(self, *parameters): self.parameters += parameters def __repr__(self): input = u', '.join([param.__name__ for param in self.parameters if param.input == True]) output = u', '.join([param.__name__ for param in self.parameters if param.output == True]) return "<Application %r: (%s) --> (%s)>" %(self.__name__, input, output) class Participant: interface.implements(interfaces.IParticipantDefinition) def __init__(self, name=None): self.__name__ = name self.description = None def __repr__(self): return "Participant(%r)" %self.__name__
zope.wfmc
/zope.wfmc-3.5.0.tar.gz/zope.wfmc-3.5.0/src/zope/wfmc/process.py
process.py
import sys import xml.sax import xml.sax.xmlreader import xml.sax.handler import zope.wfmc.process xpdlns = "http://www.wfmc.org/2002/XPDL1.0" class HandlerError(Exception): def __init__(self, orig, tag, locator): self.orig = orig self.tag = tag self.xml = locator.getSystemId() self.line = locator.getLineNumber() def __repr__(self): return ('%r\nFile "%s", line %s. in %s' % (self.orig, self.xml, self.line, self.tag)) def __str__(self): return ('%s\nFile "%s", line %s. in %s' % (self.orig, self.xml, self.line, self.tag)) class Package(dict): def __init__(self): self.applications = {} self.participants = {} def defineApplications(self, **applications): for id, application in applications.items(): application.id = id self.applications[id] = application def defineParticipants(self, **participants): for id, participant in participants.items(): participant.id = id self.participants[id] = participant class XPDLHandler(xml.sax.handler.ContentHandler): start_handlers = {} end_handlers = {} text = u'' ProcessDefinitionFactory = zope.wfmc.process.ProcessDefinition ParticipantFactory = zope.wfmc.process.Participant ApplicationFactory = zope.wfmc.process.Application ActivityDefinitionFactory = zope.wfmc.process.ActivityDefinition TransitionDefinitionFactory = zope.wfmc.process.TransitionDefinition def __init__(self, package): self.package = package self.stack = [] def startElementNS(self, name, qname, attrs): handler = self.start_handlers.get(name) if handler: try: result = handler(self, attrs) except: raise HandlerError(sys.exc_info()[1], name[1], self.locator ), None, sys.exc_info()[2] else: result = None if result is None: # Just dup the top of the stack result = self.stack[-1] self.stack.append(result) self.text = u'' def endElementNS(self, name, qname): last = self.stack.pop() handler = self.end_handlers.get(name) if handler: try: handler(self, last) except: raise HandlerError(sys.exc_info()[1], name[1], self.locator ), None, sys.exc_info()[2] self.text = u'' def characters(self, text): self.text += text def setDocumentLocator(self, locator): self.locator = locator ###################################################################### # Application handlers # Pointless container elements that we want to "ignore" by having them # dup their containers: def Package(self, attrs): package = self.package package.id = attrs[(None, 'Id')] package.__name__ = attrs.get((None, 'Name')) return package start_handlers[(xpdlns, 'Package')] = Package def WorkflowProcess(self, attrs): id = attrs[(None, 'Id')] process = self.ProcessDefinitionFactory(id) process.__name__ = attrs.get((None, 'Name')) # Copy package data: process.defineApplications(**self.package.applications) process.defineParticipants(**self.package.participants) self.package[id] = process return process start_handlers[(xpdlns, 'WorkflowProcess')] = WorkflowProcess paramter_types = { 'IN': zope.wfmc.process.InputParameter, 'OUT': zope.wfmc.process.OutputParameter, 'INOUT': zope.wfmc.process.InputOutputParameter, } def FormalParameter(self, attrs): mode = attrs.get((None, 'Mode'), 'IN') id = attrs[(None, 'Id')] self.stack[-1].defineParameters(*[self.paramter_types[mode](id)]) start_handlers[(xpdlns, 'FormalParameter')] = FormalParameter def Participant(self, attrs): id = attrs[(None, 'Id')] name = attrs.get((None, 'Name')) participant = self.ParticipantFactory(name) self.stack[-1].defineParticipants(**{str(id): participant}) return participant start_handlers[(xpdlns, 'Participant')] = Participant def Application(self, attrs): id = attrs[(None, 'Id')] name = attrs.get((None, 'Name')) app = self.ApplicationFactory() app.id = id if name: app.__name__ = name return app start_handlers[(xpdlns, 'Application')] = Application def application(self, app): self.stack[-1].defineApplications(**{str(app.id): app}) end_handlers[(xpdlns, 'Application')] = application def description(self, ignored): if self.stack[-1] is not None: self.stack[-1].description = self.text end_handlers[(xpdlns, 'Description')] = description ###################################################################### # Activity definitions def ActivitySet(self, attrs): raise NotImplementedError("ActivitySet") end_handlers[(xpdlns, 'ActivitySet')] = ActivitySet def Activity(self, attrs): id = attrs[(None, 'Id')] name = attrs.get((None, 'Name')) activity = self.ActivityDefinitionFactory(name) activity.id = id self.stack[-1].defineActivities(**{str(id): activity}) return activity start_handlers[(xpdlns, 'Activity')] = Activity def Tool(self, attrs): return Tool(attrs[(None, 'Id')]) start_handlers[(xpdlns, 'Tool')] = Tool def tool(self, tool): self.stack[-1].addApplication(tool.id, tool.parameters) end_handlers[(xpdlns, 'Tool')] = tool def actualparameter(self, ignored): self.stack[-1].parameters += (self.text, ) end_handlers[(xpdlns, 'ActualParameter')] = actualparameter def performer(self, ignored): self.stack[-1].definePerformer(self.text.strip()) end_handlers[(xpdlns, 'Performer')] = performer def Join(self, attrs): Type = attrs.get((None, 'Type')) if Type == u'AND': self.stack[-1].andJoin(True) start_handlers[(xpdlns, 'Join')] = Join def Split(self, attrs): Type = attrs.get((None, 'Type')) if Type == u'AND': self.stack[-1].andSplit(True) start_handlers[(xpdlns, 'Split')] = Split def TransitionRef(self, attrs): Id = attrs.get((None, 'Id')) self.stack[-1].addOutgoing(Id) start_handlers[(xpdlns, 'TransitionRef')] = TransitionRef # Activity definitions ###################################################################### def Transition(self, attrs): id = attrs[(None, 'Id')] name = attrs.get((None, 'Name')) from_ = attrs.get((None, 'From')) to = attrs.get((None, 'To')) transition = self.TransitionDefinitionFactory(from_, to) transition.id = id transition.__name__ = name return transition start_handlers[(xpdlns, 'Transition')] = Transition def transition(self, transition): self.stack[-1].defineTransitions(transition) end_handlers[(xpdlns, 'Transition')] = transition def condition(self, ignored): assert isinstance(self.stack[-1], self.TransitionDefinitionFactory) text = self.text self.stack[-1].condition = TextCondition("(%s)" % text) end_handlers[(xpdlns, 'Condition')] = condition class Tool: def __init__(self, id): self.id = id parameters = () class TextCondition: def __init__(self, source): self.source = source # make sure that we can compile the source compile(source, '<string>', 'eval') def __getstate__(self): return {'source': self.source} def __call__(self, data): # We *depend* on being able to use the data's dict. # TODO This needs to be part of the contract. try: compiled = self._v_compiled except AttributeError: self._v_compiled = compile(self.source, '<string>', 'eval') compiled = self._v_compiled return eval(compiled, {'__builtins__': None}, data.__dict__) def read(file): src = xml.sax.xmlreader.InputSource(getattr(file, 'name', '<string>')) src.setByteStream(file) parser = xml.sax.make_parser() package = Package() parser.setContentHandler(XPDLHandler(package)) parser.setFeature(xml.sax.handler.feature_namespaces, True) parser.parse(src) return package
zope.wfmc
/zope.wfmc-3.5.0.tar.gz/zope.wfmc-3.5.0/src/zope/wfmc/xpdl.py
xpdl.py
# TODO: This doesn't work properly for protocol 2 pickles yet; that # still needs to be dealt with. Particular issues that need to be # addressed involve supporting the changes for new-style objects. import base64 import marshal import re import struct from pickle import Unpickler from pickle import \ PERSID, NONE, INT, BININT, BININT1, BININT2, LONG, FLOAT, \ BINFLOAT, STRING, BINSTRING, SHORT_BINSTRING, UNICODE, \ BINUNICODE, TUPLE, EMPTY_TUPLE, EMPTY_LIST, EMPTY_DICT, LIST, \ DICT, INST, OBJ, GLOBAL, REDUCE, GET, BINGET, LONG_BINGET, PUT, \ BINPUT, LONG_BINPUT, STOP, MARK, BUILD, SETITEMS, SETITEM, \ BINPERSID, APPEND, APPENDS try: from pickle import NEWTRUE, NEWFALSE except ImportError: TRUE = INT + "01\n" FALSE = INT + "00\n" _bool_support = False else: TRUE = NEWTRUE FALSE = NEWFALSE _bool_support = True from cStringIO import StringIO mdumps = marshal.dumps mloads = marshal.loads identifier = re.compile("^[_a-zA-Z][_a-zA-Z0-9]{1,40}$").match def _convert_sub(string): # We don't want to get returns "normalized away, so we quote them # This means we can't use cdata. rpos = string.find('\r') lpos = string.find('<') apos = string.find('&') if rpos >= 0 or lpos >= 0 or apos >= 0: # Need to do something about special characters if rpos < 0 and string.find(']]>') < 0: # can use cdata string = "<![CDATA[%s]]>" % string else: if apos >= 0: string = string.replace("&", "&amp;") if lpos >= 0: string = string.replace("<", "&lt;") if rpos >= 0: string = string.replace("\r", "&#x0d;") return '', string # Function unconvert takes a encoding and a string and # returns the original string def unconvert_string(encoding, string): if encoding == 'base64': return base64.decodestring(string) elif encoding: raise ValueError('bad encoding', encoding) return string def unconvert_unicode(encoding, string): if encoding == 'base64': string = base64.decodestring(string.encode('ascii')) elif encoding: raise ValueError('bad encoding', encoding) return string class Base(object): id = '' def __str__(self): result = [] self.output(result.append) return ''.join(result) def output(self, data, indent=0): raise TypeError("No output method defined") def __eq__(self, other): if self is other: return 1 if type(self) != type(other): return 1 return self.__dict__ == other.__dict__ class Global(Base): def __init__(self, module, name): self.module=module self.name=name def output(self, write, indent=0): if self.id: id = ' id="%s"' % self.id else: id = '' name = self.__class__.__name__.lower() write( '%s<%s%s name="%s" module="%s"/>\n' % ( ' '*indent, name, id, self.name, self.module) ) _reconstructor_global = Global('copy_reg', '_reconstructor') _object_global = Global('__builtin__', 'object') class Scalar(Base): def __init__(self, v): self._v=v def value(self): return self._v def output(self, write, indent=0, strip=0): if self.id: id = ' id="%s"' % self.id else: id = '' name = self.__class__.__name__.lower() write( '%s<%s%s>%s</%s>' % ( ' '*indent, name, id, self.value(), name) ) if not strip: write('\n') class Int(Scalar): pass class Long(Scalar): def value(self): result = str(self._v) return result class Float(Scalar): def value(self): return `self._v` _binary_char = re.compile("[^\n\t\r -\x7e]").search class String(Scalar): def __init__(self, v, encoding=''): encoding, v = self.convert(v) self.encoding = encoding Scalar.__init__(self, v) def convert(self, string): """Convert a string to a form that can be included in XML text""" if _binary_char(string): string = base64.encodestring(string)[:-1] return 'base64', string return _convert_sub(string) def output(self, write, indent=0, strip=0): if self.id: id = ' id="%s"' % self.id else: id = '' encoding = getattr(self, 'encoding', '') if encoding: encoding = ' encoding="%s"' % encoding else: encoding = '' name = self.__class__.__name__.lower() write('%s<%s%s%s>' % (' '*indent, name, id, encoding)) write(self.value()) write('</%s>' % name) if not strip: write('\n') # TODO: use of a regular expression here seems to be brittle # due to fuzzy semantics of unicode "surrogates". # Eventually, we should probably rewrite this as a C # function. _invalid_xml_char = re.compile( u'[' u'\x00-\x08' u'\x0b-\x0c' u'\x0e-\x1f' # Hack to get around utf-8 encoding bug(?) for surogates. + unichr(0xd800)+u'-'+unichr(0xdfff) + # u'\ud800-\udfff' u'\ufffe\uffff' u']' ).search class Unicode(String): def convert(self, string): if _invalid_xml_char(string): string = string.encode('utf-8') string = base64.encodestring(string)[:-1] return 'base64', string return _convert_sub(string.encode('utf-8')) class Wrapper(Base): def __init__(self, v): self._v = v def value(self): return self._v def output_nonscalar(self, write, name, id, v, str_indent, indent): write('%s<%s%s>\n' % (str_indent, name, id)) v.output(write, indent+2) write('%s</%s>\n' % (str_indent, name)) def output(self, write, indent=0): if self.id: id = ' id="%s"' % self.id else: id = '' name = self.__class__.__name__.lower() v = self._v str_indent = ' '*indent if isinstance(v, Scalar): write('%s<%s%s> ' % (str_indent, name, id)) v.output(write, strip=1) write(' </%s>\n' % name) else: return self.output_nonscalar( write, name, id, v, str_indent, indent) class CloseWrapper(Wrapper): # TODO: This doesn't do what I want anymore because we can't strip v def _output_nonscalar(self, write, name, id, v, str_indent, indent): write('%s<%s%s> ' % (str_indent, name, id)) v.output(write, indent+2) write(' </%s>\n' % name) class Collection(Base): def value(self, write, indent): raise AttributeError('value') def output(self, write, indent=0): if self.id: id = ' id="%s"' % self.id else: id= '' name = self.__class__.__name__.lower() i=' '*indent if self: write('%s<%s%s>\n' % (i, name, id)) self.value(write, indent+2) write('%s</%s>\n' % (i, name)) else: write('%s<%s%s />\n' % (i, name, id)) class Key(Wrapper): pass class Name(Wrapper): pass class Value(Wrapper): pass class Dictionary(Collection): key_name = 'key' item_name = 'item' key_class = Key def __init__(self): self._d = [] def __len__(self): return len(self._d) def __setitem__(self, k, v): self._d.append((k,v)) def value(self, write, indent): ind = ' '*indent ind4 = indent+4 begin = '%s<%s>\n' % (ind, self.item_name) end = '%s</%s>\n' % (ind, self.item_name) for key, value in self._d: if (key.__class__ is String and not key.encoding and identifier(key.value()) ): id = getattr(key, 'id', '') if id: id = ' id="%s"' % id write('%s<%s %s="%s"%s>\n' % (ind, self.item_name, self.key_name, key.value(), id)) value.output(write, ind4) write(end) else: write(begin) ind2 = indent+2 self.key_class(key).output(write, ind2) Value(value).output(write, ind2) write(end) class Attributes(Dictionary): key_name = 'name' item_name = 'attribute' key_class = Name def __init__(self, dictionary): Dictionary.__init__(self) self.__dict__.update(dictionary.__dict__) class Sequence(Collection): def __init__(self, v=None): if not v: v = [] self._subs = v def __getitem__(self, i): return self._subs[i] def __len__(self): return len(self._subs) def append(self, v): self._subs.append(v) def extend(self, v): self._subs.extend(v) def value(self, write, indent): for v in self._subs: v.output(write, indent) class List(Sequence): pass class Tuple(Sequence): pass class Klass(CloseWrapper): pass class Arguments(CloseWrapper): pass class State(CloseWrapper): pass class Pickle(Wrapper): pass class Persistent(Wrapper): pass class NamedScalar(Scalar): def __init__(self, name): self.name = name def output(self, write, indent=0, strip=0): write("%s<%s/>" % (' '*indent, self.name)) if not strip: write('\n') none = NamedScalar("none") true = NamedScalar("true") false = NamedScalar("false") class Reference(Scalar): def output(self, write, indent=0, strip=0): write('%s<reference id="%s"/>' % (' '*indent,self._v)) if not strip: write('\n') Get=Reference # Get is pickle name, but Reference is nicer name class Object(Sequence): pass class Classic_Object(Sequence): pass class Initialized_Object(Sequence): def __init__(self, klass, args): self.klass = klass self.args = args Sequence.__init__(self, [Klass(klass), Arguments(args)]) def __setstate__(self, v): self.state = v self.append(State(v)) def output(self, write, indent=0): klass = self.klass args = self.args if (klass == _reconstructor_global and isinstance(args, Tuple) and len(args) == 3 and args[1] == _object_global and args[2] == none and isinstance(getattr(self, 'state', None), Dictionary) ): klass = args[0] return Object((Klass(klass), Attributes(self.state), ) ).output(write, indent) if (not args and isinstance(getattr(self, 'state', None), Dictionary)): # Common simple case we want to optimize return Classic_Object((self._subs[0], Attributes(self.state) ) ).output(write, indent) return Sequence.output(self, write, indent) class ToXMLUnpickler(Unpickler): def __init__(self, *args): Unpickler.__init__(self, *args) self.__put_objects = {} self.__get_info = {} # id and object self.__got = 0 def load(self): return Pickle(Unpickler.load(self)) dispatch = {} dispatch.update(Unpickler.dispatch) def persistent_load(self, v): return Persistent(v) def load_persid(self): pid = self.readline()[:-1] self.append(self.persistent_load(String(pid))) dispatch[PERSID] = load_persid def load_none(self): self.append(none) dispatch[NONE] = load_none if _bool_support: def load_false(self): self.append(false) dispatch[NEWFALSE] = load_false def load_true(self): self.append(true) dispatch[NEWTRUE] = load_true def load_int(self): s = self.readline()[:-1] i = int(s) if s[0] == "0": if i == 1: self.append(true) return elif i == 0 and s != "0": # s == "00" self.append(false) return self.append(Int(i)) dispatch[INT] = load_int def load_binint(self): self.append(Int(mloads('i' + self.read(4)))) dispatch[BININT] = load_binint def load_binint1(self): self.append(Int(mloads('i' + self.read(1) + '\000\000\000'))) dispatch[BININT1] = load_binint1 def load_binint2(self): self.append(Int(mloads('i' + self.read(2) + '\000\000'))) dispatch[BININT2] = load_binint2 def load_long(self): self.append(Long(long(self.readline()[:-1], 0))) dispatch[LONG] = load_long def load_float(self): self.append(Float(float(self.readline()[:-1]))) dispatch[FLOAT] = load_float def load_binfloat(self, unpack=struct.unpack): self.append(Float(unpack('>d', self.read(8))[0])) dispatch[BINFLOAT] = load_binfloat def load_string(self): self.append(String(eval(self.readline()[:-1], {'__builtins__': {}}))) # Let's be careful dispatch[STRING] = load_string def load_binstring(self): len = mloads('i' + self.read(4)) self.append(String(self.read(len))) dispatch[BINSTRING] = load_binstring def load_short_binstring(self): len = mloads('i' + self.read(1) + '\000\000\000') self.append(String(self.read(len))) dispatch[SHORT_BINSTRING] = load_short_binstring def load_unicode(self): self.append(Unicode( unicode(self.readline()[:-1],'raw-unicode-escape') )) dispatch[UNICODE] = load_unicode def load_binunicode(self): len = mloads('i' + self.read(4)) self.append(Unicode(unicode(self.read(len),'utf-8'))) dispatch[BINUNICODE] = load_binunicode def load_tuple(self): k = self.marker() self.stack[k:] = [Tuple(self.stack[k+1:])] dispatch[TUPLE] = load_tuple def load_empty_tuple(self): self.stack.append(Tuple()) dispatch[EMPTY_TUPLE] = load_empty_tuple def load_empty_list(self): self.stack.append(List()) dispatch[EMPTY_LIST] = load_empty_list def load_empty_dictionary(self): self.stack.append(Dictionary()) dispatch[EMPTY_DICT] = load_empty_dictionary def load_list(self): k = self.marker() self.stack[k:] = [List(self.stack[k+1:])] dispatch[LIST] = load_list def load_dict(self): k = self.marker() d = Dictionary() items = self.stack[k+1:] for i in range(0, len(items), 2): key = items[i] value = items[i+1] d[key] = value self.stack[k:] = [d] dispatch[DICT] = load_dict def load_inst(self): k = self.marker() args = Tuple(self.stack[k+1:]) del self.stack[k:] module = self.readline()[:-1] name = self.readline()[:-1] value = Initialized_Object(Global(module, name), args) self.append(value) dispatch[INST] = load_inst def load_obj(self): stack = self.stack k = self.marker() klass = stack[k + 1] del stack[k + 1] args = Tuple(stack[k + 1:]) del stack[k:] value = Initialized_Object(klass,args) self.append(value) dispatch[OBJ] = load_obj def load_global(self): module = self.readline()[:-1] name = self.readline()[:-1] self.append(Global(module, name)) dispatch[GLOBAL] = load_global def load_reduce(self): stack = self.stack callable = stack[-2] arg_tup = stack[-1] del stack[-2:] value = Initialized_Object(callable, arg_tup) self.append(value) dispatch[REDUCE] = load_reduce idprefix = 'o' def __get(self, i): get_info = self.__get_info.get(i) if get_info is None: ob = self.__put_objects[i] if (ob.__class__ is String and not ob.encoding and identifier(ob.value()) ): # We don't want this memoized get_id = None else: get_id = `self.__got` self.__got += 1 ob.id = self.idprefix+get_id get_info = get_id, ob self.__get_info[i] = get_info else: get_id = get_info[0] if get_id is not None: # Normal case self.append(Get(self.idprefix+get_id)) else: ob = get_info[1] self.append(ob) def __put(self, i): ob = self.stack[-1] self.__put_objects[i] = ob def load_get(self): i = self.readline()[:-1] self.__get(i) dispatch[GET] = load_get def load_binget(self): i = mloads('i' + self.read(1) + '\000\000\000') self.__get(`i`) dispatch[BINGET] = load_binget def load_long_binget(self): i = mloads('i' + self.read(4)) self.__get(`i`) dispatch[LONG_BINGET] = load_long_binget def load_put(self): i = self.readline()[:-1] self.__put(i) dispatch[PUT] = load_put def load_binput(self): i = mloads('i' + self.read(1) + '\000\000\000') self.__put(`i`) dispatch[BINPUT] = load_binput def load_long_binput(self): i = mloads('i' + self.read(4)) self.__put(`i`) dispatch[LONG_BINPUT] = load_long_binput def ToXMLload(file): return ToXMLUnpickler(file).load() def ToXMLloads(str): file = StringIO(str) return ToXMLUnpickler(file).load() class xmlPickler(object): binary = 1 def __init__(self): self._stack = [] self._push([]) def _push(self, top): self._stack.append(top) self._append = top.append def _pop(self): _stack = self._stack top = _stack.pop() self._append = _stack[-1].append return top def handle_starttag(self, tag, attrs): # Convert attrs to dict, if necessary if type(attrs) is list: x=0 temp={} while x<len(attrs): temp[attrs[x]]=attrs[x+1] x=x+2 attrs=temp self._push([tag, attrs]) def handle_endtag(self, tag): top = self._pop() if tag == 'global': top = self.global_(tag, top) else: try: m = getattr(self, tag) except AttributeError: try: tag = tag.encode('us-ascii') except: pass raise ValueError( "unrecognized element in XML pickle: %r" % tag) else: top = m(tag, top) self._append(top) def handle_data(self, data): if data.strip() or (self._stack[-1][0] in ('string', 'unicode')): self._append(data) def get_value(self): for s in self._stack[0][0]: if type(s) is unicode: print self._stack[0][0] return ''.join(self._stack[0][0]) def pickle(self, tag, data, STOP_tuple = (STOP, )): v = data[2] if type(v) is list: v.append(STOP) else: v += STOP_tuple return v def none(self, tag, data, NONE_tuple = (NONE, )): return NONE_tuple def true(self, tag, data): return TRUE, def false(self, tag, data): return FALSE, def long(self, tag, data): return ((LONG + ''.join(data[2:]).strip().encode('ascii') + 'L\n'), ) def save_wrapper(self, tag, data): return data[2] arguments = value = key = name = klass = state = save_wrapper def persis(self, tag, data): v = tuple(data[2]) if self.binary: return v + (BINPERSID, ) else: return (PERSID, ) + v def persistent(self, tag, data): v = tuple(data[2]) if self.binary: return v + (BINPERSID, ) else: return (PERSID, ) + v def int(self, tag, data): object = ''.join(data[2:]).strip() if self.binary: object = int(object) # If the int is small enough to fit in a signed 4-byte 2's-comp # format, we can store it more efficiently than the general # case. high_bits = object >> 31 # note that Python shift sign-extends if high_bits == 0 or high_bits == -1: # All high bits are copies of bit 2**31, so the value # fits in a 4-byte signed int. i = mdumps(object)[1:] assert len(i) == 4 if i[-2:] == '\000\000': # fits in 2-byte unsigned int if i[-3] == '\000': # fits in 1-byte unsigned int return (BININT1, i[0]) else: return (BININT2, i[:2]) else: return (BININT, i) # Text pickle, or int too big to fit in signed 4-byte format. return (INT, object, '\n') def float(self, tag, data): v = ''.join(data[2:]).strip().encode('ascii') if self.binary: return BINFLOAT, struct.pack('>d',float(v)) else: return FLOAT, v, '\n' def _string(self, v, attrs): if self.binary: l = len(v) s = mdumps(l)[1:] if (l<256): v = SHORT_BINSTRING, s[0], v else: v = BINSTRING, s, v else: v = STRING, `v`, "\n" return self.put(v, attrs) def string(self, tag, data): v = ''.join(data[2:]).encode('ascii') attrs = data[1] encoding = attrs.get('encoding') if encoding: v = unconvert_string(encoding, v) return self._string(v, attrs) def unicode(self, tag, data): v = ''.join(data[2:]).encode('utf-8') attrs = data[1] encoding = attrs.get('encoding') if encoding: v = unconvert_unicode(encoding, v) if self.binary: # v = v.encode('utf-8') l = len(v) s = mdumps(l)[1:] v = (BINUNICODE, s, v) else: v = unicode(v, 'utf-8') v = v.replace("\\", "\\u005c") v = v.replace("\n", "\\u000a") v = (UNICODE, v.encode('raw-unicode-escape'), '\n') return self.put(v, attrs) def tuple(self, tag, data): T = data[2:] if not T: return (EMPTY_TUPLE, ) v = [MARK] for x in T: v.extend(x) v.append(TUPLE) return self.put(v, data[1]) def list(self, tag, data, EMPTY_LIST_tuple = (EMPTY_LIST, )): L = data[2:] attrs = data[1] v = [] if self.binary: v.extend(self.put(EMPTY_LIST_tuple, attrs)) if L: v.append(MARK) for x in L: v.extend(x) v.append(APPENDS) else: v.extend(self.put((MARK, LIST), attrs)) for x in L: v.extend(x) v.append(APPEND) return v def put(self, v, attrs): """Add a PUT command, if necessary. If v is a list, then the PUT is added to the list and the list is returned. """ id = attrs.get('id', '').encode('ascii') if id: prefix = id.rfind('.') if prefix >= 0: id=id[prefix+1:] elif id[0] in 'io': id=id[1:] if self.binary: id=int(id) s=mdumps(id)[1:] if (id < 256): id=s[0] put = BINPUT else: id=s put= LONG_BINPUT id=put+id else: id=PUT+id+"\012" if type(v) is list: v.append(id) else: v = v + (id, ) return v def dictionary(self, tag, data, EMPTY_DICT_tuple = (EMPTY_DICT, )): D = data[2:] v = [] if self.binary: v.extend(self.put(EMPTY_DICT_tuple, data[1])) if D: v.append(MARK) for x in D: v.extend(x) v.append(SETITEMS) else: v.extend(self.put((MARK, DICT), data[1])) for x in D: v.extend(x) v.append(SETITEM) return v attributes = dictionary def reference(self, tag, data): attrs = data[1] id = attrs['id'].encode('ascii') prefix = id.rfind('.') if prefix >= 0: id = id[prefix+1:] elif id[0] in 'oi': id = id[1:] get = GET if self.binary: id=int(id) s=mdumps(id)[1:] if (id < 256): id=s[0] get = BINGET else: id = s get = LONG_BINGET v=get+id else: v=get+id+'\n' return (v, ) def initialized_object(self, tag, data): args_pickle = data[3] v = [MARK] v.extend(data[2]) if args_pickle != (EMPTY_TUPLE, ): v.extend(args_pickle[1:-1]) v.append(OBJ) v = self.put(v, data[1]) if len(data) > 4: v.extend(data[4]) v.append(BUILD) return v def object(self, tag, data): v = ['(ccopy_reg\n_reconstructor\n'] v.extend(data[2]) v.append('c__builtin__\nobject\nN') v.append(OBJ) v = self.put(v, data[1]) v.extend(data[3]) v.append(BUILD) return v def classic_object(self, tag, data): v = [MARK] v.extend(data[2]) v.append(OBJ) v = self.put(v, data[1]) v.extend(data[3]) v.append(BUILD) return v def global_(self, tag, data): attrs=data[1] module = attrs['module'].encode('ascii') name = attrs['name'].encode('ascii') return self.put((GLOBAL, module, '\n', name, '\n'), attrs) def item(self, tag, data, key_name = 'key'): attrs = data[1] if key_name in attrs: assert len(data) == 3 key = attrs[key_name].encode('ascii') key = self._string(key, attrs) value = data[2] if type(value) is list: value[0:0] = list(key) else: value = tuple(key) + value return value else: assert len(data) == 4 key = data[2] if type(key) is not list: key = list(key) key.extend(data[3]) return key def attribute(self, tag, data): return self.item(tag, data, 'name')
zope.xmlpickle
/zope.xmlpickle-3.4.0.tar.gz/zope.xmlpickle-3.4.0/src/zope/xmlpickle/ppml.py
ppml.py
from xml.parsers import expat from cStringIO import StringIO from cPickle import loads as _standard_pickle_loads from pickle import \ Pickler as _StandardPickler, \ MARK as _MARK, \ EMPTY_DICT as _EMPTY_DICT, \ DICT as _DICT, \ SETITEM as _SETITEM, \ SETITEMS as _SETITEMS from zope.xmlpickle import ppml class _PicklerThatSortsDictItems(_StandardPickler): dispatch = {} dispatch.update(_StandardPickler.dispatch) def save_dict(self, object): d = id(object) write = self.write save = self.save memo = self.memo if self.bin: write(_EMPTY_DICT) else: write(_MARK + _DICT) memo_len = len(memo) self.write(self.put(memo_len)) memo[d] = (memo_len, object) using_setitems = (self.bin and (len(object) > 1)) if using_setitems: write(_MARK) items = object.items() items.sort() for key, value in items: save(key) save(value) if not using_setitems: write(_SETITEM) if using_setitems: write(_SETITEMS) dispatch[dict] = save_dict def _dumpsUsing_PicklerThatSortsDictItems(object, bin = 0): file = StringIO() _PicklerThatSortsDictItems(file, bin).dump(object) return file.getvalue() def toxml(p, index=0): """Convert a standard Python pickle to xml You can provide a pickle string and get XML of an individual pickle: >>> import pickle >>> s = pickle.dumps(42) >>> print toxml(s).strip() <?xml version="1.0" encoding="utf-8" ?> <pickle> <int>42</int> </pickle> If the string contains multiple pickles: >>> l = [1] >>> import StringIO >>> f = StringIO.StringIO() >>> pickler = pickle.Pickler(f) >>> pickler.dump(l) >>> pickler.dump(42) >>> pickler.dump([42, l]) >>> s = f.getvalue() You can supply indexes to access individual pickles: >>> print toxml(s).strip() <?xml version="1.0" encoding="utf-8" ?> <pickle> <list> <int>1</int> </list> </pickle> >>> print toxml(s, 0).strip() <?xml version="1.0" encoding="utf-8" ?> <pickle> <list> <int>1</int> </list> </pickle> >>> print toxml(s, 1).strip() <?xml version="1.0" encoding="utf-8" ?> <pickle> <int>42</int> </pickle> >>> print toxml(s, 2).strip() <?xml version="1.0" encoding="utf-8" ?> <pickle> <list> <int>42</int> <reference id="o0"/> </list> </pickle> Note that all of the pickles in a string share a common memo, so the last pickle in the example above has a reference to the list pickled in the first pickle. """ u = ppml.ToXMLUnpickler(StringIO(p)) while index > 0: xmlob = u.load() index -= 1 xmlob = u.load() r = ['<?xml version="1.0" encoding="utf-8" ?>\n'] xmlob.output(r.append) return ''.join(r) def dumps(ob): """Serialize an object to XML """ p = _dumpsUsing_PicklerThatSortsDictItems(ob, 1) return toxml(p) def fromxml(xml): """Convert xml to a standard Python pickle """ handler = ppml.xmlPickler() parser = expat.ParserCreate() parser.CharacterDataHandler = handler.handle_data parser.StartElementHandler = handler.handle_starttag parser.EndElementHandler = handler.handle_endtag parser.Parse(xml) pickle = handler.get_value() pickle = str(pickle) return pickle def loads(xml): """Create an object from serialized XML """ pickle = fromxml(xml) ob = _standard_pickle_loads(pickle) return ob
zope.xmlpickle
/zope.xmlpickle-3.4.0.tar.gz/zope.xmlpickle-3.4.0/src/zope/xmlpickle/xmlpickle.py
xmlpickle.py
Changelog ========= 0.9 - 2013-03-02 ---------------- - Modernized `z2_kgs` code and updated it to work with Github. - Modernized `ztk_kgs` code and skip the `zopeapp-versions` file for ZTK 2+. 0.8 - 2010-09-09 ---------------- - Do not override existing version pins defined in the ``versions.cfg`` by versions from the extends lines. This refs https://bugs.launchpad.net/zope2/+bug/623428. 0.7 - 2010-07-13 ---------------- - Added support for having an ``extends`` line pointing to another version file and still creating a full index. 0.6 - 2010-07-13 ---------------- - Support packages with underscores in their name. 0.5 - 2010-06-30 ---------------- - Disable the index building for a ZTK release. 0.4 - 2010-06-26 ---------------- - Added support for creating a Zope Toolkit index. - Update ``package_urls`` to ``release_urls`` as specified in http://wiki.python.org/moin/PyPiXmlRpc. 0.3 - 2010-06-13 ---------------- - Added support for inline comments in the versions section. - Readme style fixes. 0.2 - 2010-04-05 ---------------- * Avoid hardcoded upper_names list. 0.1.5 - 2009-12-25 ------------------ * sanity check for download_url * better parameter check 0.1.4 - 2009-08-06 ------------------ * better parameter check 0.1.3 - 2009-04-25 ------------------ * generate a versions.cfg file within the index directory 0.1.2 - 2009-04-25 ------------------ * removed hard-coded Zope 2 version 0.1.1 - 2009-04-25 ------------------ * bahhh...fixed broken package 0.1.0 - 2009-04-24 ------------------ * Initial release
zope.z2release
/zope.z2release-0.9.zip/zope.z2release-0.9/CHANGES.rst
CHANGES.rst
Changelog ========= 0.8 (2016-04-28) ---------------- - Add a ``ZopeCookieSession.set`` method (PR #4). 0.7.1 (2015-12-16) ------------------ - Packaging bug: fix rendering of ``README.txt`` in ``--long-description`` output. 0.7 (2015-12-16) ---------------- - Fix example ZCML snippet in ``README.rst`` (PR #3). - Fix ZCML namespace in ``zope2/sessioncookie/meta.zcml`` (PR #3). - Add script for uninstalling the root traversal hook (PR #2). 0.6.1 (2015-12-08) ------------------ - Packaging bug: add missing ``MANIFEST.in``. 0.6 (2015-11-23) ---------------- - Transferred copyright to Zope Foundation, relicensed to ZPL 2.1. - Rename from ``zope2.signedsessioncookie`` -> ``zope2.sessioncookie``. - Replace locally-defined ``EncryptingPickleSerialzer`` with ``pyramid_nacl_session.EncryptedSerializer``. Closes #8 and #9. 0.5 (2015-10-08) ---------------- - Add support for (optionally) encrypting session cookies, rather than signing them. 0.4 (2015-10-05) ---------------- - Add an attribute, ``signedsessioncookie_installed``, to the root object during installation. 0.3 (2015-09-30) ---------------- - Fix rendering ``http_only`` cookie attribute. 0.2 (2015-09-29) ---------------- - Add support for extra Pyramid session configuration via ZCML: ``hash_algorithm``, ``timeout``, ``reissue_time``. - Suppress empty / None values in cookie attributes passed to ``ZPublisher.HTTPResponse.setCookie``. - Refactor install script to allow reuse from other modules. - Fix compatibility w/ ``zope.configuration 3.7.4``. 0.1 (2015-09-18) ---------------- - Initial release.
zope2.sessioncookie
/zope2.sessioncookie-0.8.tar.gz/zope2.sessioncookie-0.8/CHANGES.rst
CHANGES.rst
``zope2.sessioncookie`` ============================= Bridge to allow using Pyramid's `cookie session implementation <http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/sessions.html>`_ in Zope2. .. note:: Initial development of this library was sponsored by ZeOmega Inc. Installation ------------ 1. Clone the repository. E.g.:: $ cd /path/to/ $ git clone [email protected]:zopefoundation/zope2.sessioncookie 2. Get ``zope2.sessioncookie`` installed on the Python path. E.g.:: $ cd /path/to/zope2.sessioncookie $ /path/to/virtualenv_with_zope2/bin/pip install -e . ... 3. Copy / link the ``zope2.sessioncookie-meta.zcml`` file into the ``$INSTANCE_HOME/etc/package-includes`` of your Zope instance. (You might need to create the directory first.) E.g.:: $ cd /path/to/zopes_instance $ mkdir -p etc/package-includes $ cd etc/package-includes $ ln -s \ /path/to/zope2.sessioncookie/zope2.sessioncookie-meta.zcml . 4. Generate a 32-byte, hexlified secret:: $ /path/to/virtualenv_with_zope2/bin/print_secret DEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEF 4. Edit the ``site.zcml`` for your instance. E.g.:: $ cd /path/to/zopes_instance $ vim etc/site.zcml Add an XML namespace declaration at the top, e.g.:: xmlns:sc="https://github.com/zopefoundation/zope2.sessioncookie" Add a stanza near the end, configuring the cookie session. E.g.:: <sc:sessioncookie secret="DEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEF" secure="False" encrypt="True"/> 5. Run the installation script, which disables the standard session manager and adds the new hook. E.g.:: $ bin/zopectl run \ /path/to/zope2.sessioncookie/zope2/sessioncookie/scripts/install.py 6. (Re)start your Zope instance. Test methods which set session variables, and inspect request / response cookies to see that ``_ZopeId`` is no longer being set, while ``session`` *is* set (with encrypted, base64-encoded data).
zope2.sessioncookie
/zope2.sessioncookie-0.8.tar.gz/zope2.sessioncookie-0.8/README.rst
README.rst
from zope.interface import Attribute from zope.interface import Interface from zope.schema import Bool from zope.schema import Int from zope.schema import TextLine class ISignedSessionCookieConfig(Interface): """Schema for <sessioncookie> directive. """ secret = TextLine( title=u"Secret", description=u"Secret used to sign the cookie value", required=True, ) salt = TextLine( title=u"Salt", description=u"Salt used to sign the cookie value", required=False, ) cookie_name = TextLine( title=u"Cookie Name", description=u"Name of the session cookie", required=False, ) max_age = Int( title=u"Max Age", description=u"Max age (in seconds) of the session cookie", required=False, ) path = TextLine( title=u"Cookie Path", description=u"Path of the session cookie", required=False, ) domain = TextLine( title=u"Cookie Domain", description=u"Domain of the session cookie", required=False, ) secure = Bool( title=u"Secure", description=u"Return the session cookie only over HTTPS?", required=False, ) http_only = Bool( title=u"HTTP Only", description=u"Mark the session cookie invisible to Javascript?", required=False, ) hash_algorithm = TextLine( title=u"Hash Algorithm", description=u"Name of algorithm used to sign cookie state", default=u"sha512", required=False, ) timeout = Int( title=u"Timeout", description=u"Timeout (in seconds) for the session cookie value", required=False, ) reissue_time = Int( title=u"Reissue Time", description=u"Time (in seconds) for updating cookie value on access", required=False, ) encrypt = Bool( title=u"Encrypt Cookie", description=u"Encrypt cookie text (requires ``pyCrypto``)?", required=False, ) class ISignedSessionCookieCreated(Interface): """ Event interface for newly-created session. I.e., no session cookie was present in the browser beforehand. """ session = Attribute("Newly-created session")
zope2.sessioncookie
/zope2.sessioncookie-0.8.tar.gz/zope2.sessioncookie-0.8/zope2/sessioncookie/interfaces.py
interfaces.py
from AccessControl.SecurityInfo import ClassSecurityInfo from AccessControl.class_init import InitializeClass from ZPublisher.interfaces import IPubBeforeCommit from pyramid.session import BaseCookieSessionFactory from pyramid.session import SignedCookieSessionFactory from zope.component import adapter from zope.component import getUtility from zope.component import provideHandler from zope.event import notify from zope.interface import implementer from .interfaces import ISignedSessionCookieConfig from .interfaces import ISignedSessionCookieCreated ZopeCookieSession = None def _getSessionClass(): """Defer initializing session class parameters at import time. Wait until ZCA is available. """ global ZopeCookieSession if ZopeCookieSession is None: config = getUtility(ISignedSessionCookieConfig) attrs = config.getCookieAttrs() if 'serializer' in attrs: PyramidCookieSession = BaseCookieSessionFactory(**attrs) else: PyramidCookieSession = SignedCookieSessionFactory(**attrs) class ZopeCookieSession(PyramidCookieSession): """Wrap Pyramid's class, adding Zope2 security majyk. """ security = ClassSecurityInfo() security.setDefaultAccess('allow') security.declareObjectPublic() def __guarded_getitem__(self, key): return self[key] def __guarded_setitem__(self, key, value): self[key] = value def __guarded_delitem__(self, key): del self[key] def set(self, key, value): self[key] = value InitializeClass(ZopeCookieSession) return ZopeCookieSession @implementer(ISignedSessionCookieCreated) class SignedSessionCookieCreated(object): """Event implementation: new session created.""" def __init__(self, session): self.session = session def ssc_hook(container, request): """Hook for '__before_traverse__' on root object. Establishes 'pyramid.session'-compatible methods on request/response, and sets up the wrapper session class. """ # Make the request emulate Pyramid's response. request._response_callbacks = [] def _add_response_callback(func): request._response_callbacks.append(func) request.add_response_callback = _add_response_callback # Make the response emulate Pyramid's response. response = request.RESPONSE def _setCookie(name, value, quoted=True, **kw): scrubbed = dict([(k, v) for k, v in kw.items() if v]) scrubbed['http_only'] = scrubbed.pop('httponly') response.setCookie(name, value, quoted=quoted, **scrubbed) response.set_cookie = _setCookie # Set up the lazy SESSION implementation. klass = _getSessionClass() def _with_event(): session = klass(request) if klass._cookie_name not in request.cookies: notify(SignedSessionCookieCreated(session)) return session request.set_lazy('SESSION', _with_event) @adapter(IPubBeforeCommit) def _emulate_pyramid_response_callback(event): request = event.request response = request.RESPONSE for callback in getattr(request, '_response_callbacks', ()): callback(request, response) provideHandler(_emulate_pyramid_response_callback)
zope2.sessioncookie
/zope2.sessioncookie-0.8.tar.gz/zope2.sessioncookie-0.8/zope2/sessioncookie/__init__.py
__init__.py
============ Introduction ============ Zope2.ZodbBrowser is a web application to browse, inspect and introspect Zope's zodb objects. It is inspired on smalltalk's class browser and zodbbrowsers for zope3. There is a demo video available at `YouTube's menttes channel <http://www.youtube.com/watch?v=GkOpdnC5zvs/>`_. ==================================== Using ZodbBrowser with your buildout ==================================== If you already have a buildout for Zope2.13 or Plone4 running, edit buildout.cfg to add zope2.zodbbrowser to eggs and zcml sections at buildout and instance parts respectively. :: [buildout] ... eggs = zope2.zodbbrowser ... [instance] ... zcml = zope2.zodbbrowser Then run bin/buildout to make the changes effective. ================ Buildout Install ================ :: $ svn co http://zodbbrowser.googlecode.com/svn/buildout/ zodbbrowser $ python2.6 bootstrap.py $ bin/buildout -v $ bin/instance fg ================== Use of zodbbrowser ================== To access zodbbrowser add /zodbbrowser in your zope instance url, for example: http://localhost:8080/zodbbrowser ========= Changelog ========= 0.2 experimental version ------------------------ - Added ui.layout for better layout and resizable panels. Thanks to Quimera. - Updated jquery from 1.4.2 to 1.4.4. - Added Pretty printing format to show propertie's values. Thanks to Laurence Rowe and Emanuel Sartor. - Added support for older pythons 2.4 , 2.5. Thanks to Laurence Rowe. - Included module and file path for source code. Thanks to davidjb. - Added z3c.autoinclude.plugin support to remove the zcml entry on buildout. Thanks to aclark. 0.1 experimental version ------------------------ - Initial release includes: Class and Ancestors, Properties, Callables and Interfaces provided. - Support for Zope 2.13.x and Plone 4.0. Not tested with older or newer versions of Zope although it should work. - Support for Firefox 3.6 and Chrome 5.0. No support Internet Explorer yet.
zope2.zodbbrowser
/zope2.zodbbrowser-0.2.tar.gz/zope2.zodbbrowser-0.2/README.txt
README.txt
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile from Products.Five.browser import BrowserView from zope.interface import providedBy try: import json except ImportError: import simplejson as json error = "ERROR " class Elements(BrowserView): """For every object we clasify its kind of properties. """ def lista(self, is_call = 1): """ 1: callable, 2: not callable, 3: both """ elems = dir(self.context) result = [] for i in elems: try: elem = getattr(self.context, i) if callable(elem) and is_call == 1: result.append({"title": i}) if not callable(elem) and is_call == 2: result.append({"title": i}) if is_call == 3: result.append({"title": i}) except: result.append(error + i) return result def properties_and_callables(self): """ returns callables of the current context """ return json.dumps( self.lista(3) , ensure_ascii= True, indent=4) def properties(self): """ returns properties of the current context """ return json.dumps( self.lista(2) , ensure_ascii= True, indent=4) def callables(self): """ returns callables of the current context """ return json.dumps( self.lista(1) , ensure_ascii= True, indent=4) def interfaces(self): """ return interfaces provided by current context """ myobj = self.context myinterfaces = tuple(providedBy(self.context)) result = [ ] for i in myinterfaces: result.append({"title": i.__name__ }) return json.dumps( result , ensure_ascii= True, indent=4) def interfaces_not_provided(self): """ """ def adapts(self): """ """ from zope.component import getGlobalSiteManager sm = getGlobalSiteManager() aa = [i for i in sm.registeredAdapters()] def class_ancestors(self): """ """ content_tree = build_class_tree(self.context.__class__) return json.dumps(content_tree, ensure_ascii= True, indent=4) def build_class_tree(elem, level = 1024): if level <= 0 or elem == object: return None level -= 1 myclass = elem myclassbase = myclass.__bases__ node = {} children = [] for i in myclassbase: result = build_class_tree(i, level) if result: children.append(result) node["title"] = myclass.__name__ if len(children): node["children"] = children node["key"] = myclass.__name__ node["isFolder"] = True #node["isLazy"] = True return node
zope2.zodbbrowser
/zope2.zodbbrowser-0.2.tar.gz/zope2.zodbbrowser-0.2/zope2/zodbbrowser/right.py
right.py
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile from Products.Five.browser import BrowserView import inspect from zope.interface import providedBy from pprint import pformat try: import json except ImportError: import simplejson as json try: from pygments import highlight from pygments.lexers import PythonLexer from pygments.formatters import HtmlFormatter except: print 'no pygments' class Source(BrowserView): """ """ def get_method(self): """ """ myclass = self.context.__class__ try: mymethod_name = self.request['QUERY_STRING'].split('/')[0] except: return '' try: code = inspect.getsource(getattr( myclass, mymethod_name)) source = highlight(code, PythonLexer(), HtmlFormatter()) except TypeError: source = '<pre>' + inspect.getsource(getattr( myclass, mymethod_name)) + '</pre>' except NameError: source = inspect.getsource(getattr( myclass, mymethod_name)) except: source = "" status = 'Reading ' + inspect.getsourcefile(myclass) result = { 'status': status, 'bottom': source} return json.dumps(result, ensure_ascii= True, indent=4) def get_class(self): """ XXX: if the are a monkey patch i wont know about it """ myclass = self.context.__class__ ancestors = {} get_ancestors(myclass, ancestors) try: mysupclass_name = self.request['QUERY_STRING'].split('/')[0] except: return '' mysupclass = ancestors[mysupclass_name] try: code = '### Reading' + inspect.getsourcefile(mysupclass) code = inspect.getsource(mysupclass ) source = highlight(code, PythonLexer(), HtmlFormatter()) except TypeError: source = '<pre>' + inspect.getsource( mysupclass) + '</pre>' except NameError: source = inspect.getsource(mysupclass) except: source = "" status = 'Reading ' + inspect.getsourcefile(mysupclass) result = { 'status': status, 'bottom': source} return json.dumps(result, ensure_ascii= True, indent=4) def get_interface(self): """ """ try: myinterface_name = self.request['QUERY_STRING'].split('/')[0] except: return '' interfacesdict = {} get_interfaces( tuple(providedBy(self.context)) , interfacesdict) myiclass = interfacesdict[myinterface_name] try: code = inspect.getsource(myiclass) source = highlight(code, PythonLexer(), HtmlFormatter()) except TypeError: source = '<pre>' + inspect.getsource(myiclass) + '</pre>' except NameError: source = inspect.getsource(myiclass) except: source = "" status = 'Reading ' + inspect.getsourcefile(myiclass) result = { 'status': status, 'bottom': source} return json.dumps(result, ensure_ascii= True, indent=4) def get_property(self): """ Return property type and current value """ try: prop = getattr(self.context, self.request['QUERY_STRING'].split('/')[0]) status = 'Type: ' + str(type(prop)).replace(">","").replace("<","") code = pformat(prop) source = highlight(code, PythonLexer(), HtmlFormatter()) except TypeError: source = '<pre>' + str(prop) + '</pre>' except NameError: source = str(prop) except: source = "" result = { 'status': status, 'bottom': source} return json.dumps(result, ensure_ascii= True, indent=4) def get_interfaces(c, interfaces): for i in c: interfaces[i.__name__] = i def get_ancestors(c, ancestors = {}): ancestors[c.__name__] = c for i in c.__bases__: get_ancestors(i, ancestors)
zope2.zodbbrowser
/zope2.zodbbrowser-0.2.tar.gz/zope2.zodbbrowser-0.2/zope2/zodbbrowser/bottom.py
bottom.py
var _canLog = true; function _log(mode, msg) { /** * Usage: logMsg("%o was toggled", this); */ if( !_canLog ){ return; } // Remove first argument var args = Array.prototype.slice.apply(arguments, [1]); // Prepend timestamp var dt = new Date(); var tag = dt.getHours()+":"+dt.getMinutes()+":"+dt.getSeconds()+"."+dt.getMilliseconds(); args[0] = tag + " - " + args[0]; try { switch( mode ) { case "info": window.console.info.apply(window.console, args); break; case "warn": window.console.warn.apply(window.console, args); break; default: window.console.log.apply(window.console, args); break; } } catch(e) { if( !window.console ){ _canLog = false; // Permanently disable, when logging is not supported by the browser } } } function logMsg(msg) { Array.prototype.unshift.apply(arguments, ["debug"]); _log.apply(this, arguments); } // Forward declaration var getDynaTreePersistData = null; /************************************************************************* * Constants */ var DTNodeStatus_Error = -1; var DTNodeStatus_Loading = 1; var DTNodeStatus_Ok = 0; // Start of local namespace (function($) { /************************************************************************* * Common tool functions. */ var Class = { create: function() { return function() { this.initialize.apply(this, arguments); }; } }; // Tool function to get dtnode from the event target: function getDtNodeFromElement(el) { var iMax = 5; while( el && iMax-- ) { if(el.dtnode) { return el.dtnode; } el = el.parentNode; } return null; } function noop() { } /************************************************************************* * Class DynaTreeNode */ var DynaTreeNode = Class.create(); DynaTreeNode.prototype = { initialize: function(parent, tree, data) { /** * @constructor */ this.parent = parent; this.tree = tree; if ( typeof data === "string" ){ data = { title: data }; } if( data.key === undefined ){ data.key = "_" + tree._nodeCount++; } this.data = $.extend({}, $.ui.dynatree.nodedatadefaults, data); this.li = null; // not yet created this.span = null; // not yet created this.ul = null; // not yet created this.childList = null; // no subnodes yet this.isLoading = false; // Lazy content is being loaded this.hasSubSel = false; this.bExpanded = false; this.bSelected = false; }, toString: function() { return "DynaTreeNode<" + this.data.key + ">: '" + this.data.title + "'"; }, toDict: function(recursive, callback) { var dict = $.extend({}, this.data); dict.activate = ( this.tree.activeNode === this ); dict.focus = ( this.tree.focusNode === this ); dict.expand = this.bExpanded; dict.select = this.bSelected; if( callback ){ callback(dict); } if( recursive && this.childList ) { dict.children = []; for(var i=0, l=this.childList.length; i<l; i++ ){ dict.children.push(this.childList[i].toDict(true, callback)); } } else { delete dict.children; } return dict; }, fromDict: function(dict) { /** * Update node data. If dict contains 'children', then also replace * the hole sub tree. */ var children = dict.children; if(children === undefined){ this.data = $.extend(this.data, dict); this.render(); return; } dict = $.extend({}, dict); dict.children = undefined; this.data = $.extend(this.data, dict); this.removeChildren(); this.addChild(children); }, _getInnerHtml: function() { var opts = this.tree.options; var cache = this.tree.cache; var level = this.getLevel(); var res = ""; // connector (expanded, expandable or simple) if( level < opts.minExpandLevel ) { if(level > 1){ res += cache.tagConnector; } // .. else (i.e. for root level) skip expander/connector altogether } else if( this.hasChildren() !== false ) { res += cache.tagExpander; } else { res += cache.tagConnector; } // Checkbox mode if( opts.checkbox && this.data.hideCheckbox !== true && !this.data.isStatusNode ) { res += cache.tagCheckbox; } // folder or doctype icon if ( this.data.icon ) { res += "<img src='" + opts.imagePath + this.data.icon + "' alt='' />"; } else if ( this.data.icon === false ) { // icon == false means 'no icon' noop(); // keep JSLint happy } else { // icon == null means 'default icon' res += cache.tagNodeIcon; } // node name var tooltip = this.data.tooltip ? " title='" + this.data.tooltip + "'" : ""; if( opts.noLink || this.data.noLink ) { res += "<span style='display: inline-block;' class='" + opts.classNames.title + "'" + tooltip + ">" + this.data.title + "</span>"; }else{ res += "<a href='#' class='" + opts.classNames.title + "'" + tooltip + ">" + this.data.title + "</a>"; } return res; }, _fixOrder: function() { /** * Make sure, that <li> order matches childList order. */ var cl = this.childList; if( !cl ){ return; } var childLI = this.ul.firstChild; for(var i=0, l=cl.length-1; i<l; i++) { var childNode1 = cl[i]; var childNode2 = childLI.dtnode; if( childNode1 !== childNode2 ) { this.tree.logDebug("_fixOrder: mismatch at index " + i + ": " + childNode1 + " != " + childNode2); this.ul.insertBefore(childNode1.li, childNode2.li); } else { childLI = childLI.nextSibling; } } }, render: function(useEffects) { /** * create <li><span>..</span> .. </li> tags for this node. * * <li id='key'> // This div contains the node's span and list of child div's. * <span class='title'>S S S A</span> // Span contains graphic spans and title <a> tag * <ul> // only present, when node has children * <li>child1</li> * <li>child2</li> * </ul> * </li> */ // this.tree.logDebug("%s.render(%s)", this, useEffects); // --- var opts = this.tree.options; var cn = opts.classNames; var isLastSib = this.isLastSibling(); if( !this.parent && !this.ul ) { // Root node has only a <ul> this.li = this.span = null; this.ul = document.createElement("ul"); if( opts.minExpandLevel > 1 ){ this.ul.className = cn.container + " " + cn.noConnector; }else{ this.ul.className = cn.container; } } else if( this.parent ) { // Create <li><span /> </li> if( ! this.li ) { this.li = document.createElement("li"); this.li.dtnode = this; if( this.data.key && opts.generateIds ){ this.li.id = opts.idPrefix + this.data.key; } this.span = document.createElement("span"); this.span.className = cn.title; this.li.appendChild(this.span); if( !this.parent.ul ) { // This is the parent's first child: create UL tag // (Hidden, because it will be this.parent.ul = document.createElement("ul"); this.parent.ul.style.display = "none"; this.parent.li.appendChild(this.parent.ul); // if( opts.minExpandLevel > this.getLevel() ){ // this.parent.ul.className = cn.noConnector; // } } this.parent.ul.appendChild(this.li); } // set node connector images, links and text this.span.innerHTML = this._getInnerHtml(); // Set classes for current status var cnList = []; cnList.push(cn.node); if( this.data.isFolder ){ cnList.push(cn.folder); } if( this.bExpanded ){ cnList.push(cn.expanded); } if( this.hasChildren() !== false ){ cnList.push(cn.hasChildren); } if( this.data.isLazy && this.childList === null ){ cnList.push(cn.lazy); } if( isLastSib ){ cnList.push(cn.lastsib); } if( this.bSelected ){ cnList.push(cn.selected); } if( this.hasSubSel ){ cnList.push(cn.partsel); } if( this.tree.activeNode === this ){ cnList.push(cn.active); } if( this.data.addClass ){ cnList.push(this.data.addClass); } // IE6 doesn't correctly evaluate multiple class names, // so we create combined class names that can be used in the CSS cnList.push(cn.combinedExpanderPrefix + (this.bExpanded ? "e" : "c") + (this.data.isLazy && this.childList === null ? "d" : "") + (isLastSib ? "l" : "") ); cnList.push(cn.combinedIconPrefix + (this.bExpanded ? "e" : "c") + (this.data.isFolder ? "f" : "") ); this.span.className = cnList.join(" "); // TODO: we should not set this in the <span> tag also, if we set it here: this.li.className = isLastSib ? cn.lastsib : ""; // Hide children, if node is collapsed // this.ul.style.display = ( this.bExpanded || !this.parent ) ? "" : "none"; } if( this.bExpanded && this.childList ) { for(var i=0, l=this.childList.length; i<l; i++) { this.childList[i].render(); } this._fixOrder(); } // Hide children, if node is collapsed if( this.ul ) { var isHidden = (this.ul.style.display === "none"); var isExpanded = !!this.bExpanded; // logMsg("isHidden:%s", isHidden); if( useEffects && opts.fx && (isHidden === isExpanded) ) { var duration = opts.fx.duration || 200; $(this.ul).animate(opts.fx, duration); } else { this.ul.style.display = ( this.bExpanded || !this.parent ) ? "" : "none"; } } }, /** Return '/id1/id2/id3'. */ getKeyPath: function(excludeSelf) { var path = []; this.visitParents(function(node){ if(node.parent){ path.unshift(node.data.key); } }, !excludeSelf); return "/" + path.join(this.tree.options.keyPathSeparator); }, getParent: function() { return this.parent; }, getChildren: function() { return this.childList; }, /** Check if node has children (returns undefined, if not sure). */ hasChildren: function() { if(this.data.isLazy){ if(this.childList === null || this.childList === undefined){ // Not yet loaded return undefined; }else if(this.childList.length === 0){ // Loaded, but response was empty return false; }else if(this.childList.length === 1 && this.childList[0].isStatusNode()){ // Currently loading or load error return undefined; } return true; } return !!this.childList; }, isFirstSibling: function() { var p = this.parent; return !p || p.childList[0] === this; }, isLastSibling: function() { var p = this.parent; return !p || p.childList[p.childList.length-1] === this; }, getPrevSibling: function() { if( !this.parent ){ return null; } var ac = this.parent.childList; for(var i=1, l=ac.length; i<l; i++){ // start with 1, so prev(first) = null if( ac[i] === this ){ return ac[i-1]; } } return null; }, getNextSibling: function() { if( !this.parent ){ return null; } var ac = this.parent.childList; for(var i=0, l=ac.length-1; i<l; i++){ // up to length-2, so next(last) = null if( ac[i] === this ){ return ac[i+1]; } } return null; }, isStatusNode: function() { return (this.data.isStatusNode === true); }, isChildOf: function(otherNode) { return (this.parent && this.parent === otherNode); }, isDescendantOf: function(otherNode) { if(!otherNode){ return false; } var p = this.parent; while( p ) { if( p === otherNode ){ return true; } p = p.parent; } return false; }, /**Sort child list by title. * cmd: optional compare function. * deep: optional: pass true to sort all descendant nodes. */ sortChildren: function(cmp, deep) { var cl = this.childList; if( !cl ){ return; } cmp = cmp || function(a, b) { return a.data.title === b.data.title ? 0 : a.data.title > b.data.title; }; cl.sort(cmp); if( deep ){ for(var i=0, l=cl.length; i<l; i++){ if( cl[i].childList ){ cl[i].sortChildren(cmp, "$norender$"); } } } if( deep !== "$norender$" ){ this.render(); } }, _setStatusNode: function(data) { // Create, modify or remove the status child node (pass 'null', to remove it). var firstChild = ( this.childList ? this.childList[0] : null ); if( !data ) { if ( firstChild && firstChild.isStatusNode()) { try{ // I've seen exceptions here with loadKeyPath... if(this.ul){ this.ul.removeChild(firstChild.li); } }catch(e){} if( this.childList.length === 1 ){ this.childList = []; }else{ this.childList.shift(); } } } else if ( firstChild ) { data.isStatusNode = true; data.key = "_statusNode"; firstChild.data = data; firstChild.render(); } else { data.isStatusNode = true; data.key = "_statusNode"; firstChild = this.addChild(data); } }, setLazyNodeStatus: function(lts, opts) { var tooltip = (opts && opts.tooltip) ? opts.tooltip : null; var info = (opts && opts.info) ? " (" + opts.info + ")" : ""; switch( lts ) { case DTNodeStatus_Ok: this._setStatusNode(null); $(this.span).removeClass(this.tree.options.classNames.nodeLoading); this.isLoading = false; this.render(); if( this.tree.options.autoFocus ) { if( this === this.tree.tnRoot && this.childList && this.childList.length > 0) { // special case: using ajaxInit this.childList[0].focus(); } else { this.focus(); } } break; case DTNodeStatus_Loading: this.isLoading = true; $(this.span).addClass(this.tree.options.classNames.nodeLoading); // The root is hidden, so we set a temporary status child if(!this.parent){ this._setStatusNode({ title: this.tree.options.strings.loading + info, tooltip: tooltip, addClass: this.tree.options.classNames.nodeWait }); } break; case DTNodeStatus_Error: this.isLoading = false; // $(this.span).addClass(this.tree.options.classNames.nodeError); this._setStatusNode({ title: this.tree.options.strings.loadError + info, tooltip: tooltip, addClass: this.tree.options.classNames.nodeError }); break; default: throw "Bad LazyNodeStatus: '" + lts + "'."; } }, _parentList: function(includeRoot, includeSelf) { var l = []; var dtn = includeSelf ? this : this.parent; while( dtn ) { if( includeRoot || dtn.parent ){ l.unshift(dtn); } dtn = dtn.parent; } return l; }, getLevel: function() { /** * Return node depth. 0: System root node, 1: visible top-level node. */ var level = 0; var dtn = this.parent; while( dtn ) { level++; dtn = dtn.parent; } return level; }, _getTypeForOuterNodeEvent: function(event) { /** Return the inner node span (title, checkbox or expander) if * event.target points to the outer span. * This function should fix issue #93: * FF2 ignores empty spans, when generating events (returning the parent instead). */ var cns = this.tree.options.classNames; var target = event.target; // Only process clicks on an outer node span (probably due to a FF2 event handling bug) if( target.className.indexOf(cns.node) < 0 ) { return null; } // Event coordinates, relative to outer node span: var eventX = event.pageX - target.offsetLeft; var eventY = event.pageY - target.offsetTop; for(var i=0, l=target.childNodes.length; i<l; i++) { var cn = target.childNodes[i]; var x = cn.offsetLeft - target.offsetLeft; var y = cn.offsetTop - target.offsetTop; var nx = cn.clientWidth, ny = cn.clientHeight; // alert (cn.className + ": " + x + ", " + y + ", s:" + nx + ", " + ny); if( eventX >= x && eventX <= (x+nx) && eventY >= y && eventY <= (y+ny) ) { // alert("HIT "+ cn.className); if( cn.className==cns.title ){ return "title"; }else if( cn.className==cns.expander ){ return "expander"; }else if( cn.className==cns.checkbox ){ return "checkbox"; }else if( cn.className==cns.nodeIcon ){ return "icon"; } } } return "prefix"; }, getEventTargetType: function(event) { // Return the part of a node, that a click event occured on. // Note: there is no check, if the event was fired on TIHS node. var tcn = event && event.target ? event.target.className : ""; var cns = this.tree.options.classNames; if( tcn === cns.title ){ return "title"; }else if( tcn === cns.expander ){ return "expander"; }else if( tcn === cns.checkbox ){ return "checkbox"; }else if( tcn === cns.nodeIcon ){ return "icon"; }else if( tcn === cns.empty || tcn === cns.vline || tcn === cns.connector ){ return "prefix"; }else if( tcn.indexOf(cns.node) >= 0 ){ // FIX issue #93 return this._getTypeForOuterNodeEvent(event); } return null; }, isVisible: function() { // Return true, if all parents are expanded. var parents = this._parentList(true, false); for(var i=0, l=parents.length; i<l; i++){ if( ! parents[i].bExpanded ){ return false; } } return true; }, makeVisible: function() { // Make sure, all parents are expanded var parents = this._parentList(true, false); for(var i=0, l=parents.length; i<l; i++){ parents[i]._expand(true); } }, focus: function() { // TODO: check, if we already have focus // this.tree.logDebug("dtnode.focus(): %o", this); this.makeVisible(); try { $(this.span).find(">a").focus(); } catch(e) { } }, isFocused: function() { return (this.tree.tnFocused === this); }, _activate: function(flag, fireEvents) { // (De)Activate - but not focus - this node. this.tree.logDebug("dtnode._activate(%o, fireEvents=%o) - %o", flag, fireEvents, this); var opts = this.tree.options; if( this.data.isStatusNode ){ return; } if ( fireEvents && opts.onQueryActivate && opts.onQueryActivate.call(this.tree, flag, this) === false ){ return; // Callback returned false } if( flag ) { // Activate if( this.tree.activeNode ) { if( this.tree.activeNode === this ){ return; } this.tree.activeNode.deactivate(); } if( opts.activeVisible ){ this.makeVisible(); } this.tree.activeNode = this; if( opts.persist ){ $.cookie(opts.cookieId+"-active", this.data.key, opts.cookie); } this.tree.persistence.activeKey = this.data.key; $(this.span).addClass(opts.classNames.active); if ( fireEvents && opts.onActivate ){ opts.onActivate.call(this.tree, this); } } else { // Deactivate if( this.tree.activeNode === this ) { if ( opts.onQueryActivate && opts.onQueryActivate.call(this.tree, false, this) === false ){ return; // Callback returned false } $(this.span).removeClass(opts.classNames.active); if( opts.persist ) { // Note: we don't pass null, but ''. So the cookie is not deleted. // If we pass null, we also have to pass a COPY of opts, because $cookie will override opts.expires (issue 84) $.cookie(opts.cookieId+"-active", "", opts.cookie); } this.tree.persistence.activeKey = null; this.tree.activeNode = null; if ( fireEvents && opts.onDeactivate ){ opts.onDeactivate.call(this.tree, this); } } } }, activate: function() { // Select - but not focus - this node. // this.tree.logDebug("dtnode.activate(): %o", this); this._activate(true, true); }, activateSilently: function() { this._activate(true, false); }, deactivate: function() { // this.tree.logDebug("dtnode.deactivate(): %o", this); this._activate(false, true); }, isActive: function() { return (this.tree.activeNode === this); }, _userActivate: function() { // Handle user click / [space] / [enter], according to clickFolderMode. var activate = true; var expand = false; if ( this.data.isFolder ) { switch( this.tree.options.clickFolderMode ) { case 2: activate = false; expand = true; break; case 3: activate = expand = true; break; } } if( this.parent === null ) { expand = false; } if( expand ) { this.toggleExpand(); this.focus(); } if( activate ) { this.activate(); } }, _setSubSel: function(hasSubSel) { if( hasSubSel ) { this.hasSubSel = true; $(this.span).addClass(this.tree.options.classNames.partsel); } else { this.hasSubSel = false; $(this.span).removeClass(this.tree.options.classNames.partsel); } }, _fixSelectionState: function() { // fix selection status, for multi-hier mode // this.tree.logDebug("_fixSelectionState(%o) - %o", this.bSelected, this); var p, i, l; if( this.bSelected ) { // Select all children this.visit(function(node){ node.parent._setSubSel(true); node._select(true, false, false); }); // Select parents, if all children are selected p = this.parent; while( p ) { p._setSubSel(true); var allChildsSelected = true; for(i=0, l=p.childList.length; i<l; i++) { var n = p.childList[i]; if( !n.bSelected && !n.data.isStatusNode ) { allChildsSelected = false; break; } } if( allChildsSelected ){ p._select(true, false, false); } p = p.parent; } } else { // Deselect all children this._setSubSel(false); this.visit(function(node){ node._setSubSel(false); node._select(false, false, false); }); // Deselect parents, and recalc hasSubSel p = this.parent; while( p ) { p._select(false, false, false); var isPartSel = false; for(i=0, l=p.childList.length; i<l; i++) { if( p.childList[i].bSelected || p.childList[i].hasSubSel ) { isPartSel = true; break; } } p._setSubSel(isPartSel); p = p.parent; } } }, _select: function(sel, fireEvents, deep) { // Select - but not focus - this node. // this.tree.logDebug("dtnode._select(%o) - %o", sel, this); var opts = this.tree.options; if( this.data.isStatusNode ){ return; } // if( this.bSelected === sel ) { // this.tree.logDebug("dtnode._select(%o) IGNORED - %o", sel, this); return; } // Allow event listener to abort selection if ( fireEvents && opts.onQuerySelect && opts.onQuerySelect.call(this.tree, sel, this) === false ){ return; // Callback returned false } // Force single-selection if( opts.selectMode==1 && sel ) { this.tree.visit(function(node){ if( node.bSelected ) { // Deselect; assuming that in selectMode:1 there's max. one other selected node node._select(false, false, false); return false; } }); } this.bSelected = sel; // this.tree._changeNodeList("select", this, sel); if( sel ) { if( opts.persist ){ this.tree.persistence.addSelect(this.data.key); } $(this.span).addClass(opts.classNames.selected); if( deep && opts.selectMode === 3 ){ this._fixSelectionState(); } if ( fireEvents && opts.onSelect ){ opts.onSelect.call(this.tree, true, this); } } else { if( opts.persist ){ this.tree.persistence.clearSelect(this.data.key); } $(this.span).removeClass(opts.classNames.selected); if( deep && opts.selectMode === 3 ){ this._fixSelectionState(); } if ( fireEvents && opts.onSelect ){ opts.onSelect.call(this.tree, false, this); } } }, select: function(sel) { // Select - but not focus - this node. // this.tree.logDebug("dtnode.select(%o) - %o", sel, this); if( this.data.unselectable ){ return this.bSelected; } return this._select(sel!==false, true, true); }, toggleSelect: function() { // this.tree.logDebug("dtnode.toggleSelect() - %o", this); return this.select(!this.bSelected); }, isSelected: function() { return this.bSelected; }, _loadContent: function() { try { var opts = this.tree.options; this.tree.logDebug("_loadContent: start - %o", this); this.setLazyNodeStatus(DTNodeStatus_Loading); if( true === opts.onLazyRead.call(this.tree, this) ) { // If function returns 'true', we assume that the loading is done: this.setLazyNodeStatus(DTNodeStatus_Ok); // Otherwise (i.e. if the loading was started as an asynchronous process) // the onLazyRead(dtnode) handler is expected to call dtnode.setLazyNodeStatus(DTNodeStatus_Ok/_Error) when done. this.tree.logDebug("_loadContent: succeeded - %o", this); } } catch(e) { this.tree.logWarning("_loadContent: failed - %o", e); this.setLazyNodeStatus(DTNodeStatus_Error, {tooltip: ""+e}); } }, _expand: function(bExpand, forceSync) { if( this.bExpanded === bExpand ) { this.tree.logDebug("dtnode._expand(%o) IGNORED - %o", bExpand, this); return; } this.tree.logDebug("dtnode._expand(%o) - %o", bExpand, this); var opts = this.tree.options; if( !bExpand && this.getLevel() < opts.minExpandLevel ) { this.tree.logDebug("dtnode._expand(%o) prevented collapse - %o", bExpand, this); return; } if ( opts.onQueryExpand && opts.onQueryExpand.call(this.tree, bExpand, this) === false ){ return; // Callback returned false } this.bExpanded = bExpand; // Persist expand state if( opts.persist ) { if( bExpand ){ this.tree.persistence.addExpand(this.data.key); }else{ this.tree.persistence.clearExpand(this.data.key); } } // Do not apply animations in init phase, or before lazy-loading var allowEffects = !(this.data.isLazy && this.childList === null) && !this.isLoading && !forceSync; this.render(allowEffects); // Auto-collapse mode: collapse all siblings if( this.bExpanded && this.parent && opts.autoCollapse ) { var parents = this._parentList(false, true); for(var i=0, l=parents.length; i<l; i++){ parents[i].collapseSiblings(); } } // If the currently active node is now hidden, deactivate it if( opts.activeVisible && this.tree.activeNode && ! this.tree.activeNode.isVisible() ) { this.tree.activeNode.deactivate(); } // Expanding a lazy node: set 'loading...' and call callback if( bExpand && this.data.isLazy && this.childList === null && !this.isLoading ) { this._loadContent(); return; } if ( opts.onExpand ){ opts.onExpand.call(this.tree, bExpand, this); } }, expand: function(flag) { flag = (flag !== false); if( !this.childList && !this.data.isLazy && flag ){ return; // Prevent expanding empty nodes } else if( this.parent === null && !flag ){ return; // Prevent collapsing the root } this._expand(flag); }, scheduleAction: function(mode, ms) { /** Schedule activity for delayed execution (cancel any pending request). * scheduleAction('cancel') will cancel the request. */ if( this.tree.timer ) { clearTimeout(this.tree.timer); this.tree.logDebug("clearTimeout(%o)", this.tree.timer); } var self = this; // required for closures switch (mode) { case "cancel": // Simply made sure that timer was cleared break; case "expand": this.tree.timer = setTimeout(function(){ self.tree.logDebug("setTimeout: trigger expand"); self.expand(true); }, ms); break; case "activate": this.tree.timer = setTimeout(function(){ self.tree.logDebug("setTimeout: trigger activate"); self.activate(); }, ms); break; default: throw "Invalid mode " + mode; } this.tree.logDebug("setTimeout(%s, %s): %s", mode, ms, this.tree.timer); }, toggleExpand: function() { this.expand(!this.bExpanded); }, collapseSiblings: function() { if( this.parent === null ){ return; } var ac = this.parent.childList; for (var i=0, l=ac.length; i<l; i++) { if ( ac[i] !== this && ac[i].bExpanded ){ ac[i]._expand(false); } } }, _onClick: function(event) { // this.tree.logDebug("dtnode.onClick(" + event.type + "): dtnode:" + this + ", button:" + event.button + ", which: " + event.which); var targetType = this.getEventTargetType(event); if( targetType === "expander" ) { // Clicking the expander icon always expands/collapses this.toggleExpand(); this.focus(); // issue 95 } else if( targetType === "checkbox" ) { // Clicking the checkbox always (de)selects this.toggleSelect(); this.focus(); // issue 95 } else { this._userActivate(); var aTag = this.span.getElementsByTagName("a"); if(aTag[0]){ // issue 154 // TODO: check if still required on IE 9: // Chrome and Safari don't focus the a-tag on click, // but calling focus() seem to have problems on IE: // http://code.google.com/p/dynatree/issues/detail?id=154 if(!$.browser.msie){ aTag[0].focus(); } }else{ // 'noLink' option was set return true; } } // Make sure that clicks stop, otherwise <a href='#'> jumps to the top return false; }, _onDblClick: function(event) { // this.tree.logDebug("dtnode.onDblClick(" + event.type + "): dtnode:" + this + ", button:" + event.button + ", which: " + event.which); }, _onKeydown: function(event) { // this.tree.logDebug("dtnode.onKeydown(" + event.type + "): dtnode:" + this + ", charCode:" + event.charCode + ", keyCode: " + event.keyCode + ", which: " + event.which); var handled = true, sib; // alert("keyDown" + event.which); switch( event.which ) { // charCodes: // case 43: // '+' case 107: // '+' case 187: // '+' @ Chrome, Safari if( !this.bExpanded ){ this.toggleExpand(); } break; // case 45: // '-' case 109: // '-' case 189: // '+' @ Chrome, Safari if( this.bExpanded ){ this.toggleExpand(); } break; //~ case 42: // '*' //~ break; //~ case 47: // '/' //~ break; // case 13: // <enter> // <enter> on a focused <a> tag seems to generate a click-event. // this._userActivate(); // break; case 32: // <space> this._userActivate(); break; case 8: // <backspace> if( this.parent ){ this.parent.focus(); } break; case 37: // <left> if( this.bExpanded ) { this.toggleExpand(); this.focus(); // } else if( this.parent && (this.tree.options.rootVisible || this.parent.parent) ) { } else if( this.parent && this.parent.parent ) { this.parent.focus(); } break; case 39: // <right> if( !this.bExpanded && (this.childList || this.data.isLazy) ) { this.toggleExpand(); this.focus(); } else if( this.childList ) { this.childList[0].focus(); } break; case 38: // <up> sib = this.getPrevSibling(); while( sib && sib.bExpanded && sib.childList ){ sib = sib.childList[sib.childList.length-1]; } // if( !sib && this.parent && (this.tree.options.rootVisible || this.parent.parent) ) if( !sib && this.parent && this.parent.parent ){ sib = this.parent; } if( sib ){ sib.focus(); } break; case 40: // <down> if( this.bExpanded && this.childList ) { sib = this.childList[0]; } else { var parents = this._parentList(false, true); for(var i=parents.length-1; i>=0; i--) { sib = parents[i].getNextSibling(); if( sib ){ break; } } } if( sib ){ sib.focus(); } break; default: handled = false; } // Return false, if handled, to prevent default processing return !handled; }, _onKeypress: function(event) { // onKeypress is only hooked to allow user callbacks. // We don't process it, because IE and Safari don't fire keypress for cursor keys. // this.tree.logDebug("dtnode.onKeypress(" + event.type + "): dtnode:" + this + ", charCode:" + event.charCode + ", keyCode: " + event.keyCode + ", which: " + event.which); }, _onFocus: function(event) { // Handles blur and focus events. // this.tree.logDebug("dtnode.onFocus(%o): %o", event, this); var opts = this.tree.options; if ( event.type == "blur" || event.type == "focusout" ) { if ( opts.onBlur ){ opts.onBlur.call(this.tree, this); } if( this.tree.tnFocused ){ $(this.tree.tnFocused.span).removeClass(opts.classNames.focused); } this.tree.tnFocused = null; if( opts.persist ){ $.cookie(opts.cookieId+"-focus", "", opts.cookie); } } else if ( event.type=="focus" || event.type=="focusin") { // Fix: sometimes the blur event is not generated if( this.tree.tnFocused && this.tree.tnFocused !== this ) { this.tree.logDebug("dtnode.onFocus: out of sync: curFocus: %o", this.tree.tnFocused); $(this.tree.tnFocused.span).removeClass(opts.classNames.focused); } this.tree.tnFocused = this; if ( opts.onFocus ){ opts.onFocus.call(this.tree, this); } $(this.tree.tnFocused.span).addClass(opts.classNames.focused); if( opts.persist ){ $.cookie(opts.cookieId+"-focus", this.data.key, opts.cookie); } } // TODO: return anything? // return false; }, visit: function(fn, includeSelf) { // Call fn(node) for all child nodes. Stop iteration, if fn() returns false. var res = true; if( includeSelf === true ) { res = fn(this); if( res === false || res == "skip" ){ return res; } } if(this.childList){ for(var i=0, l=this.childList.length; i<l; i++){ res = this.childList[i].visit(fn, true); if( res === false ){ break; } } } return res; }, visitParents: function(fn, includeSelf) { // Visit parent nodes (bottom up) if(includeSelf && fn(this) === false){ return false; } var p = this.parent; while( p ) { if(fn(p) === false){ return false; } p = p.parent; } return true; }, remove: function() { // Remove this node // this.tree.logDebug ("%s.remove()", this); if ( this === this.tree.root ){ throw "Cannot remove system root"; } return this.parent.removeChild(this); }, removeChild: function(tn) { // Remove tn from list of direct children. var ac = this.childList; if( ac.length == 1 ) { if( tn !== ac[0] ){ throw "removeChild: invalid child"; } return this.removeChildren(); } if( tn === this.tree.activeNode ){ tn.deactivate(); } if( this.tree.options.persist ) { if( tn.bSelected ){ this.tree.persistence.clearSelect(tn.data.key); } if ( tn.bExpanded ){ this.tree.persistence.clearExpand(tn.data.key); } } tn.removeChildren(true); // this.div.removeChild(tn.div); this.ul.removeChild(tn.li); for(var i=0, l=ac.length; i<l; i++) { if( ac[i] === tn ) { this.childList.splice(i, 1); // delete tn; // JSLint complained break; } } }, removeChildren: function(isRecursiveCall, retainPersistence) { // Remove all child nodes (more efficiently than recursive remove()) this.tree.logDebug("%s.removeChildren(%o)", this, isRecursiveCall); var tree = this.tree; var ac = this.childList; if( ac ) { for(var i=0, l=ac.length; i<l; i++) { var tn = ac[i]; if ( tn === tree.activeNode && !retainPersistence ){ tn.deactivate(); } if( this.tree.options.persist && !retainPersistence ) { if( tn.bSelected ){ this.tree.persistence.clearSelect(tn.data.key); } if ( tn.bExpanded ){ this.tree.persistence.clearExpand(tn.data.key); } } tn.removeChildren(true, retainPersistence); if(this.ul){ this.ul.removeChild(tn.li); } /* try{ this.ul.removeChild(tn.li); }catch(e){ this.tree.logDebug("%s.removeChildren: couldnt remove LI", this, e); } */ // delete tn; JSLint complained } // Set to 'null' which is interpreted as 'not yet loaded' for lazy // nodes this.childList = null; } if( ! isRecursiveCall ) { // this._expand(false); // this.isRead = false; this.isLoading = false; this.render(); } }, setTitle: function(title) { this.fromDict({title: title}); }, reload: function(force) { throw "Use reloadChildren() instead"; }, reloadChildren: function(callback) { // Reload lazy content (expansion state is maintained). if( this.parent === null ){ throw "Use tree.reload() instead"; }else if( ! this.data.isLazy ){ throw "node.reloadChildren() requires lazy nodes."; } // appendAjax triggers 'nodeLoaded' event. // We listen to this, if a callback was passed to reloadChildren if(callback){ var self = this; var eventType = "nodeLoaded.dynatree." + this.tree.$tree.attr("id") + "." + this.data.key; this.tree.$tree.bind(eventType, function(e, node, isOk){ self.tree.$tree.unbind(eventType); self.tree.logInfo("loaded %o, %o, %o", e, node, isOk); if(node !== self){ throw "got invalid load event"; } callback.call(self.tree, node, isOk); }); } // The expansion state is maintained this.removeChildren(); this._loadContent(); // if( this.bExpanded ) { // // Remove children first, to prevent effects being applied // this.removeChildren(); // // then force re-expand to trigger lazy loading //// this.expand(false); //// this.expand(true); // this._loadContent(); // } else { // this.removeChildren(); // this._loadContent(); // } }, /** * Make sure the node with a given key path is available in the tree. */ _loadKeyPath: function(keyPath, callback) { var tree = this.tree; tree.logDebug("%s._loadKeyPath(%s)", this, keyPath); if(keyPath === ""){ throw "Key path must not be empty"; } var segList = keyPath.split(tree.options.keyPathSeparator); if(segList[0] === ""){ throw "Key path must be relative (don't start with '/')"; } var seg = segList.shift(); for(var i=0, l=this.childList.length; i < l; i++){ var child = this.childList[i]; if( child.data.key === seg ){ if(segList.length === 0) { // Found the end node callback.call(tree, child, "ok"); }else if(child.data.isLazy && (child.childList === null || child.childList === undefined)){ tree.logDebug("%s._loadKeyPath(%s) -> reloading %s...", this, keyPath, child); var self = this; child.reloadChildren(function(node, isOk){ // After loading, look for direct child with that key if(isOk){ tree.logDebug("%s._loadKeyPath(%s) -> reloaded %s.", node, keyPath, node); callback.call(tree, child, "loaded"); node._loadKeyPath(segList.join(tree.options.keyPathSeparator), callback); }else{ tree.logWarning("%s._loadKeyPath(%s) -> reloadChildren() failed.", self, keyPath); callback.call(tree, child, "error"); } }); // Note: this line gives a JSLint warning (Don't make functions within a loop) // we can ignore it, since it will only be exectuted once, the the loop is ended // See also http://stackoverflow.com/questions/3037598/how-to-get-around-the-jslint-error-dont-make-functions-within-a-loop } else { callback.call(tree, child, "loaded"); // Look for direct child with that key child._loadKeyPath(segList.join(tree.options.keyPathSeparator), callback); } return; } } // Could not find key tree.logWarning("Node not found: " + seg); return; }, resetLazy: function() { // Discard lazy content. if( this.parent === null ){ throw "Use tree.reload() instead"; }else if( ! this.data.isLazy ){ throw "node.resetLazy() requires lazy nodes."; } this.expand(false); this.removeChildren(); }, _addChildNode: function(dtnode, beforeNode) { /** * Internal function to add one single DynatreeNode as a child. * */ var tree = this.tree; var opts = tree.options; var pers = tree.persistence; // tree.logDebug("%s._addChildNode(%o)", this, dtnode); // --- Update and fix dtnode attributes if necessary dtnode.parent = this; // if( beforeNode && (beforeNode.parent !== this || beforeNode === dtnode ) ) // throw "<beforeNode> must be another child of <this>"; // --- Add dtnode as a child if ( this.childList === null ) { this.childList = []; } else if( ! beforeNode ) { // Fix 'lastsib' $(this.childList[this.childList.length-1].span).removeClass(opts.classNames.lastsib); } if( beforeNode ) { var iBefore = $.inArray(beforeNode, this.childList); if( iBefore < 0 ){ throw "<beforeNode> must be a child of <this>"; } this.childList.splice(iBefore, 0, dtnode); // alert(this.childList); } else { // Append node this.childList.push(dtnode); } // --- Handle persistence // Initial status is read from cookies, if persistence is active and // cookies are already present. // Otherwise the status is read from the data attributes and then persisted. var isInitializing = tree.isInitializing(); if( opts.persist && pers.cookiesFound && isInitializing ) { // Init status from cookies // tree.logDebug("init from cookie, pa=%o, dk=%o", pers.activeKey, dtnode.data.key); if( pers.activeKey == dtnode.data.key ){ tree.activeNode = dtnode; } if( pers.focusedKey == dtnode.data.key ){ tree.focusNode = dtnode; } dtnode.bExpanded = ($.inArray(dtnode.data.key, pers.expandedKeyList) >= 0); dtnode.bSelected = ($.inArray(dtnode.data.key, pers.selectedKeyList) >= 0); // tree.logDebug(" key=%o, bSelected=%o", dtnode.data.key, dtnode.bSelected); } else { // Init status from data (Note: we write the cookies after the init phase) // tree.logDebug("init from data"); if( dtnode.data.activate ) { tree.activeNode = dtnode; if( opts.persist ){ pers.activeKey = dtnode.data.key; } } if( dtnode.data.focus ) { tree.focusNode = dtnode; if( opts.persist ){ pers.focusedKey = dtnode.data.key; } } dtnode.bExpanded = ( dtnode.data.expand === true ); // Collapsed by default if( dtnode.bExpanded && opts.persist ){ pers.addExpand(dtnode.data.key); } dtnode.bSelected = ( dtnode.data.select === true ); // Deselected by default /* Doesn't work, cause pers.selectedKeyList may be null if( dtnode.bSelected && opts.selectMode==1 && pers.selectedKeyList && pers.selectedKeyList.length>0 ) { tree.logWarning("Ignored multi-selection in single-mode for %o", dtnode); dtnode.bSelected = false; // Fixing bad input data (multi selection for mode:1) } */ if( dtnode.bSelected && opts.persist ){ pers.addSelect(dtnode.data.key); } } // Always expand, if it's below minExpandLevel // tree.logDebug ("%s._addChildNode(%o), l=%o", this, dtnode, dtnode.getLevel()); if ( opts.minExpandLevel >= dtnode.getLevel() ) { // tree.logDebug ("Force expand for %o", dtnode); this.bExpanded = true; } // In multi-hier mode, update the parents selection state // issue #82: only if not initializing, because the children may not exist yet // if( !dtnode.data.isStatusNode && opts.selectMode==3 && !isInitializing ) // dtnode._fixSelectionState(); // In multi-hier mode, update the parents selection state if( dtnode.bSelected && opts.selectMode==3 ) { var p = this; while( p ) { if( !p.hasSubSel ){ p._setSubSel(true); } p = p.parent; } } // render this node and the new child if ( tree.bEnableUpdate ){ this.render(); } return dtnode; }, addChild: function(obj, beforeNode) { /** * Add a node object as child. * * This should be the only place, where a DynaTreeNode is constructed! * (Except for the root node creation in the tree constructor) * * @param obj A JS object (may be recursive) or an array of those. * @param {DynaTreeNode} beforeNode (optional) sibling node. * * Data format: array of node objects, with optional 'children' attributes. * [ * { title: "t1", isFolder: true, ... } * { title: "t2", isFolder: true, ..., * children: [ * {title: "t2.1", ..}, * {..} * ] * } * ] * A simple object is also accepted instead of an array. * */ // this.tree.logDebug("%s.addChild(%o, %o)", this, obj, beforeNode); if(typeof(obj) == "string"){ throw "Invalid data type for " + obj; }else if( !obj || obj.length === 0 ){ // Passed null or undefined or empty array return; }else if( obj instanceof DynaTreeNode ){ return this._addChildNode(obj, beforeNode); } if( !obj.length ){ // Passed a single data object obj = [ obj ]; } var prevFlag = this.tree.enableUpdate(false); var tnFirst = null; for (var i=0, l=obj.length; i<l; i++) { var data = obj[i]; var dtnode = this._addChildNode(new DynaTreeNode(this, this.tree, data), beforeNode); if( !tnFirst ){ tnFirst = dtnode; } // Add child nodes recursively if( data.children ){ dtnode.addChild(data.children, null); } } this.tree.enableUpdate(prevFlag); return tnFirst; }, append: function(obj) { this.tree.logWarning("node.append() is deprecated (use node.addChild() instead)."); return this.addChild(obj, null); }, appendAjax: function(ajaxOptions) { var self = this; this.removeChildren(false, true); this.setLazyNodeStatus(DTNodeStatus_Loading); // Debug feature: force a delay, to simulate slow loading... if(ajaxOptions.debugLazyDelay){ var ms = ajaxOptions.debugLazyDelay; ajaxOptions.debugLazyDelay = 0; this.tree.logInfo("appendAjax: waiting for debugLazyDelay " + ms); setTimeout(function(){self.appendAjax(ajaxOptions);}, ms); return; } // Ajax option inheritance: $.ajaxSetup < $.ui.dynatree.prototype.options.ajaxDefaults < tree.options.ajaxDefaults < ajaxOptions var orgSuccess = ajaxOptions.success; var orgError = ajaxOptions.error; var eventType = "nodeLoaded.dynatree." + this.tree.$tree.attr("id") + "." + this.data.key; var options = $.extend({}, this.tree.options.ajaxDefaults, ajaxOptions, { success: function(data, textStatus){ // <this> is the request options // self.tree.logDebug("appendAjax().success"); var prevPhase = self.tree.phase; self.tree.phase = "init"; // postProcess is similar to the standard dataFilter hook, // but it is also called for JSONP if( options.postProcess ){ data = options.postProcess.call(this, data, this.dataType); } if(!$.isArray(data) || data.length !== 0){ self.addChild(data, null); } self.tree.phase = "postInit"; if( orgSuccess ){ orgSuccess.call(options, self); } self.tree.logInfo("trigger " + eventType); self.tree.$tree.trigger(eventType, [self, true]); self.tree.phase = prevPhase; // This should be the last command, so node.isLoading is true // while the callbacks run self.setLazyNodeStatus(DTNodeStatus_Ok); if($.isArray(data) && data.length === 0){ // Set to [] which is interpreted as 'no children' for lazy // nodes self.childList = []; self.render(); } }, error: function(XMLHttpRequest, textStatus, errorThrown){ // <this> is the request options self.tree.logWarning("appendAjax failed:", textStatus, ":\n", XMLHttpRequest, "\n", errorThrown); if( orgError ){ orgError.call(options, self, XMLHttpRequest, textStatus, errorThrown); } self.tree.$tree.trigger(eventType, [self, false]); self.setLazyNodeStatus(DTNodeStatus_Error, {info: textStatus, tooltip: ""+errorThrown}); } }); $.ajax(options); }, move: function(targetNode, mode) { /**Move this node to targetNode. * mode 'child': append this node as last child of targetNode. * This is the default. To be compatble with the D'n'd * hitMode, we also accept 'over'. * mode 'before': add this node as sibling before targetNode. * mode 'after': add this node as sibling after targetNode. */ var pos; if(this === targetNode){ return; } if( !this.parent ){ throw "Cannot move system root"; } if(mode === undefined || mode == "over"){ mode = "child"; } var prevParent = this.parent; var targetParent = (mode === "child") ? targetNode : targetNode.parent; if( targetParent.isDescendantOf(this) ){ throw "Cannot move a node to it's own descendant"; } // Unlink this node from current parent if( this.parent.childList.length == 1 ) { this.parent.childList = null; this.parent.bExpanded = false; } else { pos = $.inArray(this, this.parent.childList); if( pos < 0 ){ throw "Internal error"; } this.parent.childList.splice(pos, 1); } // Remove from source DOM parent this.parent.ul.removeChild(this.li); // Insert this node to target parent's child list this.parent = targetParent; if( targetParent.hasChildren() ) { switch(mode) { case "child": // Append to existing target children targetParent.childList.push(this); break; case "before": // Insert this node before target node pos = $.inArray(targetNode, targetParent.childList); if( pos < 0 ){ throw "Internal error"; } targetParent.childList.splice(pos, 0, this); break; case "after": // Insert this node after target node pos = $.inArray(targetNode, targetParent.childList); if( pos < 0 ){ throw "Internal error"; } targetParent.childList.splice(pos+1, 0, this); break; default: throw "Invalid mode " + mode; } } else { targetParent.childList = [ this ]; // Parent has no <ul> tag yet: if( !targetParent.ul ) { // This is the parent's first child: create UL tag // (Hidden, because it will be targetParent.ul = document.createElement("ul"); targetParent.ul.style.display = "none"; targetParent.li.appendChild(targetParent.ul); } } // Add to target DOM parent targetParent.ul.appendChild(this.li); if( this.tree !== targetNode.tree ) { // Fix node.tree for all source nodes this.visit(function(node){ node.tree = targetNode.tree; }, null, true); throw "Not yet implemented."; } // TODO: fix selection state // TODO: fix active state if( !prevParent.isDescendantOf(targetParent)) { prevParent.render(); } if( !targetParent.isDescendantOf(prevParent) ) { targetParent.render(); } // this.tree.redraw(); /* var tree = this.tree; var opts = tree.options; var pers = tree.persistence; // Always expand, if it's below minExpandLevel // tree.logDebug ("%s._addChildNode(%o), l=%o", this, dtnode, dtnode.getLevel()); if ( opts.minExpandLevel >= dtnode.getLevel() ) { // tree.logDebug ("Force expand for %o", dtnode); this.bExpanded = true; } // In multi-hier mode, update the parents selection state // issue #82: only if not initializing, because the children may not exist yet // if( !dtnode.data.isStatusNode && opts.selectMode==3 && !isInitializing ) // dtnode._fixSelectionState(); // In multi-hier mode, update the parents selection state if( dtnode.bSelected && opts.selectMode==3 ) { var p = this; while( p ) { if( !p.hasSubSel ) p._setSubSel(true); p = p.parent; } } // render this node and the new child if ( tree.bEnableUpdate ) this.render(); return dtnode; */ }, // --- end of class lastentry: undefined }; /************************************************************************* * class DynaTreeStatus */ var DynaTreeStatus = Class.create(); DynaTreeStatus._getTreePersistData = function(cookieId, cookieOpts) { // Static member: Return persistence information from cookies var ts = new DynaTreeStatus(cookieId, cookieOpts); ts.read(); return ts.toDict(); }; // Make available in global scope getDynaTreePersistData = DynaTreeStatus._getTreePersistData; DynaTreeStatus.prototype = { // Constructor initialize: function(cookieId, cookieOpts) { this._log("DynaTreeStatus: initialize"); if( cookieId === undefined ){ cookieId = $.ui.dynatree.prototype.options.cookieId; } cookieOpts = $.extend({}, $.ui.dynatree.prototype.options.cookie, cookieOpts); this.cookieId = cookieId; this.cookieOpts = cookieOpts; this.cookiesFound = undefined; this.activeKey = null; this.focusedKey = null; this.expandedKeyList = null; this.selectedKeyList = null; }, // member functions _log: function(msg) { // this.logDebug("_changeNodeList(%o): nodeList:%o, idx:%o", mode, nodeList, idx); Array.prototype.unshift.apply(arguments, ["debug"]); _log.apply(this, arguments); }, read: function() { this._log("DynaTreeStatus: read"); // Read or init cookies. this.cookiesFound = false; var cookie = $.cookie(this.cookieId + "-active"); this.activeKey = ( cookie === null ) ? "" : cookie; if( cookie !== null ){ this.cookiesFound = true; } cookie = $.cookie(this.cookieId + "-focus"); this.focusedKey = ( cookie === null ) ? "" : cookie; if( cookie !== null ){ this.cookiesFound = true; } cookie = $.cookie(this.cookieId + "-expand"); this.expandedKeyList = ( cookie === null ) ? [] : cookie.split(","); if( cookie !== null ){ this.cookiesFound = true; } cookie = $.cookie(this.cookieId + "-select"); this.selectedKeyList = ( cookie === null ) ? [] : cookie.split(","); if( cookie !== null ){ this.cookiesFound = true; } }, write: function() { this._log("DynaTreeStatus: write"); $.cookie(this.cookieId + "-active", ( this.activeKey === null ) ? "" : this.activeKey, this.cookieOpts); $.cookie(this.cookieId + "-focus", ( this.focusedKey === null ) ? "" : this.focusedKey, this.cookieOpts); $.cookie(this.cookieId + "-expand", ( this.expandedKeyList === null ) ? "" : this.expandedKeyList.join(","), this.cookieOpts); $.cookie(this.cookieId + "-select", ( this.selectedKeyList === null ) ? "" : this.selectedKeyList.join(","), this.cookieOpts); }, addExpand: function(key) { this._log("addExpand(%o)", key); if( $.inArray(key, this.expandedKeyList) < 0 ) { this.expandedKeyList.push(key); $.cookie(this.cookieId + "-expand", this.expandedKeyList.join(","), this.cookieOpts); } }, clearExpand: function(key) { this._log("clearExpand(%o)", key); var idx = $.inArray(key, this.expandedKeyList); if( idx >= 0 ) { this.expandedKeyList.splice(idx, 1); $.cookie(this.cookieId + "-expand", this.expandedKeyList.join(","), this.cookieOpts); } }, addSelect: function(key) { this._log("addSelect(%o)", key); if( $.inArray(key, this.selectedKeyList) < 0 ) { this.selectedKeyList.push(key); $.cookie(this.cookieId + "-select", this.selectedKeyList.join(","), this.cookieOpts); } }, clearSelect: function(key) { this._log("clearSelect(%o)", key); var idx = $.inArray(key, this.selectedKeyList); if( idx >= 0 ) { this.selectedKeyList.splice(idx, 1); $.cookie(this.cookieId + "-select", this.selectedKeyList.join(","), this.cookieOpts); } }, isReloading: function() { return this.cookiesFound === true; }, toDict: function() { return { cookiesFound: this.cookiesFound, activeKey: this.activeKey, focusedKey: this.activeKey, expandedKeyList: this.expandedKeyList, selectedKeyList: this.selectedKeyList }; }, // --- end of class lastentry: undefined }; /************************************************************************* * class DynaTree */ var DynaTree = Class.create(); // --- Static members ---------------------------------------------------------- DynaTree.version = "$Version: 1.0.3$"; /* DynaTree._initTree = function() { }; DynaTree._bind = function() { }; */ //--- Class members ------------------------------------------------------------ DynaTree.prototype = { // Constructor // initialize: function(divContainer, options) { initialize: function($widget) { // instance members this.phase = "init"; this.$widget = $widget; this.options = $widget.options; this.$tree = $widget.element; this.timer = null; // find container element this.divTree = this.$tree.get(0); // var parentPos = $(this.divTree).parent().offset(); // this.parentTop = parentPos.top; // this.parentLeft = parentPos.left; _initDragAndDrop(this); }, // member functions _load: function(callback) { var $widget = this.$widget; var opts = this.options; this.bEnableUpdate = true; this._nodeCount = 1; this.activeNode = null; this.focusNode = null; // Some deprecation warnings to help with migration if( opts.rootVisible !== undefined ){ _log("warn", "Option 'rootVisible' is no longer supported."); } if( opts.title !== undefined ){ _log("warn", "Option 'title' is no longer supported."); } if( opts.minExpandLevel < 1 ) { _log("warn", "Option 'minExpandLevel' must be >= 1."); opts.minExpandLevel = 1; } // _log("warn", "jQuery.support.boxModel " + jQuery.support.boxModel); // If a 'options.classNames' dictionary was passed, still use defaults // for undefined classes: if( opts.classNames !== $.ui.dynatree.prototype.options.classNames ) { opts.classNames = $.extend({}, $.ui.dynatree.prototype.options.classNames, opts.classNames); } if( opts.ajaxDefaults !== $.ui.dynatree.prototype.options.ajaxDefaults ) { opts.ajaxDefaults = $.extend({}, $.ui.dynatree.prototype.options.ajaxDefaults, opts.ajaxDefaults); } if( opts.dnd !== $.ui.dynatree.prototype.options.dnd ) { opts.dnd = $.extend({}, $.ui.dynatree.prototype.options.dnd, opts.dnd); } // Guess skin path, if not specified if(!opts.imagePath) { $("script").each( function () { var _rexDtLibName = /.*dynatree[^\/]*\.js$/i; if( this.src.search(_rexDtLibName) >= 0 ) { if( this.src.indexOf("/")>=0 ){ // issue #47 opts.imagePath = this.src.slice(0, this.src.lastIndexOf("/")) + "/skin/"; }else{ opts.imagePath = "skin/"; } logMsg("Guessing imagePath from '%s': '%s'", this.src, opts.imagePath); return false; // first match } }); } this.persistence = new DynaTreeStatus(opts.cookieId, opts.cookie); if( opts.persist ) { if( !$.cookie ){ _log("warn", "Please include jquery.cookie.js to use persistence."); } this.persistence.read(); } this.logDebug("DynaTree.persistence: %o", this.persistence.toDict()); // Cached tag strings this.cache = { tagEmpty: "<span class='" + opts.classNames.empty + "'></span>", tagVline: "<span class='" + opts.classNames.vline + "'></span>", tagExpander: "<span class='" + opts.classNames.expander + "'></span>", tagConnector: "<span class='" + opts.classNames.connector + "'></span>", tagNodeIcon: "<span class='" + opts.classNames.nodeIcon + "'></span>", tagCheckbox: "<span class='" + opts.classNames.checkbox + "'></span>", lastentry: undefined }; // Clear container, in case it contained some 'waiting' or 'error' text // for clients that don't support JS. // We don't do this however, if we try to load from an embedded UL element. if( opts.children || (opts.initAjax && opts.initAjax.url) || opts.initId ){ $(this.divTree).empty(); }else if( this.divRoot ){ $(this.divRoot).remove(); } /* // create the root element this.tnRoot = new DynaTreeNode(null, this, {title: opts.title, key: "root"}); this.tnRoot.data.isFolder = true; this.tnRoot.render(false, false); this.divRoot = this.tnRoot.div; this.divRoot.className = opts.classNames.container; // add root to container // TODO: this should be delayed until all children have been created for performance reasons this.divTree.appendChild(this.divRoot); */ // Create the root element this.tnRoot = new DynaTreeNode(null, this, {}); this.tnRoot.bExpanded = true; this.tnRoot.render(); this.divTree.appendChild(this.tnRoot.ul); var root = this.tnRoot; var isReloading = ( opts.persist && this.persistence.isReloading() ); var isLazy = false; var prevFlag = this.enableUpdate(false); this.logDebug("Dynatree._load(): read tree structure..."); // Init tree structure if( opts.children ) { // Read structure from node array root.addChild(opts.children); } else if( opts.initAjax && opts.initAjax.url ) { // Init tree from AJAX request isLazy = true; root.data.isLazy = true; this._reloadAjax(callback); } else if( opts.initId ) { // Init tree from another UL element this._createFromTag(root, $("#"+opts.initId)); } else { // Init tree from the first UL element inside the container <div> var $ul = this.$tree.find(">ul:first").hide(); this._createFromTag(root, $ul); $ul.remove(); } this._checkConsistency(); // Render html markup this.logDebug("Dynatree._load(): render nodes..."); this.enableUpdate(prevFlag); // bind event handlers this.logDebug("Dynatree._load(): bind events..."); this.$widget.bind(); // --- Post-load processing this.logDebug("Dynatree._load(): postInit..."); this.phase = "postInit"; // In persist mode, make sure that cookies are written, even if they are empty if( opts.persist ) { this.persistence.write(); } // Set focus, if possible (this will also fire an event and write a cookie) if( this.focusNode && this.focusNode.isVisible() ) { this.logDebug("Focus on init: %o", this.focusNode); this.focusNode.focus(); } if( !isLazy && opts.onPostInit ) { opts.onPostInit.call(this, isReloading, false); } this.phase = "idle"; }, // _setNoUpdate: function(silent) { // // TODO: set options to disable and re-enable updates while loading // var opts = this.options; // var prev = { // fx: opts.fx, // autoFocus: opts.autoFocus, // autoCollapse: opts.autoCollapse }; // if(silent === true){ // opts.autoFocus = false; // opts.fx = null; // opts.autoCollapse = false; // } else { // opts.autoFocus = silent.autoFocus; // opts.fx = silent.fx; // opts.autoCollapse = silent.autoCollapse; // } // return prev; // }, _reloadAjax: function(callback) { // Reload var opts = this.options; if( ! opts.initAjax || ! opts.initAjax.url ){ throw "tree.reload() requires 'initAjax' mode."; } var pers = this.persistence; var ajaxOpts = $.extend({}, opts.initAjax); // Append cookie info to the request // this.logDebug("reloadAjax: key=%o, an.key:%o", pers.activeKey, this.activeNode?this.activeNode.data.key:"?"); if( ajaxOpts.addActiveKey ){ ajaxOpts.data.activeKey = pers.activeKey; } if( ajaxOpts.addFocusedKey ){ ajaxOpts.data.focusedKey = pers.focusedKey; } if( ajaxOpts.addExpandedKeyList ){ ajaxOpts.data.expandedKeyList = pers.expandedKeyList.join(","); } if( ajaxOpts.addSelectedKeyList ){ ajaxOpts.data.selectedKeyList = pers.selectedKeyList.join(","); } // Set up onPostInit callback to be called when Ajax returns if( opts.onPostInit ) { if( ajaxOpts.success ){ this.logWarning("initAjax: success callback is ignored when onPostInit was specified."); } if( ajaxOpts.error ){ this.logWarning("initAjax: error callback is ignored when onPostInit was specified."); } var isReloading = pers.isReloading(); ajaxOpts.success = function(dtnode) { opts.onPostInit.call(dtnode.tree, isReloading, false); if(callback){ callback.call(dtnode.tree, "ok"); } }; ajaxOpts.error = function(dtnode) { opts.onPostInit.call(dtnode.tree, isReloading, true); if(callback){ callback.call(dtnode.tree, "error"); } }; } this.logDebug("Dynatree._init(): send Ajax request..."); this.tnRoot.appendAjax(ajaxOpts); }, toString: function() { // return "DynaTree '" + this.options.title + "'"; return "Dynatree '" + this.$tree.attr("id") + "'"; }, toDict: function() { return this.tnRoot.toDict(true); }, serializeArray: function(stopOnParents) { // Return a JavaScript array of objects, ready to be encoded as a JSON // string for selected nodes var nodeList = this.getSelectedNodes(stopOnParents), name = this.$tree.attr("name") || this.$tree.attr("id"), arr = []; for(var i=0, l=nodeList.length; i<l; i++){ arr.push({name: name, value: nodeList[i].data.key}); } return arr; }, getPersistData: function() { return this.persistence.toDict(); }, logDebug: function(msg) { if( this.options.debugLevel >= 2 ) { Array.prototype.unshift.apply(arguments, ["debug"]); _log.apply(this, arguments); } }, logInfo: function(msg) { if( this.options.debugLevel >= 1 ) { Array.prototype.unshift.apply(arguments, ["info"]); _log.apply(this, arguments); } }, logWarning: function(msg) { Array.prototype.unshift.apply(arguments, ["warn"]); _log.apply(this, arguments); }, isInitializing: function() { return ( this.phase=="init" || this.phase=="postInit" ); }, isReloading: function() { return ( this.phase=="init" || this.phase=="postInit" ) && this.options.persist && this.persistence.cookiesFound; }, isUserEvent: function() { return ( this.phase=="userEvent" ); }, redraw: function() { this.logDebug("dynatree.redraw()..."); this.tnRoot.render(false); this.logDebug("dynatree.redraw() done."); }, reload: function(callback) { this._load(callback); }, getRoot: function() { return this.tnRoot; }, enable: function() { this.$widget.enable(); }, disable: function() { this.$widget.disable(); }, getNodeByKey: function(key) { // Search the DOM by element ID (assuming this is faster than traversing all nodes). // $("#...") has problems, if the key contains '.', so we use getElementById() var el = document.getElementById(this.options.idPrefix + key); if( el ){ return el.dtnode ? el.dtnode : null; } // Not found in the DOM, but still may be in an unrendered part of tree var match = null; this.visit(function(node){ // window.console.log("%s", node); if(node.data.key == key) { match = node; return false; } }, true); return match; }, getActiveNode: function() { return this.activeNode; }, reactivate: function(setFocus) { // Re-fire onQueryActivate and onActivate events. var node = this.activeNode; // this.logDebug("reactivate %o", node); if( node ) { this.activeNode = null; // Force re-activating node.activate(); if( setFocus ){ node.focus(); } } }, getSelectedNodes: function(stopOnParents) { var nodeList = []; this.tnRoot.visit(function(node){ if( node.bSelected ) { nodeList.push(node); if( stopOnParents === true ){ return "skip"; // stop processing this branch } } }); return nodeList; }, activateKey: function(key) { var dtnode = (key === null) ? null : this.getNodeByKey(key); if( !dtnode ) { if( this.activeNode ){ this.activeNode.deactivate(); } this.activeNode = null; return null; } dtnode.focus(); dtnode.activate(); return dtnode; }, loadKeyPath: function(keyPath, callback) { var segList = keyPath.split(this.options.keyPathSeparator); // Remove leading '/' if(segList[0] === ""){ segList.shift(); } // Remove leading system root key if(segList[0] == this.tnRoot.data.key){ this.logDebug("Removed leading root key."); segList.shift(); } keyPath = segList.join(this.options.keyPathSeparator); return this.tnRoot._loadKeyPath(keyPath, callback); }, selectKey: function(key, select) { var dtnode = this.getNodeByKey(key); if( !dtnode ){ return null; } dtnode.select(select); return dtnode; }, enableUpdate: function(bEnable) { if ( this.bEnableUpdate==bEnable ){ return bEnable; } this.bEnableUpdate = bEnable; if ( bEnable ){ this.redraw(); } return !bEnable; // return previous value }, visit: function(fn, includeRoot) { return this.tnRoot.visit(fn, includeRoot); }, _createFromTag: function(parentTreeNode, $ulParent) { // Convert a <UL>...</UL> list into children of the parent tree node. var self = this; /* TODO: better? this.$lis = $("li:has(a[href])", this.element); this.$tabs = this.$lis.map(function() { return $("a", this)[0]; }); */ $ulParent.find(">li").each(function() { var $li = $(this); var $liSpan = $li.find(">span:first"); var title; if( $liSpan.length ) { // If a <li><span> tag is specified, use it literally. title = $liSpan.html(); } else { // If only a <li> tag is specified, use the trimmed string up to the next child <ul> tag. title = $li.html(); var iPos = title.search(/<ul/i); if( iPos>=0 ){ title = $.trim(title.substring(0, iPos)); }else{ title = $.trim(title); } // self.logDebug("%o", title); } // Parse node options from ID, title and class attributes var data = { title: title, isFolder: $li.hasClass("folder"), isLazy: $li.hasClass("lazy"), expand: $li.hasClass("expanded"), select: $li.hasClass("selected"), activate: $li.hasClass("active"), focus: $li.hasClass("focused"), noLink: $li.hasClass("noLink") }; if( $li.attr("title") ){ data.tooltip = $li.attr("title"); } if( $li.attr("id") ){ data.key = $li.attr("id"); } // If a data attribute is present, evaluate as a JavaScript object if( $li.attr("data") ) { var dataAttr = $.trim($li.attr("data")); if( dataAttr ) { if( dataAttr.charAt(0) != "{" ){ dataAttr = "{" + dataAttr + "}"; } try { $.extend(data, eval("(" + dataAttr + ")")); } catch(e) { throw ("Error parsing node data: " + e + "\ndata:\n'" + dataAttr + "'"); } } } var childNode = parentTreeNode.addChild(data); // Recursive reading of child nodes, if LI tag contains an UL tag var $ul = $li.find(">ul:first"); if( $ul.length ) { self._createFromTag(childNode, $ul); // must use 'self', because 'this' is the each() context } }); }, _checkConsistency: function() { // this.logDebug("tree._checkConsistency() NOT IMPLEMENTED - %o", this); }, _setDndStatus: function(sourceNode, targetNode, helper, hitMode, accept) { // hitMode: 'after', 'before', 'over', 'out', 'start', 'stop' var $source = sourceNode ? $(sourceNode.span) : null; var $target = $(targetNode.span); if( !this.$dndMarker ) { this.$dndMarker = $("<div id='dynatree-drop-marker'></div>") .hide() .prependTo($(this.divTree).parent()); // .prependTo("body"); logMsg("Creating marker: %o", this.$dndMarker); } /* if(hitMode === "start"){ } if(hitMode === "stop"){ // sourceNode.removeClass("dynatree-drop-target"); } */ // this.$dndMarker.attr("class", hitMode); if(hitMode === "after" || hitMode === "before" || hitMode === "over"){ // $source && $source.addClass("dynatree-drag-source"); var pos = $target.position(); switch(hitMode){ case "before": this.$dndMarker.removeClass("dynatree-drop-after dynatree-drop-over"); this.$dndMarker.addClass("dynatree-drop-before"); pos.top -= 8; break; case "after": this.$dndMarker.removeClass("dynatree-drop-before dynatree-drop-over"); this.$dndMarker.addClass("dynatree-drop-after"); pos.top += 8; break; default: this.$dndMarker.removeClass("dynatree-drop-after dynatree-drop-before"); this.$dndMarker.addClass("dynatree-drop-over"); $target.addClass("dynatree-drop-target"); pos.left += 8; } this.$dndMarker.css({"left": (pos.left) + "px", "top": (pos.top) + "px" }) .show(); // helper.addClass("dynatree-drop-hover"); } else { // $source && $source.removeClass("dynatree-drag-source"); $target.removeClass("dynatree-drop-target"); this.$dndMarker.hide(); // helper.removeClass("dynatree-drop-hover"); } if(hitMode === "after"){ $target.addClass("dynatree-drop-after"); } else { $target.removeClass("dynatree-drop-after"); } if(hitMode === "before"){ $target.addClass("dynatree-drop-before"); } else { $target.removeClass("dynatree-drop-before"); } if(accept === true){ if($source){ $source.addClass("dynatree-drop-accept"); } $target.addClass("dynatree-drop-accept"); helper.addClass("dynatree-drop-accept"); }else{ if($source){ $source.removeClass("dynatree-drop-accept"); } $target.removeClass("dynatree-drop-accept"); helper.removeClass("dynatree-drop-accept"); } if(accept === false){ if($source){ $source.addClass("dynatree-drop-reject"); } $target.addClass("dynatree-drop-reject"); helper.addClass("dynatree-drop-reject"); }else{ if($source){ $source.removeClass("dynatree-drop-reject"); } $target.removeClass("dynatree-drop-reject"); helper.removeClass("dynatree-drop-reject"); } }, _onDragEvent: function(eventName, node, otherNode, event, ui, draggable) { /** * Handles drag'n'drop functionality. * * A standard jQuery drag-and-drop process may generate these calls: * * draggable helper(): * _onDragEvent("helper", sourceNode, null, event, null, null); * start: * _onDragEvent("start", sourceNode, null, event, ui, draggable); * drag: * _onDragEvent("leave", prevTargetNode, sourceNode, event, ui, draggable); * _onDragEvent("over", targetNode, sourceNode, event, ui, draggable); * _onDragEvent("enter", targetNode, sourceNode, event, ui, draggable); * stop: * _onDragEvent("drop", targetNode, sourceNode, event, ui, draggable); * _onDragEvent("leave", targetNode, sourceNode, event, ui, draggable); * _onDragEvent("stop", sourceNode, null, event, ui, draggable); */ if(eventName !== "over"){ this.logDebug("tree._onDragEvent(%s, %o, %o) - %o", eventName, node, otherNode, this); } var opts = this.options; var dnd = this.options.dnd; var res = null; var nodeTag = $(node.span); var hitMode; switch (eventName) { case "helper": // Only event and node argument is available var helper = $("<div class='dynatree-drag-helper'><span class='dynatree-drag-helper-img' /></div>") .append($(event.target).closest('a').clone()); // Attach node reference to helper object helper.data("dtSourceNode", node); this.logDebug("helper.sourceNode=%o", helper.data("dtSourceNode")); res = helper; break; case "start": if(node.isStatusNode()) { res = false; } else if(dnd.onDragStart) { res = dnd.onDragStart(node); } if(res === false) { this.logDebug("tree.onDragStart() cancelled"); //draggable._clear(); // NOTE: the return value seems to be ignored (drag is not canceled, when false is returned) ui.helper.trigger("mouseup"); ui.helper.hide(); } else { nodeTag.addClass("dynatree-drag-source"); } break; case "enter": res = dnd.onDragEnter ? dnd.onDragEnter(node, otherNode) : null; res = { over: (res !== false) && ((res === true) || (res === "over") || $.inArray("over", res) >= 0), before: (res !== false) && ((res === true) || (res === "before") || $.inArray("before", res) >= 0), after: (res !== false) && ((res === true) || (res === "after") || $.inArray("after", res) >= 0) }; ui.helper.data("enterResponse", res); this.logDebug("helper.enterResponse: %o", res); break; case "over": var enterResponse = ui.helper.data("enterResponse"); hitMode = null; if(enterResponse === false){ // Don't call onDragOver if onEnter returned false. break; } else if(typeof enterResponse === "string") { // Use hitMode from onEnter if provided. hitMode = enterResponse; } else { // Calculate hitMode from relative cursor position. var nodeOfs = nodeTag.offset(); // var relPos = { x: event.clientX - nodeOfs.left, // y: event.clientY - nodeOfs.top }; // nodeOfs.top += this.parentTop; // nodeOfs.left += this.parentLeft; var relPos = { x: event.pageX - nodeOfs.left, y: event.pageY - nodeOfs.top }; var relPos2 = { x: relPos.x / nodeTag.width(), y: relPos.y / nodeTag.height() }; // this.logDebug("event.page: %s/%s", event.pageX, event.pageY); // this.logDebug("event.client: %s/%s", event.clientX, event.clientY); // this.logDebug("nodeOfs: %s/%s", nodeOfs.left, nodeOfs.top); //// this.logDebug("parent: %s/%s", this.parentLeft, this.parentTop); // this.logDebug("relPos: %s/%s", relPos.x, relPos.y); // this.logDebug("relPos2: %s/%s", relPos2.x, relPos2.y); if( enterResponse.after && relPos2.y > 0.75 ){ hitMode = "after"; } else if(!enterResponse.over && enterResponse.after && relPos2.y > 0.5 ){ hitMode = "after"; } else if(enterResponse.before && relPos2.y <= 0.25) { hitMode = "before"; } else if(!enterResponse.over && enterResponse.before && relPos2.y <= 0.5) { hitMode = "before"; } else if(enterResponse.over) { hitMode = "over"; } // Prevent no-ops like 'before source node' // TODO: these are no-ops when moving nodes, but not in copy mode if( dnd.preventVoidMoves ){ if(node === otherNode){ this.logDebug(" drop over source node prevented"); hitMode = null; }else if(hitMode === "before" && otherNode && node === otherNode.getNextSibling()){ this.logDebug(" drop after source node prevented"); hitMode = null; }else if(hitMode === "after" && otherNode && node === otherNode.getPrevSibling()){ this.logDebug(" drop before source node prevented"); hitMode = null; }else if(hitMode === "over" && otherNode && otherNode.parent === node && otherNode.isLastSibling() ){ this.logDebug(" drop last child over own parent prevented"); hitMode = null; } } this.logDebug("hitMode: %s - %s - %s", hitMode, (node.parent === otherNode), node.isLastSibling()); ui.helper.data("hitMode", hitMode); /* logMsg(" clientPos: %s/%s", event.clientX, event.clientY); logMsg(" clientPos: %s/%s", event.pageX, event.pageY); logMsg(" nodeOfs: %s/%s", nodeOfs.left, nodeOfs.top); logMsg(" relPos: %s/%s", relPos.x, relPos.y); logMsg(" relPos2: %s/%s: %s", relPos2.x, relPos2.y, hitMode); logMsg(" e:%o", event); */ } /* var checkPos = function(node, pos) { var dyClick = this.offset.click.top, dxClick = this.offset.click.left; var helperTop = this.positionAbs.top, helperLeft = this.positionAbs.left; var itemHeight = o.height, itemWidth = o.width; var itemTop = o.top, itemLeft = o.left; return $.ui.isOver(helperTop + dyClick, helperLeft + dxClick, itemTop, itemLeft, itemHeight, itemWidth); }; var relPos = event.()*/ // Auto-expand node (only when 'over' the node, not 'before', or 'after') if(hitMode === "over" && dnd.autoExpandMS && node.hasChildren() !== false && !node.bExpanded) { node.scheduleAction("expand", dnd.autoExpandMS); } if(hitMode && dnd.onDragOver){ res = dnd.onDragOver(node, otherNode, hitMode); } this._setDndStatus(otherNode, node, ui.helper, hitMode, res!==false); break; case "drop": // var enterResponse = ui.helper.data("enterResponse"); hitMode = ui.helper.data("hitMode"); // if(dnd.onDrop && enterResponse !== false) // dnd.onDrop(node, otherNode, hitMode) if(hitMode && dnd.onDrop){ dnd.onDrop(node, otherNode, hitMode, ui, draggable); } break; case "leave": // Cancel pending expand request node.scheduleAction("cancel"); ui.helper.data("enterResponse", null); ui.helper.data("hitMode", null); // nodeTag.removeClass("dynatree-drop-hover dynatree-drop-accept dynatree-drop-reject"); this._setDndStatus(otherNode, node, ui.helper, "out", undefined); if(dnd.onDragLeave){ dnd.onDragLeave(node, otherNode); } break; case "stop": nodeTag.removeClass("dynatree-drag-source"); if(dnd.onDragStop){ dnd.onDragStop(node); } break; default: throw "Unsupported drag event: " + eventName; } return res; }, cancelDrag: function() { var dd = $.ui.ddmanager.current; if(dd){ dd.cancel(); } }, // --- end of class lastentry: undefined }; /************************************************************************* * Widget $(..).dynatree */ $.widget("ui.dynatree", { /* init: function() { // ui.core 1.6 renamed init() to _init(): this stub assures backward compatibility _log("warn", "ui.dynatree.init() was called; you should upgrade to jquery.ui.core.js v1.8 or higher."); return this._init(); }, */ _init: function() { if( parseFloat($.ui.version) < 1.8 ) { // jquery.ui.core 1.8 renamed _init() to _create(): this stub assures backward compatibility _log("warn", "ui.dynatree._init() was called; you should upgrade to jquery.ui.core.js v1.8 or higher."); return this._create(); } // jquery.ui.core 1.8 still uses _init() to perform "default functionality" _log("debug", "ui.dynatree._init() was called; no current default functionality."); }, _create: function() { logMsg("Dynatree._create(): version='%s', debugLevel=%o.", DynaTree.version, this.options.debugLevel); var opts = this.options; // The widget framework supplies this.element and this.options. this.options.event += ".dynatree"; // namespace event var divTree = this.element.get(0); /* // Clear container, in case it contained some 'waiting' or 'error' text // for clients that don't support JS if( opts.children || (opts.initAjax && opts.initAjax.url) || opts.initId ) $(divTree).empty(); */ // Create the DynaTree object this.tree = new DynaTree(this); this.tree._load(); this.tree.logDebug("Dynatree._init(): done."); }, bind: function() { // Prevent duplicate binding this.unbind(); var eventNames = "click.dynatree dblclick.dynatree"; if( this.options.keyboard ){ // Note: leading ' '! eventNames += " keypress.dynatree keydown.dynatree"; } this.element.bind(eventNames, function(event){ var dtnode = getDtNodeFromElement(event.target); if( !dtnode ){ return true; // Allow bubbling of other events } var tree = dtnode.tree; var o = tree.options; tree.logDebug("event(%s): dtnode: %s", event.type, dtnode); var prevPhase = tree.phase; tree.phase = "userEvent"; try { switch(event.type) { case "click": return ( o.onClick && o.onClick.call(tree, dtnode, event)===false ) ? false : dtnode._onClick(event); case "dblclick": return ( o.onDblClick && o.onDblClick.call(tree, dtnode, event)===false ) ? false : dtnode._onDblClick(event); case "keydown": return ( o.onKeydown && o.onKeydown.call(tree, dtnode, event)===false ) ? false : dtnode._onKeydown(event); case "keypress": return ( o.onKeypress && o.onKeypress.call(tree, dtnode, event)===false ) ? false : dtnode._onKeypress(event); } } catch(e) { var _ = null; // issue 117 tree.logWarning("bind(%o): dtnode: %o, error: %o", event, dtnode, e); } finally { tree.phase = prevPhase; } }); // focus/blur don't bubble, i.e. are not delegated to parent <div> tags, // so we use the addEventListener capturing phase. // See http://www.howtocreate.co.uk/tutorials/javascript/domevents function __focusHandler(event) { // Handles blur and focus. // Fix event for IE: // doesn't pass JSLint: // event = arguments[0] = $.event.fix( event || window.event ); // what jQuery does: // var args = jQuery.makeArray( arguments ); // event = args[0] = jQuery.event.fix( event || window.event ); event = $.event.fix( event || window.event ); var dtnode = getDtNodeFromElement(event.target); return dtnode ? dtnode._onFocus(event) : false; } var div = this.tree.divTree; if( div.addEventListener ) { div.addEventListener("focus", __focusHandler, true); div.addEventListener("blur", __focusHandler, true); } else { div.onfocusin = div.onfocusout = __focusHandler; } // EVENTS // disable click if event is configured to something else // if (!(/^click/).test(o.event)) // this.$tabs.bind("click.tabs", function() { return false; }); }, unbind: function() { this.element.unbind(".dynatree"); }, /* TODO: we could handle option changes during runtime here (maybe to re-render, ...) setData: function(key, value) { this.tree.logDebug("dynatree.setData('" + key + "', '" + value + "')"); }, */ enable: function() { this.bind(); // Call default disable(): remove -disabled from css: $.Widget.prototype.enable.apply(this, arguments); }, disable: function() { this.unbind(); // Call default disable(): add -disabled to css: $.Widget.prototype.disable.apply(this, arguments); }, // --- getter methods (i.e. NOT returning a reference to $) getTree: function() { return this.tree; }, getRoot: function() { return this.tree.getRoot(); }, getActiveNode: function() { return this.tree.getActiveNode(); }, getSelectedNodes: function() { return this.tree.getSelectedNodes(); }, // ------------------------------------------------------------------------ lastentry: undefined }); // The following methods return a value (thus breaking the jQuery call chain): if( parseFloat($.ui.version) < 1.8 ) { $.ui.dynatree.getter = "getTree getRoot getActiveNode getSelectedNodes"; } /******************************************************************************* * Plugin default options: */ $.ui.dynatree.prototype.options = { title: "Dynatree", // Tree's name (only used for debug outpu) minExpandLevel: 1, // 1: root node is not collapsible imagePath: null, // Path to a folder containing icons. Defaults to 'skin/' subdirectory. children: null, // Init tree structure from this object array. initId: null, // Init tree structure from a <ul> element with this ID. initAjax: null, // Ajax options used to initialize the tree strucuture. autoFocus: true, // Set focus to first child, when expanding or lazy-loading. keyboard: true, // Support keyboard navigation. persist: false, // Persist expand-status to a cookie autoCollapse: false, // Automatically collapse all siblings, when a node is expanded. clickFolderMode: 3, // 1:activate, 2:expand, 3:activate and expand activeVisible: true, // Make sure, active nodes are visible (expanded). checkbox: false, // Show checkboxes. selectMode: 2, // 1:single, 2:multi, 3:multi-hier fx: null, // Animations, e.g. null or { height: "toggle", duration: 200 } noLink: false, // Use <span> instead of <a> tags for all nodes // Low level event handlers: onEvent(dtnode, event): return false, to stop default processing onClick: null, // null: generate focus, expand, activate, select events. onDblClick: null, // (No default actions.) onKeydown: null, // null: generate keyboard navigation (focus, expand, activate). onKeypress: null, // (No default actions.) onFocus: null, // null: set focus to node. onBlur: null, // null: remove focus from node. // Pre-event handlers onQueryEvent(flag, dtnode): return false, to stop processing onQueryActivate: null, // Callback(flag, dtnode) before a node is (de)activated. onQuerySelect: null, // Callback(flag, dtnode) before a node is (de)selected. onQueryExpand: null, // Callback(flag, dtnode) before a node is expanded/collpsed. // High level event handlers onPostInit: null, // Callback(isReloading, isError) when tree was (re)loaded. onActivate: null, // Callback(dtnode) when a node is activated. onDeactivate: null, // Callback(dtnode) when a node is deactivated. onSelect: null, // Callback(flag, dtnode) when a node is (de)selected. onExpand: null, // Callback(dtnode) when a node is expanded/collapsed. onLazyRead: null, // Callback(dtnode) when a lazy node is expanded for the first time. // Drag'n'drop support dnd: { // Make tree nodes draggable: onDragStart: null, // Callback(sourceNode), return true, to enable dnd onDragStop: null, // Callback(sourceNode) // helper: null, // Make tree nodes accept draggables autoExpandMS: 1000, // Expand nodes after n milliseconds of hovering. preventVoidMoves: true, // Prevent dropping nodes 'before self', etc. onDragEnter: null, // Callback(targetNode, sourceNode) onDragOver: null, // Callback(targetNode, sourceNode, hitMode) onDrop: null, // Callback(targetNode, sourceNode, hitMode) onDragLeave: null // Callback(targetNode, sourceNode) }, ajaxDefaults: { // Used by initAjax option cache: false, // false: Append random '_' argument to the request url to prevent caching. dataType: "json" // Expect json format and pass json object to callbacks. }, strings: { loading: "Loading&#8230;", loadError: "Load error!" }, generateIds: false, // Generate id attributes like <span id='dynatree-id-KEY'> idPrefix: "dynatree-id-", // Used to generate node id's like <span id="dynatree-id-<key>">. keyPathSeparator: "/", // Used by node.getKeyPath() and tree.loadKeyPath(). // cookieId: "dynatree-cookie", // Choose a more unique name, to allow multiple trees. cookieId: "dynatree", // Choose a more unique name, to allow multiple trees. cookie: { expires: null //7, // Days or Date; null: session cookie // path: "/", // Defaults to current page // domain: "jquery.com", // secure: true }, // Class names used, when rendering the HTML markup. // Note: if only single entries are passed for options.classNames, all other // values are still set to default. classNames: { container: "dynatree-container", node: "dynatree-node", folder: "dynatree-folder", // document: "dynatree-document", empty: "dynatree-empty", vline: "dynatree-vline", expander: "dynatree-expander", connector: "dynatree-connector", checkbox: "dynatree-checkbox", nodeIcon: "dynatree-icon", title: "dynatree-title", noConnector: "dynatree-no-connector", nodeError: "dynatree-statusnode-error", nodeWait: "dynatree-statusnode-wait", hidden: "dynatree-hidden", combinedExpanderPrefix: "dynatree-exp-", combinedIconPrefix: "dynatree-ico-", nodeLoading: "dynatree-loading", // disabled: "dynatree-disabled", hasChildren: "dynatree-has-children", active: "dynatree-active", selected: "dynatree-selected", expanded: "dynatree-expanded", lazy: "dynatree-lazy", focused: "dynatree-focused", partsel: "dynatree-partsel", lastsib: "dynatree-lastsib" }, debugLevel: 1, // ------------------------------------------------------------------------ lastentry: undefined }; // if( parseFloat($.ui.version) < 1.8 ) { $.ui.dynatree.defaults = $.ui.dynatree.prototype.options; } /******************************************************************************* * Reserved data attributes for a tree node. */ $.ui.dynatree.nodedatadefaults = { title: null, // (required) Displayed name of the node (html is allowed here) key: null, // May be used with activate(), select(), find(), ... isFolder: false, // Use a folder icon. Also the node is expandable but not selectable. isLazy: false, // Call onLazyRead(), when the node is expanded for the first time to allow for delayed creation of children. tooltip: null, // Show this popup text. icon: null, // Use a custom image (filename relative to tree.options.imagePath). 'null' for default icon, 'false' for no icon. addClass: null, // Class name added to the node's span tag. noLink: false, // Use <span> instead of <a> tag for this node activate: false, // Initial active status. focus: false, // Initial focused status. expand: false, // Initial expanded status. select: false, // Initial selected status. hideCheckbox: false, // Suppress checkbox display for this node. unselectable: false, // Prevent selection. // disabled: false, // The following attributes are only valid if passed to some functions: children: null, // Array of child nodes. // NOTE: we can also add custom attributes here. // This may then also be used in the onActivate(), onSelect() or onLazyTree() callbacks. // ------------------------------------------------------------------------ lastentry: undefined }; /******************************************************************************* * Drag and drop support */ function _initDragAndDrop(tree) { var dnd = tree.options.dnd || null; // Register 'connectToDynatree' option with ui.draggable if(dnd && (dnd.onDragStart || dnd.onDrop)) { _registerDnd(); } // Attach ui.draggable to this Dynatree instance if(dnd && dnd.onDragStart ) { tree.$tree.draggable({ addClasses: false, appendTo: "body", containment: false, delay: 0, distance: 4, revert: false, // Delegate draggable.start, drag, and stop events to our handler connectToDynatree: true, // Let source tree create the helper element helper: function(event) { var sourceNode = getDtNodeFromElement(event.target); return sourceNode.tree._onDragEvent("helper", sourceNode, null, event, null, null); }, _last: null }); } // Attach ui.droppable to this Dynatree instance if(dnd && dnd.onDrop) { tree.$tree.droppable({ addClasses: false, tolerance: "intersect", greedy: false, _last: null }); } } //--- Extend ui.draggable event handling -------------------------------------- var didRegisterDnd = false; var _registerDnd = function() { if(didRegisterDnd){ return; } $.ui.plugin.add("draggable", "connectToDynatree", { start: function(event, ui) { var draggable = $(this).data("draggable"); var sourceNode = ui.helper.data("dtSourceNode") || null; logMsg("draggable-connectToDynatree.start, %s", sourceNode); logMsg(" this: %o", this); logMsg(" event: %o", event); logMsg(" draggable: %o", draggable); logMsg(" ui: %o", ui); if(sourceNode) { // Adjust helper offset for tree nodes /* var sourcePosition = $(sourceNode.span).position(); var cssPosition = $(ui.helper).position(); logMsg(" draggable.offset.click: %s/%s", draggable.offset.click.left, draggable.offset.click.top); logMsg(" sourceNode.position: %s/%s", sourcePosition.left, sourcePosition.top); logMsg(" helper.position: %s/%s", cssPosition.left, cssPosition.top); logMsg(" event.target.offset: %s/%s, %sx%s", event.target.offsetLeft, event.target.offsetTop, event.target.offsetWidth, event.target.offsetHeight); logMsg(" draggable.positionAbs: %s/%s", draggable.positionAbs.left, draggable.positionAbs.top); */ // Adjust helper offset, so cursor is slightly outside top/left corner // draggable.offset.click.top -= event.target.offsetTop; // draggable.offset.click.left -= event.target.offsetLeft; draggable.offset.click.top = -2; draggable.offset.click.left = + 16; // logMsg(" draggable.offset.click FIXED: %s/%s", draggable.offset.click.left, draggable.offset.click.top); // Trigger onDragStart event // TODO: when called as connectTo..., the return value is ignored(?) return sourceNode.tree._onDragEvent("start", sourceNode, null, event, ui, draggable); } }, drag: function(event, ui) { var draggable = $(this).data("draggable"); var sourceNode = ui.helper.data("dtSourceNode") || null; var prevTargetNode = ui.helper.data("dtTargetNode") || null; var targetNode = getDtNodeFromElement(event.target); // logMsg("getDtNodeFromElement(%o): %s", event.target, targetNode); if(event.target && !targetNode){ // We got a drag event, but the targetNode could not be found // at the event location. This may happen, if the mouse // jumped over the drag helper, in which case we ignore it: var isHelper = $(event.target).closest("div.dynatree-drag-helper,#dynatree-drop-marker").length > 0; if(isHelper){ logMsg("Drag event over helper: ignored."); return; } } // logMsg("draggable-connectToDynatree.drag: targetNode(from event): %s, dtTargetNode: %s", targetNode, ui.helper.data("dtTargetNode")); ui.helper.data("dtTargetNode", targetNode); // Leaving a tree node if(prevTargetNode && prevTargetNode !== targetNode ) { prevTargetNode.tree._onDragEvent("leave", prevTargetNode, sourceNode, event, ui, draggable); } if(targetNode){ if(!targetNode.tree.options.dnd.onDrop) { // not enabled as drop target noop(); // Keep JSLint happy } else if(targetNode === prevTargetNode) { // Moving over same node targetNode.tree._onDragEvent("over", targetNode, sourceNode, event, ui, draggable); }else{ // Entering this node first time targetNode.tree._onDragEvent("enter", targetNode, sourceNode, event, ui, draggable); } } // else go ahead with standard event handling }, stop: function(event, ui) { var draggable = $(this).data("draggable"); var sourceNode = ui.helper.data("dtSourceNode") || null; // var targetNode = getDtNodeFromElement(event.target); var targetNode = ui.helper.data("dtTargetNode") || null; logMsg("draggable-connectToDynatree.stop: targetNode(from event): %s, dtTargetNode: %s", targetNode, ui.helper.data("dtTargetNode")); // var targetTree = targetNode ? targetNode.tree : null; // if(dtnode && dtnode.tree. logMsg("draggable-connectToDynatree.stop, %s", sourceNode); var mouseDownEvent = draggable._mouseDownEvent; var eventType = event.type; logMsg(" type: %o, downEvent: %o, upEvent: %o", eventType, mouseDownEvent, event); logMsg(" targetNode: %o", targetNode); var dropped = (eventType == "mouseup" && event.which == 1); if(!dropped){ logMsg("Drag was cancelled"); } if(targetNode) { if(dropped){ targetNode.tree._onDragEvent("drop", targetNode, sourceNode, event, ui, draggable); } targetNode.tree._onDragEvent("leave", targetNode, sourceNode, event, ui, draggable); } if(sourceNode){ sourceNode.tree._onDragEvent("stop", sourceNode, null, event, ui, draggable); } } }); didRegisterDnd = true; }; // --------------------------------------------------------------------------- })(jQuery);
zope2.zodbbrowser
/zope2.zodbbrowser-0.2.tar.gz/zope2.zodbbrowser-0.2/zope2/zodbbrowser/resources/jquery.dynatree.js
jquery.dynatree.js