[Zope3-checkins] CVS: zopeproducts/xmldom/tests/domapi - __init__.py:1.1 base.py:1.1 corelvl1.py:1.1 corelvl2.py:1.1 corelvl3.py:1.1 load3.py:1.1 suite.py:1.1 traversallvl2.py:1.1 xmllvl1.py:1.1 xmllvl2.py:1.1

Martijn Faassen m.faassen@vet.uu.nl
Sat, 7 Jun 2003 06:13:53 -0400


Update of /cvs-repository/zopeproducts/xmldom/tests/domapi
In directory cvs.zope.org:/tmp/cvs-serv1893/tests/domapi

Added Files:
	__init__.py base.py corelvl1.py corelvl2.py corelvl3.py 
	load3.py suite.py traversallvl2.py xmllvl1.py xmllvl2.py 
Log Message:
Added beginning of Zope 3 port of ParsedXML's DOM component. See README.txt 
for more details.


=== Added File zopeproducts/xmldom/tests/domapi/__init__.py ===
# this is a package 


=== Added File zopeproducts/xmldom/tests/domapi/base.py ===
##############################################################################
#
# Copyright (c) 2001-2003 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################

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 zopeproducts/xmldom/tests/domapi/corelvl1.py === (2261/2361 lines abridged)
##############################################################################
#
# Copyright (c) 2001-2003 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################

from base import *

import string
import xml.dom
from xml.dom import Node


# --- DOMImplementation

class DOMImplementationReadTestCase(TestCaseBase):

    def setUp(self):
        # self.implementation is already set.
        pass

    # Combinations to feed to the hasFeature method; some of these will always
    # return false, of course.
    # ('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.
    featureMatrix = (
        ('Core', None),
        #('Core', '1.0'),
        ('Core', '2.0'),
        ('Core', '3.0'),
        
        ('XML', None),
        ('XML', '1.0'),
        ('XML', '2.0'),
        ('XML', '3.0'),

        ('Traversal', None),
        ('Traversal', '1.0'),
        ('Traversal', '2.0'),
        ('Traversal', '3.0'),

        ('BogusFeature', None),

[-=- -=- -=- 2261 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 zopeproducts/xmldom/tests/domapi/corelvl2.py === (1554/1654 lines abridged)
##############################################################################
#
# Copyright (c) 2001-2003 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################

from base import *
import corelvl1
_DOMImplCase = corelvl1.DOMImplementationReadTestCase
_NodeTestCaseBase = corelvl1.NodeWriteTestCaseBase

import sys
import string
import xml.dom
from xml.dom import Node

# --- DOMIMplementation

class DOMImplementationReadTestCase(TestCaseBase):

    TEST_NAMESPACE = TEST_NAMESPACE
    TEST_PREFIX = 'aprefix'
    TEST_LOCAL_NAME = 'somelocalname'
    TEST_QUALIFIED_NAME = '%s:%s' % (TEST_PREFIX, TEST_LOCAL_NAME)

    def setUp(self):
        # self.implementation is already set.
        pass

    def checkCreateDocument(self):
        # Non namespace Document
        newDoc = self.implementation.createDocument(None, self.TEST_LOCAL_NAME,
            None)

        checkAttribute(newDoc, 'nodeType', Node.DOCUMENT_NODE)
        checkAttribute(newDoc, 'doctype', None)
        checkAttributeNot(newDoc, 'documentElement', None)
        assert newDoc.implementation is self.implementation, (
            'Created Document has different implementation.')
        checkAttribute(newDoc.documentElement, 'namespaceURI', None)
        checkAttribute(newDoc.documentElement, 'tagName', self.TEST_LOCAL_NAME)


[-=- -=- -=- 1554 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 zopeproducts/xmldom/tests/domapi/corelvl3.py ===
##############################################################################
#
# Copyright (c) 2001-2003 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""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 zopeproducts/xmldom/tests/domapi/load3.py ===
##############################################################################
#
# Copyright (c) 2001-2003 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""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 zopeproducts.xmldom import loadsave
from StringIO 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 zopeproducts/xmldom/tests/domapi/suite.py ===
##############################################################################
#
# Copyright (c) 2001-2003 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""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


=== Added File zopeproducts/xmldom/tests/domapi/traversallvl2.py === (471/571 lines abridged)
##############################################################################
#
# Copyright (c) 2001-2003 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
from base import *

import xml.dom
from xml.dom import Node

# --- NodeFilter interface. Should this be in xml.dom.__init__?

class NodeFilter:
    # Constants returned by acceptNode
    FILTER_ACCEPT                  = 1
    FILTER_REJECT                  = 2
    FILTER_SKIP                    = 3

    # Constants for whatToShow
    SHOW_ALL                       = 0xFFFFFFFF
    SHOW_ELEMENT                   = 0x00000001
    SHOW_ATTRIBUTE                 = 0x00000002
    SHOW_TEXT                      = 0x00000004
    SHOW_CDATA_SECTION             = 0x00000008
    SHOW_ENTITY_REFERENCE          = 0x00000010
    SHOW_ENTITY                    = 0x00000020
    SHOW_PROCESSING_INSTRUCTION    = 0x00000040
    SHOW_COMMENT                   = 0x00000080
    SHOW_DOCUMENT                  = 0x00000100
    SHOW_DOCUMENT_TYPE             = 0x00000200
    SHOW_DOCUMENT_FRAGMENT         = 0x00000400
    SHOW_NOTATION                  = 0x00000800

    def acceptNode(self, node):
        # By default, accept
        return self.FILTER_ACCEPT


# --- DocumentTraversal

class DocumentTraversalReadTestCase(TestCaseBase):


[-=- -=- -=- 471 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 zopeproducts/xmldom/tests/domapi/xmllvl1.py ===
##############################################################################
#
# Copyright (c) 2001-2003 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################

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 zopeproducts/xmldom/tests/domapi/xmllvl2.py ===
##############################################################################
#
# Copyright (c) 2001-2003 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################

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')