r"""Lets you manipulate XML/XHTML using a Pythonic object model. `PyMeldLite`
is a single Python module, _PyMeldLite.py_. It works with all versions of
Python from 2.2 upwards. It is a restricted version of PyMeld (see
http://www.entrian.com/PyMeld) - PyMeldLite supports only well-formed XML
with no namespaces, whereas PyMeld supports virtually all XML or HTML
documents. PyMeldLite is released under the PSF license whereas PyMeld is
released under the Sleepycat License. PyMeld and PyMeldLite support the
same API.
*Features:*
o Allows program logic and HTML to be completely separated - a graphical
designer can design the HTML in a visual XHTML editor, without needing to
deal with any non-standard syntax or non-standard attribute names. The
program code knows nothing about XML or HTML - it just deals with objects
and attributes like any other piece of Python code.
o Designed with common HTML-application programming tasks in mind.
Populating an HTML form with a record from a database is a one-liner
(using the `%` operator - see below). Building an HTML table from a set
of records is just as easy, as shown in the example below.
o Does nothing but maniplating HTML/XML, hence fits in with any other Web
toolkits you're using.
o Tracebacks always point to the right place - many Python/HTML mixing
systems use exec or eval, making bugs hard to track down.
*Quick overview*
A `PyMeldLite.Meld` object represents an XML document, or a piece of one.
All the elements in a document with `id=name` attributes are made available
by a Meld object as `object.name`. The attributes of elements are available
in the same way. A brief example is worth a thousand words:
>>> from PyMeldLite import Meld
>>> xhtml = '''
...
... '''
>>> page = Meld(xhtml) # Create a Meld object from XHTML.
>>> print page.message # Access an element within the document.
>>> print page.message.rows # Access an attribute of an element.
2
>>> page.message = "New message." # Change the content of an element.
>>> page.message.rows = 4 # Change an attribute value.
>>> del page.message.wrap # Delete an attribute.
>>> print page # Print the resulting page.
So the program logic and the HTML are completely separated - a graphical
designer can design the HTML in a visual XHTML editor, without needing to
deal with any non-standard syntax or non-standard attribute names. The
program code knows nothing about XML or HTML - it just deals with objects and
attributes like any other piece of Python code. Populating an HTML form with
a record from a database is a one-liner (using the `%` operator - see below).
Building an HTML table from a set of records is just as easy, as shown in the
example below:
*Real-world example:*
Here's a data-driven example populating a table from a data source, basing the
table on sample data put in by the page designer. Note that in the real world
the HTML would normally be a larger page read from an external file, keeping
the data and presentation separate, and the data would come from an external
source like an RDBMS. The HTML could be full of styles, images, anything you
like and it would all work just the same.
>>> xhtml = '''
...
... Example name | 21 |
...
... '''
>>> doc = Meld(xhtml)
>>> templateRow = doc.row.clone() # Take a copy of the template row, then
>>> del doc.row # delete it to make way for the real rows.
>>> for name, age in [("Richie", 30), ("Dave", 39), ("John", 78)]:
... newRow = templateRow.clone()
... newRow.name = name
... newRow.age = age
... doc.people += newRow
>>> print re.sub(r'\s*', '\n', str(doc)) # Prettify the output
Note that if you were going to subsequently manipulate the table, using
PyMeldLite or JavaScript for instance, you'd need to rename each `row`,
`name` and `age` element to have a unique name - you can do that by assigning
to the `id` attribute but I've skipped that to make the example simpler.
As the example shows, the `+=` operator appends content to an element -
appending ``s to a `` in this case.
*Shortcut: the % operator*
Using the `object.id = value` syntax for every operation can get tedious, so
there are shortcuts you can take using the `%` operator. This works just like
the built-in `%` operator for strings. The example above could have been
written like this:
>>> for name, age in [("Richie", 30), ("Dave", 39), ("John", 78)]:
... doc.people += templateRow % (name, age)
The `%` operator, given a single value or a sequence, assigns values to
elements with `id`s in the order that they appear, just like the `%` operator
for strings. Note that there's no need to call `clone()` when you're using
`%`, as it automatically returns a modified clone (again, just like `%` does
for strings). You can also use a dictionary:
>>> print templateRow % {'name': 'Frances', 'age': 39}
Frances | 39 |
That's really useful when you have a large number of data items - for
example, populating an HTML form with a record from an RDBMS becomes a
one-liner.
*Element content*
When you refer to a named element in a document, you get a Meld object
representing that whole element:
>>> page = Meld('Hello world')
>>> print page.x
Hello world
If you just want to get the content of the element as string, use the
`_content` attribute:
>>> print page.x._content
Hello world
You can also assign to `_content`, though that's directly equivalent to
assigning to the tag itself:
>>> page.x._content = "Hello again"
>>> print page
Hello again
>>> page.x = "Goodbye"
>>> print page
Goodbye
The only time that you need to assign to `_content` is when you've taken a
reference to an element within a document:
>>> x = page.x
>>> x._content = "I'm back"
>>> print page
I'm back
Saying `x = "I'm back"` would simply re-bind `x` to the string `"I'm back"`
without affecting the document.
*Non-self-closing tags*
Some web browsers don't cope with self-closing tags (eg. ``) in XHTML.
For instance, some versions of Internet Explorer don't understand
`` to be the equivalent of ``, and interpret
the rest of the document as the content of the `textarea`. For this reason,
PyMeldLite has a module-level attribute called `nonSelfClose`, which is a
dictionary whose keys are the names of the tags that shouldn't be
self-closing. `textarea` is the only such tag by default.
>>> page = Meld('''''')
>>> print page
*Legal information:*
_PyMeldLite.py_ is released under the terms of the Python Software Foundation
License - see http://www.python.org/
"""
# PyMeldLite is released under the terms of the Python Software Foundation
# License - see http://www.python.org/ It is a restricted version of PyMeld;
# see http://www.entrian.com/
__version__ = "1.0"
__author__ = "Richie Hindle "
# Entrian.Coverage: Pragma Stop
import sys, re, string
try:
True, False, bool
except NameError:
True = 1
False = 0
def bool(x):
return not not x
# Entrian.Coverage: Pragma Start
class _Fail:
"""Unambiguously identifies failed attribute lookups."""
pass
_fail = _Fail()
# Non-self-closing tags; see the module documentation.
nonSelfClose = {'textarea': None}
# Map high characters to charrefs.
def replaceHighCharacters(match):
return "%d;" % ord(match.group(1))
# Map meaningless low characters to '?'
badxml_chars = ''.join([chr(c) for c in range(0, 32) if c not in [9, 10, 13]])
badxml_map = string.maketrans(badxml_chars, '?' * len(badxml_chars))
###########################################################################
##
## Super-lightweight DOM-like tree.
##
## The externally-visible `Meld` class is just a thin wrapper around a
## lightweight DOM-like tree. The classes `_Node`, `_RootNode`,
## `_ElementNode` and `_TextNode` implement the tree, and `_TreeGenerator`
## generates it from XML source. When you do something like `page.field`,
## you are given a new `Meld` instance that refers to the underlying tree.
##
class _Node:
"""Represents a node in a document, with a dictionary of `attributes`
and a list of `children`."""
def __init__(self, attributes=None):
"""Constructs a `_Node`. Don't call this directly - `_Node` is only
ever used as a base class."""
if attributes is None:
self.attributes = {}
else:
self.attributes = attributes
self.children = []
def getElementNode(self):
"""Returns the `_ElementNode` for a node. See the `_RootNode`
documentation for why this exists. You should always go via this
when you want the children or attributes of an element that might
be the root element of a tree."""
# _RootNode overrides this.
return self
def _cloneChildren(self, newNode):
"""Populates the given node with clones of `self`'s children."""
for child in self.children:
newNode.children.append(child.clone(newNode))
def childrenToText(self):
"""Asks the children to recursively textify themselves, then returns
the resulting text."""
text = []
for child in self.children:
text.append(child.toText())
return ''.join(text)
class _RootNode(_Node):
"""The root of a tree. The root is always a `_RootNode` rather than the
top-level `_ElementNode` because there may be things like a ``
declaration outside the root element. This is why `getElementNode()`
exists."""
def __init__(self, attributes=None):
"""Constructs a `_RootNode`, optionally with a dictionary of
`attributes`."""
_Node.__init__(self, attributes)
def getElementNode(self):
"""See `_Node.getElementNode()`."""
for child in self.children:
if isinstance(child, _ElementNode):
return child
def clone(self):
"""Creates a deep clone of a node."""
newNode = _RootNode(self.attributes)
self._cloneChildren(newNode)
return newNode
def toText(self):
"""Generates the XML source for the node."""
# A _RootNode has no text of its own.
return self.childrenToText()
class _ElementNode(_Node):
"""A node representing an element in a document, with a `parent`, a `tag`,
a dictionary of `attributes` and a list of `children`."""
def __init__(self, parent, tag, attributes):
"""Constructs an `_ElementNode`, optionally with a dictionary of
`attributes`."""
_Node.__init__(self, attributes)
self.parent = parent
self.tag = tag
def clone(self, parent=None):
"""Creates a deep clone of a node."""
newNode = _ElementNode(parent, self.tag, self.attributes.copy())
self._cloneChildren(newNode)
return newNode
def toText(self):
"""Generates the XML source for the node."""
text = ['<%s' % self.tag]
attributes = self.attributes.items()
attributes.sort()
for attribute, value in attributes:
text.append(' %s="%s"' % (attribute, value))
childText = self.childrenToText()
if childText or nonSelfClose.has_key(self.tag):
text.append('>')
text.append(childText)
text.append('%s>' % self.tag)
else:
text.append('/>')
return ''.join(text)
class _TextNode(_Node):
"""A tree node representing a piece of text rather than an element."""
def __init__(self, text):
"""Constructs a `_TextNode`."""
_Node.__init__(self)
self._text = text
def clone(self, parent=None):
"""Creates a deep clone of a node."""
return _TextNode(self._text)
def toText(self):
"""Returns the text."""
return self._text
# For XML parsing we use xmllib in versions prior to 2.3, because we can't
# be sure that expat will be there, or that it will be a decent version.
# We use expat in versions 2.3 and above, because we can be sure it will
# be there and xmllib is deprecated from 2.3.
# The slightly odd Entrian.Coverage pragmas in this section make sure that
# whichever branch is taken, we get code coverage for that branch and no
# coverage failures for the other.
if sys.hexversion >> 16 < 0x203:
# Entrian.Coverage: Pragma Stop
import xmllib
class _TreeGenerator(xmllib.XMLParser):
# Entrian.Coverage: Pragma Start
"""An XML parser that generates a lightweight DOM tree. Call `feed()`
with XML source, then `close()`, then `getTree()` will give you the
tree's `_RootNode`:
>>> g = _TreeGenerator()
>>> g.feed("Stuff. ")
>>> g.feed("More stuff.")
>>> g.close()
>>> tree = g.getTree()
>>> print tree.toText()
Stuff. More stuff.
"""
def __init__(self):
xmllib.XMLParser.__init__(self,
translate_attribute_references=False)
self.entitydefs = {} # This is an xmllib.XMLParser attribute.
self._tree = _RootNode()
self._currentNode = self._tree
self._pendingText = []
def getTree(self):
"""Returns the generated tree; call `feed` then `close` first."""
return self._tree
def _collapsePendingText(self):
"""Text (any content that isn't an open/close element) is built up
in `self._pendingText` until an open/close element is seen, at
which point it gets collapsed into a `_TextNode`."""
data = ''.join(self._pendingText)
self._currentNode.children.append(_TextNode(data))
self._pendingText = []
def handle_xml(self, encoding, standalone):
xml = ''
self._pendingText.append(xml)
def handle_doctype(self, tag, pubid, syslit, data):
doctype = '' % data
else:
doctype += '>'
self._pendingText.append(doctype)
def handle_comment(self, data):
self._pendingText.append('' % data)
def handle_proc(self, name, data):
self._pendingText.append('%s %s ?>' % (name, data.strip()))
def handle_data(self, data):
self._pendingText.append(data)
def handle_charref(self, ref):
self._pendingText.append('%s;' % ref)
unknown_charref = handle_charref
def handle_entityref(self, ref):
self._pendingText.append('&%s;' % ref)
unknown_entityref = handle_entityref
def handle_cdata(self, data):
if self._pendingText:
self._collapsePendingText()
self._pendingText.append('' % data)
def unknown_starttag(self, tag, attributes):
if self._pendingText:
self._collapsePendingText()
newNode = _ElementNode(self._currentNode, tag, attributes)
self._currentNode.children.append(newNode)
self._currentNode = newNode
def unknown_endtag(self, tag):
if self._pendingText:
self._collapsePendingText()
self._currentNode = self._currentNode.parent
else:
# Entrian.Coverage: Pragma Stop
import xml.parsers.expat
class _TreeGenerator:
# Entrian.Coverage: Pragma Start
"""An XML parser that generates a lightweight DOM tree. Call `feed()`
with XML source, then `close()`, then `getTree()` will give you the
tree's `_RootNode`:
>>> g = _TreeGenerator()
>>> g.feed("Stuff. ")
>>> g.feed("More stuff.")
>>> g.close()
>>> tree = g.getTree()
>>> print tree.toText()
Stuff. More stuff.
"""
def __init__(self):
self._tree = _RootNode()
self._currentNode = self._tree
self._pendingText = []
self._parser = xml.parsers.expat.ParserCreate()
self._parser.buffer_text = True
self._parser.DefaultHandler = self.DefaultHandler
self._parser.StartElementHandler = self.StartElementHandler
self._parser.EndElementHandler = self.EndElementHandler
# All entities and charrefs, like • and , are considered
# valid - who are we to argue? Expat thinks it knows better, so we
# fool it here.
def _mungeEntities(self, data):
return re.sub(r'&([A-Za-z0-9#]+);', r':PyMeldEntity:\1:', data)
def _unmungeEntities(self, data):
return re.sub(r':PyMeldEntity:([A-Za-z0-9#]+):', r'&\1;', data)
def feed(self, data):
"""Call this with XML content to be parsed."""
data = self._mungeEntities(data)
self._parser.Parse(data)
def close(self):
"""Call this when you've passed all your XML content to `feed`."""
self._parser.Parse("", True)
def getTree(self):
"""Returns the generated tree; call `feed` then `close` first."""
return self._tree
def _collapsePendingText(self):
"""Text (any content that isn't an open/close element) is built up
in `self._pendingText` until an open/close element is seen, at
which point it gets collapsed into a `_TextNode`."""
data = ''.join(self._pendingText)
data = self._unmungeEntities(data)
self._currentNode.children.append(_TextNode(data))
self._pendingText = []
def DefaultHandler(self, data):
"""Expat handler."""
self._pendingText.append(str(data))
def StartElementHandler(self, tag, attributes):
"""Expat handler."""
if self._pendingText:
self._collapsePendingText()
newAttributes = {}
for name, value in attributes.iteritems():
newAttributes[str(name)] = self._unmungeEntities(str(value))
newNode = _ElementNode(self._currentNode, str(tag), newAttributes)
self._currentNode.children.append(newNode)
self._currentNode = newNode
def EndElementHandler(self, tag):
"""Expat handler."""
if self._pendingText:
self._collapsePendingText()
self._currentNode = self._currentNode.parent
def _generateTree(source):
"""Given some XML source, generates a lightweight DOM tree rooted at a
`_RootNode`."""
# Lots of HTML files start with a DOCTYPE declaration like this:
#
# The fact that the DTD URL is missing is deliberate - it acts as a hint
# to the browser that it should emulate historical browser behaviour. It
# also breaks xmllib, so we see whether we can spot it here and cope.
doctypeRE = r'(?i)^(\s*)'
match = re.search(doctypeRE, source)
if match:
source = source[match.end():]
doctype = match.group(1)
else:
doctype = ''
# Another hack for HTML: the DOCTYPE usually gives HTML (in upper case)
# as the root tag name, but xmllib will complain if you then use
# (lowercase) for the tag. We fix up the DOCTYPE here if it looks like
# that's the case.
rootRE = r'(?i)^\s*', '>')
value = re.sub(r'&(?![a-zA-Z0-9]+;)', '&', value)
return value
def _unquoteAttribute(self, value):
"""Unquotes an attribute value quoted by `_quoteAttribute()`."""
value = value.replace('"', '"').replace('&', '&')
return value.replace('<', '<').replace('>', '>')
def _nodeListFromSource(self, value):
"""Given a snippet of XML source, returns a list of `_Node`s."""
tree = _generateTree(""+value+"")
return tree.children[0].children
def _replaceNodeContent(self, node, value):
"""Replaces the content of the given node. If `value` is a string, it
is parsed as XML. If it is a Meld, it it cloned. The existing
children are deleted, the new nodes are set as the children of
`node`."""
if isinstance(value, Meld):
node.children = [value._tree.getElementNode().clone()]
else:
if not isinstance(value, str):
value = str(value)
node.children = self._nodeListFromSource(value)
def clone(self, readonly=False):
"""Creates a clone of a `Meld`, for instance to change an attribute
without affecting the original document:
>>> p = Meld('Hello World
')
>>> q = p.clone()
>>> q.who = "Richie"
>>> print q.who
Richie
>>> print p.who
World
By default, clones are not readonly even if the Meld from which
they're cloned is readonly (the most common reason for taking a
clone is to create a modified clone of a piece of a document). To
make a readonly clone, say `clone = object.clone(readonly=True)`."""
return Meld(self._tree.clone(), readonly)
def __getattr__(self, name):
"""`object.`, if this Meld contains an element with an `id`
attribute of `name`, returns a Meld representing that element.
Otherwise, `object.` returns the value of the attribute with
the given name, as a string. If no such attribute exists, an
AttributeError is raised.
`object._content` returns the content of the Meld, not including
the enclosing ``, as a string.
>>> p = Meld('Hello World
')
>>> print p.who
World
>>> print p.style
one
>>> print p._content
Hello World
>>> print p.who._content
World
"""
if name == '_content':
return self._tree.getElementNode().childrenToText()
if name.startswith('_'):
try:
return self.__dict__[name]
except KeyError:
raise AttributeError, name
node = self._findByID(self._tree, name)
if node:
return Meld(node, self._readonly)
attribute = self._tree.getElementNode().attributes.get(name, _fail)
if attribute is not _fail:
return self._unquoteAttribute(attribute)
raise AttributeError, "No element or attribute named %r" % name
def __setattr__(self, name, value):
"""`object. = value` sets the XML content of the element with an
`id` of `name`, or if no such element exists, sets the value of the
`name` attribute on the outermost element. If the attribute is not
already there, a new attribute is created.
>>> p = Meld('Hello World
')
>>> p.who = "Richie"
>>> p.style = "two"
>>> p.align = "center"
>>> p.who.id = "newwho"
>>> print p
Hello Richie
"""
if name.startswith('_') and name != '_content':
self.__dict__[name] = value
return
if self._readonly:
raise ReadOnlyError, READ_ONLY_MESSAGE
node = self._findByID(self._tree, name)
if hasattr(value, '_tree') and value._tree is node:
return # x.y = x.y
if not node and name == '_content':
node = self._tree.getElementNode()
if node:
self._replaceNodeContent(node, value)
else:
value = self._quoteAttribute(value)
self._tree.getElementNode().attributes[name] = value
def __delattr__(self, name):
"""Deletes the named element or attribute from the `Meld`:
>>> p = Meld('Hello World
')
>>> del p.who
>>> del p.style
>>> print p
Hello
"""
if name == '_content':
self._tree.getElementNode().children = []
return
if name.startswith('_'):
try:
del self.__dict__[name]
return
except KeyError:
raise AttributeError, name
if self._readonly:
raise ReadOnlyError, READ_ONLY_MESSAGE
node = self._findByID(self._tree, name)
if node:
node.parent.children.remove(node)
return
node = self._tree.getElementNode()
attribute = node.attributes.get(name, _fail)
if attribute is not _fail:
del node.attributes[name]
else:
raise AttributeError, "No element or attribute named %r" % name
def __iadd__(self, other):
"""`object1 += object2` appends a string or a clone of a Meld to
the end of another Meld's content. This is used to build things
like HTML tables, which are collections of other objects (eg. table
rows). See *Real-world example* in the main documentation."""
if self._readonly:
raise ReadOnlyError, READ_ONLY_MESSAGE
if isinstance(other, Meld):
nodes = [other._tree.getElementNode().clone()]
else:
nodes = self._nodeListFromSource(other)
self._tree.children.extend(nodes)
return self
def __mod__(self, values):
"""`object % value`, `object % sequence`, or `object % dictionary` all
mimic the `%` operator for strings:
>>> xml = 'Hello World'
>>> x = Meld(xml)
>>> print x % ("Howdy", "everybody")
Howdy everybody
>>> print x % {'who': 'all'}
Hello all
Assignment for sequences happens in the same order that nodes with
'id' attributes appear in the document, not including the top-level
node (because if the top-level node were included, you'd only ever
be able to assign to that and nothing else):
>>> xml = '''
...
... First one
... Second one
...
... Third one; the content includes 'f':
... Removed when 'e' is assigned to
...
... '''
>>> a = Meld(xml)
>>> print a % ('One, with a new node', 'Two', 'Three')
One, with a new node
Two
Three
Giving the wrong number of elements to `%` raises the same exceptions
as the builtin string `%` operator. Unlike the builtin `%` operator,
dictionaries don't need to specify all the keys:
>>> print x % "Howdy"
Traceback (most recent call last):
...
TypeError: not enough arguments
>>> print x % ("Howdy", "everybody", "everywhere")
Traceback (most recent call last):
...
TypeError: not all arguments converted
>>> print x % {"greeting": "Howdy"}
Howdy World
"""
# Figure out whether we have a dictionary, a sequence, or a lone value.
returnObject = self.clone()
if hasattr(values, 'values') and callable(values.values):
# It's a dictionary.
keys = values.keys()
sequence = values.values()
elif hasattr(values, '__getitem__') and \
not isinstance(values, str):
# It's a sequence.
keys = None
sequence = list(values)
else:
# Assume it's a plain value.
keys = None
sequence = [values]
# If we've derived a set of keys, just assign the values.
if keys:
for key, value in zip(keys, sequence):
node = returnObject._findByID(returnObject._tree, key)
if node:
returnObject._replaceNodeContent(node, value)
else:
# No keys, so set the values in the order they appear. This is
# a depth-first in-order search, pruned wherever we find a match
# (otherwise we'd start assigning into places we'd just
# assigned). We reverse the sequences so we can use pop().
stack = returnObject._tree.getElementNode().children[:]
stack.reverse()
sequence.reverse()
while stack and sequence:
element = stack.pop()
if element.attributes.has_key('id'):
self._replaceNodeContent(element, sequence.pop())
else:
for index in range(len(element.children)):
stack.append(element.children[-1 - index])
if sequence:
raise TypeError, "not all arguments converted"
while stack:
if stack.pop().attributes.has_key('id'):
raise TypeError, "not enough arguments"
return returnObject
def __add__(self, other):
"""`object1 + object2` turns both objects into strings and returns the
concatenation of the strings:
>>> a = Meld('1')
>>> b = Meld('2')
>>> c = Meld('3')
>>> print a + b
12
>>> print a.x + b.y + c.z
123
"""
if isinstance(other, Meld):
other = other._tree.toText()
return self._tree.toText() + other
def __radd__(self, other):
"""See `__add__`"""
# The case where `other` is a Meld can never happen, because
# __add__ will be called instead.
return other + self._tree.toText()
def __str__(self):
"""Returns the XML that this `Meld` represents. Don't call
this directly - instead convert a `Meld` to a string using
`str(object)`. `print` does this automatically, which is why
none of the examples calls `str`."""
return str(self._tree.toText())
###########################################################################
##
## Self-test code.
##
# Extra tests, for features that aren't tested by the (visible) docstrings:
__test__ = {
'_Node': _Node,
'_RootNode': _RootNode,
'_ElementNode': _ElementNode,
'_TextNode': _TextNode,
'_TreeGenerator': _TreeGenerator,
'_generateTree': _generateTree,
'': """
>>> print Meld('''
... Stuff''')
Stuff
""",
'DOCTYPE (system)': """
>>> print Meld('''
... Stuff''')
Stuff
""",
'DOCTYPE (small)': """
>>> print Meld('''
... Stuff''')
Stuff
""",
'DOCTYPE (full)': """
>>> print Meld('''
...
...
... ]>
... Stuff''')
]>
Stuff
""",
'DOCTYPE (HTML hackery)': """
>>> html = '''
... Stuff'''
>>> print Meld(html)
Stuff
""",
'XML proc': """
>>> print Meld('''
...
...
... ]>
... Stuff''')
]>
Stuff
""",
'comment': """
>>> page = Meld('''''')
>>> print page
""",
'entities and charrefs': """
>>> page = Meld('''• This "and that"...
... x''')
>>> print page.s.title
"Quoted" & Not
>>> page.s.title = page.s.title + " <>"
>>> print page.s.title
"Quoted" & Not <>
>>> print page.s
x
""",
'self-closing tags': """
>>> page = Meld('''Stuff''')
>>> page.spam = ""
>>> print page
>>> page = Meld('''''') # nonSelfClose special case
>>> print page
""",
'assigning to _content': """
>>> page = Meld('''Old''')
>>> page.s._content = "New"
>>> print page
New
>>> page._content = "All new"
>>> print page
All new
""",
'deleting _content': """
>>> page = Meld('''Old''')
>>> del page.s._content
>>> print page
""",
'constructing from an unknown type': """
>>> page = Meld(1)
Traceback (most recent call last):
...
TypeError: Melds must be constructed from ASCII strings
""",
'accessing a non-existent attribute': """
>>> page = Meld('')
>>> print page.spam
Traceback (most recent call last):
...
AttributeError: No element or attribute named 'spam'
>>> del page.spam
Traceback (most recent call last):
...
AttributeError: No element or attribute named 'spam'
""",
'cdata': """
>>> html = ''''''
>>> page = Meld(html)
>>> print page.cdataExample
""",
'add new things':"""
>>> page = Meld('''''')
>>> page.empty = "Not any more"
>>> page.empty.cols = 60
>>> print page
""",
'readonly': """
>>> page = Meld('''No!''', readonly=True)
>>> page.no = "Yes?"
Traceback (most recent call last):
...
ReadOnlyError: You can't modify this read-only Meld object
>>> page.no.attribute = "Yes?"
Traceback (most recent call last):
...
ReadOnlyError: You can't modify this read-only Meld object
>>> page.no += "More?"
Traceback (most recent call last):
...
ReadOnlyError: You can't modify this read-only Meld object
>>> del page.no
Traceback (most recent call last):
...
ReadOnlyError: You can't modify this read-only Meld object
""",
'copy from one to another': """
>>> a = Meld('One')
>>> b = Meld('Two')
>>> a.one = b.two
>>> print a
Two
>>> b.two = "New"
>>> print a # Checking for side-effects
Two
""",
'mixed-type add, radd and iadd': """
>>> a = Meld('1')
>>> print a.one + "x"
1x
>>> print "x" + a.one
x1
>>> a.one += "y"
>>> print a
1y
""",
'no unicode': r"""
>>> u = Meld(u'One')
Traceback (most recent call last):
...
TypeError: Melds must be constructed from ASCII strings
""",
'private attributes': """
>>> page = Meld('x')
>>> page._private = "Spam"
>>> print repr(page._private)
'Spam'
>>> print page
x
>>> del page._private
>>> print repr(page._private)
Traceback (most recent call last):
...
AttributeError: _private
>>> del page._private
Traceback (most recent call last):
...
AttributeError: _private
>>> print page
x
""",
'bad XML characters': """
>>> page = Meld('''
... Valentines Day Special \x96 2 bikinis for the price of one \x01
... ''') # No exception.
>>> print page
Valentines Day Special 2 bikinis for the price of one ?
"""
}
# Entrian.Coverage: Pragma Stop
def test():
"""Tests the `PyMeldLite` module, performing code coverage analysis if
`Entrian.Coverage` is available. Returns `(failed, total)`, a la
`doctest.testmod`."""
import doctest
try:
from Entrian import Coverage
Coverage.start('PyMeldLite')
except ImportError:
Coverage = False
import PyMeldLite
result = doctest.testmod(PyMeldLite)
if Coverage:
analysis = Coverage.getAnalysis()
analysis.printAnalysis()
return result
if __name__ == '__main__':
failed, total = test()
if failed == 0: # Else `doctest.testmod` prints the failures.
print "All %d tests passed." % total