Exemplo n.º 1
0
 def testQualified (self):
     # Top-level declarations are qualified regardless of presence/absence of form attribute.
     # Internal declarations follow form attribute or schema default
     for (m, ( efd, afd )) in six.iteritems(self.module_map):
         for (n, d) in six.iteritems(m.t._AttributeMap):
             if n.localName() in ('a', 'au', 'aq'):
                 self.assertEqual(n.namespace(), m.Namespace)
             elif 'taq' == n.localName():
                 self.assertEqual(n.namespace(), m.Namespace)
             elif 'tau' == n.localName():
                 self.assertEqual(n.namespace(), None)
             elif 'ta' == n.localName():
                 self.assertEqual(n.namespace(), afd)
             else:
                 self.assertFalse()
         for (n, d) in six.iteritems(m.t._ElementMap):
             if n.localName() in ('e', 'eu', 'eq'):
                 self.assertEqual(n.namespace(), m.Namespace)
             elif 'teq' == n.localName():
                 self.assertEqual(n.namespace(), m.Namespace)
             elif 'teu' == n.localName():
                 self.assertEqual(n.namespace(), None)
             elif 'te' == n.localName():
                 self.assertEqual(n.namespace(), efd)
             else:
                 self.assertFalse()
Exemplo n.º 2
0
    def rootSetOrder (self):
        """Return the nodes of the graph as a sequence of root sets.

        The first root set is the set of nodes that are roots: i.e.,
        have no incoming edges.  The second root set is the set of
        nodes that have incoming nodes in the first root set.  This
        continues until all nodes have been reached.  The sets impose
        a partial order on the nodes, without being as constraining as
        L{sccOrder}.

        @return: a list of the root sets."""
        order = []
        nodes = set(self.__nodes)
        edge_map = {}
        for (d, srcs) in six.iteritems(self.__edgeMap):
            edge_map[d] = srcs.copy()
        while nodes:
            freeset = set()
            for n in nodes:
                if not (n in edge_map):
                    freeset.add(n)
            if 0 == len(freeset):
                _log.error('dependency cycle in named components')
                return None
            order.append(freeset)
            nodes.difference_update(freeset)
            new_edge_map = {}
            for (d, srcs) in six.iteritems(edge_map):
                srcs.difference_update(freeset)
                if 0 != len(srcs):
                    new_edge_map[d] = srcs
            edge_map = new_edge_map
        return order
Exemplo n.º 3
0
 def testQualified(self):
     # Top-level declarations are qualified regardless of presence/absence of form attribute.
     # Internal declarations follow form attribute or schema default
     for (m, (efd, afd)) in six.iteritems(self.module_map):
         for (n, d) in six.iteritems(m.t._AttributeMap):
             if n.localName() in ('a', 'au', 'aq'):
                 self.assertEqual(n.namespace(), m.Namespace)
             elif 'taq' == n.localName():
                 self.assertEqual(n.namespace(), m.Namespace)
             elif 'tau' == n.localName():
                 self.assertEqual(n.namespace(), None)
             elif 'ta' == n.localName():
                 self.assertEqual(n.namespace(), afd)
             else:
                 self.assertFalse()
         for (n, d) in six.iteritems(m.t._ElementMap):
             if n.localName() in ('e', 'eu', 'eq'):
                 self.assertEqual(n.namespace(), m.Namespace)
             elif 'teq' == n.localName():
                 self.assertEqual(n.namespace(), m.Namespace)
             elif 'teu' == n.localName():
                 self.assertEqual(n.namespace(), None)
             elif 'te' == n.localName():
                 self.assertEqual(n.namespace(), efd)
             else:
                 self.assertFalse()
Exemplo n.º 4
0
 def _LexicalToKeywords(cls, text):
     lexical_re = cls.__LexicalREMap.get(cls)
     if lexical_re is None:
         pattern = '^' + cls._Lexical_fmt + '%Z?$'
         for (k, v) in six.iteritems(cls.__PatternMap):
             pattern = pattern.replace(k, v)
         lexical_re = re.compile(pattern)
         cls.__LexicalREMap[cls] = lexical_re
     match = lexical_re.match(text)
     if match is None:
         raise SimpleTypeValueError(cls, text)
     match_map = match.groupdict()
     kw = {}
     for (k, v) in six.iteritems(match_map):
         if (k in cls.__LexicalIntegerFields) and (v is not None):
             kw[k] = six.int_type(v)
     if '-' == match_map.get('negYear'):
         kw['year'] = -kw['year']
     if match_map.get('fracsec') is not None:
         kw['microsecond'] = six.int_type(
             round(1000000 * six.float_type('0%s' %
                                            (match_map['fracsec'], ))))
     else:
         # Discard any bogosity passed in by the caller
         kw.pop('microsecond', None)
     if match_map.get('tzinfo') is not None:
         kw['tzinfo'] = pyxb.utils.utility.UTCOffsetTimeZone(
             match_map['tzinfo'])
     else:
         kw.pop('tzinfo', None)
     return kw
Exemplo n.º 5
0
 def _LexicalToKeywords (cls, text):
     lexical_re = cls.__LexicalREMap.get(cls)
     if lexical_re is None:
         pattern = '^' + cls._Lexical_fmt + '%Z?$'
         for (k, v) in six.iteritems(cls.__PatternMap):
             pattern = pattern.replace(k, v)
         lexical_re = re.compile(pattern)
         cls.__LexicalREMap[cls] = lexical_re
     match = lexical_re.match(text)
     if match is None:
         raise SimpleTypeValueError(cls, text)
     match_map = match.groupdict()
     kw = { }
     for (k, v) in six.iteritems(match_map):
         if (k in cls.__LexicalIntegerFields) and (v is not None):
             kw[k] = six.int_type(v)
     if '-' == match_map.get('negYear'):
         kw['year'] = - kw['year']
     if match_map.get('fracsec') is not None:
         kw['microsecond'] = six.int_type(round(1000000 * six.float_type('0%s' % (match_map['fracsec'],))))
     else:
         # Discard any bogosity passed in by the caller
         kw.pop('microsecond', None)
     if match_map.get('tzinfo') is not None:
         kw['tzinfo'] = pyxb.utils.utility.UTCOffsetTimeZone(match_map['tzinfo'])
     else:
         kw.pop('tzinfo', None)
     return kw
Exemplo n.º 6
0
    def rootSetOrder (self):
        """Return the nodes of the graph as a sequence of root sets.

        The first root set is the set of nodes that are roots: i.e.,
        have no incoming edges.  The second root set is the set of
        nodes that have incoming nodes in the first root set.  This
        continues until all nodes have been reached.  The sets impose
        a partial order on the nodes, without being as constraining as
        L{sccOrder}.

        @return: a list of the root sets."""
        order = []
        nodes = set(self.__nodes)
        edge_map = {}
        for (d, srcs) in six.iteritems(self.__edgeMap):
            edge_map[d] = srcs.copy()
        while nodes:
            freeset = set()
            for n in nodes:
                if not (n in edge_map):
                    freeset.add(n)
            if 0 == len(freeset):
                _log.error('dependency cycle in named components')
                return None
            order.append(freeset)
            nodes.difference_update(freeset)
            new_edge_map = {}
            for (d, srcs) in six.iteritems(edge_map):
                srcs.difference_update(freeset)
                if 0 != len(srcs):
                    new_edge_map[d] = srcs
            edge_map = new_edge_map
        return order
Exemplo n.º 7
0
def emitCategoryMap(data_file):
    category_map = {}
    unicode_data = open(data_file)
    range_first = None
    last_codepoint = -1
    while True:
        line = unicode_data.readline()
        fields = line.split(';')
        if 1 >= len(fields):
            break
        codepoint = int(fields[0], 16)
        char_name = fields[1]
        category = fields[2]

        # If code points are are not listed in the file, they are in the Cn category.
        if range_first is None and last_codepoint + 1 != codepoint:
            category_map.setdefault('Cn', []).append(
                (last_codepoint + 1, codepoint))
            category_map.setdefault('C', []).append(
                (last_codepoint + 1, codepoint))
        last_codepoint = codepoint

        if char_name.endswith(', First>'):
            assert range_first is None
            range_first = codepoint
            continue
        if range_first is not None:
            assert char_name.endswith(', Last>')
            codepoint = (range_first, codepoint)
            range_first = None
        category_map.setdefault(category, []).append(codepoint)
        category_map.setdefault(category[0], []).append(codepoint)

    # Code points at the end of the Unicode range that are are not listed in
    # the file are in the Cn category.
    category_map.setdefault('Cn', []).append((last_codepoint + 1, 0x10FFFF))
    category_map.setdefault('C', []).append((last_codepoint + 1, 0x10FFFF))

    for k, v in six.iteritems(category_map):
        category_map[k] = condenseCodepoints(v)

    print('# Unicode general category properties: %d properties' %
          (len(category_map), ))
    print('PropertyMap = {')
    for (k, v) in sorted(six.iteritems(category_map)):
        print('  # %s: %d codepoint groups (%d codepoints)' %
              (k, len(v), countCodepoints(v)))
        print("  %-4s : CodePointSet([" % ("'%s'" % k, ))
        print("           %s" % (rangesToPython(v, indent=11, width=67), ))
        print("         ]),")
    print('  }')
Exemplo n.º 8
0
 def testFindWsu(self):
     self.assertEqual(3, len(wsse.tAttributedString._AttributeMap))
     for (n, ad) in six.iteritems(wsse.tAttributedString._AttributeMap):
         if (n.localName() == "agu"):
             self.assertEqual(None, n.namespace())
         else:
             self.assertEqual(wsu.Namespace, n.namespace())
     self.assertEqual(2, len(wsse.tComplexElt._ElementMap))
     for (n, ad) in six.iteritems(wsse.tComplexElt._ElementMap):
         if n.localName() == 'Elt':
             self.assertEqual(wsu.Namespace, n.namespace())
         elif n.localName() == 'local':
             self.assertEqual(None, n.namespace())
         else:
             self.assertFalse()
Exemplo n.º 9
0
 def testFindWsu (self):
     self.assertEqual(3, len(wsse.tAttributedString._AttributeMap))
     for (n, ad) in six.iteritems(wsse.tAttributedString._AttributeMap):
         if (n.localName() == "agu"):
             self.assertEqual(None, n.namespace())
         else:
             self.assertEqual(wsu.Namespace, n.namespace())
     self.assertEqual(2, len(wsse.tComplexElt._ElementMap))
     for (n, ad) in six.iteritems(wsse.tComplexElt._ElementMap):
         if n.localName() == 'Elt':
             self.assertEqual(wsu.Namespace, n.namespace())
         elif n.localName() == 'local':
             self.assertEqual(None, n.namespace())
         else:
             self.assertFalse()
Exemplo n.º 10
0
    def initialNamespaceContext(self):
        """Obtain the namespace context to be used when creating components in this namespace.

        Usually applies only to built-in namespaces, but is also used in the
        autotests when creating a namespace without a xs:schema element.  .
        Note that we must create the instance dynamically, since the
        information that goes into it has cross-dependencies that can't be
        resolved until this module has been completely loaded."""

        if self.__initialNamespaceContext is None:
            isn = {}
            if self.__contextInScopeNamespaces is not None:
                for (k, v) in six.iteritems(self.__contextInScopeNamespaces):
                    isn[k] = self.__identifyNamespace(v)
            kw = {
                'target_namespace':
                self,
                'default_namespace':
                self.__identifyNamespace(self.__contextDefaultNamespace),
                'in_scope_namespaces':
                isn
            }
            self.__initialNamespaceContext = resolution.NamespaceContext(
                None, **kw)
        return self.__initialNamespaceContext
Exemplo n.º 11
0
def _InitializeAllEsc ():
    """Set the values in _AllEsc without introducing C{k} and C{v} into
    the module."""

    _AllEsc.update({ six.u('.'): pyxb.utils.unicode.WildcardEsc })
    bs = six.unichr(0x5c)
    for k, v in six.iteritems(pyxb.utils.unicode.SingleCharEsc):
        _AllEsc[bs + six.text_type(k)] = v
    for k, v in six.iteritems(pyxb.utils.unicode.MultiCharEsc):
        _AllEsc[bs + six.text_type(k)] = v
    for k, v in six.iteritems(pyxb.utils.unicode.catEsc):
        _AllEsc[bs + six.text_type(k)] = v
    for k, v in six.iteritems(pyxb.utils.unicode.complEsc):
        _AllEsc[bs + six.text_type(k)] = v
    for k, v in six.iteritems(pyxb.utils.unicode.IsBlockEsc):
        _AllEsc[bs + six.text_type(k)] = v
Exemplo n.º 12
0
 def _loadCategoryObjects (self, category_objects):
     assert self.__categoryObjects is None
     assert not self.__constructedLocally
     ns = self.namespace()
     ns.configureCategories(six.iterkeys(category_objects))
     for (cat, obj_map) in six.iteritems(category_objects):
         current_map = ns.categoryMap(cat)
         for (local_name, component) in six.iteritems(obj_map):
             existing_component = current_map.get(local_name)
             if existing_component is None:
                 current_map[local_name] = component
             elif existing_component._allowUpdateFromOther(component):
                 existing_component._updateFromOther(component)
             else:
                 raise pyxb.NamespaceError(self, 'Load attempted to override %s %s in %s' % (cat, local_name, self.namespace()))
     self.markIncorporated()
Exemplo n.º 13
0
 def isActive (self, empty_inactive=False):
     if self.__isActive and empty_inactive:
         for (ct, cm) in six.iteritems(self._categoryMap()):
             if 0 < len(cm):
                 return True
         return False
     return self.__isActive
Exemplo n.º 14
0
 def isActive(self, empty_inactive=False):
     if self.__isActive and empty_inactive:
         for (ct, cm) in six.iteritems(self._categoryMap()):
             if 0 < len(cm):
                 return True
         return False
     return self.__isActive
Exemplo n.º 15
0
def _InitializeAllEsc():
    """Set the values in _AllEsc without introducing C{k} and C{v} into
    the module."""

    _AllEsc.update({six.u('.'): pyxb.utils.unicode.WildcardEsc})
    bs = six.unichr(0x5c)
    for k, v in six.iteritems(pyxb.utils.unicode.SingleCharEsc):
        _AllEsc[bs + six.text_type(k)] = v
    for k, v in six.iteritems(pyxb.utils.unicode.MultiCharEsc):
        _AllEsc[bs + six.text_type(k)] = v
    for k, v in six.iteritems(pyxb.utils.unicode.catEsc):
        _AllEsc[bs + six.text_type(k)] = v
    for k, v in six.iteritems(pyxb.utils.unicode.complEsc):
        _AllEsc[bs + six.text_type(k)] = v
    for k, v in six.iteritems(pyxb.utils.unicode.IsBlockEsc):
        _AllEsc[bs + six.text_type(k)] = v
Exemplo n.º 16
0
    def __getstate__ (self):
        state = self.__dict__.copy()
        # Note that the aggregate set is stored in a class variable
        # with a slightly different name than the class-level set.
        attr = '_%s%s_' % (self.__class__.__name__, self.__Attribute)
        skipped = getattr(self.__class__, attr, None)
        if skipped is None:
            skipped = set()
            for cl in self.__class__.mro():
                for (k, v) in six.iteritems(cl.__dict__):
                    if k.endswith(self.__Attribute):
                        cl2 = k[:-len(self.__Attribute)]
                        skipped.update([ '%s__%s' % (cl2, _n) for _n in v ])
            setattr(self.__class__, attr, skipped)
        for k in skipped:
            if state.get(k) is not None:
                del state[k]
        # Uncomment the following to test whether undesirable types
        # are being pickled, generally by accidently leaving a
        # reference to one in an instance private member.
        #for (k, v) in six.iteritems(state):
        #    import pyxb.namespace
        #    import xml.dom
        #    import pyxb.xmlschema.structures
        #    if isinstance(v, (pyxb.namespace.NamespaceContext, xml.dom.Node, pyxb.xmlschema.structures.Schema)):
        #        raise pyxb.LogicError('Unexpected instance of %s key %s in %s' % (type(v), k, self))

        return state
Exemplo n.º 17
0
    def __getstate__ (self):
        state = self.__dict__.copy()
        # Note that the aggregate set is stored in a class variable
        # with a slightly different name than the class-level set.
        attr = '_%s%s_' % (self.__class__.__name__, self.__Attribute)
        skipped = getattr(self.__class__, attr, None)
        if skipped is None:
            skipped = set()
            for cl in self.__class__.mro():
                for (k, v) in six.iteritems(cl.__dict__):
                    if k.endswith(self.__Attribute):
                        cl2 = k[:-len(self.__Attribute)]
                        skipped.update([ '%s__%s' % (cl2, _n) for _n in v ])
            setattr(self.__class__, attr, skipped)
        for k in skipped:
            if state.get(k) is not None:
                del state[k]
        # Uncomment the following to test whether undesirable types
        # are being pickled, generally by accidently leaving a
        # reference to one in an instance private member.
        #for (k, v) in six.iteritems(state):
        #    import pyxb.namespace
        #    import xml.dom
        #    import pyxb.xmlschema.structures
        #    if isinstance(v, (pyxb.namespace.NamespaceContext, xml.dom.Node, pyxb.xmlschema.structures.Schema)):
        #        raise pyxb.LogicError('Unexpected instance of %s key %s in %s' % (type(v), k, self))

        return state
Exemplo n.º 18
0
    def __validateModules(self):
        self.__validatePrerequisites(self._STAGE_validateModules)
        for mr in self.__moduleRecords:
            ns = mr.namespace()
            for base_uid in mr.dependsOnExternal():
                xmr = ns.lookupModuleRecordByUID(base_uid)
                if xmr is None:
                    raise pyxb.NamespaceArchiveError(
                        'Module %s depends on external module %s, not available in archive path'
                        % (mr.generationUID(), base_uid))
                if not xmr.isIncorporated():
                    _log.info('Need to incorporate data from %s', xmr)
                else:
                    _log.info('Have required base data %s', xmr)

            for origin in mr.origins():
                for (cat, names) in six.iteritems(origin.categoryMembers()):
                    if not (cat in ns.categories()):
                        continue
                    cross_objects = names.intersection(
                        six.iterkeys(ns.categoryMap(cat)))
                    if 0 < len(cross_objects):
                        raise pyxb.NamespaceArchiveError(
                            'Archive %s namespace %s module %s origin %s archive/active conflict on category %s: %s'
                            % (self.__archivePath, ns, mr, origin, cat,
                               " ".join(cross_objects)))
                    _log.info('%s no conflicts on %d names', cat, len(names))
Exemplo n.º 19
0
def emitCategoryMap (data_file):
    category_map = {}
    unicode_data = open(data_file)
    range_first = None
    last_codepoint = -1
    while True:
        line = unicode_data.readline()
        fields = line.split(';')
        if 1 >= len(fields):
            break
        codepoint = int(fields[0], 16)
        char_name = fields[1]
        category = fields[2]

        # If code points are are not listed in the file, they are in the Cn category.
        if range_first is None and last_codepoint + 1 != codepoint:
            category_map.setdefault('Cn', []).append((last_codepoint + 1, codepoint))
            category_map.setdefault('C', []).append((last_codepoint + 1, codepoint))
        last_codepoint = codepoint

        if char_name.endswith(', First>'):
            assert range_first is None
            range_first = codepoint
            continue
        if range_first is not None:
            assert char_name.endswith(', Last>')
            codepoint = ( range_first, codepoint )
            range_first = None
        category_map.setdefault(category, []).append(codepoint)
        category_map.setdefault(category[0], []).append(codepoint)

    # Code points at the end of the Unicode range that are are not listed in
    # the file are in the Cn category.
    category_map.setdefault('Cn', []).append((last_codepoint + 1, 0x10FFFF))
    category_map.setdefault('C', []).append((last_codepoint + 1, 0x10FFFF))

    for k, v in six.iteritems(category_map):
        category_map[k] = condenseCodepoints(v)

    print('# Unicode general category properties: %d properties' % (len(category_map),))
    print('PropertyMap = {')
    for (k, v) in sorted(six.iteritems(category_map)):
        print('  # %s: %d codepoint groups (%d codepoints)' % (k, len(v), countCodepoints(v)))
        print("  %-4s : CodePointSet([" % ("'%s'" % k,))
        print("           %s" % (rangesToPython(v, indent=11, width=67),))
        print("         ]),")
    print('  }')
Exemplo n.º 20
0
 def __BuildInitialPrefixMap (cls):
     if cls.__InitialScopeNamespaces is not None:
         return
     from pyxb.namespace import builtin
     cls.__InitialScopeNamespaces = builtin._UndeclaredNamespaceMap
     cls.__InitialScopePrefixes = {}
     for (pfx, ns) in six.iteritems(cls.__InitialScopeNamespaces):
         cls.__InitialScopePrefixes.setdefault(ns, set()).add(pfx)
Exemplo n.º 21
0
 def testIterItems(self):
     vals = set()
     for ee in six.iteritems(cards):
         self.assertTrue(
             isinstance(ee,
                        cards._CF_enumeration._CollectionFacet_itemType))
         vals.add(ee.value())
     self.assertEqual(self.Expected, vals)
Exemplo n.º 22
0
 def __BuildInitialPrefixMap(cls):
     if cls.__InitialScopeNamespaces is not None:
         return
     from pyxb.namespace import builtin
     cls.__InitialScopeNamespaces = builtin._UndeclaredNamespaceMap
     cls.__InitialScopePrefixes = {}
     for (pfx, ns) in six.iteritems(cls.__InitialScopeNamespaces):
         cls.__InitialScopePrefixes.setdefault(ns, set()).add(pfx)
Exemplo n.º 23
0
    def _associateOrigins (self, module_record):
        """Add links from L{pyxb.namespace.archive._ObjectOrigin} instances.

        For any resolvable item in this namespace from an origin managed by
        the module_record, ensure that item can be found via a lookup through
        that origin.

        This allows these items to be found when a single namespace comprises
        items translated from different schema at different times using
        archives to maintain consistency."""
        assert module_record.namespace() == self
        module_record.resetCategoryObjects()
        self.configureCategories([archive.NamespaceArchive._AnonymousCategory()])
        origin_set = module_record.origins()
        for (cat, cat_map) in six.iteritems(self.__categoryMap):
            for (n, v) in six.iteritems(cat_map):
                if isinstance(v, archive._ArchivableObject_mixin) and (v._objectOrigin() in origin_set):
                    v._objectOrigin().addCategoryMember(cat, n, v)
Exemplo n.º 24
0
 def _loadCategoryObjects(self, category_objects):
     assert self.__categoryObjects is None
     assert not self.__constructedLocally
     ns = self.namespace()
     ns.configureCategories(six.iterkeys(category_objects))
     for (cat, obj_map) in six.iteritems(category_objects):
         current_map = ns.categoryMap(cat)
         for (local_name, component) in six.iteritems(obj_map):
             existing_component = current_map.get(local_name)
             if existing_component is None:
                 current_map[local_name] = component
             elif existing_component._allowUpdateFromOther(component):
                 existing_component._updateFromOther(component)
             else:
                 raise pyxb.NamespaceError(
                     self, 'Load attempted to override %s %s in %s' %
                     (cat, local_name, self.namespace()))
     self.markIncorporated()
Exemplo n.º 25
0
 def testWildcard (self):
     instance = CreateFromDocument(self.xmls_wc)
     self.assertEqual(instance.attrib1, None)
     self.assertEqual(instance.attrib2, "text2")
     wca = instance.wildcardAttributeMap()
     self.assertEqual(1, len(wca))
     (attr, val) = next(six.iteritems(wca))
     self.assertEqual(attr.namespaceURI(), "urn:other")
     self.assertEqual(attr.localName(), "attrib3")
     self.assertEqual(val, "text3")
Exemplo n.º 26
0
 def testWildcard(self):
     instance = CreateFromDocument(self.xmls_wc)
     self.assertEqual(instance.attrib1, None)
     self.assertEqual(instance.attrib2, "text2")
     wca = instance.wildcardAttributeMap()
     self.assertEqual(1, len(wca))
     (attr, val) = next(six.iteritems(wca))
     self.assertEqual(attr.namespaceURI(), "urn:other")
     self.assertEqual(attr.localName(), "attrib3")
     self.assertEqual(val, "text3")
Exemplo n.º 27
0
 def details(self):
     import pyxb.binding.basis
     import pyxb.binding.content
     i = self.instance
     rv = []
     if i._element() is not None:
         rv.append('The containing element %s is defined at %s.' %
                   (i._element().name(), i._element().xsdLocation()))
     rv.append(
         'The containing element type %s is defined at %s' %
         (self.instance._Name(), six.text_type(self.instance._XSDLocation)))
     rv.append('The %s automaton %s in an accepting state.' %
               (self.instance._Name(),
                self.fac_configuration.isAccepting() and "is" or "is not"))
     if self.symbols is None:
         rv.append('Any accepted content has been stored in instance')
     elif 0 == len(self.symbols):
         rv.append('No content has been accepted')
     else:
         rv.append('The last accepted content was %s' %
                   (self.symbols[-1].value._diagnosticName(), ))
     if isinstance(self.instance, pyxb.binding.basis.complexTypeDefinition
                   ) and self.instance._IsMixed():
         rv.append('Character information content would be permitted.')
     acceptable = self.fac_configuration.acceptableSymbols()
     if 0 == len(acceptable):
         rv.append(
             'No elements or wildcards would be accepted at this point.')
     else:
         rv.append(
             'The following element and wildcard content would be accepted:'
         )
         rv2 = []
         for u in acceptable:
             if isinstance(u, pyxb.binding.content.ElementUse):
                 rv2.append('An element %s per %s' %
                            (u.elementBinding().name(), u.xsdLocation()))
             else:
                 assert isinstance(u, pyxb.binding.content.WildcardUse)
                 rv2.append('A wildcard per %s' % (u.xsdLocation(), ))
         rv.append('\t' + '\n\t'.join(rv2))
     if (self.symbol_set is None) or (0 == len(self.symbol_set)):
         rv.append('No content remains unconsumed')
     else:
         rv.append(
             'The following content was not processed by the automaton:')
         rv2 = []
         for (ed, syms) in six.iteritems(self.symbol_set):
             if ed is None:
                 rv2.append('xs:any (%u instances)' % (len(syms), ))
             else:
                 rv2.append('%s (%u instances)' % (ed.name(), len(syms)))
         rv.append('\t' + '\n\t'.join(rv2))
     return '\n'.join(rv)
Exemplo n.º 28
0
 def __str__ (self):
     rv = [ six.u('NamespaceContext ') ]
     if self.defaultNamespace() is not None:
         rv.extend([ '(defaultNamespace=', six.text_type(self.defaultNamespace()), ') '])
     if self.targetNamespace() is not None:
         rv.extend([ '(targetNamespace=', six.text_type(self.targetNamespace()), ') '])
     rv.append("\n")
     for (pfx, ns) in six.iteritems(self.inScopeNamespaces()):
         if pfx is not None:
             rv.append('  xmlns:%s=%s' % (pfx, six.text_type(ns)))
     return six.u('').join(rv)
Exemplo n.º 29
0
    def _replaceComponent_csc (self, existing_def, replacement_def):
        """Replace a component definition where present in the category maps.

        @note: This is a high-cost operation, as every item in every category
        map must be examined to see whether its value field matches
        C{existing_def}."""
        for (cat, registry) in six.iteritems(self.__categoryMap):
            for (k, v) in registry.items(): # NB: Not iteritems
                if v == existing_def:
                    del registry[k]
                    if replacement_def is not None:
                        registry[k] = replacement_def
        return getattr(super(_NamespaceCategory_mixin, self), '_replaceComponent_csc', lambda *args, **kw: replacement_def)(existing_def, replacement_def)
Exemplo n.º 30
0
 def _loadNamedObjects (self, category_map):
     """Add the named objects from the given map into the set held by this namespace.
     It is an error to name something which is already present."""
     self.configureCategories(six.iterkeys(category_map))
     for category in six.iterkeys(category_map):
         current_map = self.categoryMap(category)
         new_map = category_map[category]
         for (local_name, component) in six.iteritems(new_map):
             existing_component = current_map.get(local_name)
             if existing_component is None:
                 current_map[local_name] = component
             elif existing_component._allowUpdateFromOther(component):
                 existing_component._updateFromOther(component)
             else:
                 raise pyxb.NamespaceError(self, 'Load attempted to override %s %s in %s' % (category, local_name, self.uri()))
     self.__defineCategoryAccessors()
Exemplo n.º 31
0
 def testException (self):
     instance = trac26.eTranslateCard(trac26.eConcCardCymru('un'))
     instance.cardinal = 1
     with self.assertRaises(pyxb.IncompleteElementContentError) as cm:
         instance.validateBinding()
     e = cm.exception
     self.assertFalse(e.fac_configuration.isAccepting())
     self.assertEqual(1, len(e.symbols))
     self.assertEqual(1, len(e.symbol_set))
     (ed, syms) = next(six.iteritems(e.symbol_set))
     self.assertEqual(1, len(syms))
     self.assertEqual(instance.cardinal, syms[0])
     expect = self.Bad_details
     if pyxb.XMLStyle_minidom == pyxb._XMLStyle:
         expect = self.Bad_details_noloc
     self.assertEqual(e.details(), expect)
Exemplo n.º 32
0
 def testException(self):
     instance = trac26.eTranslateCard(trac26.eConcCardCymru('un'))
     instance.cardinal = 1
     with self.assertRaises(pyxb.IncompleteElementContentError) as cm:
         instance.validateBinding()
     e = cm.exception
     self.assertFalse(e.fac_configuration.isAccepting())
     self.assertEqual(1, len(e.symbols))
     self.assertEqual(1, len(e.symbol_set))
     (ed, syms) = next(six.iteritems(e.symbol_set))
     self.assertEqual(1, len(syms))
     self.assertEqual(instance.cardinal, syms[0])
     expect = self.Bad_details
     if pyxb.XMLStyle_minidom == pyxb._XMLStyle:
         expect = self.Bad_details_noloc
     self.assertEqual(e.details(), expect)
Exemplo n.º 33
0
    def _defineBuiltins_ox (self, structures_module):
        """Register the built-in types into the XMLSchema namespace."""

        # Defer the definitions to the structures module
        assert structures_module is not None
        structures_module._AddSimpleTypes(self)

        # A little validation here
        assert structures_module.ComplexTypeDefinition.UrTypeDefinition() == self.typeDefinitions()['anyType']
        assert structures_module.SimpleTypeDefinition.SimpleUrTypeDefinition() == self.typeDefinitions()['anySimpleType']

        # Provide access to the binding classes
        self.configureCategories(['typeBinding', 'elementBinding'])
        for ( en, td ) in six.iteritems(self.typeDefinitions()):
            if td.pythonSupport() is not None:
                self.addCategoryObject('typeBinding', en, td.pythonSupport())
Exemplo n.º 34
0
 def testException(self):
     instance = trac26.eTranslateCardMulti(trac26.eConcCardCymru('un'),
                                           trac26.eConcCardEnglish('one'),
                                           xs.int(1))
     self.assertTrue(instance.validateBinding())
     instance.cardinal.append(2)
     with self.assertRaises(pyxb.UnprocessedElementContentError) as cm:
         instance.validateBinding()
     e = cm.exception
     self.assertTrue(e.fac_configuration.isAccepting())
     self.assertEqual(3, len(e.symbols))
     self.assertEqual(1, len(e.symbol_set))
     (ed, syms) = next(six.iteritems(e.symbol_set))
     self.assertEqual(1, len(syms))
     self.assertEqual(instance.cardinal[1], syms[0])
     if pyxb.XMLStyle_minidom != pyxb._XMLStyle:
         self.assertEqual(e.details(), self.Bad_details)
Exemplo n.º 35
0
 def testException (self):
     instance = trac26.eTranslateCardMulti(trac26.eConcCardCymru('un'),
                                           trac26.eConcCardEnglish('one'),
                                           xs.int(1))
     self.assertTrue(instance.validateBinding())
     instance.cardinal.append(2)
     with self.assertRaises(pyxb.UnprocessedElementContentError) as cm:
         instance.validateBinding()
     e = cm.exception
     self.assertTrue(e.fac_configuration.isAccepting())
     self.assertEqual(3, len(e.symbols))
     self.assertEqual(1, len(e.symbol_set))
     (ed, syms) = next(six.iteritems(e.symbol_set))
     self.assertEqual(1, len(syms))
     self.assertEqual(instance.cardinal[1], syms[0])
     if pyxb.XMLStyle_minidom != pyxb._XMLStyle:
         self.assertEqual(e.details(), self.Bad_details)
Exemplo n.º 36
0
 def __str__(self):
     rv = [six.u('NamespaceContext ')]
     if self.defaultNamespace() is not None:
         rv.extend([
             '(defaultNamespace=',
             six.text_type(self.defaultNamespace()), ') '
         ])
     if self.targetNamespace() is not None:
         rv.extend([
             '(targetNamespace=',
             six.text_type(self.targetNamespace()), ') '
         ])
     rv.append("\n")
     for (pfx, ns) in six.iteritems(self.inScopeNamespaces()):
         if pfx is not None:
             rv.append('  xmlns:%s=%s' % (pfx, six.text_type(ns)))
     return six.u('').join(rv)
 def make_path(self, node, elements):
     if elements:
         elem = elements[0]
         children = node.xpath(elem, namespaces=self.NSMAP)
         if not children:
             name = elements[0]
             for ns, url in six.iteritems(self.NSMAP):
                 ns_token = ns + ':'
                 url_token = '{' + url + '}'
                 name = name.replace(ns_token, url_token)
             child = etree.Element(name)
             node.insert(0, child)
             node.insert(0, etree.Comment(" section added by maintainer "))
             self.reformat(node, node[:2])
         else:
             child = children[0]
         return self.make_path(child, elements[1:])
     return node
Exemplo n.º 38
0
    def _defineBuiltins_ox(self, structures_module):
        """Register the built-in types into the XMLSchema namespace."""

        # Defer the definitions to the structures module
        assert structures_module is not None
        structures_module._AddSimpleTypes(self)

        # A little validation here
        assert structures_module.ComplexTypeDefinition.UrTypeDefinition(
        ) == self.typeDefinitions()['anyType']
        assert structures_module.SimpleTypeDefinition.SimpleUrTypeDefinition(
        ) == self.typeDefinitions()['anySimpleType']

        # Provide access to the binding classes
        self.configureCategories(['typeBinding', 'elementBinding'])
        for (en, td) in six.iteritems(self.typeDefinitions()):
            if td.pythonSupport() is not None:
                self.addCategoryObject('typeBinding', en, td.pythonSupport())
Exemplo n.º 39
0
    def initialNamespaceContext (self):
        """Obtain the namespace context to be used when creating components in this namespace.

        Usually applies only to built-in namespaces, but is also used in the
        autotests when creating a namespace without a xs:schema element.  .
        Note that we must create the instance dynamically, since the
        information that goes into it has cross-dependencies that can't be
        resolved until this module has been completely loaded."""

        if self.__initialNamespaceContext is None:
            isn = { }
            if self.__contextInScopeNamespaces is not None:
                for (k, v) in six.iteritems(self.__contextInScopeNamespaces):
                    isn[k] = self.__identifyNamespace(v)
            kw = { 'target_namespace' : self
                 , 'default_namespace' : self.__identifyNamespace(self.__contextDefaultNamespace)
                 , 'in_scope_namespaces' : isn }
            self.__initialNamespaceContext = resolution.NamespaceContext(None, **kw)
        return self.__initialNamespaceContext
Exemplo n.º 40
0
 def details (self):
     import pyxb.binding.basis
     import pyxb.binding.content
     i = self.instance
     rv = [ ]
     if i._element() is not None:
         rv.append('The containing element %s is defined at %s.' % (i._element().name(), i._element().xsdLocation()))
     rv.append('The containing element type %s is defined at %s' % (self.instance._Name(), six.text_type(self.instance._XSDLocation)))
     rv.append('The %s automaton %s in an accepting state.' % (self.instance._Name(), self.fac_configuration.isAccepting() and "is" or "is not"))
     if self.symbols is None:
         rv.append('Any accepted content has been stored in instance')
     elif 0 == len(self.symbols):
         rv.append('No content has been accepted')
     else:
         rv.append('The last accepted content was %s' % (self.symbols[-1].value._diagnosticName(),))
     if isinstance(self.instance, pyxb.binding.basis.complexTypeDefinition) and self.instance._IsMixed():
         rv.append('Character information content would be permitted.')
     acceptable = self.fac_configuration.acceptableSymbols()
     if 0 == len(acceptable):
         rv.append('No elements or wildcards would be accepted at this point.')
     else:
         rv.append('The following element and wildcard content would be accepted:')
         rv2 = []
         for u in acceptable:
             if isinstance(u, pyxb.binding.content.ElementUse):
                 rv2.append('An element %s per %s' % (u.elementBinding().name(), u.xsdLocation()))
             else:
                 assert isinstance(u, pyxb.binding.content.WildcardUse)
                 rv2.append('A wildcard per %s' % (u.xsdLocation(),))
         rv.append('\t' + '\n\t'.join(rv2))
     if (self.symbol_set is None) or (0 == len(self.symbol_set)):
         rv.append('No content remains unconsumed')
     else:
         rv.append('The following content was not processed by the automaton:')
         rv2 = []
         for (ed, syms) in six.iteritems(self.symbol_set):
             if ed is None:
                 rv2.append('xs:any (%u instances)' % (len(syms),))
             else:
                 rv2.append('%s (%u instances)' % (ed.name(), len(syms)))
         rv.append('\t' + '\n\t'.join(rv2))
     return '\n'.join(rv)
Exemplo n.º 41
0
def _DumpDOM (n, depth=0):
    """Utility function to print a DOM tree."""

    pfx = ' ' * depth
    if (xml.dom.Node.ELEMENT_NODE == n.nodeType):
        print('%sElement[%d] %s %s with %d children' % (pfx, n._indexInParent(), n, pyxb.namespace.ExpandedName(n.name), len(n.childNodes)))
        ins = pyxb.namespace.NamespaceContext.GetNodeContext(n).inScopeNamespaces()
        print('%s%s' % (pfx, ' ; '.join([ '%s=%s' % (_k, _v.uri()) for (_k, _v) in ins.items()])))
        for (k, v) in six.iteritems(n.attributes):
            print('%s %s=%s' % (pfx, pyxb.namespace.ExpandedName(k), v))
        for cn in n.childNodes:
            _DumpDOM(cn, depth+1)
    elif (xml.dom.Node.TEXT_NODE == n.nodeType):
        #print '%sText "%s"' % (pfx, n.value)
        pass
    elif (xml.dom.Node.DOCUMENT_NODE == n.nodeType):
        print('Document node')
        _DumpDOM(n.firstChild, depth)
    else:
        print('UNRECOGNIZED %s' % (n.nodeType,))
Exemplo n.º 42
0
    def __validateModules (self):
        self.__validatePrerequisites(self._STAGE_validateModules)
        for mr in self.__moduleRecords:
            ns = mr.namespace()
            for base_uid in mr.dependsOnExternal():
                xmr = ns.lookupModuleRecordByUID(base_uid)
                if xmr is None:
                    raise pyxb.NamespaceArchiveError('Module %s depends on external module %s, not available in archive path' % (mr.generationUID(), base_uid))
                if not xmr.isIncorporated():
                    _log.info('Need to incorporate data from %s', xmr)
                else:
                    _log.info('Have required base data %s', xmr)

            for origin in mr.origins():
                for (cat, names) in six.iteritems(origin.categoryMembers()):
                    if not (cat in ns.categories()):
                        continue
                    cross_objects = names.intersection(six.iterkeys(ns.categoryMap(cat)))
                    if 0 < len(cross_objects):
                        raise pyxb.NamespaceArchiveError('Archive %s namespace %s module %s origin %s archive/active conflict on category %s: %s' % (self.__archivePath, ns, mr, origin, cat, " ".join(cross_objects)))
                    _log.info('%s no conflicts on %d names', cat, len(names))
Exemplo n.º 43
0
def NormalizeLocation (uri, parent_uri=None, prefix_map=None):
    """Normalize a URI against an optional parent_uri in the way that is
    done for C{schemaLocation} attribute values.

    If no URI schema is present, this will normalize a file system
    path.

    Optionally, the resulting absolute URI can subsequently be
    rewritten to replace specified prefix strings with alternative
    strings, e.g. to convert a remote URI to a local repository.  This
    rewriting is done after the conversion to an absolute URI, but
    before normalizing file system URIs.

    @param uri : The URI to normalize.  If C{None}, function returns
    C{None}

    @param parent_uri : The base URI against which normalization is
    done, if C{uri} is a relative URI.

    @param prefix_map : A map used to rewrite URI prefixes.  If
    C{None}, the value defaults to that stored by
    L{SetLocationPrefixRewriteMap}.

    """
    if uri is None:
        return uri
    if parent_uri is None:
        abs_uri = uri
    else:
        #if (0 > parent_uri.find(':')) and (not parent_uri.endswith(os.sep)):
        #    parent_uri = parent_uri + os.sep
        abs_uri = urlparse.urljoin(parent_uri, uri)
    if prefix_map is None:
        prefix_map = LocationPrefixRewriteMap_
    for (pfx, sub) in six.iteritems(prefix_map):
        if abs_uri.startswith(pfx):
            abs_uri = sub + abs_uri[len(pfx):]
    if 0 > abs_uri.find(':'):
        abs_uri = os.path.realpath(abs_uri)
    return abs_uri
Exemplo n.º 44
0
def NormalizeLocation(uri, parent_uri=None, prefix_map=None):
    """Normalize a URI against an optional parent_uri in the way that is
    done for C{schemaLocation} attribute values.

    If no URI schema is present, this will normalize a file system
    path.

    Optionally, the resulting absolute URI can subsequently be
    rewritten to replace specified prefix strings with alternative
    strings, e.g. to convert a remote URI to a local repository.  This
    rewriting is done after the conversion to an absolute URI, but
    before normalizing file system URIs.

    @param uri : The URI to normalize.  If C{None}, function returns
    C{None}

    @param parent_uri : The base URI against which normalization is
    done, if C{uri} is a relative URI.

    @param prefix_map : A map used to rewrite URI prefixes.  If
    C{None}, the value defaults to that stored by
    L{SetLocationPrefixRewriteMap}.

    """
    if uri is None:
        return uri
    if parent_uri is None:
        abs_uri = uri
    else:
        #if (0 > parent_uri.find(':')) and (not parent_uri.endswith(os.sep)):
        #    parent_uri = parent_uri + os.sep
        abs_uri = urlparse.urljoin(parent_uri, uri)
    if prefix_map is None:
        prefix_map = LocationPrefixRewriteMap_
    for (pfx, sub) in six.iteritems(prefix_map):
        if abs_uri.startswith(pfx):
            abs_uri = sub + abs_uri[len(pfx):]
    if 0 > abs_uri.find(':'):
        abs_uri = os.path.realpath(abs_uri)
    return abs_uri
Exemplo n.º 45
0
    def to_metadata(self):
        a = m.ArtifactMetadata()
        a.groupId = self.groupId
        a.artifactId = self.artifactId
        a.version = self.version
        a.classifier = self.classifier or None
        a.extension = self.extension or None
        a.namespace = self.namespace or None
        a.path = self.path or None
        if self.dependencies:
            deps = [d.to_metadata() for d in self.dependencies]
            a.dependencies = pyxb.BIND(*deps)
        if self.compatVersions:
            a.compatVersions = pyxb.BIND(*self.compatVersions)

        if self.aliases:
            als = [alias.to_metadata() for alias in self.aliases]
            a.aliases = pyxb.BIND(*als)

        if self.properties:
            props = [self._create_property(k, v) for k, v in six.iteritems(self.properties)]
            a.properties = pyxb.BIND(*props)
        return a
Exemplo n.º 46
0
def _DumpDOM(n, depth=0):
    """Utility function to print a DOM tree."""

    pfx = ' ' * depth
    if (xml.dom.Node.ELEMENT_NODE == n.nodeType):
        print('%sElement[%d] %s %s with %d children' %
              (pfx, n._indexInParent(), n, pyxb.namespace.ExpandedName(
                  n.name), len(n.childNodes)))
        ins = pyxb.namespace.NamespaceContext.GetNodeContext(
            n).inScopeNamespaces()
        print('%s%s' % (pfx, ' ; '.join(
            ['%s=%s' % (_k, _v.uri()) for (_k, _v) in ins.items()])))
        for (k, v) in six.iteritems(n.attributes):
            print('%s %s=%s' % (pfx, pyxb.namespace.ExpandedName(k), v))
        for cn in n.childNodes:
            _DumpDOM(cn, depth + 1)
    elif (xml.dom.Node.TEXT_NODE == n.nodeType):
        #print '%sText "%s"' % (pfx, n.value)
        pass
    elif (xml.dom.Node.DOCUMENT_NODE == n.nodeType):
        print('Document node')
        _DumpDOM(n.firstChild, depth)
    else:
        print('UNRECOGNIZED %s' % (n.nodeType, ))
Exemplo n.º 47
0
 def testFollow (self):
     m = self.a.follow
     self.assertEqual(1, len(m))
     self.assertEqual([((), frozenset())], list(six.iteritems(m)))
Exemplo n.º 48
0
    def __init__ (self,
                  dom_node=None,
                  parent_context=None,
                  including_context=None,
                  recurse=True,
                  default_namespace=None,
                  target_namespace=None,
                  in_scope_namespaces=None,
                  expanded_name=None,
                  finalize_target_namespace=True):  # MUST BE True for WSDL to work with minidom
        """Determine the namespace context that should be associated with the
        given node and, optionally, its element children.

        Primarily this class maintains a map between namespaces and prefixes
        used in QName instances.  The initial map comprises the bound prefixes
        (C{xml} and C{xmlns}), prefixes inherited from C{parent_context}, and
        prefixes passed through the C{in_scope_namespaces}
        parameter to the constructor.  This map is then augmented by any
        namespace declarations present in a passed C{dom_node}.  The initial
        map prior to augmentation may be restored through the L{reset()}
        method.

        @param dom_node: The DOM node
        @type dom_node: C{xml.dom.Element}
        @keyword parent_context: Optional value that specifies the context
        associated with C{dom_node}'s parent node.  If not provided, only the
        C{xml} namespace is in scope.
        @type parent_context: L{NamespaceContext}
        @keyword recurse: If True (default), create namespace contexts for all
        element children of C{dom_node}
        @type recurse: C{bool}
        @keyword default_namespace: Optional value to set as the default
        namespace.  Values from C{parent_context} would override this, as
        would an C{xmlns} attribute in the C{dom_node}.
        @type default_namespace: L{NamespaceContext}
        @keyword target_namespace: Optional value to set as the target
        namespace.  Values from C{parent_context} would override this, as
        would a C{targetNamespace} attribute in the C{dom_node}
        @type target_namespace: L{NamespaceContext}
        @keyword in_scope_namespaces: Optional value to set as the initial set
        of in-scope namespaces.  The always-present namespaces are added to
        this if necessary.
        @type in_scope_namespaces: C{dict} mapping prefix C{string} to L{Namespace}.
        """
        from pyxb.namespace import builtin

        if dom_node is not None:
            try:
                assert dom_node.__namespaceContext is None
            except AttributeError:
                pass
            dom_node.__namespaceContext = self

        self.__defaultNamespace = default_namespace
        self.__targetNamespace = target_namespace
        if self.__InitialScopeNamespaces is None:
            self.__BuildInitialPrefixMap()
        self.__inScopeNamespaces = self.__InitialScopeNamespaces
        self.__inScopePrefixes = self.__InitialScopePrefixes
        self.__mutableInScopeNamespaces = False
        self.__namespacePrefixCounter = 0

        if parent_context is not None:
            self.__inScopeNamespaces = parent_context.__inScopeNamespaces
            self.__inScopePrefixes = parent_context.__inScopePrefixes
            if parent_context.__mutableInScopeNamespaces:
                self.__clonePrefixMap()
            self.__defaultNamespace = parent_context.defaultNamespace()
            self.__targetNamespace = parent_context.targetNamespace()
            self.__fallbackToTargetNamespace = parent_context.__fallbackToTargetNamespace
        if in_scope_namespaces is not None:
            self.__clonePrefixMap()
            self.__mutableInScopeNamespaces = True
            for (pfx, ns) in six.iteritems(in_scope_namespaces):
                self.__removePrefixMap(pfx)
                self.__addPrefixMap(pfx, ns)

        # Record a copy of the initial mapping, exclusive of namespace
        # directives from C{dom_node}, so we can reset to that state.
        self.__initialScopeNamespaces = self.__inScopeNamespaces
        self.__initialScopePrefixes = self.__inScopePrefixes
        self.__mutableInScopeNamespaces = False

        if self.__targetNamespace is None:
            self.__pendingReferencedNamespaces = set()
        attribute_map = {}
        if dom_node is not None:
            if expanded_name is None:
                expanded_name = pyxb.namespace.ExpandedName(dom_node)
            for ai in range(dom_node.attributes.length):
                attr = dom_node.attributes.item(ai)
                if builtin.XMLNamespaces.uri() == attr.namespaceURI:
                    prefix = attr.localName
                    if 'xmlns' == prefix:
                        prefix = None
                    self.processXMLNS(prefix, attr.value)
                else:
                    if attr.namespaceURI is not None:
                        uri = utility.NamespaceForURI(attr.namespaceURI, create_if_missing=True)
                        key = pyxb.namespace.ExpandedName(uri, attr.localName)
                    else:
                        key = pyxb.namespace.ExpandedName(None, attr.localName)
                    attribute_map[key] = attr.value

        if finalize_target_namespace:
            tns_uri = None
            tns_attr = self._TargetNamespaceAttribute(expanded_name)
            if tns_attr is not None:
                tns_uri = attribute_map.get(tns_attr)
                self.finalizeTargetNamespace(tns_uri, including_context=including_context)

        # Store in each node the in-scope namespaces at that node;
        # we'll need them for QName interpretation of attribute
        # values.
        if (dom_node is not None) and recurse:
            from xml.dom import Node
            assert Node.ELEMENT_NODE == dom_node.nodeType
            for cn in dom_node.childNodes:
                if Node.ELEMENT_NODE == cn.nodeType:
                    NamespaceContext(dom_node=cn, parent_context=self, recurse=True)
Exemplo n.º 49
0
 def __clonePrefixMap (self):
     self.__inScopeNamespaces = self.__inScopeNamespaces.copy()
     isp = {}
     for (ns, pfxs) in six.iteritems(self.__inScopePrefixes):
         isp[ns] = pfxs.copy()
     self.__inScopePrefixes = isp
Exemplo n.º 50
0
 def __clonePrefixMap(self):
     self.__inScopeNamespaces = self.__inScopeNamespaces.copy()
     isp = {}
     for (ns, pfxs) in six.iteritems(self.__inScopePrefixes):
         isp[ns] = pfxs.copy()
     self.__inScopePrefixes = isp
Exemplo n.º 51
0
def ResolveSiblingNamespaces (sibling_namespaces):
    """Resolve all components in the sibling_namespaces.

    @param sibling_namespaces : A set of namespaces expected to be closed
    under dependency."""

    for ns in sibling_namespaces:
        ns.configureCategories([archive.NamespaceArchive._AnonymousCategory()])
        ns.validateComponentModel()

    def __keyForCompare (dependency_map):
        """Sort namespaces so dependencies get resolved first.

        Uses the trick underlying functools.cmp_to_key(), but optimized for
        this special case.  The dependency map is incorporated into the class
        definition by scope.
        """
        class K (object):
            def __init__ (self, ns, *args):
                self.__ns = ns

            # self compares less than other if self.ns is in the dependency set
            # of other.ns but not vice-versa.
            def __lt__ (self, other):
                return ((self.__ns in dependency_map.get(other.__ns, set())) \
                            and not (other.__ns in dependency_map.get(self.__ns, set())))

            # self compares equal to other if their namespaces are either
            # mutually dependent or independent.
            def __eq__ (self, other):
                return (self.__ns in dependency_map.get(other.__ns, set())) == (other.__ns in dependency_map.get(self.__ns, set()))

            # All other order metrics are derived.
            def __ne__ (self, other):
                return not self.__eq__(other)
            def __le__ (self, other):
                return self.__lt__(other) or self.__eq__(other)
            def __gt__ (self, other):
                return other.__lt__(self.__ns)
            def __ge__ (self, other):
                return other.__lt__(self.__ns) or self.__eq__(other)
        return K

    need_resolved_set = set(sibling_namespaces)
    dependency_map = {}
    last_state = None
    while need_resolved_set:
        need_resolved_list = list(need_resolved_set)
        if dependency_map:
            need_resolved_list.sort(key=__keyForCompare(dependency_map))
        need_resolved_set = set()
        dependency_map = {}
        for ns in need_resolved_list:
            if not ns.needsResolution():
                continue
            if not ns.resolveDefinitions(allow_unresolved=True):
                deps = dependency_map.setdefault(ns, set())
                for (c, dcs) in six.iteritems(ns._unresolvedDependents()):
                    for dc in dcs:
                        dns = dc.expandedName().namespace()
                        if dns != ns:
                            deps.add(dns)
                _log.info('Holding incomplete resolution %s depending on: ', ns.uri(), six.u(' ; ').join([ six.text_type(_dns) for _dns in deps ]))
                need_resolved_set.add(ns)
        # Exception termination check: if we have the same set of incompletely
        # resolved namespaces, and each has the same number of unresolved
        # components, assume there's an truly unresolvable dependency: either
        # due to circularity, or because there was an external namespace that
        # was missed from the sibling list.
        state = []
        for ns in need_resolved_set:
            state.append( (ns, len(ns._unresolvedComponents())) )
        state = tuple(state)
        if last_state == state:
            raise pyxb.LogicError('Unexpected external dependency in sibling namespaces: %s' % (six.u('\n  ').join( [six.text_type(_ns) for _ns in need_resolved_set ]),))
        last_state = state
Exemplo n.º 52
0
    def __init__(self,
                 dom_node=None,
                 parent_context=None,
                 including_context=None,
                 recurse=True,
                 default_namespace=None,
                 target_namespace=None,
                 in_scope_namespaces=None,
                 expanded_name=None,
                 finalize_target_namespace=True
                 ):  # MUST BE True for WSDL to work with minidom
        """Determine the namespace context that should be associated with the
        given node and, optionally, its element children.

        Primarily this class maintains a map between namespaces and prefixes
        used in QName instances.  The initial map comprises the bound prefixes
        (C{xml} and C{xmlns}), prefixes inherited from C{parent_context}, and
        prefixes passed through the C{in_scope_namespaces}
        parameter to the constructor.  This map is then augmented by any
        namespace declarations present in a passed C{dom_node}.  The initial
        map prior to augmentation may be restored through the L{reset()}
        method.

        @param dom_node: The DOM node
        @type dom_node: C{xml.dom.Element}
        @keyword parent_context: Optional value that specifies the context
        associated with C{dom_node}'s parent node.  If not provided, only the
        C{xml} namespace is in scope.
        @type parent_context: L{NamespaceContext}
        @keyword recurse: If True (default), create namespace contexts for all
        element children of C{dom_node}
        @type recurse: C{bool}
        @keyword default_namespace: Optional value to set as the default
        namespace.  Values from C{parent_context} would override this, as
        would an C{xmlns} attribute in the C{dom_node}.
        @type default_namespace: L{NamespaceContext}
        @keyword target_namespace: Optional value to set as the target
        namespace.  Values from C{parent_context} would override this, as
        would a C{targetNamespace} attribute in the C{dom_node}
        @type target_namespace: L{NamespaceContext}
        @keyword in_scope_namespaces: Optional value to set as the initial set
        of in-scope namespaces.  The always-present namespaces are added to
        this if necessary.
        @type in_scope_namespaces: C{dict} mapping prefix C{string} to L{Namespace}.
        """
        from pyxb.namespace import builtin

        if dom_node is not None:
            try:
                assert dom_node.__namespaceContext is None
            except AttributeError:
                pass
            dom_node.__namespaceContext = self

        self.__defaultNamespace = default_namespace
        self.__targetNamespace = target_namespace
        if self.__InitialScopeNamespaces is None:
            self.__BuildInitialPrefixMap()
        self.__inScopeNamespaces = self.__InitialScopeNamespaces
        self.__inScopePrefixes = self.__InitialScopePrefixes
        self.__mutableInScopeNamespaces = False
        self.__namespacePrefixCounter = 0

        if parent_context is not None:
            self.__inScopeNamespaces = parent_context.__inScopeNamespaces
            self.__inScopePrefixes = parent_context.__inScopePrefixes
            if parent_context.__mutableInScopeNamespaces:
                self.__clonePrefixMap()
            self.__defaultNamespace = parent_context.defaultNamespace()
            self.__targetNamespace = parent_context.targetNamespace()
            self.__fallbackToTargetNamespace = parent_context.__fallbackToTargetNamespace
        if in_scope_namespaces is not None:
            self.__clonePrefixMap()
            self.__mutableInScopeNamespaces = True
            for (pfx, ns) in six.iteritems(in_scope_namespaces):
                self.__removePrefixMap(pfx)
                self.__addPrefixMap(pfx, ns)

        # Record a copy of the initial mapping, exclusive of namespace
        # directives from C{dom_node}, so we can reset to that state.
        self.__initialScopeNamespaces = self.__inScopeNamespaces
        self.__initialScopePrefixes = self.__inScopePrefixes
        self.__mutableInScopeNamespaces = False

        if self.__targetNamespace is None:
            self.__pendingReferencedNamespaces = set()
        attribute_map = {}
        if dom_node is not None:
            if expanded_name is None:
                expanded_name = pyxb.namespace.ExpandedName(dom_node)
            for ai in range(dom_node.attributes.length):
                attr = dom_node.attributes.item(ai)
                if builtin.XMLNamespaces.uri() == attr.namespaceURI:
                    prefix = attr.localName
                    if 'xmlns' == prefix:
                        prefix = None
                    self.processXMLNS(prefix, attr.value)
                else:
                    if attr.namespaceURI is not None:
                        uri = utility.NamespaceForURI(attr.namespaceURI,
                                                      create_if_missing=True)
                        key = pyxb.namespace.ExpandedName(uri, attr.localName)
                    else:
                        key = pyxb.namespace.ExpandedName(None, attr.localName)
                    attribute_map[key] = attr.value

        if finalize_target_namespace:
            tns_uri = None
            tns_attr = self._TargetNamespaceAttribute(expanded_name)
            if tns_attr is not None:
                tns_uri = attribute_map.get(tns_attr)
                self.finalizeTargetNamespace(
                    tns_uri, including_context=including_context)

        # Store in each node the in-scope namespaces at that node;
        # we'll need them for QName interpretation of attribute
        # values.
        if (dom_node is not None) and recurse:
            from xml.dom import Node
            assert Node.ELEMENT_NODE == dom_node.nodeType
            for cn in dom_node.childNodes:
                if Node.ELEMENT_NODE == cn.nodeType:
                    NamespaceContext(dom_node=cn,
                                     parent_context=self,
                                     recurse=True)
Exemplo n.º 53
0
    NCName_re = re.compile('^%s$' % (NCName_pat,))
    QName_pat = '(%s:)?%s' % (NCName_pat, NCName_pat)
    QName_re = re.compile('^%s$' % (QName_pat,))

# Production 24 : Single Character Escapes
SingleCharEsc = { 'n' : CodePointSet(0x0A),
                  'r' : CodePointSet(0x0D),
                  't' : CodePointSet(0x09) }
for c in r'\|.-^?*+{}()[]':
    SingleCharEsc[c] = CodePointSet(ord(c))

# Production 25 : Category Escapes
# Production 26: Complemented Category Escapes
catEsc = { }
complEsc = { }
for k, v in six.iteritems(PropertyMap):
    catEsc[six.u('p{%s}') % (k,)] = v
    catEsc[six.u('P{%s}') % (k,)] = v.negate()

# Production 36 : IsBlock escapes
IsBlockEsc = { }
for k, v in six.iteritems(BlockMap):
    IsBlockEsc[six.u('p{Is%s}') % (k,)] = v
    IsBlockEsc[six.u('P{Is%s}') % (k,)] = v.negate()

# Production 37 : Multi-Character Escapes
WildcardEsc = CodePointSet(ord('\n'), ord('\r')).negate()
MultiCharEsc = { }
MultiCharEsc['s'] = CodePointSet(0x20, ord('\t'), ord('\n'), ord('\r'))
MultiCharEsc['S'] = MultiCharEsc['s'].negate()
MultiCharEsc['i'] = CodePointSet(XML1p0e2.Letter).add(ord('_')).add(ord(':'))
Exemplo n.º 54
0

# Production 24 : Single Character Escapes
SingleCharEsc = {
    'n': CodePointSet(0x0A),
    'r': CodePointSet(0x0D),
    't': CodePointSet(0x09)
}
for c in r'\|.-^?*+{}()[]':
    SingleCharEsc[c] = CodePointSet(ord(c))

# Production 25 : Category Escapes
# Production 26: Complemented Category Escapes
catEsc = {}
complEsc = {}
for k, v in six.iteritems(PropertyMap):
    catEsc[six.u('p{%s}') % (k, )] = v
    catEsc[six.u('P{%s}') % (k, )] = v.negate()

# Production 36 : IsBlock escapes
IsBlockEsc = {}
for k, v in six.iteritems(BlockMap):
    IsBlockEsc[six.u('p{Is%s}') % (k, )] = v
    IsBlockEsc[six.u('P{Is%s}') % (k, )] = v.negate()

# Production 37 : Multi-Character Escapes
WildcardEsc = CodePointSet(ord('\n'), ord('\r')).negate()
MultiCharEsc = {}
MultiCharEsc['s'] = CodePointSet(0x20, ord('\t'), ord('\n'), ord('\r'))
MultiCharEsc['S'] = MultiCharEsc['s'].negate()
MultiCharEsc['i'] = CodePointSet(XML1p0e2.Letter).add(ord('_')).add(ord(':'))
Exemplo n.º 55
0
XMLStyle_saxer = 2
"""Use pyxb.binding.saxer when converting documents to binding instances.
This style supports location information in the bindings.  It produces binding
instances directly, without going through a DOM stage, so is faster than
XMLStyle_saxdom.  However, since the pyxb.xmlschema.structures classes require
a DOM model, XMLStyle_saxdom will be used for pyxb.utils.domutils.StringToDOM
if this style is selected."""

_XMLStyle = XMLStyle_saxer
"""The current XML processing style."""

_XMLStyleMap = { 'minidom' : XMLStyle_minidom,
                 'saxdom' : XMLStyle_saxdom,
                 'saxer' : XMLStyle_saxer }
_XMLStyleMapReverse = dict([ (_v, _k) for (_k, _v) in six.iteritems(_XMLStyleMap) ])

_XMLStyle_envvar = 'PYXB_XML_STYLE'

def _SetXMLStyle (style=None):
    """Set the interface used to parse XML content.

    This can be invoked within code.  The system default of L{XMLStyle_saxer}
    can also be overridden at runtime by setting the environment variable
    C{PYXB_XML_STYLE} to one of C{minidom}, C{saxdom}, or C{saxer}.

    @param style: One of L{XMLStyle_minidom}, L{XMLStyle_saxdom},
    L{XMLStyle_saxer}.  If not provided, the system default is used.
    """
    global _XMLStyle
    if style is None:
Exemplo n.º 56
0
 def testIterItems (self):
     vals = set()
     for ee in six.iteritems(cards):
         self.assertTrue(isinstance(ee, cards._CF_enumeration._CollectionFacet_itemType))
         vals.add(ee.value())
     self.assertEqual(self.Expected, vals)