[Zope3-checkins] CVS: zopeproducts/xml/dom/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

Philipp von Weitershausen philikon@philikon.de
Fri, 20 Jun 2003 11:11:40 -0400


Update of /cvs-repository/zopeproducts/xml/dom/tests/domapi
In directory cvs.zope.org:/tmp/cvs-serv15767/xml/dom/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:
Moved the xml_examples, xslt, xslt_examples and xmldom products to one
xml product.


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


=== Added File zopeproducts/xml/dom/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/xml/dom/tests/domapi/corelvl1.py === (1961/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),
        ('BogusFeature', '1.0'),
        ('BogusFeature', '2.0'),
        ('BogusFeature', '3.0'),
    )

    def checkHasFeature(self):
        impl = self.implementation
        for feature, level in self.featureMatrix:
            result1 = impl.hasFeature(feature, level)
            result2 = impl.hasFeature(string.upper(feature), level)
            result3 = impl.hasFeature(string.lower(feature), level)

            expect = ((feature, level) in self.supportedFeatures)

            assert result1 == result2 and result1 == result3, (
                "Different results from different case feature string.")

            assert (result1 and 1 or 0) == expect, (
                "Test for %s, version %s should have returned %s, "
                "returned %s" % (repr(feature), repr(level), repr(expect),
                    repr(result1)))


# --- Node

class NodeReadTestCaseBase(TestCaseBase):

    nodeTypes = (
        'ATTRIBUTE_NODE',
        'CDATA_SECTION_NODE',
        'COMMENT_NODE',
        'DOCUMENT_FRAGMENT_NODE',
        'DOCUMENT_NODE',
        'DOCUMENT_TYPE_NODE',
        'ELEMENT_NODE',
        'ENTITY_NODE',
        'ENTITY_REFERENCE_NODE',
        'NOTATION_NODE',
        'PROCESSING_INSTRUCTION_NODE',
        'TEXT_NODE',
    )

    def checkNodeTypeConstants(self):
        for type in self.nodeTypes:
            checkAttribute(self.node, type, getattr(Node, type))
    
    def checkAttributes(self):
        if self.node.nodeType == Node.ELEMENT_NODE:
            checkLength(self.node.attributes, 0)
        else:
            checkAttribute(self.node, 'attributes', None)

        checkReadOnly(self.node, 'attributes')

    def checkChildNodes(self):
        if self.node.nodeType in (Node.ATTRIBUTE_NODE,
                Node.DOCUMENT_NODE,
                Node.ENTITY_NODE):
            expectedLength = 1

        else:
            expectedLength = 0

        checkLength(self.node.childNodes, expectedLength)
        checkReadOnly(self.node, 'childNodes')

    def checkFirstChild(self):
        # The following node types are expected to have one childNode.
        if self.node.nodeType not in (Node.ATTRIBUTE_NODE,
                Node.DOCUMENT_NODE,
                Node.ENTITY_NODE):
            expected = None

        else:
            expected = self.node.childNodes[0]

        checkAttributeSameNode(self.node, 'firstChild', expected)
        checkReadOnly(self.node, 'firstChild')
        if expected:
            checkAttributeSameNode(self.node.firstChild, 'parentNode', 
                self.node)

    def checkLastChild(self):
        # The following node types are expected to have one childNode.
        if self.node.nodeType not in (Node.ATTRIBUTE_NODE,
                Node.DOCUMENT_NODE,
                Node.ENTITY_NODE):
            expected = None

        else:
            expected = self.node.childNodes[0]

        checkAttributeSameNode(self.node, 'lastChild', expected)
        checkReadOnly(self.node, 'lastChild')
        if expected:
            checkAttributeSameNode(self.node.lastChild, 'parentNode', 
                self.node)

    def checkNextSibling(self):
        checkAttribute(self.node, 'nextSibling', None)
        checkReadOnly(self.node, 'nextSibling')

    nodeNameMap = {
        Node.CDATA_SECTION_NODE:     '#cdata-section',
        Node.COMMENT_NODE:           '#comment',
        Node.DOCUMENT_NODE:          '#document',
        Node.DOCUMENT_FRAGMENT_NODE: '#document-fragment',
        Node.TEXT_NODE:              '#text',
    }
            
    def checkNodeName(self):
        if self.node.nodeType in (Node.ATTRIBUTE_NODE,
                Node.DOCUMENT_TYPE_NODE):
            expected = self.node.name

        elif self.node.nodeType == Node.ELEMENT_NODE:
            expected = self.node.tagName

        elif self.node.nodeType in (Node.ENTITY_NODE,
                Node.ENTITY_REFERENCE_NODE,
                Node.NOTATION_NODE):
            expected = self.expectedNodeName

        elif self.node.nodeType == Node.PROCESSING_INSTRUCTION_NODE:
            expected = self.node.target

        else:
            expected = self.nodeNameMap[self.node.nodeType]

        checkAttribute(self.node, 'nodeName', expected)
        checkReadOnly(self.node, "nodeName")
 
    def checkNodeType(self):
        checkAttribute(self.node, 'nodeType', self.expectedType)
        checkReadOnly(self.node, "nodeType")

    emptyNodeValueList = (
        Node.DOCUMENT_FRAGMENT_NODE,
        Node.DOCUMENT_NODE,
        Node.DOCUMENT_TYPE_NODE,
        Node.ELEMENT_NODE,
        Node.ENTITY_NODE,
        Node.ENTITY_REFERENCE_NODE,
        Node.NOTATION_NODE,
    )

    def checkNodeValue(self):
        if self.node.nodeType in self.emptyNodeValueList:
            expected = None


[-=- -=- -=- 1961 lines omitted -=- -=- -=-]


    def setUp(self):
        self.createDocument()
        self.list = self.document.childNodes

    def checkGetLength(self):
        checkLength(self.list, 1)
        self.document.appendChild(self.document.createComment('foo'))
        # A NodeList is 'live', changes to source Node should be reflected
        checkLength(self.list, 2)

    def checkItem(self):
        newNode = self.document.createComment('foo')
        self.document.appendChild(newNode)
        # A NodeList is 'live', changes to source Node should be reflected
        isSameNode(newNode, self.list.item(1))

        # This extends to the Nodes contained in the NodeList
        newNode.data = 'bar'
        checkAttribute(self.list.item(1), 'data', 'bar')


# --- NamedNodeMap

class NamedNodeMapReadTestCase(TestCaseBase):

    def setUp(self):
        self.map = self.createDocument().createElement("foo")._get_attributes()

    def checkGetLength(self):
        checkLength(self.map, 0)

    def checkGetNamedItem(self):
        assert self.map.getNamedItem("uuu") is None

    def checkRemoveNamedItem(self):
        try:
            self.map.removeNamedItem("uuu")
            assert 0, "expected NotFoundErr to be raised"
        except xml.dom.NotFoundErr:
            pass

    def checkItem(self):
        assert self.map.item(0) is None

    def checkGetItem(self):
        try:
            self.map["uuu"]
            assert 0, "expected KeyError to be raised"
        except KeyError:
            pass

    def checkGet(self):
        assert self.map.get("uuu", 5) == 5

    def checkHasKey(self):
        assert not self.map.has_key("uuu")

    def checkItems(self):
        assert self.map.items() == []

    def checkKeys(self):
        assert self.map.keys() == []

    def checkValues(self):
        assert self.map.values() == []    


class NonemptyNamedNodeMapWriteTestCase(TestCaseBase):

    def setUp(self):
        self.map = self.createDocument().createElement("foo")._get_attributes()
        self.attribute = self.document.createAttribute("attrName")
        self.attribute.value = "attrValue"
        self.map.setNamedItem(self.attribute)

    def checkRemoveNonexistentNamedItem(self):
        try:
            self.map.removeNamedItem("uuu")
            assert 0, "did not catch expected DOMException"
        except xml.dom.DOMException:
            pass

    def checkRemoveNamedItem(self):
        attribute2 = self.document.createAttribute("attrName2")
        self.map.setNamedItem(attribute2)        
        attrOut = self.map.removeNamedItem("attrName2")
        assert isSameNode(attrOut, attribute2)

    def checkRemoveNamedItemNotFound(self):
        try:
            self.map.removeNamedItem("bogus")
        except xml.dom.NotFoundErr:
            pass
        else:
            assert 0, (
                "Expected an exception when trying to remove non-existing "
                "entry.")

    def checkGetLength(self):
        checkLength(self.map, 1)

    def checkGetNamedItem(self):
        assert isSameNode(self.attribute, self.map.getNamedItem("attrName"))

    def checkGetNonexistentNamedItem(self):
        assert self.map.getNamedItem("uuu") is None

    def checkItem(self):
        assert isSameNode(self.map.item(0), self.attribute)
        assert isSameNode(self.attribute, self.map.item(0))

    def checkGetNonexistentItem(self):
        try:
            self.map["uuu"]
            assert 0, "expected KeyError to be raised"
        except KeyError:
            pass

    def checkGetItem(self):
        assert isSameNode(self.attribute, self.map["attrName"])

    def checkGet(self):
        assert isSameNode(self.attribute, self.map.get("attrName"))

    def checkHasKey(self):
        assert self.map.has_key("attrName")
        assert not self.map.has_key("uuu")

    def checkItems(self):
        key, node = self.map.items()[0]
        assert key == "attrName" and isSameNode(self.attribute, node)

    def checkKeys(self):
        assert self.map.keys() == ["attrName"]

    def checkValues(self):
        L = []
        for attr in self.map.values():
            L.append(attr.value)
        assert L == ["attrValue"], "bad values list: %s" % `L`

    def checkSetNamedItem(self):
        newAttr = self.document.createAttribute('someAttr')
        newAttr.value = 'spam'
        
        retVal = self.map.setNamedItem(newAttr)
        assert retVal is None, "setNamedItem returned %s" % repr(retVal)
        checkLength(self.map, 2)
        assert isSameNode(self.map.getNamedItem('someAttr'), newAttr), (
            "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/xml/dom/tests/domapi/corelvl2.py === (1254/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)

    def checkCreateDocumentWithNamespace(self):
        newDoc = self.implementation.createDocument(self.TEST_NAMESPACE,
            self.TEST_QUALIFIED_NAME, None)

        checkAttribute(newDoc.documentElement, 'namespaceURI', 
            self.TEST_NAMESPACE)
        checkAttribute(newDoc.documentElement, 'tagName', 
            self.TEST_QUALIFIED_NAME)

    def checkCreateDocumentWithDocumentType(self):
        docType = self.implementation.createDocumentType(
            self.TEST_QUALIFIED_NAME, 'uri:public', 'uri:system')
        newDoc = self.implementation.createDocument(None, self.TEST_LOCAL_NAME,
            docType)

        checkAttributeSameNode(newDoc, 'doctype', docType)

    def checkCreateDocumentIllegalCharacterErr(self):
        try:
            self.implementation.createDocument(self.TEST_NAMESPACE, 
                '4_prefix:5_illegal', None)
        except xml.dom.InvalidCharacterErr:
            pass
        else:
            assert 0, "Created Document with illegal qualified name."

    def checkCreateDocumentMalformedQA(self):
        try:
            self.implementation.createDocument(self.TEST_NAMESPACE,
                'malformed:qualfied:name', None)
        except xml.dom.NamespaceErr:
            pass
        else:
            assert 0, "Created document with a malformed qualified name."
        
        try:
            self.implementation.createDocument(self.TEST_NAMESPACE,
                ':malformed_qn', None)
        except xml.dom.NamespaceErr:
            pass
        else:
            assert 0, "Created document with a malformed qualified name."

    def checkCreateDocumentWithPrefixNoNamespace(self):
        try:
            self.implementation.createDocument(None, self.TEST_QUALIFIED_NAME,
                None)
        except xml.dom.NamespaceErr:
            pass
        else:
            assert 0, "Created document with a prefix but no namespace."

    def checkCreateDocumentWithXMLPrefixWrongNamespace(self):
        try:
            self.implementation.createDocument(self.TEST_NAMESPACE, 'xml:nope',
                None)
        except xml.dom.NamespaceErr:
            pass
        else:
            assert 0, (
                "Created document with a 'xml' prefix but not the XML "
                "namespace.")

    def checkCreateDocumentWithUsedDocType(self):
        docType = self.implementation.createDocumentType(
            self.TEST_QUALIFIED_NAME, 'uri:public', 'uri:system')
        self.implementation.createDocument(None, self.TEST_LOCAL_NAME,
            docType)
        try:
            self.implementation.createDocument(None, self.TEST_LOCAL_NAME,
                docType)
        except xml.dom.WrongDocumentErr:
            pass
        else:
            assert 0, (
                "Used a doctype that was already in use to create a new "
                "Document.")

    def checkCreateDocumentType(self):
        docType = self.implementation.createDocumentType(
            self.TEST_QUALIFIED_NAME, 'uri:public', 'uri:system')

        checkAttribute(docType, 'ownerDocument', None)
        checkAttribute(docType, 'name', self.TEST_QUALIFIED_NAME)
        checkAttribute(docType, 'publicId', 'uri:public')
        checkAttribute(docType, 'systemId', 'uri:system')

        checkLength(docType.entities, 0)
        checkLength(docType.notations, 0)

    def checkCreateDocumentTypeIllegalCharacterErr(self):
        try:
            self.implementation.createDocumentType('4_prefix:5_illegal',
                'uri:public', 'uri:system')
        except xml.dom.InvalidCharacterErr:
            pass
        else:
            assert 0, "Created Document Type with illegal qualified name."

    def checkCreateDocumentTypeMalformedQA(self):
        try:
            self.implementation.createDocumentType('malformed:qualfied:name',
                'uri:public', 'uri:system')
        except xml.dom.NamespaceErr:
            pass
        else:
            assert 0, "Created Document Type with a malformed qualified name."

        try:
            self.implementation.createDocumentType(':malformed_qn',
                'uri:public', 'uri:system')
        except xml.dom.NamespaceErr:
            pass
        else:
            assert 0, "Created Document Type with a malformed qualified name."


# --- Node

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

    def checkLocalName(self):
        if self.node.nodeType in (Node.ATTRIBUTE_NODE,
                Node.ELEMENT_NODE):
            expect = self.TEST_LOCAL_NAME
            noNS = self.nodeNoNS
        else:
            expect = None
            noNS = None

        checkAttribute(self.node, 'localName', expect)
        checkReadOnly(self.node, 'localName')

        if noNS:
            checkAttribute(noNS, 'localName', None)

    def checkNameSpaceURI(self):
        if self.node.nodeType in (Node.ATTRIBUTE_NODE,
                Node.ELEMENT_NODE):
            expect = self.TEST_NAMESPACE
            noNS = self.nodeNoNS
        else:
            expect = None
            noNS = None


[-=- -=- -=- 1254 lines omitted -=- -=- -=-]

##         assert el.hasAttributeNS(TEST_NAMESPACE, 'foo'), (
##             'Removing specified attribute should bring back default '
##             'attribute.')
##         assert el.getAttributeNS(TEST_NAMESPACE, 'foo') == 'bar', (
##             "Wrong value of default attribute found, expected 'bar', "
##             "found %s" % repr(el.getAttributeNS(TEST_NAMESPACE, 'foo')))
##         checkAttribute(el.getAttributeNodeNS(TEST_NAMESPACE, 'foo'),
##             'specified', 0)

##     def checkRemoveNamedItemNS(self):
##         el = self.document.documentElement
##         # Replace default with specified attr
##         el.setAttributeNS(TEST_NAMESPACE, 'foo', 'baz')

##         el.attributes.removeNamedItemNS(TEST_NAMESPACE, 'foo')
##         assert el.hasAttributeNS(TEST_NAMESPACE, 'foo'), \
##             'Removing specified attribute should bring back default attribute.'
##         assert el.getAttributeNS(TEST_NAMESPACE, 'foo') == 'bar', (
##             "Wrong value of default attribute found, expected 'bar', found %s"
##             % repr(el.getAttributeNS(TEST_NAMESPACE, 'foo')))
##         checkAttribute(el.getAttributeNodeNS(TEST_NAMESPACE, 'foo'),
##             'specified', 0)

##     def checkSetAttributeNS(self):
##         el = self.document.documentElement
##         el.setAttributeNS(TEST_NAMESPACE, 'foo', 'baz')
##         checkAttribute(el.getAttributeNodeNS(TEST_NAMESPACE, 'foo'),
##             'specified', 1)

##     def checkSetAttributeNodeNS(self):
##         el = self.document.documentElement
##         newAttr = self.document.createAttributeNS(TEST_NAMESPACE, 'foo')
##         newAttr.value = 'baz'
##         el.setAttributeNode(newAttr)
##         checkAttribute(el.getAttributeNodeNS(TEST_NAMESPACE, 'foo'),
##             'specified', 1)


# --- DocumentFragment

class DocumentFragmentReadTestCase(NodeReadTestCaseBase):

    def setUp(self):
        self.docfrag = self.createDocument().createDocumentFragment()
        self.node = self.docfrag

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

        frag.appendChild(self.document.createComment('foo'))
        frag.appendChild(self.document.createTextNode('bar'))
        
        clone = foreignDoc.importNode(frag, 0)
        deepClone = foreignDoc.importNode(frag, 1)

        assert not isSameNode(frag, clone), "Clone is same Node as original."
        assert not isSameNode(frag, deepClone), (
            "Clone is same Node as original.")

        checkAttributeSameNode(clone, 'ownerDocument', foreignDoc)
        checkAttributeSameNode(deepClone, 'ownerDocument', foreignDoc)
        checkAttribute(clone, 'parentNode', None)
        checkAttribute(deepClone, 'parentNode', None)
        checkLength(clone.childNodes, 0)
        checkLength(deepClone.childNodes, frag.childNodes.length)

        for i in range(deepClone.childNodes.length):
            checkAttribute(deepClone.childNodes.item(i), 'nodeType',
                frag.childNodes.item(i).nodeType)
            checkAttribute(deepClone.childNodes.item(i), 'data',
                frag.childNodes.item(i).data)
            checkAttributeSameNode(deepClone.childNodes.item(i),
                'ownerDocument', foreignDoc)


class DocumentFragmentWriteTestCase(NodeWriteTestCaseBase):

    def setUp(self):
        self.docfrag = self.createDocument().createDocumentFragment()
        self.node = self.docfrag


# --- NamedNodeMap

class NamedNodeMapWriteTestCase(TestCaseBase):

    TEST_NAMESPACE = NodeReadTestCaseBase.TEST_NAMESPACE
    TEST_PREFIX = NodeReadTestCaseBase.TEST_PREFIX
    TEST_LOCAL_NAME = NodeReadTestCaseBase.TEST_LOCAL_NAME
    TEST_QUALIFIED_NAME = NodeReadTestCaseBase.TEST_QUALIFIED_NAME

    def setUp(self):
        self.map = self.createDocument().createElement("foo")._get_attributes()
        self.attribute = self.document.createAttributeNS(self.TEST_NAMESPACE,
            self.TEST_QUALIFIED_NAME)
        self.attribute.value = "attrValue"
        self.map.setNamedItemNS(self.attribute)

    def checkGetNamedItemNS(self):
        node = self.map.getNamedItemNS(self.TEST_NAMESPACE, 
            self.TEST_LOCAL_NAME)

        assert node is not None, "getNamedItemNS didn't retrieve attribute."
        assert isSameNode(node, self.attribute), (
            "getNamedItemNS retrieved incorrect attribute.")

    def checkGetNamedItemNSWrongNamespace(self):
        node = self.map.getNamedItemNS('uri:foo', self.TEST_LOCAL_NAME)
        assert node is None, "getNamedItemNS returned an attribute."

    def checkGetNamedItemNSWrongLocalname(self):
        node = self.map.getNamedItemNS(self.TEST_NAMESPACE, 'bar')
        assert node is None, "getNamedItemNS returned an attribute."

    def checkRemoveNamedItemNS(self):
        node = self.map.removeNamedItemNS(self.TEST_NAMESPACE,
            self.TEST_LOCAL_NAME)

        assert node is not None, (
            "removeNamedItemNS didn't return an attribute.")
        assert isSameNode(node, self.attribute), (
            "removeNamedItemNS returned incorrect attribute.")
        assert self.map.getNamedItemNS(self.TEST_NAMESPACE, 
            self.TEST_LOCAL_NAME) is None, "Attribute was not removed."
        checkLength(self.map, 0)

    def checkRemoveNamedItemNSNotFound(self):
        # Exceptions
        try:
            self.map.removeNamedItemNS('uri:foo', 'bar:baz')
        except xml.dom.NotFoundErr:
            pass
        else:
            assert 0, "Removal of non-existent item succeeded."

    def checkSetNamedItemNS(self):
        newAttr = self.document.createAttributeNS(self.TEST_NAMESPACE,
            'qname:someAttr')
        newAttr.value = 'spam'
        
        retVal = self.map.setNamedItemNS(newAttr)
        assert retVal is None, "setNamedItemNS returned %s" % repr(retVal)
        checkLength(self.map, 2)
        assert isSameNode(self.map.getNamedItemNS(self.TEST_NAMESPACE,
            'someAttr'), newAttr), (
                "setNamedItemNS store seems to have failed, can't retrieve.")

    def checkSetNamedItemNSReplaceExisting(self):
        newAttr = self.document.createAttributeNS(self.TEST_NAMESPACE,
            '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/xml/dom/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/xml/dom/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.xml.dom 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/xml/dom/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/xml/dom/tests/domapi/traversallvl2.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 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):

    def setUp(self):
        self.createDocumentNS()

    def checkCreateNodeIterator(self):
        root = self.document
        whatToShow = NodeFilter.SHOW_ALL
        filter = NodeFilter()
        
        iterator = self.document.createNodeIterator(root, whatToShow, filter, 1)

        checkAttributeSameNode(iterator, 'root', root)
        checkAttribute(iterator, 'whatToShow', whatToShow)
        assert iterator.filter is filter, (
            "Created iterator has got a different filter object. Expected %s, "
            "found %s." % (repr(filter), repr(iterator.filter)))
        checkAttribute(iterator, 'expandEntityReferences', 1)

    def checkCreateNodeIteratorNoRoot(self):
        try:
            self.document.createNodeIterator(None, NodeFilter.SHOW_ALL, None, 0)
        except xml.dom.NotSupportedErr:
            pass
        else:
            assert 0, "Was allowed to create a NodeIterator without a root."

    def checkCreateTreeWalker(self):
        root = self.document
        whatToShow = NodeFilter.SHOW_ALL
        filter = NodeFilter()
        
        walker = self.document.createTreeWalker(root, whatToShow, filter, 1)

        checkAttributeSameNode(walker, 'root', root)
        checkAttribute(walker, 'whatToShow', whatToShow)
        assert walker.filter is filter, (
            "Created walker has got a different filter object. Expected %s, "
            "found %s." % (repr(filter), repr(walker.filter)))
        checkAttribute(walker, 'expandEntityReferences', 1)

    def checkCreateTreeWalkerNoRoot(self):
        try:
            self.document.createTreeWalker(None, NodeFilter.SHOW_ALL, None, 0)
        except xml.dom.NotSupportedErr:
            pass
        else:
            assert 0, "Was allowed to create a TreeWalker without a root."

# --- NodeIterator

class NodeIteratorTestCase(TestCaseBase):

    def setUp(self):
        # Create a tree of elements. Alphabetic order denotes document order.
        docType = self.implementation.createDocumentType('A', None, None)
        self.document = doc = self.implementation.createDocument(None, 'A',
            docType)

        self.A = a = doc.documentElement
        self.B = a.appendChild(doc.createTextNode('B'))
        self.C = c = a.appendChild(doc.createElement('C'))
        self.D = c.appendChild(doc.createCDATASection('D'))
        self.E = c.appendChild(doc.createProcessingInstruction('E', 'A PI'))
        self.F = a.appendChild(doc.createComment('F'))
        self.G = a.appendChild(doc.createTextNode('G'))

        self.all = (doc, docType, a, self.B, c, self.D, self.E, self.F, self.G)

    def iterate(self, iterator, expectedNodes):
        all = expectedNodes[:]
        while 1:
            nextNode = iterator.nextNode()

            if nextNode is None:
                assert not all, (
                    "nextNode returned None before end, still expected to "
                    "see %s." % `all`)
                break

            assert all, (
                "nextNode returned %s when we should've gotten None." %
                `nextNode`)

            expect = all.pop(0)
            assert isSameNode(expect, nextNode), (
                "nextNode returned %s, expected %s." % (`nextNode`, `expect`))

        all = expectedNodes[:]
        while 1:
            previousNode = iterator.previousNode()

            if previousNode is None:
                assert not all, (
                    "previousNode returned None before end, still expected to "
                    "see %s." % `all`)
                break

            assert all, (
                "previousNode returned %s when we should've gotten None." %
                `previousNode`)

            expect = all.pop()
            assert isSameNode(expect, previousNode), (
                "previousNode returned %s, expected %s." % (`previousNode`,
                    `expect`))

    def checkIteratorNoFilter(self):
        iterator = self.document.createNodeIterator(self.document,
            NodeFilter.SHOW_ALL, None, 0)

        self.iterate(iterator, list(self.all))

    def checkIteratorOnlyTextNodes(self):
        iterator = self.document.createNodeIterator(self.document,
            NodeFilter.SHOW_TEXT, None, 0)

        self.iterate(iterator, [self.B, self.G])

    def checkIteratorAllButTextNodes(self):
        iterator = self.document.createNodeIterator(self.document,
            NodeFilter.SHOW_ALL ^ NodeFilter.SHOW_TEXT, None, 0)

        self.iterate(iterator, list(self.all[:3] + self.all[4:8]))

    def checkIteratorFilterSkipC(self):
        class SkipCFilter(NodeFilter):
            def acceptNode(self, node):
                if node.nodeName == 'C':
                    return self.FILTER_SKIP
                else:
                    return self.FILTER_ACCEPT

        iterator = self.document.createNodeIterator(self.document,
            NodeFilter.SHOW_ALL, SkipCFilter(), 0)

        self.iterate(iterator, list(self.all[:4] + self.all[5:]))

    def checkIteratorFilterRejectC(self):
        class RejectCFilter(NodeFilter):
            def acceptNode(self, node):
                if node.nodeName == 'C':
                    return self.FILTER_REJECT
                else:
                    return self.FILTER_ACCEPT

        iterator = self.document.createNodeIterator(self.document,
            NodeFilter.SHOW_ALL, RejectCFilter(), 0)

        self.iterate(iterator, list(self.all[:4] + self.all[5:]))

    def checkIteratorOnlyTextNodesFilterSkipG(self):
        class SkipGFilter(NodeFilter):
            def acceptNode(self, node):
                if node.nodeValue == 'G':
                    return self.FILTER_SKIP
                else:
                    return self.FILTER_ACCEPT

        iterator = self.document.createNodeIterator(self.document,
            NodeFilter.SHOW_TEXT, SkipGFilter(), 0)

        self.iterate(iterator, [self.B])

    def checkIteratorPreviousNode(self):
        iterator = self.document.createNodeIterator(self.document,
            NodeFilter.SHOW_ALL, None, 0)
        
        assert iterator.previousNode() is None, (
            "previousNode on a fresh iterator did not return None.")

    def checkIteratorNextNodeInvalidState(self):
        iterator = self.document.createNodeIterator(self.document,
            NodeFilter.SHOW_ALL, None, 0)
        iterator.detach()

        try:
            iterator.nextNode()
        except xml.dom.InvalidStateErr:
            pass
        else:
            assert 0, (
                "Was allowed to call nextNode() on a detached NodeIterator.")

    def checkIteratorPreviousNodeInvalidState(self):
        iterator = self.document.createNodeIterator(self.document,
            NodeFilter.SHOW_ALL, None, 0)
        iterator.detach()

        try:
            iterator.previousNode()
        except xml.dom.InvalidStateErr:
            pass
        else:
            assert 0, (
                "Was allowed to call previousNode() on a detached "
                "NodeIterator.")

    def checkIteratorFilterException(self):
        class ExceptionFilter(NodeFilter):
            def acceptNode(self, node):
                raise KeyError, (
                    "Test exception to see if it will propagate.")

        iterator = self.document.createNodeIterator(self.document,
            NodeFilter.SHOW_ALL, ExceptionFilter(), 0)

        try:
            iterator.nextNode()
        except KeyError:
            pass
        else:
            assert 0, "NodeIterator caught exception raised in filter."


# -- TreeWalker

class TreeWalkerTestCase(TestCaseBase):
    
    def setUp(self):
        # Create a tree of elements. Alphabetic order denotes document order.
        docType = self.implementation.createDocumentType('A', None, None)
        self.document = doc = self.implementation.createDocument(None, 'A',
            docType)

        self.A = a = doc.documentElement
        self.B = a.appendChild(doc.createTextNode('B'))
        self.C = c = a.appendChild(doc.createElement('C'))
        self.D = c.appendChild(doc.createCDATASection('D'))
        self.E = c.appendChild(doc.createProcessingInstruction('E', 'A PI'))
        self.F = a.appendChild(doc.createComment('F'))
        self.G = a.appendChild(doc.createTextNode('G'))

        self.all = (doc, docType, a, self.B, c, self.D, self.E, self.F, self.G)

    def iterate(self, walker, advanceMethod, retreatMethod,
                expectedNodesNext, expectedNodesPrevious = None):
        "Exercise methods given in advanceMethod, retreatMethod"
        if not expectedNodesPrevious:
            expectedNodesPrevious = expectedNodesNext
        all = expectedNodesNext[:]
        current = walker.currentNode
        while 1:
            if current is None:
                assert not all, (
                    "%s returned None before end, still expected to "
                    "see %s. TreeWalker.currentNode is %s." % (
                    advanceMethod, `all`, `walker.currentNode`))
                break

            assert all, (
                "%s returned %s when we should've gotten None. "
                "TreeWalker.currentNode is %s." % (
                advanceMethod, `current`, `walker.currentNode`))

            expect = all.pop(0)
            assert isSameNode(expect, current), (
                "%s returned %s, expected %s. TreeWalker.currentNode is "
                "%s." % (advanceMethod, `current`, `expect`,
                         `walker.currentNode`))

            current = getattr(walker, advanceMethod)()

        all = expectedNodesPrevious[:]
        current = walker.currentNode
        while 1:
            if current is None:
                assert not all, (
                    "%s returned None before end, still expected to "
                    "see %s. TreeWalker.currentNode is %s." % (
                    retreatMethod, `all`, `walker.currentNode`))
                break

            assert all, (
                "%s returned %s when we should've gotten None. "
                "TreeWalker.currentNode is %s." % (
                retreatMethod, `current`, `walker.currentNode`))

            expect = all.pop()
            assert isSameNode(expect, current), (
                "%s returned %s, expected %s. "
                "TreeWalker.currentNode is %s." % (
                retreatMethod, `current`, `expect`, `walker.currentNode`))

            current = getattr(walker, retreatMethod)()

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

        self.iterate(walker, "nextNode", "previousNode", list(self.all))

    def checkWalkerOnlyTextNodesIterate(self):
        walker = self.document.createTreeWalker(self.document,
            NodeFilter.SHOW_TEXT, None, 0)

        self.iterate(walker, "nextNode", "previousNode",
                     [self.document, self.B, self.G], [self.B, self.G])
                     
    def checkWalkerAllButTextNodesIterate(self):
        walker = self.document.createTreeWalker(self.document,
            NodeFilter.SHOW_ALL ^ NodeFilter.SHOW_TEXT, None, 0)

        self.iterate(walker, "nextNode", "previousNode",
                     list(self.all[:3] + self.all[4:8]))

    def checkWalkerFilterSkipCIterate(self):
        class SkipCFilter(NodeFilter):
            def acceptNode(self, node):
                if node.nodeName == 'C':
                    return self.FILTER_SKIP
                else:
                    return self.FILTER_ACCEPT

        walker = self.document.createTreeWalker(self.document,
            NodeFilter.SHOW_ALL, SkipCFilter(), 0)

        self.iterate(walker, "nextNode", "previousNode",
                     list(self.all[:4] + self.all[5:]))
                     

    def checkWalkerFilterRejectCIterate(self):
        class RejectCFilter(NodeFilter):
            def acceptNode(self, node):
                if node.nodeName == 'C':
                    return self.FILTER_REJECT
                else:
                    return self.FILTER_ACCEPT

        walker = self.document.createTreeWalker(self.document,
            NodeFilter.SHOW_ALL, RejectCFilter(), 0)

        self.iterate(walker, "nextNode", "previousNode",
                     list(self.all[:4] + self.all[7:]))
                     
    def checkWalkerOnlyTextNodesFilterSkipG(self):
        class SkipGFilter(NodeFilter):
            def acceptNode(self, node):
                if node.nodeValue == 'G':
                    return self.FILTER_SKIP
                else:
                    return self.FILTER_ACCEPT

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

        self.iterate(walker, "nextNode", "previousNode",
                     [self.document, self.B], [self.B,])

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

        walker.firstChild() # doctype
        walker.nextSibling() # A
        walker.firstChild() # B
        walker.nextSibling() # C
        walker.firstChild() # D
        self.iterate(walker, "parentNode", "firstChild",
                     [self.D, self.C, self.A, self.document],
                     [self.document.doctype, self.document],)

    def checkWalkerOnlyTextNodesParentNodeFirstChild(self):
        walker = self.document.createTreeWalker(self.document,
            NodeFilter.SHOW_TEXT, None, 0)

        self.iterate(walker, "firstChild", "parentNode",
                     [self.document])
                     
    def checkWalkerAllButTextNodesParentNodeFirstChild(self):
        walker = self.document.createTreeWalker(self.document,
            NodeFilter.SHOW_ALL ^ NodeFilter.SHOW_TEXT, None, 0)

        walker.firstChild() # doctype
        walker.nextSibling() # A
        self.iterate(walker, "firstChild", "parentNode",
                     [self.A, self.C, self.D],
                     [self.document, self.A, self.C, self.D],)

    # "first visible child" might be seen to imply "first child that
    # is visible", rather than "first visible descendent", but the
    # examples skip to descendents.
    def checkWalkerFilterSkipCFirstChild(self):
        class SkipCFilter(NodeFilter):
            def acceptNode(self, node):
                if node.nodeName == 'C':
                    return self.FILTER_SKIP
                else:
                    return self.FILTER_ACCEPT

        self.A.removeChild(self.B)
        
        walker = self.document.createTreeWalker(self.document,
            NodeFilter.SHOW_ALL, SkipCFilter(), 0)

        walker.firstChild() # doctype
        walker.nextSibling() # A
        self.iterate(walker, "firstChild", "parentNode",
                     [self.A, self.D],
                     [self.document, self.A, self.D])

    # also checks parentNode robustness under currentNode move
    def checkWalkerFilterSkipCParentNode(self):
        class SkipCFilter(NodeFilter):
            def acceptNode(self, node):
                if node.nodeName == 'C':
                    return self.FILTER_SKIP
                else:
                    return self.FILTER_ACCEPT
       
        walker = self.document.createTreeWalker(self.document,
            NodeFilter.SHOW_ALL, SkipCFilter(), 0)

        walker.firstChild() # doctype
        walker.nextSibling() # A
        walker.firstChild() # B
        self.C.appendChild(self.B)
        
        self.iterate(walker, "parentNode", "firstChild",
                     [self.B, self.A, self.document],
                     [self.document.doctype, self.document])

    def checkWalkerFilterRejectCFirstChild(self):
        class RejectCFilter(NodeFilter):
            def acceptNode(self, node):
                if node.nodeName == 'C':
                    return self.FILTER_REJECT
                else:
                    return self.FILTER_ACCEPT

        self.A.removeChild(self.B)

        walker = self.document.createTreeWalker(self.document,
            NodeFilter.SHOW_ALL, RejectCFilter(), 0)

        walker.firstChild() # doctype
        walker.nextSibling() # A
        self.iterate(walker, "firstChild", "parentNode",
                     [self.A, self.F],
                     [self.document, self.A, self.F])

    # also tests parentNode robustness under currentNode move
    def checkWalkerFilterRejectCParentNode(self):
        class RejectCFilter(NodeFilter):
            def acceptNode(self, node):
                if node.nodeName == 'C':
                    return self.FILTER_REJECT
                else:
                    return self.FILTER_ACCEPT

        walker = self.document.createTreeWalker(self.document,
            NodeFilter.SHOW_ALL, RejectCFilter(), 0)

        walker.firstChild() # doctype
        walker.nextSibling() # A
        walker.firstChild() # B
        self.C.appendChild(self.B)

        self.iterate(walker, "parentNode", "firstChild",
                     [self.B, self.A, self.document],
                     [self.document.doctype, self.document])
                     
    def checkWalkerOnlyTextNodesParentNodeFirstChildFilterSkipB(self):
        class SkipBFilter(NodeFilter):
            def acceptNode(self, node):
                if node.nodeValue == 'B':
                    return self.FILTER_SKIP
                else:
                    return self.FILTER_ACCEPT

        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/xml/dom/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/xml/dom/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')