Browse Source

py3 compatibility work (incomplete)

The builds will fail to due valid flake8 problems. Anyome is welcomed to solve some of them as I will not make a new release before they are all fixed.

Signed-off-by: Sorin Sbarnea <sorin.sbarnea@gmail.com>
main
Sorin Sbarnea 8 years ago
parent
commit
1e065ce6c8
12 changed files with 177 additions and 103 deletions
  1. +2
    -1
      MANIFEST.in
  2. +2
    -4
      requirements-dev.txt
  3. +1
    -0
      requirements.txt
  4. +7
    -5
      setup.cfg
  5. +10
    -12
      setup.py
  6. +3
    -1
      tests/test_wsdl.py
  7. +7
    -1
      tox.ini
  8. +4
    -3
      wstools/TimeoutSocket.py
  9. +7
    -7
      wstools/Utility.py
  10. +22
    -13
      wstools/WSDLTools.py
  11. +108
    -54
      wstools/XMLSchema.py
  12. +4
    -2
      wstools/c14n.py

+ 2
- 1
MANIFEST.in View File

@@ -1,5 +1,6 @@
include README.rst include README.rst
include CHANGES.txt include CHANGES.txt
include requirements.txt
include requirements-dev.txt
recursive-include docs *.* recursive-include docs *.*
recursive-include wstools *.py recursive-include wstools *.py


+ 2
- 4
requirements-dev.txt View File

@@ -1,9 +1,7 @@
autopep8
coverage coverage
coveralls coveralls
flake8 flake8
flake8-docstrings>=0.2.8
flake8-pep257>=1.0.5 flake8-pep257>=1.0.5
nose
pytest pytest
pytest-flake8
pytest-cov
pytest-timeout

+ 1
- 0
requirements.txt View File

@@ -1 +1,2 @@
setuptools
six six

+ 7
- 5
setup.cfg View File

@@ -13,9 +13,10 @@ all_files = 1
upload-dir = docs/build/html upload-dir = docs/build/html


[pytest] [pytest]
norecursedirs = . .svn jira _build tmp* lib/third lib *.egg bin distutils build docs demo
norecursedirs = . .git .svn tox _build tmp* lib/third lib *.egg bin distutils build docs demo
python_files = *.py python_files = *.py
addopts = -p no:xdist --ignore=setup.py --tb=long -rsxX -v --maxfail=10 --flake8 tests
addopts = -p no:xdist --ignore=setup.py --tb=long -rsxX -v --maxfail=10 tests
# remove "--flake8" due to weir errors
timeout=60 timeout=60
# --maxfail=2 -n4 # --maxfail=2 -n4
# -n4 runs up to 4 parallel procs # -n4 runs up to 4 parallel procs
@@ -23,13 +24,14 @@ timeout=60
# --durations=3 report the top 3 longest tests # --durations=3 report the top 3 longest tests


# these are important for distributed testing, to speedup their execution we minimize what we sync # these are important for distributed testing, to speedup their execution we minimize what we sync
rsyncdirs = . jira demo docs
rsyncdirs = . demo docs
rsyncignore = .hg .git rsyncignore = .hg .git
flake8-max-line-length = 99 flake8-max-line-length = 99
flake8-ignore = D D100 E402
#flake8-ignore=D,D102
flake8-ignore=D D102


[flake8] [flake8]
max-line-length=160 max-line-length=160
exclude=build exclude=build
statistics=yes statistics=yes
ignore = D,E402
ignore=D,E402

+ 10
- 12
setup.py View File

@@ -9,6 +9,7 @@ import codecs


from setuptools import setup, find_packages, Command from setuptools import setup, find_packages, Command
from setuptools.command.test import test as TestCommand from setuptools.command.test import test as TestCommand
from pip.req import parse_requirements


NAME = "wstools" NAME = "wstools"
url = "https://github.com/pycontribs/wstools.git" url = "https://github.com/pycontribs/wstools.git"
@@ -46,14 +47,6 @@ class PyTest(TestCommand):
if sys.stdout.isatty(): if sys.stdout.isatty():
# when run manually we enable fail fast # when run manually we enable fail fast
self.pytest_args.append("--maxfail=1") self.pytest_args.append("--maxfail=1")
try:
import coveralls # noqa
self.pytest_args.append("--cov=%s" % NAME)
self.pytest_args.extend(["--cov-report", "term"])
self.pytest_args.extend(["--cov-report", "xml"])

except ImportError:
pass


def finalize_options(self): def finalize_options(self):
TestCommand.finalize_options(self) TestCommand.finalize_options(self)
@@ -130,7 +123,12 @@ class PreRelease(Command):
raise RuntimeError( raise RuntimeError(
"Current version of the package is equal or lower than the already published ones (PyPi). Increse version to be able to pass prerelease stage.") "Current version of the package is equal or lower than the already published ones (PyPi). Increse version to be able to pass prerelease stage.")


requires = ['autopep8', 'six', 'pep8', 'pytest-cov', 'pytest-pep8', 'setuptools', 'pytest', 'pytest-timeout']

def get_requirements(*path):
req_path = os.path.join(*path)
reqs = parse_requirements(req_path, session=False)
return [str(ir.req) for ir in reqs]



setup( setup(
name=NAME, name=NAME,
@@ -138,9 +136,9 @@ setup(
cmdclass={'test': PyTest, 'release': Release, 'prerelease': PreRelease}, cmdclass={'test': PyTest, 'release': Release, 'prerelease': PreRelease},
packages=find_packages(exclude=['tests']), packages=find_packages(exclude=['tests']),
include_package_data=True, include_package_data=True,
tests_require=requires,
setup_requires=requires,
install_requires=requires,
tests_require=get_requirements(base_path, 'requirements-dev.txt'),
setup_requires=['setuptools'],
install_requires=get_requirements(base_path, 'requirements.txt'),


license='BSD', license='BSD',
description="WSDL parsing services package for Web Services for Python. see" + url, description="WSDL parsing services package for Web Services for Python. see" + url,


+ 3
- 1
tests/test_wsdl.py View File

@@ -4,7 +4,7 @@
# Joshua R. Boverhof, David W. Robertson, LBNL # Joshua R. Boverhof, David W. Robertson, LBNL
# See LBNLCopyright for copyright notice! # See LBNLCopyright for copyright notice!
########################################################################### ###########################################################################
"""Unittests."""
import sys import sys
import unittest import unittest
import os import os
@@ -28,6 +28,7 @@ nameGenerator = None




def makeTestSuite(section='services_by_file'): def makeTestSuite(section='services_by_file'):
"""makeTestSuite."""
global nameGenerator global nameGenerator


cp, numTests = setUpOptions(section) cp, numTests = setUpOptions(section)
@@ -39,6 +40,7 @@ def makeTestSuite(section='services_by_file'):




class WSDLToolsTestCase(unittest.TestCase): class WSDLToolsTestCase(unittest.TestCase):
""""""


def __init__(self, methodName='runTest'): def __init__(self, methodName='runTest'):
unittest.TestCase.__init__(self, methodName) unittest.TestCase.__init__(self, methodName)


+ 7
- 1
tox.ini View File

@@ -1,9 +1,11 @@
[tox] [tox]
minversion = 2.3.1 minversion = 2.3.1
envlist = {py27,py34,py35}-{win,linux,darwin} envlist = {py27,py34,py35}-{win,linux,darwin}
#envlist = {py35}-{win,linux,darwin}
addopts = --ignore=setup.py addopts = --ignore=setup.py
skip_missing_interpreters = true skip_missing_interpreters = true
tox_pyenv_fallback=True tox_pyenv_fallback=True
ignore_errors=False


[testenv] [testenv]
sitepackages=True sitepackages=True
@@ -17,4 +19,8 @@ deps=
-rrequirements-dev.txt -rrequirements-dev.txt


commands= commands=
python -m py.test --cov-report xml
python -m flake8
python setup.py build test install sdist bdist_wheel

# Note: do not try to use pytest-flake8 due to https://github.com/tholo/pytest-flake8/issues/8
# python -m py.test --cov-report xml

+ 4
- 3
wstools/TimeoutSocket.py View File

@@ -1,3 +1,7 @@
import socket
import select
import errno

"""Based on code from timeout_socket.py, with some tweaks for compatibility. """Based on code from timeout_socket.py, with some tweaks for compatibility.
These tweaks should really be rolled back into timeout_socket, but it's These tweaks should really be rolled back into timeout_socket, but it's
not totally clear who is maintaining it at this point. In the meantime, not totally clear who is maintaining it at this point. In the meantime,
@@ -15,9 +19,6 @@


ident = "$Id$" ident = "$Id$"


import socket
import select
import errno


WSAEINVAL = getattr(errno, 'WSAEINVAL', 10022) WSAEINVAL = getattr(errno, 'WSAEINVAL', 10022)




+ 7
- 7
wstools/Utility.py View File

@@ -946,7 +946,7 @@ class ElementProxy(Base, MessageInterface):
self.node.setAttributeNS(namespaceURI, qualifiedName, value) self.node.setAttributeNS(namespaceURI, qualifiedName, value)


############################################# #############################################
#General Methods
# General Methods
############################################# #############################################
def isFault(self): def isFault(self):
'''check to see if this is a soap:fault message. '''check to see if this is a soap:fault message.
@@ -1007,7 +1007,7 @@ class ElementProxy(Base, MessageInterface):
doctype=doctype) doctype=doctype)
self.node = document.childNodes[0] self.node = document.childNodes[0]


#set up reserved namespace attributes
# set up reserved namespace attributes
for prefix, nsuri in self.reserved_ns.items(): for prefix, nsuri in self.reserved_ns.items():
self._setAttributeNS(namespaceURI=self._xmlns_nsuri, self._setAttributeNS(namespaceURI=self._xmlns_nsuri,
qualifiedName='%s:%s' % (self._xmlns_prefix, qualifiedName='%s:%s' % (self._xmlns_prefix,
@@ -1015,7 +1015,7 @@ class ElementProxy(Base, MessageInterface):
value=nsuri) value=nsuri)


############################################# #############################################
#Methods for attributes
# Methods for attributes
############################################# #############################################
def hasAttribute(self, namespaceURI, localName): def hasAttribute(self, namespaceURI, localName):
return self._dom.hasAttr(self._getNode(), name=localName, return self._dom.hasAttr(self._getNode(), name=localName,
@@ -1038,7 +1038,7 @@ class ElementProxy(Base, MessageInterface):


def createAttributeNS(self, namespace, name, value): def createAttributeNS(self, namespace, name, value):
document = self._getOwnerDocument() document = self._getOwnerDocument()
##this function doesn't exist!! it has only two arguments
# this function doesn't exist!! it has only two arguments
attrNode = document.createAttributeNS(namespace, name, value) attrNode = document.createAttributeNS(namespace, name, value)


def setAttributeNS(self, namespaceURI, localName, value): def setAttributeNS(self, namespaceURI, localName, value):
@@ -1070,7 +1070,7 @@ class ElementProxy(Base, MessageInterface):
self._setAttributeNS(XMLNS.BASE, 'xmlns:%s' % prefix, namespaceURI) self._setAttributeNS(XMLNS.BASE, 'xmlns:%s' % prefix, namespaceURI)


############################################# #############################################
#Methods for elements
# Methods for elements
############################################# #############################################
def createElementNS(self, namespace, qname): def createElementNS(self, namespace, qname):
''' '''
@@ -1157,7 +1157,7 @@ class ElementProxy(Base, MessageInterface):
return self._dom.getElementText(self.node, preserve_ws=True) return self._dom.getElementText(self.node, preserve_ws=True)


############################################# #############################################
#Methods for text nodes
# Methods for text nodes
############################################# #############################################
def createAppendTextNode(self, pyobj): def createAppendTextNode(self, pyobj):
node = self.createTextNode(pyobj) node = self.createTextNode(pyobj)
@@ -1170,7 +1170,7 @@ class ElementProxy(Base, MessageInterface):
return ElementProxy(self.sw, node) return ElementProxy(self.sw, node)


############################################# #############################################
#Methods for retrieving namespaceURI's
# Methods for retrieving namespaceURI's
############################################# #############################################
def findNamespaceURI(self, qualifiedName): def findNamespaceURI(self, qualifiedName):
parts = SplitQName(qualifiedName) parts = SplitQName(qualifiedName)


+ 22
- 13
wstools/WSDLTools.py View File

@@ -150,8 +150,10 @@ class WSDL:
child = DOM.getElement(self.document, None) child = DOM.getElement(self.document, None)
child.setAttributeNS(None, 'targetNamespace', self.targetNamespace) child.setAttributeNS(None, 'targetNamespace', self.targetNamespace)
child.setAttributeNS(XMLNS.BASE, 'xmlns:wsdl', namespaceURI) child.setAttributeNS(XMLNS.BASE, 'xmlns:wsdl', namespaceURI)
child.setAttributeNS(XMLNS.BASE, 'xmlns:xsd', 'http://www.w3.org/1999/XMLSchema')
child.setAttributeNS(XMLNS.BASE, 'xmlns:soap', 'http://schemas.xmlsoap.org/wsdl/soap/')
child.setAttributeNS(XMLNS.BASE, 'xmlns:xsd',
'http://www.w3.org/1999/XMLSchema')
child.setAttributeNS(XMLNS.BASE, 'xmlns:soap',
'http://schemas.xmlsoap.org/wsdl/soap/')
child.setAttributeNS(XMLNS.BASE, 'xmlns:tns', self.targetNamespace) child.setAttributeNS(XMLNS.BASE, 'xmlns:tns', self.targetNamespace)


if self.name: if self.name:
@@ -253,7 +255,7 @@ class WSDL:
docs = GetDocumentation(element) docs = GetDocumentation(element)
ptype = self.addPortType(name, docs, targetNamespace) ptype = self.addPortType(name, docs, targetNamespace)
#operations = DOM.getElements(element, 'operation', NS_WSDL) #operations = DOM.getElements(element, 'operation', NS_WSDL)
#ptype.load(operations)
# ptype.load(operations)
ptype.load(element) ptype.load(element)
continue continue


@@ -290,9 +292,10 @@ class WSDL:
reader = SchemaReader(base_url=base_location) reader = SchemaReader(base_url=base_location)
for item in DOM.getElements(element, None, None): for item in DOM.getElements(element, None, None):
if item.localName == 'schema': if item.localName == 'schema':
schema = reader.loadFromNode(WSDLToolsAdapter(self), item)
schema = reader.loadFromNode(
WSDLToolsAdapter(self), item)
# XXX <types> could have been imported # XXX <types> could have been imported
#schema.setBaseUrl(self.location)
# schema.setBaseUrl(self.location)
schema.setBaseUrl(base_location) schema.setBaseUrl(base_location)
self.types.addSchema(schema) self.types.addSchema(schema)
else: else:
@@ -364,7 +367,7 @@ class WSDL:
attr = attrsNS[attrkey].cloneNode(1) attr = attrsNS[attrkey].cloneNode(1)
child.setAttributeNode(attr) child.setAttributeNode(attr)


#XXX Quick Hack, should be in WSDL Namespace.
# XXX Quick Hack, should be in WSDL Namespace.
if child.localName == 'import': if child.localName == 'import':
rlocation = child.getAttributeNS(None, 'location') rlocation = child.getAttributeNS(None, 'location')
alocation = basejoin(location, rlocation) alocation = basejoin(location, rlocation)
@@ -717,7 +720,8 @@ class Operation(Element):
return self.input return self.input


def setOutput(self, message, name='', documentation='', action=None): def setOutput(self, message, name='', documentation='', action=None):
self.output = MessageRole('output', message, name, documentation, action)
self.output = MessageRole(
'output', message, name, documentation, action)
self.output.parent = weakref.ref(self) self.output.parent = weakref.ref(self)
return self.output return self.output


@@ -822,7 +826,7 @@ class Binding(Element):


item = DOM.getElement(element, 'input', None, None) item = DOM.getElement(element, 'input', None, None)
if item is not None: if item is not None:
#TODO: addInputBinding?
# TODO: addInputBinding?
mbinding = MessageRoleBinding('input') mbinding = MessageRoleBinding('input')
mbinding.documentation = GetDocumentation(item) mbinding.documentation = GetDocumentation(item)
opbinding.input = mbinding opbinding.input = mbinding
@@ -1187,7 +1191,8 @@ class SoapBinding:
def toDom(self, node): def toDom(self, node):
wsdl = self.getWSDL() wsdl = self.getWSDL()
ep = ElementProxy(None, node) ep = ElementProxy(None, node)
epc = ep.createAppendElement(DOM.GetWSDLSoapBindingUri(wsdl.version), 'binding')
epc = ep.createAppendElement(
DOM.GetWSDLSoapBindingUri(wsdl.version), 'binding')
if self.transport: if self.transport:
epc.setAttributeNS(None, "transport", self.transport) epc.setAttributeNS(None, "transport", self.transport)
if self.style: if self.style:
@@ -1205,7 +1210,8 @@ class SoapAddressBinding:
def toDom(self, node): def toDom(self, node):
wsdl = self.getWSDL() wsdl = self.getWSDL()
ep = ElementProxy(None, node) ep = ElementProxy(None, node)
epc = ep.createAppendElement(DOM.GetWSDLSoapBindingUri(wsdl.version), 'address')
epc = ep.createAppendElement(
DOM.GetWSDLSoapBindingUri(wsdl.version), 'address')
epc.setAttributeNS(None, "location", self.location) epc.setAttributeNS(None, "location", self.location)




@@ -1221,7 +1227,8 @@ class SoapOperationBinding:
def toDom(self, node): def toDom(self, node):
wsdl = self.getWSDL() wsdl = self.getWSDL()
ep = ElementProxy(None, node) ep = ElementProxy(None, node)
epc = ep.createAppendElement(DOM.GetWSDLSoapBindingUri(wsdl.version), 'operation')
epc = ep.createAppendElement(
DOM.GetWSDLSoapBindingUri(wsdl.version), 'operation')
if self.soapAction: if self.soapAction:
epc.setAttributeNS(None, 'soapAction', self.soapAction) epc.setAttributeNS(None, 'soapAction', self.soapAction)
if self.style: if self.style:
@@ -1248,7 +1255,8 @@ class SoapBodyBinding:
def toDom(self, node): def toDom(self, node):
wsdl = self.getWSDL() wsdl = self.getWSDL()
ep = ElementProxy(None, node) ep = ElementProxy(None, node)
epc = ep.createAppendElement(DOM.GetWSDLSoapBindingUri(wsdl.version), 'body')
epc = ep.createAppendElement(
DOM.GetWSDLSoapBindingUri(wsdl.version), 'body')
epc.setAttributeNS(None, "use", self.use) epc.setAttributeNS(None, "use", self.use)
epc.setAttributeNS(None, "namespace", self.namespace) epc.setAttributeNS(None, "namespace", self.namespace)


@@ -1271,7 +1279,8 @@ class SoapFaultBinding:
def toDom(self, node): def toDom(self, node):
wsdl = self.getWSDL() wsdl = self.getWSDL()
ep = ElementProxy(None, node) ep = ElementProxy(None, node)
epc = ep.createAppendElement(DOM.GetWSDLSoapBindingUri(wsdl.version), 'body')
epc = ep.createAppendElement(
DOM.GetWSDLSoapBindingUri(wsdl.version), 'body')
epc.setAttributeNS(None, "use", self.use) epc.setAttributeNS(None, "use", self.use)
epc.setAttributeNS(None, "name", self.name) epc.setAttributeNS(None, "name", self.name)
if self.namespace is not None: if self.namespace is not None:


+ 108
- 54
wstools/XMLSchema.py View File

@@ -94,7 +94,8 @@ class SchemaReader:
""" """
for schemaLocation, val in schema.includes.items(): for schemaLocation, val in schema.includes.items():
if schemaLocation in self._includes: if schemaLocation in self._includes:
schema.addIncludeSchema(schemaLocation, self._imports[schemaLocation])
schema.addIncludeSchema(
schemaLocation, self._imports[schemaLocation])


def addSchemaByLocation(self, location, schema): def addSchemaByLocation(self, location, schema):
"""provide reader with schema document for a location. """provide reader with schema document for a location.
@@ -303,7 +304,8 @@ class DOMAdapter(DOMAdapterInterface):
namespace = DOM.findNamespaceURI(prefix, self.__node) namespace = DOM.findNamespaceURI(prefix, self.__node)
except DOMException as ex: except DOMException as ex:
if prefix != 'xml': if prefix != 'xml':
raise SchemaError('%s namespace not declared for %s' % (prefix, self.__node._get_tagName()))
raise SchemaError('%s namespace not declared for %s' % (
prefix, self.__node._get_tagName()))
namespace = XMLNS.XML namespace = XMLNS.XML
return namespace return namespace


@@ -565,7 +567,8 @@ class XMLSchemaComponent(XMLBase, MarkerInterface):
and not (type(self.__class__.required) == type(XMLSchemaComponent.required) and not (type(self.__class__.required) == type(XMLSchemaComponent.required)
and type(self.__class__.attributes) == type(XMLSchemaComponent.attributes) and type(self.__class__.attributes) == type(XMLSchemaComponent.attributes)
and type(self.__class__.contents) == type(XMLSchemaComponent.contents)): and type(self.__class__.contents) == type(XMLSchemaComponent.contents)):
raise RuntimeError('Bad type for a class variable in %s' % self.__class__)
raise RuntimeError(
'Bad type for a class variable in %s' % self.__class__)


def getItemTrace(self): def getItemTrace(self):
"""Returns a node trace up to the <schema> item. """Returns a node trace up to the <schema> item.
@@ -642,11 +645,13 @@ class XMLSchemaComponent(XMLBase, MarkerInterface):
if not tdc: if not tdc:
return return


obj = self.getSchemaItem(collection, tdc.getTargetNamespace(), tdc.getName())
obj = self.getSchemaItem(
collection, tdc.getTargetNamespace(), tdc.getName())
if obj: if obj:
return obj return obj


# raise SchemaError, 'No schema item "%s" in collection %s' %(tdc, collection)
# raise SchemaError, 'No schema item "%s" in collection %s' %(tdc,
# collection)
return return


def getSchemaItem(self, collection, namespace, name): def getSchemaItem(self, collection, namespace, name):
@@ -663,14 +668,16 @@ class XMLSchemaComponent(XMLBase, MarkerInterface):
try: try:
obj = getattr(parent, collection)[name] obj = getattr(parent, collection)[name]
except KeyError as ex: except KeyError as ex:
raise KeyError('targetNamespace(%s) collection(%s) has no item(%s)' % (namespace, collection, name))
raise KeyError('targetNamespace(%s) collection(%s) has no item(%s)' % (
namespace, collection, name))


return obj return obj


if not namespace in parent.imports: if not namespace in parent.imports:
if namespace in BUILT_IN_NAMESPACES: if namespace in BUILT_IN_NAMESPACES:
# built-in just return # built-in just return
# WARNING: expecting import if "redefine" or add to built-in namespace.
# WARNING: expecting import if "redefine" or add to built-in
# namespace.
return return


raise SchemaError('schema "%s" does not import namespace "%s"' % ( raise SchemaError('schema "%s" does not import namespace "%s"' % (
@@ -688,7 +695,8 @@ class XMLSchemaComponent(XMLBase, MarkerInterface):
# built-in just return # built-in just return
return return


raise SchemaError('no schema instance for imported namespace (%s).' % (namespace))
raise SchemaError(
'no schema instance for imported namespace (%s).' % (namespace))


if not isinstance(schema, XMLSchema): if not isinstance(schema, XMLSchema):
raise TypeError('expecting XMLSchema instance not "%r"' % schema) raise TypeError('expecting XMLSchema instance not "%r"' % schema)
@@ -696,7 +704,8 @@ class XMLSchemaComponent(XMLBase, MarkerInterface):
try: try:
obj = getattr(schema, collection)[name] obj = getattr(schema, collection)[name]
except KeyError as ex: except KeyError as ex:
raise KeyError('targetNamespace(%s) collection(%s) has no item(%s)' % (namespace, collection, name))
raise KeyError('targetNamespace(%s) collection(%s) has no item(%s)' % (
namespace, collection, name))


return obj return obj


@@ -723,7 +732,8 @@ class XMLSchemaComponent(XMLBase, MarkerInterface):
""" """
if type(attribute) in (list, tuple): if type(attribute) in (list, tuple):
if len(attribute) != 2: if len(attribute) != 2:
raise LookupError('To access attributes must use name or (namespace,name)')
raise LookupError(
'To access attributes must use name or (namespace,name)')


ns_dict = self.attributes.get(attribute[0]) ns_dict = self.attributes.get(attribute[0])
if ns_dict is None: if ns_dict is None:
@@ -768,20 +778,24 @@ class XMLSchemaComponent(XMLBase, MarkerInterface):
for k, v in node.getAttributeDictionary().items(): for k, v in node.getAttributeDictionary().items():
prefix, value = SplitQName(k) prefix, value = SplitQName(k)
if value == XMLSchemaComponent.xmlns: if value == XMLSchemaComponent.xmlns:
self.attributes[value][prefix or XMLSchemaComponent.xmlns_key] = v
self.attributes[value][
prefix or XMLSchemaComponent.xmlns_key] = v
elif prefix: elif prefix:
ns = node.getNamespace(prefix) ns = node.getNamespace(prefix)
if not ns: if not ns:
raise SchemaError('no namespace for attribute prefix %s' % prefix)
raise SchemaError(
'no namespace for attribute prefix %s' % prefix)
if ns not in self.attributes: if ns not in self.attributes:
self.attributes[ns] = {} self.attributes[ns] = {}
elif value in self.attributes[ns]: elif value in self.attributes[ns]:
raise SchemaError('attribute %s declared multiple times in %s' % (value, ns))
raise SchemaError(
'attribute %s declared multiple times in %s' % (value, ns))
self.attributes[ns][value] = v self.attributes[ns][value] = v
elif not value in self.attributes: elif not value in self.attributes:
self.attributes[value] = v self.attributes[value] = v
else: else:
raise SchemaError('attribute %s declared multiple times' % value)
raise SchemaError(
'attribute %s declared multiple times' % value)


if not isinstance(self, WSDLToolsAdapter): if not isinstance(self, WSDLToolsAdapter):
self.__checkAttributes() self.__checkAttributes()
@@ -830,7 +844,8 @@ class XMLSchemaComponent(XMLBase, MarkerInterface):
""" """
for a in self.__class__.required: for a in self.__class__.required:
if not a in self.attributes: if not a in self.attributes:
raise SchemaError('class instance %s, missing required attribute %s' % (self.__class__, a))
raise SchemaError(
'class instance %s, missing required attribute %s' % (self.__class__, a))
for a, v in self.attributes.items(): for a, v in self.attributes.items():
# attribute #other, ie. not in empty namespace # attribute #other, ie. not in empty namespace
if type(v) is dict: if type(v) is dict:
@@ -842,7 +857,8 @@ class XMLSchemaComponent(XMLBase, MarkerInterface):


if (a not in self.__class__.attributes.keys()) and not\ if (a not in self.__class__.attributes.keys()) and not\
(self.isAttribute() and self.isReference()): (self.isAttribute() and self.isReference()):
raise SchemaError('%s, unknown attribute(%s, %s)' % (self.getItemTrace(), a, self.attributes[a]))
raise SchemaError('%s, unknown attribute(%s, %s)' % (
self.getItemTrace(), a, self.attributes[a]))




class WSDLToolsAdapter(XMLSchemaComponent): class WSDLToolsAdapter(XMLSchemaComponent):
@@ -968,7 +984,8 @@ class Annotation(XMLSchemaComponent):
#print_debug('class %s, any skipped' %self.__class__, 5) #print_debug('class %s, any skipped' %self.__class__, 5)
continue continue
else: else:
raise SchemaError('Unknown component (%s)' % (i.getTagName()))
raise SchemaError('Unknown component (%s)' %
(i.getTagName()))
self.content = tuple(content) self.content = tuple(content)


class Appinfo(XMLSchemaComponent): class Appinfo(XMLSchemaComponent):
@@ -1003,7 +1020,8 @@ class Annotation(XMLSchemaComponent):
#print_debug('class %s, any skipped' %self.__class__, 5) #print_debug('class %s, any skipped' %self.__class__, 5)
continue continue
else: else:
raise SchemaError('Unknown component (%s)' % (i.getTagName()))
raise SchemaError('Unknown component (%s)' %
(i.getTagName()))
self.content = tuple(content) self.content = tuple(content)




@@ -1386,7 +1404,8 @@ class XMLSchema(XMLSchemaComponent):
self.annotation = Annotation(self) self.annotation = Annotation(self)
self.annotation.fromDom(i) self.annotation.fromDom(i)
else: else:
raise SchemaError('Unknown component (%s)' % (i.getTagName()))
raise SchemaError('Unknown component (%s)' %
(i.getTagName()))


def getSchema(self): def getSchema(self):
"""if schema is not defined, first look for a Schema class instance """if schema is not defined, first look for a Schema class instance
@@ -1420,7 +1439,8 @@ class XMLSchema(XMLSchemaComponent):
self._schema = schema self._schema = schema


if 'schemaLocation' not in self.attributes: if 'schemaLocation' not in self.attributes:
raise NoSchemaLocationWarning('no schemaLocation attribute in import')
raise NoSchemaLocationWarning(
'no schemaLocation attribute in import')


reader.loadFromURL(self.attributes.get('schemaLocation'), schema) reader.loadFromURL(self.attributes.get('schemaLocation'), schema)


@@ -1456,7 +1476,8 @@ class XMLSchema(XMLSchemaComponent):
self.annotation = Annotation(self) self.annotation = Annotation(self)
self.annotation.fromDom(i) self.annotation.fromDom(i)
else: else:
raise SchemaError('Unknown component (%s)' % (i.getTagName()))
raise SchemaError('Unknown component (%s)' %
(i.getTagName()))


def getSchema(self): def getSchema(self):
"""if schema is not defined, first look for a Schema class instance """if schema is not defined, first look for a Schema class instance
@@ -1465,7 +1486,8 @@ class XMLSchema(XMLSchemaComponent):
""" """
if not self._schema: if not self._schema:
schema = self._parent() schema = self._parent()
self._schema = schema.getIncludeSchemas().get(self.attributes['schemaLocation'])
self._schema = schema.getIncludeSchemas().get(
self.attributes['schemaLocation'])
if not self._schema: if not self._schema:
url = self.attributes['schemaLocation'] url = self.attributes['schemaLocation']
reader = SchemaReader(base_url=schema.getBaseUrl()) reader = SchemaReader(base_url=schema.getBaseUrl())
@@ -1678,7 +1700,8 @@ class AttributeGroupDefinition(XMLSchemaComponent,
required = ['name'] required = ['name']
attributes = {'id': None, attributes = {'id': None,
'name': None} 'name': None}
contents = {'xsd': ['annotation', 'attribute', 'attributeGroup', 'anyAttribute']}
contents = {'xsd': ['annotation', 'attribute',
'attributeGroup', 'anyAttribute']}
tag = 'attributeGroup' tag = 'attributeGroup'


def __init__(self, parent): def __init__(self, parent):
@@ -1712,11 +1735,13 @@ class AttributeGroupDefinition(XMLSchemaComponent,
content[-1].fromDom(contents[indx]) content[-1].fromDom(contents[indx])
elif component == 'anyAttribute': elif component == 'anyAttribute':
if len(contents) != indx + 1: if len(contents) != indx + 1:
raise SchemaError('anyAttribute is out of order in %s' % self.getItemTrace())
raise SchemaError(
'anyAttribute is out of order in %s' % self.getItemTrace())
content.append(AttributeWildCard(self)) content.append(AttributeWildCard(self))
content[-1].fromDom(contents[indx]) content[-1].fromDom(contents[indx])
else: else:
raise SchemaError('Unknown component (%s)' % (contents[indx].getTagName()))
raise SchemaError('Unknown component (%s)' %
(contents[indx].getTagName()))


self.attr_content = tuple(content) self.attr_content = tuple(content)


@@ -1802,7 +1827,8 @@ class IdentityConstrants(XMLSchemaComponent):
fields[-1].fromDom(i) fields[-1].fromDom(i)
continue continue
else: else:
raise SchemaError('Unknown component (%s)' % (i.getTagName()))
raise SchemaError('Unknown component (%s)' %
(i.getTagName()))
else: else:
raise SchemaError('Unknown component (%s)' % (i.getTagName())) raise SchemaError('Unknown component (%s)' % (i.getTagName()))
self.fields = tuple(fields) self.fields = tuple(fields)
@@ -1824,9 +1850,11 @@ class IdentityConstrants(XMLSchemaComponent):
self.annotation = Annotation(self) self.annotation = Annotation(self)
self.annotation.fromDom(i) self.annotation.fromDom(i)
else: else:
raise SchemaError('Unknown component (%s)' % (i.getTagName()))
raise SchemaError(
'Unknown component (%s)' % (i.getTagName()))
else: else:
raise SchemaError('Unknown component (%s)' % (i.getTagName()))
raise SchemaError('Unknown component (%s)' %
(i.getTagName()))


class Selector(Constraint): class Selector(Constraint):


@@ -2023,7 +2051,8 @@ class ElementDeclaration(XMLSchemaComponent,


def setConstraints(self, constraints): def setConstraints(self, constraints):
self._constraints = tuple(constraints) self._constraints = tuple(constraints)
constraints = property(getConstraints, setConstraints, None, "tuple of key, keyref, unique constraints")
constraints = property(getConstraints, setConstraints,
None, "tuple of key, keyref, unique constraints")


def fromDom(self, node): def fromDom(self, node):
self.setAttributes(node) self.setAttributes(node)
@@ -2051,7 +2080,8 @@ class ElementDeclaration(XMLSchemaComponent,
constraints.append(Unique(self)) constraints.append(Unique(self))
constraints[-1].fromDom(i) constraints[-1].fromDom(i)
else: else:
raise SchemaError('Unknown component (%s)' % (i.getTagName()))
raise SchemaError('Unknown component (%s)' %
(i.getTagName()))
else: else:
raise SchemaError('Unknown component (%s)' % (i.getTagName())) raise SchemaError('Unknown component (%s)' % (i.getTagName()))


@@ -2104,7 +2134,8 @@ Local elements can be qualified or unqualifed according
return True return True
if form == 'unqualified': if form == 'unqualified':
return False return False
raise SchemaError('Bad form (%s) for element: %s' % (form, self.getItemTrace()))
raise SchemaError('Bad form (%s) for element: %s' %
(form, self.getItemTrace()))




class ElementReference(XMLSchemaComponent, class ElementReference(XMLSchemaComponent,
@@ -2153,7 +2184,8 @@ class ElementReference(XMLSchemaComponent,
self.annotation = Annotation(self) self.annotation = Annotation(self)
self.annotation.fromDom(i) self.annotation.fromDom(i)
else: else:
raise SchemaError('Unknown component (%s)' % (i.getTagName()))
raise SchemaError('Unknown component (%s)' %
(i.getTagName()))




class ElementWildCard(LocalElementDeclaration, WildCardMarker): class ElementWildCard(LocalElementDeclaration, WildCardMarker):
@@ -2209,7 +2241,8 @@ class ElementWildCard(LocalElementDeclaration, WildCardMarker):
self.annotation = Annotation(self) self.annotation = Annotation(self)
self.annotation.fromDom(i) self.annotation.fromDom(i)
else: else:
raise SchemaError('Unknown component (%s)' % (i.getTagName()))
raise SchemaError('Unknown component (%s)' %
(i.getTagName()))




###################################################### ######################################################
@@ -2267,7 +2300,8 @@ class Sequence(XMLSchemaComponent,
elif component == 'any': elif component == 'any':
content.append(ElementWildCard(self)) content.append(ElementWildCard(self))
else: else:
raise SchemaError('Unknown component (%s)' % (i.getTagName()))
raise SchemaError('Unknown component (%s)' %
(i.getTagName()))
content[-1].fromDom(i) content[-1].fromDom(i)
else: else:
raise SchemaError('Unknown component (%s)' % (i.getTagName())) raise SchemaError('Unknown component (%s)' % (i.getTagName()))
@@ -2317,7 +2351,8 @@ class All(XMLSchemaComponent,
else: else:
content.append(LocalElementDeclaration(self)) content.append(LocalElementDeclaration(self))
else: else:
raise SchemaError('Unknown component (%s)' % (i.getTagName()))
raise SchemaError('Unknown component (%s)' %
(i.getTagName()))
content[-1].fromDom(i) content[-1].fromDom(i)
else: else:
raise SchemaError('Unknown component (%s)' % (i.getTagName())) raise SchemaError('Unknown component (%s)' % (i.getTagName()))
@@ -2376,7 +2411,8 @@ class Choice(XMLSchemaComponent,
elif component == 'any': elif component == 'any':
content.append(ElementWildCard(self)) content.append(ElementWildCard(self))
else: else:
raise SchemaError('Unknown component (%s)' % (i.getTagName()))
raise SchemaError('Unknown component (%s)' %
(i.getTagName()))
content[-1].fromDom(i) content[-1].fromDom(i)
else: else:
raise SchemaError('Unknown component (%s)' % (i.getTagName())) raise SchemaError('Unknown component (%s)' % (i.getTagName()))
@@ -2426,7 +2462,8 @@ class ModelGroupDefinition(XMLSchemaComponent,
elif component == 'sequence' and not self.content: elif component == 'sequence' and not self.content:
self.content = Sequence(self) self.content = Sequence(self)
else: else:
raise SchemaError('Unknown component (%s)' % (i.getTagName()))
raise SchemaError('Unknown component (%s)' %
(i.getTagName()))
self.content.fromDom(i) self.content.fromDom(i)
else: else:
raise SchemaError('Unknown component (%s)' % (i.getTagName())) raise SchemaError('Unknown component (%s)' % (i.getTagName()))
@@ -2474,7 +2511,8 @@ class ModelGroupReference(XMLSchemaComponent,
self.annotation = Annotation(self) self.annotation = Annotation(self)
self.annotation.fromDom(i) self.annotation.fromDom(i)
else: else:
raise SchemaError('Unknown component (%s)' % (i.getTagName()))
raise SchemaError('Unknown component (%s)' %
(i.getTagName()))
else: else:
raise SchemaError('Unknown component (%s)' % (i.getTagName())) raise SchemaError('Unknown component (%s)' % (i.getTagName()))


@@ -2526,7 +2564,8 @@ class ComplexType(XMLSchemaComponent,
if m in ('true', '1'): if m in ('true', '1'):
return True return True


raise SchemaError('invalid value for attribute mixed(%s): %s' % (m, self.getItemTrace()))
raise SchemaError(
'invalid value for attribute mixed(%s): %s' % (m, self.getItemTrace()))


def getAttributeContent(self): def getAttributeContent(self):
return self.attr_content return self.attr_content
@@ -2582,13 +2621,15 @@ class ComplexType(XMLSchemaComponent,
if contents[indx].hasattr('ref'): if contents[indx].hasattr('ref'):
self.attr_content.append(AttributeReference(self)) self.attr_content.append(AttributeReference(self))
else: else:
self.attr_content.append(LocalAttributeDeclaration(self))
self.attr_content.append(
LocalAttributeDeclaration(self))
elif component == 'attributeGroup': elif component == 'attributeGroup':
self.attr_content.append(AttributeGroupReference(self)) self.attr_content.append(AttributeGroupReference(self))
elif component == 'anyAttribute': elif component == 'anyAttribute':
self.attr_content.append(AttributeWildCard(self)) self.attr_content.append(AttributeWildCard(self))
else: else:
raise SchemaError('Unknown component (%s): %s' % (contents[indx].getTagName(), self.getItemTrace()))
raise SchemaError('Unknown component (%s): %s' % (
contents[indx].getTagName(), self.getItemTrace()))
self.attr_content[-1].fromDom(contents[indx]) self.attr_content[-1].fromDom(contents[indx])
indx += 1 indx += 1


@@ -2617,9 +2658,11 @@ class ComplexType(XMLSchemaComponent,
elif component == 'extension' and not self.derivation: elif component == 'extension' and not self.derivation:
self.derivation = self.__class__.Extension(self) self.derivation = self.__class__.Extension(self)
else: else:
raise SchemaError('Unknown component (%s)' % (i.getTagName()))
raise SchemaError(
'Unknown component (%s)' % (i.getTagName()))
else: else:
raise SchemaError('Unknown component (%s)' % (i.getTagName()))
raise SchemaError('Unknown component (%s)' %
(i.getTagName()))
self.derivation.fromDom(i) self.derivation.fromDom(i)
self.content = self.derivation self.content = self.derivation


@@ -2650,7 +2693,8 @@ class ComplexType(XMLSchemaComponent,
return False return False
if m in ('true', '1'): if m in ('true', '1'):
return True return True
raise SchemaError('invalid value for attribute mixed(%s): %s' % (m, self.getItemTrace()))
raise SchemaError(
'invalid value for attribute mixed(%s): %s' % (m, self.getItemTrace()))


class _DerivationBase(XMLSchemaComponent): class _DerivationBase(XMLSchemaComponent):


@@ -2722,16 +2766,20 @@ class ComplexType(XMLSchemaComponent,
if contents[indx].hasattr('ref'): if contents[indx].hasattr('ref'):
self.attr_content.append(AttributeReference(self)) self.attr_content.append(AttributeReference(self))
else: else:
self.attr_content.append(LocalAttributeDeclaration(self))
self.attr_content.append(
LocalAttributeDeclaration(self))
elif component == 'attributeGroup': elif component == 'attributeGroup':
if contents[indx].hasattr('ref'): if contents[indx].hasattr('ref'):
self.attr_content.append(AttributeGroupReference(self))
self.attr_content.append(
AttributeGroupReference(self))
else: else:
self.attr_content.append(AttributeGroupDefinition(self))
self.attr_content.append(
AttributeGroupDefinition(self))
elif component == 'anyAttribute': elif component == 'anyAttribute':
self.attr_content.append(AttributeWildCard(self)) self.attr_content.append(AttributeWildCard(self))
else: else:
raise SchemaError('Unknown component (%s)' % (contents[indx].getTagName()))
raise SchemaError('Unknown component (%s)' %
(contents[indx].getTagName()))
self.attr_content[-1].fromDom(contents[indx]) self.attr_content[-1].fromDom(contents[indx])
indx += 1 indx += 1


@@ -2839,7 +2887,8 @@ class ComplexType(XMLSchemaComponent,
elif component == 'anyAttribute': elif component == 'anyAttribute':
content.append(AttributeWildCard(self)) content.append(AttributeWildCard(self))
else: else:
raise SchemaError('Unknown component (%s)' % (contents[indx].getTagName()))
raise SchemaError('Unknown component (%s)' %
(contents[indx].getTagName()))
content[-1].fromDom(contents[indx]) content[-1].fromDom(contents[indx])
indx += 1 indx += 1
self.attr_content = tuple(content) self.attr_content = tuple(content)
@@ -2907,7 +2956,8 @@ class ComplexType(XMLSchemaComponent,
self.content.append(AnonymousSimpleType(self)) self.content.append(AnonymousSimpleType(self))
self.content[-1].fromDom(contents[indx]) self.content[-1].fromDom(contents[indx])
else: else:
raise SchemaError('Unknown component (%s)' % (contents[indx].getTagName()))
raise SchemaError('Unknown component (%s)' %
(contents[indx].getTagName()))
content[-1].fromDom(contents[indx]) content[-1].fromDom(contents[indx])
indx += 1 indx += 1
self.attr_content = tuple(content) self.attr_content = tuple(content)
@@ -3007,7 +3057,8 @@ class SimpleType(XMLSchemaComponent,
""" """
attributes = {'id': None, attributes = {'id': None,
'base': None} 'base': None}
contents = {'xsd': ['annotation', 'simpleType'] + RestrictionMarker.facets}
contents = {'xsd': ['annotation', 'simpleType'] +
RestrictionMarker.facets}
tag = 'restriction' tag = 'restriction'


def __init__(self, parent): def __init__(self, parent):
@@ -3046,7 +3097,8 @@ class SimpleType(XMLSchemaComponent,
elif component in RestrictionMarker.facets: elif component in RestrictionMarker.facets:
self.facets.append(contents[indx]) self.facets.append(contents[indx])
else: else:
raise SchemaError('Unknown component (%s)' % (contents[indx].getTagName()))
raise SchemaError('Unknown component (%s)' %
(contents[indx].getTagName()))
self.content = tuple(content) self.content = tuple(content)


class Union(XMLSchemaComponent, class Union(XMLSchemaComponent,
@@ -3086,7 +3138,8 @@ class SimpleType(XMLSchemaComponent,
content.append(AnonymousSimpleType(self)) content.append(AnonymousSimpleType(self))
content[-1].fromDom(contents[indx]) content[-1].fromDom(contents[indx])
else: else:
raise SchemaError('Unknown component (%s)' % (contents[indx].getTagName()))
raise SchemaError('Unknown component (%s)' %
(contents[indx].getTagName()))
self.content = tuple(content) self.content = tuple(content)


class List(XMLSchemaComponent, class List(XMLSchemaComponent,
@@ -3139,7 +3192,8 @@ class SimpleType(XMLSchemaComponent,
self.content.fromDom(contents[indx]) self.content.fromDom(contents[indx])
break break
else: else:
raise SchemaError('Unknown component (%s)' % (contents[indx].getTagName()))
raise SchemaError('Unknown component (%s)' %
(contents[indx].getTagName()))




class AnonymousSimpleType(SimpleType, class AnonymousSimpleType(SimpleType,


+ 4
- 2
wstools/c14n.py View File

@@ -350,7 +350,8 @@ class _implementation:
n = "xmlns" # DOM bug workaround n = "xmlns" # DOM bug workaround
ns_local[n] = a.nodeValue ns_local[n] = a.nodeValue
elif a.namespaceURI == XMLNS.XML: elif a.namespaceURI == XMLNS.XML:
if inclusive or (in_subset and _in_subset(self.subset, a)): # 020925 Test to see if attribute node in subset
# 020925 Test to see if attribute node in subset
if inclusive or (in_subset and _in_subset(self.subset, a)):
xml_attrs_local[a.nodeName] = a # 0426 xml_attrs_local[a.nodeName] = a # 0426
else: else:
if _in_subset(self.subset, a): # 020925 Test to see if attribute node in subset if _in_subset(self.subset, a): # 020925 Test to see if attribute node in subset
@@ -428,7 +429,8 @@ class _implementation:
W('>') W('>')


# Push state, recurse, pop state. # Push state, recurse, pop state.
state, self.state = self.state, (ns_local, ns_rendered, xml_attrs, ns_unused_inherited)
state, self.state = self.state, (ns_local,
ns_rendered, xml_attrs, ns_unused_inherited)
for c in _children(node): for c in _children(node):
_implementation.handlers[c.nodeType](self, c) _implementation.handlers[c.nodeType](self, c)
self.state = state self.state = state


Loading…
Cancel
Save