[zopeorg-checkins] CVS: Products/ParsedXML/tests/domapi - Base.py:1.1 CoreLvl1.py:1.1 CoreLvl2.py:1.1 CoreLvl3.py:1.1 Load3.py:1.1 TraversalLvl2.py:1.1 XMLLvl1.py:1.1 XMLLvl2.py:1.1 __init__.py:1.1

Sidnei da Silva sidnei at x3ng.com.br
Fri May 30 11:17:33 EDT 2003


Update of /cvs-zopeorg/Products/ParsedXML/tests/domapi
In directory cvs.zope.org:/tmp/cvs-serv19195/ParsedXML/tests/domapi

Added Files:
	Base.py CoreLvl1.py CoreLvl2.py CoreLvl3.py Load3.py 
	TraversalLvl2.py XMLLvl1.py XMLLvl2.py __init__.py 
Log Message:
Adding products needed for migration of NZO

=== Added File Products/ParsedXML/tests/domapi/Base.py ===
##############################################################################
# 
# Zope Public License (ZPL) Version 1.0
# -------------------------------------
# 
# Copyright (c) Digital Creations.  All rights reserved.
# 
# This license has been certified as Open Source(tm).
# 
# 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 above copyright
#    notice, this list of conditions, and the following disclaimer.
# 
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions, and the following disclaimer in
#    the documentation and/or other materials provided with the
#    distribution.
# 
# 3. Digital Creations requests that attribution be given to Zope
#    in any manner possible. Zope includes a "Powered by Zope"
#    button that is installed by default. While it is not a license
#    violation to remove this button, it is requested that the
#    attribution remain. A significant investment has been put
#    into Zope, and this effort will continue if the Zope community
#    continues to grow. This is one way to assure that growth.
# 
# 4. All advertising materials and documentation mentioning
#    features derived from or use of this software must display
#    the following acknowledgement:
# 
#      "This product includes software developed by Digital Creations
#      for use in the Z Object Publishing Environment
#      (http://www.zope.org/)."
# 
#    In the event that the product being advertised includes an
#    intact Zope distribution (with copyright and license included)
#    then this clause is waived.
# 
# 5. Names associated with Zope or Digital Creations must not be used to
#    endorse or promote products derived from this software without
#    prior written permission from Digital Creations.
# 
# 6. Modified redistributions of any form whatsoever must retain
#    the following acknowledgment:
# 
#      "This product includes software developed by Digital Creations
#      for use in the Z Object Publishing Environment
#      (http://www.zope.org/)."
# 
#    Intact (re-)distributions of any official Zope release do not
#    require an external acknowledgement.
# 
# 7. Modifications are encouraged but must be packaged separately as
#    patches to official Zope releases.  Distributions that do not
#    clearly separate the patches from the original work must be clearly
#    labeled as unofficial distributions.  Modifications which do not
#    carry the name Zope may be packaged in any form, as long as they
#    conform to all of the clauses above.
# 
# 
# Disclaimer
# 
#   THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``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 DIGITAL CREATIONS OR ITS
#   CONTRIBUTORS 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.
# 
# 
# This software consists of contributions made by Digital Creations and
# many individuals on behalf of Digital Creations.  Specific
# attributions are listed in the accompanying credits file.
# 
##############################################################################

import xml.dom
from xml.dom import Node

import sys
import unittest

# Namespace URI for namespace tests
TEST_NAMESPACE = 'uri:namespacetests'

# Convenience map for assert messages
TYPE_NAME = {
        Node.ATTRIBUTE_NODE:                'Attribute',
        Node.CDATA_SECTION_NODE:            'CDATA Section',
        Node.COMMENT_NODE:                  'Comment',
        Node.DOCUMENT_FRAGMENT_NODE:        'Document Fragment',
        Node.DOCUMENT_NODE:                 'Document',
        Node.DOCUMENT_TYPE_NODE:            'DocumentType',
        Node.ELEMENT_NODE:                  'Element',
        Node.ENTITY_NODE:                   'Entity',
        Node.ENTITY_REFERENCE_NODE:         'Entity Reference',
        Node.NOTATION_NODE:                 'Notation',
        Node.PROCESSING_INSTRUCTION_NODE:   'Processing Instruction',
        Node.TEXT_NODE:                     'Text',
   }

def checkAttribute(node, attribute, value):
    """Check that an attribute holds the expected value, and that the
    corresponding accessor method, if provided, returns an equivalent
    value."""
    #
    v1 = getattr(node, attribute)
    if v1 != value:
        raise AssertionError(
            "attribute value does not match\n  expected: %s\n  found: %s"
            % (`value`, `v1`))
    if hasattr(node, "_get_" + attribute):
        v2 = getattr(node, "_get_" + attribute)()
        if v2 != value:
            raise AssertionError(
                "accessor result does not match\n  expected: %s\n  found: %s"
                % (`value`, `v2`))
        if v1 != v2:
            raise AssertionError(
                "attribute & accessor result don't compare equal\n"
                "  attribute: %s\n  accessor: %s"
                % (`v1`, `v2`))


def checkAttributeNot(node, attribute, value):
    """Check that an attribute doesn't hold a specific failing value,
    and that the corresponding accessor method, if provided, returns
    an equivalent value."""
    #
    v1 = getattr(node, attribute)
    if v1 == value:
        raise AssertionError(
           "attribute value should not match\n  found: %s" % `v1`)
    if hasattr(node, "_get_" + attribute):
        v2 = getattr(node, "_get_" + attribute)()
        if v2 == value:
            raise AssertionError(
                "accessor result should not match\n  found: %s" % `v2`)
        if v1 != v2:
            raise AssertionError(
                "attribute & accessor result don't compare equal\n"
                "  attribute: %s\n  accessor: %s"
                % (`v1`, `v2`))

def checkAttributeSameNode(node, attribute, value):
    v1 = getattr(node, attribute)
    if value is None:
        if v1 is not None:
            raise AssertionError(
                "attribute value does not match\n  expected: %s\n  found: %s"
                % (`value`, `v1`))
    else:
        if not isSameNode(value, v1):
            raise AssertionError(
                "attribute value does not match\n  expected: %s\n  found: %s"
                % (`value`, `v1`))
    if hasattr(node, "_get_" + attribute):
        v2 = getattr(node, "_get_" + attribute)()
        if value is None:
            if v2 is not None:
                raise AssertionError(
                    "accessor result does not match\n"
                    "  expected: %s\n  found: %s" % (`value`, `v2`))
        elif not isSameNode(value, v2):
            raise AssertionError(
                "accessor result does not match\n"
                "  expected: %s\n  found: %s" % (`value`, `v2`))


def checkReadOnly(node, attribute):
    try:
        setattr(node, attribute, "don't set this!")
    except xml.dom.NoModificationAllowedErr:
        pass
    else:
        raise AssertionError("write-access to the '%s' attribute not blocked"
                             % attribute)

    if hasattr(node, "_set_" + attribute):
        # setter implemented; make sure it won't allow update
        try:
            getattr(node, "_set_" + attribute)("don't set this!")
        except xml.dom.NoModificationAllowedErr:
            pass
        else:
            raise AssertionError("_set_%s() allowed attribute update"
                                 % attribute)


def checkLength(node, value):
    checkAttribute(node, "length", value)
    if len(node) != value:
        raise AssertionError("broken support for __len__()")
    checkReadOnly(node, "length")


def isSameNode(node1, node2):
    """Compare two nodes, returning true if they are the same.

    Use the DOM lvl 3 Node.isSameNode method if available, otherwise use a
    simple 'is' test.

    """

    if hasattr(node1, 'isSameNode'):
        return node1.isSameNode(node2)
    else:
        return node1 is node2


class TestCaseBase(unittest.TestCase):

    def createDocumentNS(self):
        self.document = self.implementation.createDocument(
            TEST_NAMESPACE, 'foo:bar', None)
        return self.document

    def createDocument(self):
        self.document = self.implementation.createDocument(None, 'root', None)
        return self.document

def buildCases(modName, feature, level):
    cases = []
    add = cases.append
    objects = sys.modules[modName].__dict__
    for obj in objects.keys():
        if obj[-8:] != 'TestCase': continue
        add((objects[obj], feature, level))

    return list(cases)


=== Added File Products/ParsedXML/tests/domapi/CoreLvl1.py === (2331/2431 lines abridged)
##############################################################################
# 
# Zope Public License (ZPL) Version 1.0
# -------------------------------------
# 
# Copyright (c) Digital Creations.  All rights reserved.
# 
# This license has been certified as Open Source(tm).
# 
# 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 above copyright
#    notice, this list of conditions, and the following disclaimer.
# 
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions, and the following disclaimer in
#    the documentation and/or other materials provided with the
#    distribution.
# 
# 3. Digital Creations requests that attribution be given to Zope
#    in any manner possible. Zope includes a "Powered by Zope"
#    button that is installed by default. While it is not a license
#    violation to remove this button, it is requested that the
#    attribution remain. A significant investment has been put
#    into Zope, and this effort will continue if the Zope community
#    continues to grow. This is one way to assure that growth.
# 
# 4. All advertising materials and documentation mentioning
#    features derived from or use of this software must display
#    the following acknowledgement:
# 
#      "This product includes software developed by Digital Creations
#      for use in the Z Object Publishing Environment
#      (http://www.zope.org/)."
# 
#    In the event that the product being advertised includes an
#    intact Zope distribution (with copyright and license included)
#    then this clause is waived.
# 
# 5. Names associated with Zope or Digital Creations must not be used to
#    endorse or promote products derived from this software without
#    prior written permission from Digital Creations.
# 
# 6. Modified redistributions of any form whatsoever must retain
#    the following acknowledgment:
# 
#      "This product includes software developed by Digital Creations
#      for use in the Z Object Publishing Environment

[-=- -=- -=- 2331 lines omitted -=- -=- -=-]

            "setNamedItem store seems to have failed, can't retrieve.")

    def checkSetNamedItemReplacingExistingNode(self):
        newAttr = self.document.createAttribute('someAttr')
        self.map.setNamedItem(newAttr)
        anotherAttr = self.document.createAttribute('someAttr')
        anotherAttr.value = 'eggs'

        retVal = self.map.setNamedItem(newAttr)
        assert retVal is not None, "setNamedItem returned None"
        assert isSameNode(retVal, newAttr), (
            "setNamedItem didn't return replaced Node.")
        checkLength(self.map, 2)

    def checkSetNamedItemWrongDocument(self):
        newDoc = self.implementation.createDocument(None, 'foo', None)
        foreignAttr = newDoc.createAttribute('someAttr')
        try:
            self.map.setNamedItem(foreignAttr)
        except xml.dom.WrongDocumentErr:
            pass
        else:
            assert 0, "Was allowed to add foreign Node to NamedNodeMap."

    def checkSetNamedItemAlreadyInUse(self):
        el = self.document.createElement('someElement')
        attr = self.document.createAttribute('someAttribute')
        el.setAttributeNode(attr)
        try:
           self.map.setNamedItem(attr)
        except xml.dom.InuseAttributeErr:
            pass
        else:
            assert 0, (
                "Was allowed to add attribute already in use to NamedNodeMap.")

    def checkSetNamedItemHierarchyRequestErr(self):
        # See DOM erratum core-4.
        textNode = self.document.createTextNode('text node')
        try:
            self.map.setNamedItem(textNode)
        except xml.dom.HierarchyRequestErr:
            pass
        else:
            assert 0, (
                "Was allowed to add a Node Type not belonging in this "
                "NamedNodeMap (a Text Node to a map of attributes).")


cases = buildCases(__name__, 'Core', None)


=== Added File Products/ParsedXML/tests/domapi/CoreLvl2.py === (1624/1724 lines abridged)
##############################################################################
# 
# Zope Public License (ZPL) Version 1.0
# -------------------------------------
# 
# Copyright (c) Digital Creations.  All rights reserved.
# 
# This license has been certified as Open Source(tm).
# 
# 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 above copyright
#    notice, this list of conditions, and the following disclaimer.
# 
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions, and the following disclaimer in
#    the documentation and/or other materials provided with the
#    distribution.
# 
# 3. Digital Creations requests that attribution be given to Zope
#    in any manner possible. Zope includes a "Powered by Zope"
#    button that is installed by default. While it is not a license
#    violation to remove this button, it is requested that the
#    attribution remain. A significant investment has been put
#    into Zope, and this effort will continue if the Zope community
#    continues to grow. This is one way to assure that growth.
# 
# 4. All advertising materials and documentation mentioning
#    features derived from or use of this software must display
#    the following acknowledgement:
# 
#      "This product includes software developed by Digital Creations
#      for use in the Z Object Publishing Environment
#      (http://www.zope.org/)."
# 
#    In the event that the product being advertised includes an
#    intact Zope distribution (with copyright and license included)
#    then this clause is waived.
# 
# 5. Names associated with Zope or Digital Creations must not be used to
#    endorse or promote products derived from this software without
#    prior written permission from Digital Creations.
# 
# 6. Modified redistributions of any form whatsoever must retain
#    the following acknowledgment:
# 
#      "This product includes software developed by Digital Creations
#      for use in the Z Object Publishing Environment

[-=- -=- -=- 1624 lines omitted -=- -=- -=-]

            'qname:someAttr')
        self.map.setNamedItemNS(newAttr)
        anotherAttr = self.document.createAttributeNS(self.TEST_NAMESPACE,
            'anotherQN:someAttr')
        anotherAttr.value = 'eggs'

        retVal = self.map.setNamedItemNS(newAttr)
        assert retVal is not None, "setNamedItemNS returned None"
        assert isSameNode(retVal, newAttr), (
            "setNamedItemNS didn't return replaced Node.")
        checkLength(self.map, 2)

    def checkSetNamedItemNSWrongDocument(self):
        newDoc = self.implementation.createDocument(None, 'foo', None)
        foreignAttr = newDoc.createAttributeNS(self.TEST_NAMESPACE,
            self.TEST_QUALIFIED_NAME)
        try:
            self.map.setNamedItem(foreignAttr)
        except xml.dom.WrongDocumentErr:
            pass
        else:
            assert 0, "Was allowed to add foreign Node to NamedNodeMap."

    def checkSetNamedItemNSAlreadyInUse(self):
        el = self.document.createElement('someElement')
        attr = self.document.createAttributeNS(self.TEST_NAMESPACE,
            self.TEST_QUALIFIED_NAME)
        el.setAttributeNode(attr)
        try:
           self.map.setNamedItem(attr)
        except xml.dom.InuseAttributeErr:
            pass
        else:
            assert 0, (
                "Was allowed to add attribute already in use to NamedNodeMap.")

    def checkSetNamedItemNSHierarchyRequestErr(self):
        # See DOM erratum core-4.
        element = self.document.createElementNS(TEST_NAMESPACE, 'foo:bar')
        try:
            self.map.setNamedItemNS(element)
        except xml.dom.HierarchyRequestErr:
            pass
        else:
            assert 0, (
                "Was allowed to add a Node Type not belonging in this "
                "NamedNodeMap (an Element Node to a map of attributes).")


cases = buildCases(__name__, 'Core', '2.0')


=== Added File Products/ParsedXML/tests/domapi/CoreLvl3.py ===
"""Test cases for DOM Core Level 3."""

import xml.dom

import Base


class WhitespaceInElementContentTestCase(Base.TestCaseBase):

    def checkWhiteSpaceInElementContent(self):
        TEXT = """<!DOCTYPE doc [
          <!ELEMENT doc (foo+)>
        ]>
        <doc>
          <foo/>
        </doc>"""
        doc = self.parse(TEXT)
        for node in doc.documentNode.childNodes:
            if node.nodeType == xml.dom.Node.TEXT_NODE:
                if not node.isWhitespaceInElementContent:
                    self.fail("founc whitespace node not identified"
                              " as whitespace-in-element-contnet")

    def checkWhiteSpaceInUnknownContent(self, subset=""):
        TEXT = """<!DOCTYPE doc %s>
        <doc>
          <foo/>
        </doc>""" % subset
        doc = self.parse(TEXT)
        for node in doc.documentNode.childNodes:
            if node.nodeType == xml.dom.Node.TEXT_NODE:
                if node.isWhitespaceInElementContent:
                    self.fail("founc whitespace node in mixed content marked"
                              " as whitespace-in-element-contnet")

    def checkWhiteSpaceInMixedContent(self):
        assert 0
        self.checkWhiteSpaceInUnknownContent("""[
          <!ELEMENT doc (#PCDATA | foo)*>
        ]""")


cases = Base.buildCases(__name__, 'Core', '3.0')


=== Added File Products/ParsedXML/tests/domapi/Load3.py ===
##############################################################################
# 
# Zope Public License (ZPL) Version 1.0
# -------------------------------------
# 
# Copyright (c) Digital Creations.  All rights reserved.
# 
# This license has been certified as Open Source(tm).
# 
# 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 above copyright
#    notice, this list of conditions, and the following disclaimer.
# 
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions, and the following disclaimer in
#    the documentation and/or other materials provided with the
#    distribution.
# 
# 3. Digital Creations requests that attribution be given to Zope
#    in any manner possible. Zope includes a "Powered by Zope"
#    button that is installed by default. While it is not a license
#    violation to remove this button, it is requested that the
#    attribution remain. A significant investment has been put
#    into Zope, and this effort will continue if the Zope community
#    continues to grow. This is one way to assure that growth.
# 
# 4. All advertising materials and documentation mentioning
#    features derived from or use of this software must display
#    the following acknowledgement:
# 
#      "This product includes software developed by Digital Creations
#      for use in the Z Object Publishing Environment
#      (http://www.zope.org/)."
# 
#    In the event that the product being advertised includes an
#    intact Zope distribution (with copyright and license included)
#    then this clause is waived.
# 
# 5. Names associated with Zope or Digital Creations must not be used to
#    endorse or promote products derived from this software without
#    prior written permission from Digital Creations.
# 
# 6. Modified redistributions of any form whatsoever must retain
#    the following acknowledgment:
# 
#      "This product includes software developed by Digital Creations
#      for use in the Z Object Publishing Environment
#      (http://www.zope.org/)."
# 
#    Intact (re-)distributions of any official Zope release do not
#    require an external acknowledgement.
# 
# 7. Modifications are encouraged but must be packaged separately as
#    patches to official Zope releases.  Distributions that do not
#    clearly separate the patches from the original work must be clearly
#    labeled as unofficial distributions.  Modifications which do not
#    carry the name Zope may be packaged in any form, as long as they
#    conform to all of the clauses above.
# 
# 
# Disclaimer
# 
#   THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``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 DIGITAL CREATIONS OR ITS
#   CONTRIBUTORS 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.
# 
# 
# This software consists of contributions made by Digital Creations and
# many individuals on behalf of Digital Creations.  Specific
# attributions are listed in the accompanying credits file.
# 
##############################################################################

"""Tests for the 'Load' part of the Load/Save component from DOM Level 3.

Note that the Load/Save component is a working draft and not a final
recommendation.
"""

import xml.dom

import Base
from Products.ParsedXML.DOM import LoadSave
from Products.ParsedXML.StrIO import StringIO


class BuilderTestCaseBase(Base.TestCaseBase):
    def createBuilder(self):
        return self.implementation.createDOMBuilder()


class BuilderFeatureConformanceTestCase(BuilderTestCaseBase):
    """Test that the DOMBuilder has the defaults and allows setting
    all features required by the W3C specification.

    The features are not exercised, but every value that is required
    to be supported is tested and set.
    """

    FEATURES = {
        # feature-name: (default, must-support-true, must-support-false)
        "namespaces": (1, 1, 0),
        "namespace-declarations": (1, 1, 0),
        "validation": (0, 0, 1),
        "external-general-entities": (1, 1, 0),
        "external-parameter-entities": (1, 1, 0),
        "validate-if-cm": (0, 0, 1),
        "create-entity-ref-nodes": (1, 1, 0),
        "entity-nodes": (1, 1, 0),
        "white-space-in-element-content": (1, 1, 0),
        "cdata-nodes": (1, 1, 0),
        "comments": (1, 1, 1),
        "charset-overrides-xml-encoding": (1, 1, 1),
        }

    def checkFeatureDefaults(self):
        for item in self.FEATURES.items():
            feature, (default, xxx, xxx) = item
            b = self.createBuilder()
            value = b.getFeature(feature) and 1 or 0
            self.assert_(value == default,
                         "default feature value not right")

    def checkRequiredFeatureSettings(self):
        for item in self.FEATURES.items():
            feature, (xxx, require_true, require_false) = item
            b = self.createBuilder()
            if require_true:
                self.assert_(b.canSetFeature(feature, 1),
                             "builder indicates feature cannot be enabled")
                b.setFeature(feature, 1)
                self.assert_(b.getFeature(feature),
                             "enabling feature failed")
            if require_false:
                self.assert_(b.canSetFeature(feature, 0),
                             "builder indicates feature cannot be disabled")
                b.setFeature(feature, 0)
                self.assert_(not b.getFeature(feature),
                             "disabling feature failed")

    def checkSupportsFeatures(self):
        b = self.createBuilder()
        for feature in self.FEATURES.keys():
            self.assert_(b.supportsFeature(feature),
                         "builder reports non-support for required feature")

    def checkEntityNodesFeatureSideEffect(self):
        b = self.createBuilder()
        b.setFeature("entity-nodes", 0)
        self.assert_(not b.getFeature("create-entity-ref-nodes"),
                     "setting entity-nodes to false should turn off"
                     " create-entity-ref-nodes")

    def checkUnknownFeature(self):
        b = self.createBuilder()
        self.assertRaises(xml.dom.NotFoundErr,
                          b.setFeature, "non-existant-feature", 0)
        self.assertRaises(xml.dom.NotFoundErr,
                          b.getFeature, "non-existant-feature")
        self.assert_(not b.supportsFeature("non-existant-feature"),
                     "expected non-existant-feature to raise"
                     " xml.dom.NotFoundErr")
        self.assert_(not b.canSetFeature("non-existant-feature", 0),
                     "builder allows setting of non-existant feature"
                     " to false")
        self.assert_(not b.canSetFeature("non-existant-feature", 1),
                     "builder allows setting of non-existant feature"
                     " to true")

    def checkWhiteSpaceInElementContentDiscarded(self):
        TEXT = """<!DOCTYPE doc [
          <!ELEMENT doc (foo+)>
        ]>
        <doc>
          <foo/>
        </doc>"""
        doc = self._parse(TEXT, {"white-space-in-element-content": 0})
        for node in doc.documentElement.childNodes:
            if node.nodeType == xml.dom.Node.TEXT_NODE:
                self.fail("founc whitespace-in-element-content node which"
                          " should bave been excluded")

    def checkCommentsOmitted(self):
        doc = self._parse("<doc><!-- comment --></doc>",
                          {"comments": 0})
        self.assert_(doc.documentElement.childNodes.length == 0,
                     "comment node was returned as part of the document")

    def checkCDATAAsText(self):
        doc = self._parse("<doc><![CDATA[<<!--stuff-->>]]></doc>",
                          {"cdata-nodes": 0})
        self.assert_(doc.documentElement.childNodes[0].data
                     == "<<!--stuff-->>")
        self.assert_(doc.documentElement.childNodes.length == 1)

    def checkWithoutNamespaces(self):
        doc = self._parse("<doc xmlns='foo' xmlns:tal='bar' tal:attr='value'>"
                          "  <tal:element tal:attr2='another'/>"
                          "</doc>",
                          {"namespaces": 0})
        docelem = doc.documentElement
        self.assert_(docelem.namespaceURI is None)
        self.assert_(docelem.prefix is None)
        self.assert_(docelem.getAttributeNode("xmlns").namespaceURI is None)
        self.assert_(docelem.getAttributeNode("xmlns").prefix is None)
        self.assert_(docelem.getAttributeNode("tal:attr").namespaceURI is None)
        self.assert_(docelem.getAttributeNode("tal:attr").prefix is None)
        elem = docelem.firstChild
        self.assert_(elem.namespaceURI is None)
        self.assert_(elem.prefix is None)

    def checkWithoutNamespaceDeclarations(self):
        doc = self._parse("<doc xmlns='foo' xmlns:tal='bar' tal:attr='value'>"
                          "<tal:element tal:attr2='another'/>"
                          "</doc>",
                          {"namespace-declarations": 0})
        docelem = doc.documentElement
        self.failIf(docelem.hasAttribute("xmlns"))
        self.failIf(docelem.hasAttribute("xmlns:tal"))
        self.assert_(docelem.attributes.length == 1)

    # We can't just name this parse(), since the framework overwrites
    # that name on the actual instances.
    #
    def _parse(self, source, flags={}):
        b = self.createBuilder()
        for feature, value in flags.items():
            b.setFeature(feature, value)
        fp = StringIO(source)
        inpsrc = LoadSave.DOMInputSource()
        inpsrc.byteStream = fp
        return b.parseDOMInputSource(inpsrc)


cases = Base.buildCases(__name__, "Load", "3.0")


=== Added File Products/ParsedXML/tests/domapi/TraversalLvl2.py === (543/643 lines abridged)
##############################################################################
# 
# Zope Public License (ZPL) Version 1.0
# -------------------------------------
# 
# Copyright (c) Digital Creations.  All rights reserved.
# 
# This license has been certified as Open Source(tm).
# 
# 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 above copyright
#    notice, this list of conditions, and the following disclaimer.
# 
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions, and the following disclaimer in
#    the documentation and/or other materials provided with the
#    distribution.
# 
# 3. Digital Creations requests that attribution be given to Zope
#    in any manner possible. Zope includes a "Powered by Zope"
#    button that is installed by default. While it is not a license
#    violation to remove this button, it is requested that the
#    attribution remain. A significant investment has been put
#    into Zope, and this effort will continue if the Zope community
#    continues to grow. This is one way to assure that growth.
# 
# 4. All advertising materials and documentation mentioning
#    features derived from or use of this software must display
#    the following acknowledgement:
# 
#      "This product includes software developed by Digital Creations
#      for use in the Z Object Publishing Environment
#      (http://www.zope.org/)."
# 
#    In the event that the product being advertised includes an
#    intact Zope distribution (with copyright and license included)
#    then this clause is waived.
# 
# 5. Names associated with Zope or Digital Creations must not be used to
#    endorse or promote products derived from this software without
#    prior written permission from Digital Creations.
# 
# 6. Modified redistributions of any form whatsoever must retain
#    the following acknowledgment:
# 
#      "This product includes software developed by Digital Creations
#      for use in the Z Object Publishing Environment

[-=- -=- -=- 543 lines omitted -=- -=- -=-]

        walker = self.document.createTreeWalker(self.document,
            NodeFilter.SHOW_TEXT, SkipBFilter(), 0)

        self.iterate(walker, "firstChild", "parentNode",
                     [self.document, self.G])

    def checkWalkerNoFilterNextSiblingPreviousSibling(self):
        walker = self.document.createTreeWalker(self.document,
            NodeFilter.SHOW_ALL, None, 0)
        
        assert walker.previousSibling() is None, (
            "previousSibling on a fresh walker did not return None.")

        # move to B to make more interesting
        walker.firstChild() # doctype
        walker.nextSibling() # A
        walker.firstChild() # B
        self.iterate(walker, "nextSibling", "previousSibling",
                     [self.B, self.C, self.F, self.G])

    def checkWalkerNoFilterLastChild(self):
        walker = self.document.createTreeWalker(self.document,
            NodeFilter.SHOW_ALL, None, 0)

        # move to A to make more interesting
        walker.firstChild() # doctype
        walker.nextSibling() # A
        retNode = walker.lastChild()
        assert isSameNode(retNode, walker.currentNode)
        assert isSameNode(self.G, walker.currentNode)

    def checkWalkerPreviousNode(self):
        walker = self.document.createTreeWalker(self.document,
            NodeFilter.SHOW_ALL, None, 0)
        
        assert walker.previousNode() is None, (
            "previousNode on a fresh walker did not return None.")

    def checkCurrentNodeNoneNotSupported(self):
        walker = self.document.createTreeWalker(self.document,
            NodeFilter.SHOW_ALL, None, 0)

        try:
            walker.currentNode = None
        except xml.dom.NotSupportedErr:
            pass
        else:
            assert 0, "Was allowed to set currentNode to None."

cases = buildCases(__name__, 'Traversal', '2.0')


=== Added File Products/ParsedXML/tests/domapi/XMLLvl1.py ===
##############################################################################
# 
# Zope Public License (ZPL) Version 1.0
# -------------------------------------
# 
# Copyright (c) Digital Creations.  All rights reserved.
# 
# This license has been certified as Open Source(tm).
# 
# 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 above copyright
#    notice, this list of conditions, and the following disclaimer.
# 
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions, and the following disclaimer in
#    the documentation and/or other materials provided with the
#    distribution.
# 
# 3. Digital Creations requests that attribution be given to Zope
#    in any manner possible. Zope includes a "Powered by Zope"
#    button that is installed by default. While it is not a license
#    violation to remove this button, it is requested that the
#    attribution remain. A significant investment has been put
#    into Zope, and this effort will continue if the Zope community
#    continues to grow. This is one way to assure that growth.
# 
# 4. All advertising materials and documentation mentioning
#    features derived from or use of this software must display
#    the following acknowledgement:
# 
#      "This product includes software developed by Digital Creations
#      for use in the Z Object Publishing Environment
#      (http://www.zope.org/)."
# 
#    In the event that the product being advertised includes an
#    intact Zope distribution (with copyright and license included)
#    then this clause is waived.
# 
# 5. Names associated with Zope or Digital Creations must not be used to
#    endorse or promote products derived from this software without
#    prior written permission from Digital Creations.
# 
# 6. Modified redistributions of any form whatsoever must retain
#    the following acknowledgment:
# 
#      "This product includes software developed by Digital Creations
#      for use in the Z Object Publishing Environment
#      (http://www.zope.org/)."
# 
#    Intact (re-)distributions of any official Zope release do not
#    require an external acknowledgement.
# 
# 7. Modifications are encouraged but must be packaged separately as
#    patches to official Zope releases.  Distributions that do not
#    clearly separate the patches from the original work must be clearly
#    labeled as unofficial distributions.  Modifications which do not
#    carry the name Zope may be packaged in any form, as long as they
#    conform to all of the clauses above.
# 
# 
# Disclaimer
# 
#   THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``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 DIGITAL CREATIONS OR ITS
#   CONTRIBUTORS 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.
# 
# 
# This software consists of contributions made by Digital Creations and
# many individuals on behalf of Digital Creations.  Specific
# attributions are listed in the accompanying credits file.
# 
##############################################################################

from Base import *
from CoreLvl1 import NodeReadTestCaseBase, NodeWriteTestCaseBase
from CoreLvl1 import TextReadTestCase, TextWriteTestCase
TextReadTestCaseBase = TextReadTestCase
TextWriteTestCaseBase = TextWriteTestCase
del TextReadTestCase
del TextWriteTestCase

import xml.dom
from xml.dom import Node

# --- DocumentType

class DocumentTypeReadTestCase(NodeReadTestCaseBase):

    def setUp(self):
        self.doctype = self.node = self.implementation.createDocumentType(
            'foo', None, None)
        self.expectedType = Node.DOCUMENT_TYPE_NODE

        doc = self.parse("""
            <!DOCTYPE doc [
                <!ENTITY internalParsedE "Entity text">

                <!NOTATION aNotation PUBLIC "uri:public">
                <!ENTITY publicUnparsedE PUBLIC "uri:public" "uri:system"
                    NDATA aNotation>
                <!ENTITY systemUnparsedE SYSTEM "uri:system" NDATA aNotation>
            ]>
            <doc/>""")

        self.doctypeInternalSubset = doc.doctype

    def checkName(self):
        checkAttribute(self.doctype, 'name', 'foo')
        checkReadOnly(self.doctype, 'name')

    def checkEmptyEntities(self):
        assert self.doctype.entities.length == 0

    def checkEntitiesInternalSubset(self):
        checkLength(self.doctypeInternalSubset.entities, 3)

        entity = self.doctypeInternalSubset.entities.getNamedItem(
            'internalParsedE')

    def checkEntitiesRemoveReadOnly(self):
        try:
            self.doctypeInternalSubset.entities.removeNamedItem(
                'internalParsedE')
        except xml.dom.NoModificationAllowedErr:
            pass
        else:
            assert 0, 'Was allowed to remove entity.'

    def checkEntitiesSetReadOnly(self):
        entity = self.doctypeInternalSubset.entities.item(0)
        try:
            self.doctypeInternalSubset.entities.setNamedItem(entity)
        except xml.dom.NoModificationAllowedErr:
            pass
        else:
            assert 0, 'Was allowed to set entity.'

    def checkEmptyNotations(self):
        assert self.doctype.notations.length == 0

    def checkNotationsInternalSubset(self):
        checkLength(self.doctypeInternalSubset.notations, 1)

        notation = self.doctypeInternalSubset.notations.getNamedItem(
            'aNotation')

    def checkNotationsRemoveReadOnly(self):
        try:
            self.doctypeInternalSubset.notations.removeNamedItem(
                'aNotation')
        except xml.dom.NoModificationAllowedErr:
            pass
        else:
            assert 0, 'Was allowed to remove notation.'

    def checkNotationsSetReadOnly(self):
        notation = self.doctypeInternalSubset.notations.item(0)
        try:
            self.doctypeInternalSubset.notations.setNamedItem(notation)
        except xml.dom.NoModificationAllowedErr:
            pass
        else:
            assert 0, 'Was allowed to set notation.'

    def checkCloneNode(self):
        # TODO: Implementation dependent, what should we test?
        pass


class DocumentTypeWriteTestCase(NodeWriteTestCaseBase):

    def setUp(self):
        self.createDocument() # Needed for Node tests
        self.doctype = self.node = self.implementation.createDocumentType(
            'foo', None, None)


# --- ProcessingInstruction

class ProcessingInstructionReadTestCase(NodeReadTestCaseBase):

    def setUp(self):
        self.pi = self.createDocument().createProcessingInstruction("pit",
                                                                    "pid")
        self.node = self.pi
        self.expectedType = Node.PROCESSING_INSTRUCTION_NODE

    def checkGetTarget(self):
        checkAttribute(self.pi, "target", "pit")

    def checkGetData(self):
        checkAttribute(self.pi, "data", "pid")

    def checkCloneNode(self):
        clone = self.pi.cloneNode(0)
        deepClone = self.pi.cloneNode(1)

        assert not isSameNode(self.pi, clone), "Clone is same as original."
        assert not isSameNode(self.pi, deepClone), "Clone is same as original."
        
        checkAttribute(clone, 'parentNode', None)
        checkAttribute(deepClone, 'parentNode', None)
        checkAttribute(clone, 'nodeType', self.pi.nodeType)
        checkAttribute(deepClone, 'nodeType', self.pi.nodeType)
        checkAttribute(clone, 'data', self.pi.data)
        checkAttribute(deepClone, 'data', self.pi.data)
        checkAttribute(clone, 'target', self.pi.target)
        checkAttribute(deepClone, 'target', self.pi.target)
        checkLength(clone.childNodes, 0)
        checkLength(deepClone.childNodes, 0)


class ProcessingInstructionWriteTestCase(NodeWriteTestCaseBase):

    def setUp(self):
        self.pi = self.createDocument().createProcessingInstruction("pit",
                                                                    "pid")
        self.node = self.pi

    def checkSetData(self):
        self.pi._set_data("uggg")
        checkAttribute(self.pi, "data", "uggg")
        

# --- CDATASection

class CDATASectionReadTestCase(TextReadTestCaseBase):

    def setUp(self):
        self.chardata = self.node = self.createDocument().createCDATASection(
            "com")
        self.expectedType = Node.CDATA_SECTION_NODE


class CDATASectionWriteTestCase(TextWriteTestCaseBase):

    def setUp(self):
        self.chardata = self.node = self.createDocument().createCDATASection(
            "com")


# --- EntityReference

class EntityReferenceReadTestCase(NodeReadTestCaseBase):

    def setUp(self):
        self.entref = self.node = self.createDocument().createEntityReference(
            "eref")
        self.expectedType = Node.ENTITY_REFERENCE_NODE
        self.expectedNodeName = 'eref'

    def checkCloneNode(self):
        pass # TODO: Fill in meaningful test here.


class EntityReferenceWriteTestCase(NodeWriteTestCaseBase):

    def setUp(self):
        self.entref = self.node = self.createDocument().createEntityReference(
            "eref")

    # TODO: An ENTITY_REFERENCE_NODE Node will have childNodes when the
    # entity it refers to has childNodes. We need entities first before we write
    # tests for that.


# --- Entity

class EntityReadTestCase(NodeReadTestCaseBase):

    def setUp(self):
        doc = self.document = self.parse("""
            <!DOCTYPE doc [
                <!ENTITY internalParsedE "Entity text">

                <!NOTATION aNotation PUBLIC "uri:public">
                <!ENTITY publicUnparsedE PUBLIC "uri:public" "uri:system"
                    NDATA aNotation>
                <!ENTITY systemUnparsedE SYSTEM "uri:system" NDATA aNotation>
            ]>
            <doc/>
        """)

        self.node = self.internalParsed = doc.doctype.entities.getNamedItem(
            'internalParsedE')
        self.publicUnparsed = doc.doctype.entities.getNamedItem(
            'publicUnparsedE')
        self.systemUnparsed = doc.doctype.entities.getNamedItem(
            'systemUnparsedE')

        self.expectedNodeName = 'internalParsedE'
        self.expectedType = Node.ENTITY_NODE

    def checkPublicIdReadOnly(self):
        checkReadOnly(self.node, 'publicId')

    def checkPublicIdInternalParsed(self):
        checkAttribute(self.internalParsed, 'publicId', None)
    
    def checkPublicIdPublicUnparsed(self):
        checkAttribute(self.publicUnparsed, 'publicId', 'uri:public')
    
    def checkPublicIdSystemUnparsed(self):
        checkAttribute(self.systemUnparsed, 'publicId', None)
    
    def checkSystemIdReadOnly(self):
        checkReadOnly(self.node, 'systemId')
    
    def checkSystemIdInternalParsed(self):
        checkAttribute(self.internalParsed, 'systemId', None)
    
    def checkSystemIdPublicUnparsed(self):
        checkAttribute(self.publicUnparsed, 'systemId', 'uri:system')
    
    def checkSystemIdSystemUnparsed(self):
        checkAttribute(self.systemUnparsed, 'systemId', 'uri:system')
    
    def checkNotationNameReadOnly(self):
        checkReadOnly(self.node, 'notationName')

    def checkNotationNameInternalParsed(self):
        checkAttribute(self.internalParsed, 'notationName', None)

    def checkNotationNamePublicUnparsed(self):
        checkAttribute(self.publicUnparsed, 'notationName', 'aNotation')

    def checkNotationNameSystemUnparsed(self):
        checkAttribute(self.systemUnparsed, 'notationName', 'aNotation')

    def checkSubTreeInternalParsed(self):
        entity = self.internalParsed

        assert entity.hasChildNodes(), (
            'Internal Parsed Entity has no subtree representing the value.')
        checkAttribute(entity.firstChild, 'nodeType', Node.TEXT_NODE)
        checkAttribute(entity.firstChild, 'data', 'Entity text')
        checkReadOnly(entity.firstChild, 'data')
    
    def checkSubTreePublicUnparsed(self):
        assert not self.publicUnparsed.hasChildNodes(), (
            'An unparsed entity should not have a sub-tree.')
    
    def checkSubTreeSystemUnparsed(self):
        assert not self.systemUnparsed.hasChildNodes(), (
            'An unparsed entity should not have a sub-tree.')

class EntityWriteTestCase(NodeWriteTestCaseBase):

    def setUp(self):
        doc = self.document = self.parse("""
            <!DOCTYPE doc [
                <!ENTITY internalParsedE "Entity text">
            ]>
            <doc/>
        """)

        self.node = doc.doctype.entities.getNamedItem('internalParsedE')


# --- Notation

class NotationReadTestCase(NodeReadTestCaseBase):

    def setUp(self):
        doc = self.document = self.parse("""
            <!DOCTYPE doc [
                <!NOTATION publicExternalN PUBLIC "uri:public" "uri:system">
                <!NOTATION systemExternalN SYSTEM "uri:system">
                <!NOTATION publicN PUBLIC "uri:public">
            ]>
            <doc/>
        """)

        self.node = self.publicExternal = doc.doctype.notations.getNamedItem(
            'publicExternalN')
        self.systemExternal = doc.doctype.notations.getNamedItem(
            'systemExternalN')
        self.public = doc.doctype.notations.getNamedItem('publicN')

        self.expectedNodeName = 'publicExternalN'
        self.expectedType = Node.NOTATION_NODE

    def checkPublicIdReadOnly(self):
        checkReadOnly(self.node, 'publicId')
    
    def checkPublicIdPublicExternal(self):
        checkAttribute(self.publicExternal, 'publicId', 'uri:public')

    def checkPublicIdSystemExternal(self):
        checkAttribute(self.systemExternal, 'publicId', None)

    def checkPublicIdPublic(self):
        checkAttribute(self.public, 'publicId', 'uri:public')

    def checkSystemIdReadOnly(self):
        checkReadOnly(self.node, 'systemId')
    
    def checkSystemIdPublicExternal(self):
        checkAttribute(self.publicExternal, 'systemId', 'uri:system')

    def checkSystemIdSystemExternal(self):
        checkAttribute(self.systemExternal, 'systemId', 'uri:system')

    def checkSystemIdPublic(self):
        checkAttribute(self.public, 'systemId', None)

        
class NotationWriteTestCase(NodeWriteTestCaseBase):

    def setUp(self):
        doc = self.document = self.parse("""
            <!DOCTYPE doc [
                <!NOTATION aNotation PUBLIC "uri:public">
            ]>
            <doc/>
        """)

        self.node = doc.doctype.notations.getNamedItem('aNotation')


cases = buildCases(__name__, 'XML', '1.0')


=== Added File Products/ParsedXML/tests/domapi/XMLLvl2.py ===
##############################################################################
# 
# Zope Public License (ZPL) Version 1.0
# -------------------------------------
# 
# Copyright (c) Digital Creations.  All rights reserved.
# 
# This license has been certified as Open Source(tm).
# 
# 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 above copyright
#    notice, this list of conditions, and the following disclaimer.
# 
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions, and the following disclaimer in
#    the documentation and/or other materials provided with the
#    distribution.
# 
# 3. Digital Creations requests that attribution be given to Zope
#    in any manner possible. Zope includes a "Powered by Zope"
#    button that is installed by default. While it is not a license
#    violation to remove this button, it is requested that the
#    attribution remain. A significant investment has been put
#    into Zope, and this effort will continue if the Zope community
#    continues to grow. This is one way to assure that growth.
# 
# 4. All advertising materials and documentation mentioning
#    features derived from or use of this software must display
#    the following acknowledgement:
# 
#      "This product includes software developed by Digital Creations
#      for use in the Z Object Publishing Environment
#      (http://www.zope.org/)."
# 
#    In the event that the product being advertised includes an
#    intact Zope distribution (with copyright and license included)
#    then this clause is waived.
# 
# 5. Names associated with Zope or Digital Creations must not be used to
#    endorse or promote products derived from this software without
#    prior written permission from Digital Creations.
# 
# 6. Modified redistributions of any form whatsoever must retain
#    the following acknowledgment:
# 
#      "This product includes software developed by Digital Creations
#      for use in the Z Object Publishing Environment
#      (http://www.zope.org/)."
# 
#    Intact (re-)distributions of any official Zope release do not
#    require an external acknowledgement.
# 
# 7. Modifications are encouraged but must be packaged separately as
#    patches to official Zope releases.  Distributions that do not
#    clearly separate the patches from the original work must be clearly
#    labeled as unofficial distributions.  Modifications which do not
#    carry the name Zope may be packaged in any form, as long as they
#    conform to all of the clauses above.
# 
# 
# Disclaimer
# 
#   THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``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 DIGITAL CREATIONS OR ITS
#   CONTRIBUTORS 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.
# 
# 
# This software consists of contributions made by Digital Creations and
# many individuals on behalf of Digital Creations.  Specific
# attributions are listed in the accompanying credits file.
# 
##############################################################################

from Base import *
import CoreLvl2
TextReadTestCaseBase = CoreLvl2.TextReadTestCase
TextWriteTestCaseBase = CoreLvl2.TextWriteTestCase
NodeReadTestCaseBase = CoreLvl2.NodeReadTestCaseBase
NodeWriteTestCaseBase = CoreLvl2.NodeWriteTestCaseBase
del CoreLvl2

import xml.dom
from xml.dom import Node

# --- DocumentType

class DocumentTypeReadTestCase(NodeReadTestCaseBase):

    def setUp(self):
        self.doctype = self.node = self.implementation.createDocumentType(
            'foo:bar', 'uri:foo', 'uri:bar')

    def checkInternalSubset(self):
        # The DOM Level 2 recommendation is not clear on the value of the
        # internalSubset attribute when there isn't one; this test relies
        # on a clarification from Joe Kesselman:
        #
        # http://lists.w3.org/Archives/Public/www-dom/2001AprJun/0009.html
        #
        checkAttribute(self.doctype, 'internalSubset', None)
        checkReadOnly(self.doctype, 'internalSubset')

    def checkPublicId(self):
        checkAttribute(self.doctype, 'publicId', 'uri:foo')
        checkReadOnly(self.doctype, 'publicId')

    def checkSystemId(self):
        checkAttribute(self.doctype, 'systemId', 'uri:bar')
        checkReadOnly(self.doctype, 'systemId')

    def checkImportNode(self):
        foreignDoc = self.implementation.createDocument(None, 'foo', None)
        try:
            foreignDoc.importNode(self.doctype, 0)
        except xml.dom.NotSupportedErr:
            pass
        else:
            assert 0, "Was allowed to import a Document Type Node."


class DocumentTypeWriteTestCase(NodeWriteTestCaseBase):

    def setUp(self):
        self.doctype = self.node = self.implementation.createDocumentType(
            'foo:bar', 'uri:foo', 'uri:bar')


# --- ProcessingInstruction

class ProcessingInstructionReadTestCase(NodeReadTestCaseBase):

    def setUp(self):
        self.pi = self.createDocument().createProcessingInstruction("pit",
                                                                    "pid")
        self.node = self.pi

    def checkImportNode(self):
        foreignDoc = self.implementation.createDocument(None, 'foo', None)

        clone = foreignDoc.importNode(self.pi, 0)
        deepClone = foreignDoc.importNode(self.pi, 1)

        assert not isSameNode(self.pi, clone), "Clone is same as original."
        assert not isSameNode(self.pi, deepClone), "Clone is same as original."
        
        checkAttributeSameNode(clone, 'ownerDocument', foreignDoc)
        checkAttributeSameNode(deepClone, 'ownerDocument', foreignDoc)
        checkAttribute(clone, 'parentNode', None)
        checkAttribute(deepClone, 'parentNode', None)
        checkAttribute(clone, 'nodeType', self.pi.nodeType)
        checkAttribute(deepClone, 'nodeType', self.pi.nodeType)
        checkAttribute(clone, 'data', self.pi.data)
        checkAttribute(deepClone, 'data', self.pi.data)
        checkAttribute(clone, 'target', self.pi.target)
        checkAttribute(deepClone, 'target', self.pi.target)
        checkLength(clone.childNodes, 0)
        checkLength(deepClone.childNodes, 0)


class ProcessingInstructionWriteTestCase(NodeWriteTestCaseBase):

    def setUp(self):
        self.pi = self.createDocument().createProcessingInstruction("pit",
                                                                    "pid")
        self.node = self.pi


# --- CDATASection

class CDATASectionReadTestCase(TextReadTestCaseBase):

    def setUp(self):
        self.chardata = self.node = self.createDocument().createCDATASection(
            "com")


class CDATASectionWriteTestCase(TextWriteTestCaseBase):

    def setUp(self):
        self.chardata = self.node = self.createDocument().createCDATASection(
            "com")


# --- EntityReference

class EntityReferenceReadTestCase(NodeReadTestCaseBase):

    def setUp(self):
        self.entref = self.node = self.createDocument().createEntityReference(
            "eref")

    def checkImportNode(self):
        pass # TODO: Fill in meaningful test here.


class EntityReferenceWriteTestCase(NodeWriteTestCaseBase):

    def setUp(self):
        self.entref = self.node = self.createDocument().createEntityReference(
            "eref")


# --- Entity

class EntityReadTestCase(NodeReadTestCaseBase):

    def setUp(self):
        doc = self.document = self.parse("""
            <!DOCTYPE doc [
                <!ENTITY internalParsedE "Entity text">
            ]>
            <doc/>
        """)

        self.node = doc.doctype.entities.getNamedItem('internalParsedE')


class EntityWriteTestCase(NodeWriteTestCaseBase):

    def setUp(self):
        doc = self.document = self.parse("""
            <!DOCTYPE doc [
                <!ENTITY internalParsedE "Entity text">
            ]>
            <doc/>
        """)

        self.node = doc.doctype.entities.getNamedItem('internalParsedE')


# --- Notation

class NotationReadTestCase(NodeReadTestCaseBase):

    def setUp(self):
        doc = self.document = self.parse("""
            <!DOCTYPE doc [
                <!NOTATION aNotation PUBLIC "uri:public">
            ]>
            <doc/>
        """)

        self.node = doc.doctype.notations.getNamedItem('aNotation')


class NotationWriteTestCase(NodeWriteTestCaseBase):

    def setUp(self):
        doc = self.document = self.parse("""
            <!DOCTYPE doc [
                <!NOTATION aNotation PUBLIC "uri:public">
            ]>
            <doc/>
        """)

        self.node = doc.doctype.notations.getNamedItem('aNotation')


cases = buildCases(__name__, 'XML', '2.0')


=== Added File Products/ParsedXML/tests/domapi/__init__.py ===
##############################################################################
# 
# Zope Public License (ZPL) Version 1.0
# -------------------------------------
# 
# Copyright (c) Digital Creations.  All rights reserved.
# 
# This license has been certified as Open Source(tm).
# 
# 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 above copyright
#    notice, this list of conditions, and the following disclaimer.
# 
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions, and the following disclaimer in
#    the documentation and/or other materials provided with the
#    distribution.
# 
# 3. Digital Creations requests that attribution be given to Zope
#    in any manner possible. Zope includes a "Powered by Zope"
#    button that is installed by default. While it is not a license
#    violation to remove this button, it is requested that the
#    attribution remain. A significant investment has been put
#    into Zope, and this effort will continue if the Zope community
#    continues to grow. This is one way to assure that growth.
# 
# 4. All advertising materials and documentation mentioning
#    features derived from or use of this software must display
#    the following acknowledgement:
# 
#      "This product includes software developed by Digital Creations
#      for use in the Z Object Publishing Environment
#      (http://www.zope.org/)."
# 
#    In the event that the product being advertised includes an
#    intact Zope distribution (with copyright and license included)
#    then this clause is waived.
# 
# 5. Names associated with Zope or Digital Creations must not be used to
#    endorse or promote products derived from this software without
#    prior written permission from Digital Creations.
# 
# 6. Modified redistributions of any form whatsoever must retain
#    the following acknowledgment:
# 
#      "This product includes software developed by Digital Creations
#      for use in the Z Object Publishing Environment
#      (http://www.zope.org/)."
# 
#    Intact (re-)distributions of any official Zope release do not
#    require an external acknowledgement.
# 
# 7. Modifications are encouraged but must be packaged separately as
#    patches to official Zope releases.  Distributions that do not
#    clearly separate the patches from the original work must be clearly
#    labeled as unofficial distributions.  Modifications which do not
#    carry the name Zope may be packaged in any form, as long as they
#    conform to all of the clauses above.
# 
# 
# Disclaimer
# 
#   THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``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 DIGITAL CREATIONS OR ITS
#   CONTRIBUTORS 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.
# 
# 
# This software consists of contributions made by Digital Creations and
# many individuals on behalf of Digital Creations.  Specific
# attributions are listed in the accompanying credits file.
# 
##############################################################################

"""A suite of unit tests for the Python DOM API.

This suite will test a DOM API for compliance with the DOM API, level 2. It
assumes that the DOM tested supports at least both the Core and XML features. It
requires PyUnit; see http://pyunit.sourceforge.net/.

Example for the python minidom (which is an incomplete implementation):

from xml.dom.minidom import DOMImplementation, parseString
from domapi import DOMImplementationTestSuite

def MiniDomParseString(self, xml):
    return parseString(xml)

def test_suite():
    '''Return a test suite for the Zope testing framework.'''
    return DOMImplementationTestSuite(DOMImplementation(), MiniDomParseString)

if __name__ == '__main__':
    import unittest
    unittest.TextTestRunner().run(test_suite())

"""

import unittest
import CoreLvl1, CoreLvl2, CoreLvl3, XMLLvl1, XMLLvl2, TraversalLvl2, Load3

cases = (
    CoreLvl1.cases +
    CoreLvl2.cases +
    CoreLvl3.cases +
    XMLLvl1.cases +
    XMLLvl2.cases +
    TraversalLvl2.cases +
    Load3.cases
)

def DOMImplementationTestSuite(implementation, parseMethod, verbose=0):
    """ Create a testsuite for DOM lvl 2 compliance, given a DOM Implementation.

    To test a DOM implementation, hand in a DOMImplementation object, and a
    method that will take a string holding an XML document and returns a
    Document Node created from the XML.

    Then run the returned unittest testsuite.

    Note that the signature of the parse method is (self, xmlString) and should
    parse the xml string with namespaces turned on. It will be used to create
    Nodes which normally cannot be created using the DOM API, like Notations and
    Entities.

    """

    # First test for minimal feature support
    assert (implementation.hasFeature('Core', '2.0') and
        implementation.hasFeature('XML', '2.0')), (
        "This DOMImplementation doesn't feature the level 2 Core and XML API.")

    suite = unittest.TestSuite()
    # The minimal set of features that should return 1 on hasFeature. 
    # ('Core', '1.0') was never defined for DOM level 1, it was implicit. Most
    # DOM level 2 implementations return true, but this is a courtesy.
    supportedFeatures = {
        ('Core', None): 1,
        ('Core', '2.0'): 1,
        ('XML', None): 1,
        ('XML', '1.0'): 1,
        ('XML', '2.0'): 1,
    }

    for case, feature, version in cases:
        if implementation.hasFeature(feature, version):
            case.implementation = implementation
            case.parse = parseMethod
            suite.addTest(unittest.makeSuite(case, 'check'))

            supportedFeatures[(feature, version)] = 1
            supportedFeatures[(feature, None)] = 1
        else:
            if verbose:
                 print ("Test %s skipped: DOM feature not supported.\n" %
                    case.__name__)

    # Record supported features.
    CoreLvl1.DOMImplementationReadTestCase.supportedFeatures = (
        supportedFeatures.keys())
    CoreLvl2.NodeReadTestCaseBase.supportedFeatures = (
        supportedFeatures.keys())

    return suite





More information about the zopeorg-checkins mailing list