pythonelementtreepython-unittestcelementtree

Verifying cElementTree or elementTree node type


I have used cElementTree to parse XML files in my application and it works beautifully, however, now I wanted to write some unit tests to check whether the results of my methods return expected results.

In one of my tests I want to check whether a retrieved element from the tree is indeed an Element type:

self.assertIsInstance(myElem, Element, 'Incorrect type for myElem')

When I execute my test, I am getting the following error:

TypeError: isinstance() arg 2 must be a class, type or tuple of classes and types.

What is Element then if it is not a class or a type? I could not find many details about this in the documentation.


Solution

  • I found this excerpt from the source code, File : ElementTree.py

    ##
    # Element factory.  This function returns an object implementing the
    # standard Element interface.  The exact class or type of that object
    # is implementation dependent, but it will always be compatible with
    # the {@link #_ElementInterface} class in this module.
    # <p>
    # The element name, attribute names, and attribute values can be
    # either 8-bit ASCII strings or Unicode strings.
    #
    # @param tag The element name.
    # @param attrib An optional dictionary, containing element attributes.
    # @param **extra Additional attributes, given as keyword arguments.
    # @return An element instance.
    # @defreturn Element
    
    def Element(tag, attrib={}, **extra):
        attrib = attrib.copy()
        attrib.update(extra)
        return _ElementInterface(tag, attrib)
    

    So, Element is ultimately a factory method.