def testOrphan (self): i = self.makeText() # Drop the second bold dropped = i.bold.pop() self.assertEqual(vc.orphanElementInContent, vc.IGNORE_ONCE) xmlt = six.u('<text>Intro with <bold>bold text</bold> and <ital>italicized text with <bold>bold</bold> inside</ital> ending with a little text.</text>') xmld = xmlt.encode('utf-8') self.assertEqual(i.toxml('utf-8', root_only=True), xmld) vc._setOrphanElementInContent(vc.GIVE_UP) self.assertEqual(vc.orphanElementInContent, vc.GIVE_UP) self.assertEqual(gvc.orphanElementInContent, gvc.IGNORE_ONCE) xmlt = six.u('<text>Intro with <bold>bold text</bold> and <ital>italicized text with <bold>bold</bold> inside</ital> ending with a little text.</text>') xmld = xmlt.encode('utf-8') self.assertEqual(i.toxml('utf-8', root_only=True), xmld) vc._setOrphanElementInContent(vc.RAISE_EXCEPTION) self.assertEqual(vc.orphanElementInContent, vc.RAISE_EXCEPTION) self.assertEqual(gvc.orphanElementInContent, gvc.IGNORE_ONCE) if sys.version_info[:2] < (2, 7): self.assertRaises(pyxb.OrphanElementContentError, i.toxml, 'utf-8', root_only=True) return with self.assertRaises(pyxb.OrphanElementContentError) as cm: xmld = i.toxml('utf-8', root_only=True) e = cm.exception self.assertEqual(e.instance, i) self.assertEqual(e.preferred.value, dropped)
def testGenerationValidation(self): ship_to = USAddress('Robert Smith', 'General Delivery') po = purchaseOrder(ship_to) self.assertEqual('General Delivery', po.shipTo.street) self.assertTrue(po.billTo is None) self.assertTrue(pyxb.RequireValidWhenGenerating()) self.assertRaises(pyxb.IncompleteElementContentError, po.toxml) try: pyxb.RequireValidWhenGenerating(False) self.assertFalse(pyxb.RequireValidWhenGenerating()) xmlt = six.u( '<ns1:purchaseOrder xmlns:ns1="http://www.example.com/PO1"><shipTo><street>General Delivery</street><name>Robert Smith</name></shipTo></ns1:purchaseOrder>' ) xmlta = six.u( '<ns1:purchaseOrder xmlns:ns1="http://www.example.com/PO1"><shipTo><name>Robert Smith</name><street>General Delivery</street></shipTo></ns1:purchaseOrder>' ) xmlds = [_xmlt.encode('utf-8') for _xmlt in (xmlt, xmlta)] self.assertTrue(po.toxml("utf-8", root_only=True) in xmlds) finally: pyxb.RequireValidWhenGenerating(True) self.assertRaises(pyxb.UnrecognizedContentError, CreateFromDocument, xmlt) self.assertTrue(pyxb.RequireValidWhenParsing()) try: pyxb.RequireValidWhenParsing(False) self.assertFalse(pyxb.RequireValidWhenParsing()) po2 = CreateFromDocument(xmlt) finally: pyxb.RequireValidWhenParsing(True) self.assertEqual('General Delivery', po2.shipTo.street) self.assertTrue(po2.billTo is None)
def XMLToPython(pattern): """Convert the given pattern to the format required for Python regular expressions. @param pattern: A Unicode string defining a pattern consistent with U{XML regular expressions<http://www.w3.org/TR/xmlschema-2/index.html#regexs>}. @return: A Unicode string specifying a Python regular expression that matches the same language as C{pattern}.""" assert isinstance(pattern, six.text_type) new_pattern_elts = [] new_pattern_elts.append('^(') position = 0 while position < len(pattern): cg = MaybeMatchCharacterClass(pattern, position) if cg is None: ch = pattern[position] if ch == six.u('^') or ch == six.u('$'): # These characters have no special meaning in XSD. But they # match start and end of string in Python, so they have to # be escaped. new_pattern_elts.append(six.unichr(0x5c) + ch) else: new_pattern_elts.append(ch) position += 1 else: (cps, position) = cg new_pattern_elts.append(cps.asPattern()) new_pattern_elts.append(')$') return ''.join(new_pattern_elts)
def testContainerAssignment (self): i = xs.string(self.body, _element=anything) instance = container() instance.anything = i explicit_xml = instance.toxml("utf-8") instance.anything = xs.string(self.body) implicit_xml = instance.toxml("utf-8") self.assertEqual(explicit_xml, implicit_xml) instance.anything = xs.int(43) self.assertTrue(isinstance(instance.anything, xs.int)) int_xml = instance.toxml("utf-8") instance.anything = self.body self.assertTrue(isinstance(instance.anything, xs.anyType)) oc = instance.anything.orderedContent() self.assertEqual(1, len(oc)) self.assertTrue(isinstance(oc[0], pyxb.binding.basis.NonElementContent)) xmlt = six.u('<container><anything>something</anything></container>') xmld = xmlt.encode('utf-8') self.assertEqual(xmld, instance.toxml('utf-8', root_only=True)) instance.anything = 43 self.assertTrue(isinstance(instance.anything, xs.anyType)) oc = instance.anything.orderedContent() self.assertEqual(1, len(oc)) self.assertTrue(isinstance(oc[0], pyxb.binding.basis.NonElementContent)) xmlt = six.u('<container><anything>43</anything></container>') xmld = xmlt.encode('utf-8') self.assertEqual(xmld, instance.toxml('utf-8', root_only=True))
def testGenerationValidation (self): ship_to = USAddress('Robert Smith', 'General Delivery') po = purchaseOrder(ship_to) self.assertEqual('General Delivery', po.shipTo.street) self.assertTrue(po.billTo is None) self.assertTrue(pyxb.RequireValidWhenGenerating()) self.assertRaises(pyxb.IncompleteElementContentError, po.toxml) try: pyxb.RequireValidWhenGenerating(False) self.assertFalse(pyxb.RequireValidWhenGenerating()) xmlt = six.u('<ns1:purchaseOrder xmlns:ns1="http://www.example.com/PO1"><shipTo><street>General Delivery</street><name>Robert Smith</name></shipTo></ns1:purchaseOrder>') xmlta = six.u('<ns1:purchaseOrder xmlns:ns1="http://www.example.com/PO1"><shipTo><name>Robert Smith</name><street>General Delivery</street></shipTo></ns1:purchaseOrder>') xmlds = [ _xmlt.encode('utf-8') for _xmlt in (xmlt, xmlta) ] self.assertTrue(po.toxml("utf-8", root_only=True) in xmlds) finally: pyxb.RequireValidWhenGenerating(True) self.assertRaises(pyxb.UnrecognizedContentError, CreateFromDocument, xmlt) self.assertTrue(pyxb.RequireValidWhenParsing()) try: pyxb.RequireValidWhenParsing(False) self.assertFalse(pyxb.RequireValidWhenParsing()) po2 = CreateFromDocument(xmlt) finally: pyxb.RequireValidWhenParsing(True) self.assertEqual('General Delivery', po2.shipTo.street) self.assertTrue(po2.billTo is None)
def testAltMultichoice(self): xmlt = six.u('<ns1:altmultiplechoice xmlns:ns1="URN:test-mg-choice"/>') xmld = xmlt.encode('utf-8') dom = pyxb.utils.domutils.StringToDOM(xmlt) instance = altmultiplechoice.createFromDOM(dom.documentElement) self.assertEqual(0, len(instance.first)) self.assertEqual(0, len(instance.second)) self.assertEqual(0, len(instance.third)) self.assertEqual(ToDOM(instance).toxml("utf-8"), xmld) xmlt = six.u( '<ns1:altmultiplechoice xmlns:ns1="URN:test-mg-choice"><first/></ns1:altmultiplechoice>' ) xmld = xmlt.encode('utf-8') dom = pyxb.utils.domutils.StringToDOM(xmlt) instance = altmultiplechoice.createFromDOM(dom.documentElement) self.assertEqual(1, len(instance.first)) self.assertEqual(0, len(instance.second)) self.assertEqual(0, len(instance.third)) self.assertEqual(ToDOM(instance).toxml("utf-8"), xmld) xmlt = six.u( '<ns1:altmultiplechoice xmlns:ns1="URN:test-mg-choice"><first/><first/><third/></ns1:altmultiplechoice>' ) xmld = xmlt.encode('utf-8') dom = pyxb.utils.domutils.StringToDOM(xmlt) instance = altmultiplechoice.createFromDOM(dom.documentElement) self.assertEqual(2, len(instance.first)) self.assertEqual(0, len(instance.second)) self.assertEqual(1, len(instance.third)) self.assertEqual(ToDOM(instance).toxml("utf-8"), xmld)
def testContainerAssignment(self): i = xs.string(self.body, _element=anything) instance = container() instance.anything = i explicit_xml = instance.toxml("utf-8") instance.anything = xs.string(self.body) implicit_xml = instance.toxml("utf-8") self.assertEqual(explicit_xml, implicit_xml) instance.anything = xs.int(43) self.assertTrue(isinstance(instance.anything, xs.int)) int_xml = instance.toxml("utf-8") instance.anything = self.body self.assertTrue(isinstance(instance.anything, xs.anyType)) oc = instance.anything.orderedContent() self.assertEqual(1, len(oc)) self.assertTrue(isinstance(oc[0], pyxb.binding.basis.NonElementContent)) xmlt = six.u('<container><anything>something</anything></container>') xmld = xmlt.encode('utf-8') self.assertEqual(xmld, instance.toxml('utf-8', root_only=True)) instance.anything = 43 self.assertTrue(isinstance(instance.anything, xs.anyType)) oc = instance.anything.orderedContent() self.assertEqual(1, len(oc)) self.assertTrue(isinstance(oc[0], pyxb.binding.basis.NonElementContent)) xmlt = six.u('<container><anything>43</anything></container>') xmld = xmlt.encode('utf-8') self.assertEqual(xmld, instance.toxml('utf-8', root_only=True))
def XMLToPython (pattern): """Convert the given pattern to the format required for Python regular expressions. @param pattern: A Unicode string defining a pattern consistent with U{XML regular expressions<http://www.w3.org/TR/xmlschema-2/index.html#regexs>}. @return: A Unicode string specifying a Python regular expression that matches the same language as C{pattern}.""" assert isinstance(pattern, six.text_type) new_pattern_elts = [] new_pattern_elts.append('^(') position = 0 while position < len(pattern): cg = MaybeMatchCharacterClass(pattern, position) if cg is None: ch = pattern[position] if ch == six.u('^') or ch == six.u('$'): # These characters have no special meaning in XSD. But they # match start and end of string in Python, so they have to # be escaped. new_pattern_elts.append(six.unichr(0x5c) + ch) else: new_pattern_elts.append(ch) position += 1 else: (cps, position) = cg new_pattern_elts.append(cps.asPattern()) new_pattern_elts.append(')$') return ''.join(new_pattern_elts)
def testSingleChoice(self): xmlt = six.u( '<ns1:choice xmlns:ns1="URN:test-mg-choice"><first/></ns1:choice>') xmld = xmlt.encode('utf-8') dom = pyxb.utils.domutils.StringToDOM(xmlt) instance = choice.createFromDOM(dom.documentElement) self.onlyFirst(instance) self.assertEqual(ToDOM(instance).toxml("utf-8"), xmld) xmlt = six.u( '<ns1:choice xmlns:ns1="URN:test-mg-choice"><second/></ns1:choice>' ) xmld = xmlt.encode('utf-8') dom = pyxb.utils.domutils.StringToDOM(xmlt) instance = choice.createFromDOM(dom.documentElement) self.onlySecond(instance) self.assertEqual(ToDOM(instance).toxml("utf-8"), xmld) xmlt = six.u( '<ns1:choice xmlns:ns1="URN:test-mg-choice"><third/></ns1:choice>') xmld = xmlt.encode('utf-8') dom = pyxb.utils.domutils.StringToDOM(xmlt) instance = choice.createFromDOM(dom.documentElement) self.onlyThird(instance) self.assertEqual(ToDOM(instance).toxml("utf-8"), xmld)
def __str__(self): import pyxb.binding.basis if isinstance(self.value, pyxb.binding.basis._TypeBinding_mixin): return six.u('Type %s cannot be created from %s: %s') % ( self.type._Name(), self.value._Name(), self.value) return six.u('Type %s cannot be created from: %s') % ( self.type._Name(), self.value)
def testCrossedRestriction(self): # Content model elements that are consistent with parent # should share its fields; those that change something should # override it. self.assertEqual(st.extendedName._ElementMap['title'], restExtName._ElementMap['title']) self.assertEqual(st.extendedName._ElementMap['forename'], restExtName._ElementMap['forename']) self.assertEqual(st.extendedName._ElementMap['surname'], restExtName._ElementMap['surname']) self.assertEqual(st.extendedName._ElementMap['generation'], restExtName._ElementMap['generation']) xmlt = six.u('<personName><surname>Smith</surname></personName>') dom = pyxb.utils.domutils.StringToDOM(xmlt) instance = st.personName.Factory(_dom_node=dom.documentElement) xmlt = six.u( '<personName><surname>Smith</surname><generation>Jr.</generation></personName>' ) dom = pyxb.utils.domutils.StringToDOM(xmlt) self.__basis_log.setLevel(logging.ERROR) self.assertRaises(UnrecognizedContentError, st.personName.Factory, _dom_node=dom.documentElement) self.__basis_log.level = self.__basis_loglevel xmlt = xmlt.replace('personName', 'extendedName') dom = pyxb.utils.domutils.StringToDOM(xmlt) instance = st.extendedName.Factory(_dom_node=dom.documentElement) xmlt = xmlt.replace('extendedName', 'restExtName') dom = pyxb.utils.domutils.StringToDOM(xmlt) instance = restExtName.Factory(_dom_node=dom.documentElement)
def testOrphan(self): i = self.makeText() # Drop the second bold dropped = i.bold.pop() self.assertEqual(vc.orphanElementInContent, vc.IGNORE_ONCE) xmlt = six.u( '<text>Intro with <bold>bold text</bold> and <ital>italicized text with <bold>bold</bold> inside</ital> ending with a little text.</text>' ) xmld = xmlt.encode('utf-8') self.assertEqual(i.toxml('utf-8', root_only=True), xmld) vc._setOrphanElementInContent(vc.GIVE_UP) self.assertEqual(vc.orphanElementInContent, vc.GIVE_UP) self.assertEqual(gvc.orphanElementInContent, gvc.IGNORE_ONCE) xmlt = six.u( '<text>Intro with <bold>bold text</bold> and <ital>italicized text with <bold>bold</bold> inside</ital> ending with a little text.</text>' ) xmld = xmlt.encode('utf-8') self.assertEqual(i.toxml('utf-8', root_only=True), xmld) vc._setOrphanElementInContent(vc.RAISE_EXCEPTION) self.assertEqual(vc.orphanElementInContent, vc.RAISE_EXCEPTION) self.assertEqual(gvc.orphanElementInContent, gvc.IGNORE_ONCE) if sys.version_info[:2] < (2, 7): self.assertRaises(pyxb.OrphanElementContentError, i.toxml, 'utf-8', root_only=True) return with self.assertRaises(pyxb.OrphanElementContentError) as cm: xmld = i.toxml('utf-8', root_only=True) e = cm.exception self.assertEqual(e.instance, i) self.assertEqual(e.preferred.value, dropped)
def testSGTime(self): xmlt = six.u('<when><sgTime>2009-06-15T17:50:00Z</sgTime></when>') xmld = xmlt.encode('utf-8') dom = pyxb.utils.domutils.StringToDOM(xmlt) self.assertRaises(pyxb.AbstractElementError, CreateFromDOM, dom.documentElement) saxer = pyxb.binding.saxer.make_parser(fallback_namespace=Namespace) handler = saxer.getContentHandler() self.assertRaises(pyxb.AbstractElementError, saxer.parse, io.StringIO(xmlt)) xmlt = six.u('<sgTime>2009-06-15T17:50:00Z</sgTime>') xmld = xmlt.encode('utf-8') dom = pyxb.utils.domutils.StringToDOM(xmlt) self.assertRaises(pyxb.AbstractElementError, CreateFromDOM, dom.documentElement) self.assertRaises(pyxb.AbstractElementError, saxer.parse, io.StringIO(xmlt)) xmlt = six.u('<ISO8601>2009-06-15T17:50:00Z</ISO8601>') xmld = xmlt.encode('utf-8') dom = pyxb.utils.domutils.StringToDOM(xmlt) instance = CreateFromDOM(dom.documentElement) self.assertEqual(instance._element(), ISO8601) saxer.parse(io.StringIO(xmlt)) instance = handler.rootObject() self.assertEqual(instance._element(), ISO8601)
def testAddAttributes (self): x = wildcard() self.assertEqual(six.u('<wildcard/>'), x.toxml('utf-8', root_only=True).decode('utf-8')) x.attr = False self.assertEqual(six.u('<wildcard attr="false"/>').encode('utf-8'), x.toxml('utf-8', root_only=True)) x._setAttribute(ns1.createExpandedName('w1'), 'val') self.assertEqual(six.u('<wildcard attr="false" n1:w1="val" xmlns:n1="urn:issue14.1"/>').encode('utf-8'), x.toxml('utf-8', root_only=True))
def testMultichoice (self): xmlt = six.u('<ns1:multiplechoice xmlns:ns1="URN:test-mg-choice"/>') xmld = xmlt.encode('utf-8') dom = pyxb.utils.domutils.StringToDOM(xmlt) instance = multiplechoice.createFromDOM(dom.documentElement) self.assertEqual(0, len(instance.first)) self.assertEqual(0, len(instance.second)) self.assertEqual(0, len(instance.third)) self.assertEqual(ToDOM(instance).toxml("utf-8"), xmld) xmlt = six.u('<ns1:multiplechoice xmlns:ns1="URN:test-mg-choice"><first/></ns1:multiplechoice>') xmld = xmlt.encode('utf-8') dom = pyxb.utils.domutils.StringToDOM(xmlt) instance = multiplechoice.createFromDOM(dom.documentElement) self.assertEqual(1, len(instance.first)) self.assertEqual(0, len(instance.second)) self.assertEqual(0, len(instance.third)) self.assertEqual(ToDOM(instance).toxml("utf-8"), xmld) xmlt = six.u('<ns1:multiplechoice xmlns:ns1="URN:test-mg-choice"><first/><first/><first/><third/></ns1:multiplechoice>') xmld = xmlt.encode('utf-8') dom = pyxb.utils.domutils.StringToDOM(xmlt) instance = multiplechoice.createFromDOM(dom.documentElement) self.assertEqual(3, len(instance.first)) self.assertEqual(0, len(instance.second)) self.assertEqual(1, len(instance.third)) self.assertEqual(ToDOM(instance).toxml("utf-8"), xmld)
def testTooManySingle (self): xmlt = six.u('<ns1:choice xmlns:ns1="URN:test-mg-choice"><first/><second/></ns1:choice>') dom = pyxb.utils.domutils.StringToDOM(xmlt) self.assertRaises(UnrecognizedContentError, choice.createFromDOM, dom.documentElement) xmlt = six.u('<ns1:choice xmlns:ns1="URN:test-mg-choice"><second/><third/></ns1:choice>') dom = pyxb.utils.domutils.StringToDOM(xmlt) self.assertRaises(UnrecognizedContentError, choice.createFromDOM, dom.documentElement)
def testAddElements (self): bds = pyxb.utils.domutils.BindingDOMSupport() elt = bds.createChildElement(ns2.createExpandedName('e2')) bds.appendTextChild('content', elt) x = wildcard() self.assertEqual(six.u('<wildcard/>').encode('utf-8'), x.toxml('utf-8', root_only=True)) x._appendWildcardElement(elt) self.assertEqual(six.u('<wildcard xmlns:n2="urn:issue14.2"><n2:e2>content</n2:e2></wildcard>').encode('utf-8'), x.toxml('utf-8', root_only=True))
class TestProhibitedAttributeError(unittest.TestCase): Good_xmlt = six.u('<eAttributes aProhibited="6" aReq="4"/>') Good_xmld = Good_xmlt.encode('utf-8') Bad_xmlt = six.u('<eAttributesProhibited aProhibited="6" aReq="4"/>') Bad_xmld = Bad_xmlt.encode('utf-8') def testSchemaSupport(self): i1 = trac26.eAttributes(aReq=2, aProhibited=6) self.assertTrue(i1.validateBinding()) i2 = trac26.eAttributesProhibited(aReq=2) self.assertTrue(i2.validateBinding()) self.assertTrue(isinstance(i2, type(i1))) self.assertFalse(isinstance(i1, type(i2))) instance = trac26.CreateFromDocument(self.Good_xmlt) self.assertEqual(self.Good_xmld, instance.toxml('utf-8', root_only=True)) def testConstructor(self): instance = None with self.assertRaises(pyxb.ProhibitedAttributeError) as cm: instance = trac26.eAttributesProhibited(aReq=2, aProhibited=6) def testAssignment(self): instance = trac26.eAttributesProhibited(aReq=2) with self.assertRaises(pyxb.ProhibitedAttributeError) as cm: instance.aProhibited = 6 def testSet(self): instance = trac26.eAttributesProhibited(aReq=2) au = instance._AttributeMap['aProhibited'] with self.assertRaises(pyxb.ProhibitedAttributeError) as cm: au.set(instance, 6) def testDocument(self): instance = None with self.assertRaises(pyxb.ProhibitedAttributeError) as cm: instance = trac26.CreateFromDocument(self.Bad_xmlt) e = cm.exception self.assertFalse(e.instance is None) self.assertEqual(e.type, trac26.tAttributesProhibited) self.assertFalse((e.location is None) and (pyxb.XMLStyle_saxer == pyxb._XMLStyle)) if e.location is not None: self.assertEqual(1, e.location.lineNumber) self.assertEqual(0, e.location.columnNumber) self.assertEqual( str(e), "Attempt to reference prohibited attribute aProhibited in type <class 'trac26.tAttributesProhibited'>" ) def testDisplay(self): instance = trac26.eAttributesProhibited(aReq=2) if DisplayException: instance.aProhibited = 6 def testDisplayDoc(self): if DisplayException: instance = trac26.CreateFromDocument(self.Bad_xmlt)
class TestProperties(unittest.TestCase): street_content = '''95 Main St. Anytown, AS 12345-6789''' street_xmlt = six.u('<street>%s</street>') % (street_content, ) street_xmld = street_xmlt.encode('utf-8') street_dom = pyxb.utils.domutils.StringToDOM(street_xmlt).documentElement address1_xmlt = six.u('<name>Customer</name><street>95 Main St</street>') address2_xmlt = six.u( '<name>Sugar Mama</name><street>24 E. Dearling Ave.</street>') def testPythonElementSimpleContent(self): elt = USAddress._ElementMap['street'].elementBinding()( self.street_content) self.assertEqual(self.street_content, elt) self.assertEqual(ToDOM(elt).toxml("utf-8"), self.street_xmld) def testDOMElementSimpleContent(self): elt = USAddress._ElementMap['street'].elementBinding().createFromDOM( self.street_dom) self.assertEqual(ToDOM(elt).toxml("utf-8"), self.street_xmld) def testPythonElementComplexContent_Element(self): addr = USAddress(name='Customer', street='95 Main St') self.assertEqual('95 Main St', addr.street) addr = USAddress('Customer', '95 Main St') self.assertEqual('95 Main St', addr.street) addr.street = '43 West Oak' self.assertEqual('43 West Oak', addr.street) def testDOM_CTD_element(self): # NB: USAddress is a CTD, not an element. xmlt = six.u('<shipTo>%s</shipTo>') % (self.address1_xmlt, ) dom = pyxb.utils.domutils.StringToDOM(xmlt) addr2 = USAddress.Factory(_dom_node=dom.documentElement) def testPurchaseOrder(self): po = purchaseOrder(shipTo=USAddress(name='Customer', street='95 Main St'), billTo=USAddress(name='Sugar Mama', street='24 E. Dearling Ave'), comment='Thanks!') xmld = ToDOM(po).toxml("utf-8") xml1t = '<ns1:purchaseOrder xmlns:ns1="http://www.example.com/altPO1"><shipTo><name>Customer</name><street>95 Main St</street></shipTo><billTo><name>Sugar Mama</name><street>24 E. Dearling Ave</street></billTo><ns1:comment>Thanks!</ns1:comment></ns1:purchaseOrder>' xml1d = xml1t.encode('utf-8') self.assertEqual(xmld, xml1d) dom = pyxb.utils.domutils.StringToDOM(xml1t) po2 = purchaseOrder.createFromDOM(dom.documentElement) self.assertEqual(ToDOM(po2).toxml("utf-8"), xml1d) xml2t = '<purchaseOrder xmlns="http://www.example.com/altPO1"><shipTo><name>Customer</name><street>95 Main St</street></shipTo><billTo><name>Sugar Mama</name><street>24 E. Dearling Ave</street></billTo><comment>Thanks!</comment></purchaseOrder>' xml2d = xml2t.encode('utf-8') bds = pyxb.utils.domutils.BindingDOMSupport() bds.setDefaultNamespace(Namespace) self.assertEqual(ToDOM(po2, dom_support=bds).toxml("utf-8"), xml2d)
def testEnumerations (self): instance = CreateFromDocument(six.u('<qne xmlns:ns1="urn:issue13.1">ns1:one</qne>')) self.assertEqual(instance.value(), ns1.createExpandedName('one')) with self.assertRaises(pyxb.SimpleFacetValueError) as cm: instance = CreateFromDocument(six.u('<qne xmlns:ns1="urn:issue13.1">ns1:un</qne>')) self.assertEqual('Type tQNE enumeration constraint violated by value {urn:issue13.1}un', str(cm.exception)) with self.assertRaises(pyxb.SimpleFacetValueError) as cm: instance = CreateFromDocument(six.u('<qne xmlns:ns1="urn:issue13.2">ns1:one</qne>')) self.assertEqual('Type tQNE enumeration constraint violated by value {urn:issue13.2}one', str(cm.exception))
def testDeep (self): w = wrapper(BIND(BIND(4, deep=4), BIND('hi'))) xmlt = six.u('<wrapper><holding><optional deep="4">4</optional><required>hi</required></holding></wrapper>') xmld = xmlt.encode('utf-8') self.assertEqual(w.toxml("utf-8", root_only=True), xmld) w = wrapper(BIND(BIND('hi', deep=2))) xmlt = six.u('<wrapper><holding><required deep="2">hi</required></holding></wrapper>') xmld = xmlt.encode('utf-8') self.assertEqual(w.toxml("utf-8", root_only=True), xmld)
def testStrings (self): encoded_values = [ six.u('01'), six.u('00'), six.u('ab'), six.u('Ab'), six.u('AB12') ] for et in encoded_values: ed = et.encode('utf-8') v = xsd.hexBinary.Factory(ed) self.assertEqual(v, ed) v = xsd.hexBinary.Factory(et, _from_xml=True) self.assertEqual(len(et)//2, len(v)) self.assertEqual(et.upper(), v.xsdLiteral())
def testBasic(self): xmlt = six.u('<elt>30313233</elt>') xmld = xmlt.encode('utf-8') instance = CreateFromDocument(xmlt) self.assertEqual(b'0123', instance.value()) xmlt = six.u('<elt Color="33323130">30313233</elt>') xmld = xmlt.encode('utf-8') instance = CreateFromDocument(xmlt) self.assertEqual(b'0123', instance.value()) self.assertEqual(b'3210', instance.Color)
def testFixedMultichoice (self): xmlt = six.u('<fixedMultichoice xmlns="URN:test-mg-choice"></fixedMultichoice>') dom = pyxb.utils.domutils.StringToDOM(xmlt) instance = fixedMultichoice.createFromDOM(dom.documentElement) xmlt = six.u('<ns1:fixedMultichoice xmlns:ns1="URN:test-mg-choice"><A/><A/></ns1:fixedMultichoice>') dom = pyxb.utils.domutils.StringToDOM(xmlt) instance = fixedMultichoice.createFromDOM(dom.documentElement) xmlt = six.u('<ns1:fixedMultichoice xmlns:ns1="URN:test-mg-choice"><A/><B/></ns1:fixedMultichoice>') dom = pyxb.utils.domutils.StringToDOM(xmlt) self.assertRaises(UnrecognizedContentError, fixedMultichoice.createFromDOM, dom.documentElement)
def testBasic (self): xmlt = six.u('<elt>30313233</elt>') xmld = xmlt.encode('utf-8') instance = CreateFromDocument(xmlt) self.assertEqual(b'0123', instance.value()) xmlt = six.u('<elt Color="33323130">30313233</elt>') xmld = xmlt.encode('utf-8') instance = CreateFromDocument(xmlt) self.assertEqual(b'0123', instance.value()) self.assertEqual(b'3210', instance.Color)
class TestIncompleteElementContentError(unittest.TestCase): Good_xmlt = six.u( '<eTranslateCard><eConcCardCymru>un</eConcCardCymru><eConcCardEnglish>one</eConcCardEnglish><cardinal>1</cardinal></eTranslateCard>' ) Good_xmld = Good_xmlt.encode('utf-8') Bad_xmlt = six.u( '<eTranslateCard><eConcCardEnglish>one</eConcCardEnglish><cardinal>1</cardinal></eTranslateCard>' ) Bad_xmld = Bad_xmlt.encode('utf-8') Bad_details = '''The containing element eTranslateCard is defined at trac26.xsd[124:2]. The containing element type tTranslateCard is defined at trac26.xsd[115:2] The tTranslateCard automaton is not in an accepting state. The last accepted content was eConcCardCymru The following element and wildcard content would be accepted: \tAn element eConcCardEnglish per trac26.xsd[119:8] The following content was not processed by the automaton: \tcardinal (1 instances)''' Bad_details_noloc = '''The containing element eTranslateCard is defined at None. The containing element type tTranslateCard is defined at None The tTranslateCard automaton is not in an accepting state. The last accepted content was eConcCardCymru The following element and wildcard content would be accepted: \tAn element eConcCardEnglish per None The following content was not processed by the automaton: \tcardinal (1 instances)''' def testSchemaSupport(self): instance = trac26.eTranslateCard(trac26.eConcCardCymru('un'), trac26.eConcCardEnglish('one'), xs.int(1)) self.assertTrue(instance.validateBinding()) instance = trac26.CreateFromDocument(self.Good_xmlt) self.assertEqual(self.Good_xmld, instance.toxml('utf-8', root_only=True)) instance = trac26.eTranslateCard(trac26.eConcCardCymru('un')) instance.cardinal = 1 instance.eConcCardEnglish = 'one' self.assertTrue(instance.validateBinding()) 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)
def testReplaceString (self): self.assertEqual("test", ReplaceString("test", _from_xml=True)) self.assertEqual(" test", ReplaceString(" test", _from_xml=True)) self.assertEqual(" test", ReplaceString("\ttest", _from_xml=True)) self.assertEqual(" test ", ReplaceString("\ttest\n\r", _from_xml=True)) self.assertEqual(" test too ", ReplaceString("\ttest\n\rtoo\n", _from_xml=True)) self.assertEqual("test", ReplaceString(six.u("test"), _from_xml=True)) self.assertEqual(" test", ReplaceString(six.u(" test"), _from_xml=True)) self.assertEqual(" test", ReplaceString(six.u("\ttest"), _from_xml=True)) self.assertEqual(" test ", ReplaceString(six.u("\ttest\n\r"), _from_xml=True)) self.assertEqual(" test too ", ReplaceString(six.u("\ttest\n\rtoo\n"), _from_xml=True))
def testElements (self): instance = CreateFromDocument(six.u('<qn>nons</qn>')) self.assertEqual(six.u('nons'), instance) self.assertEqual(six.u('<qn>nons</qn>').encode('utf-8'), instance.toxml('utf-8',root_only=True)) instance = CreateFromDocument(six.u('<qn>xml:nons</qn>')) self.assertTrue(isinstance(instance, pyxb.namespace.ExpandedName)) self.assertEqual(pyxb.namespace.XML, instance.namespace()) self.assertEqual(pyxb.namespace.XML.createExpandedName('nons'), instance) xmld = instance.toxml('utf-8',root_only=True) self.assertEqual(instance, CreateFromDocument(xmld)) self.assertEqual(six.u('<qn xmlns:xml="http://www.w3.org/XML/1998/namespace">xml:nons</qn>').encode('utf-8'), xmld)
def testSubstitutions (self): xmlt = six.u('<elt attrOne="low" xsi:type="alt1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><first>content</first></elt>') doc = pyxb.utils.domutils.StringToDOM(xmlt) instance = CreateFromDOM(doc.documentElement) self.assertEqual('content', instance.first) self.assertEqual('low', instance.attrOne) xmlt = six.u('<elt attrTwo="hi" xsi:type="alt2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><second/></elt>') doc = pyxb.utils.domutils.StringToDOM(xmlt) instance = CreateFromDOM(doc.documentElement) self.assertTrue(instance.second is not None) self.assertEqual('hi', instance.attrTwo)
def test (self): self.assertEqual(Cardinals.one, Cardinals('one')) self.assertEqual(Cardinals.one, Cardinals(six.u('one'))) self.assertEqual(Cardinals.three, Cardinals('three')) self.assertEqual(Cardinals.three, Cardinals(six.u('three'))) self.assertRaises(SimpleFacetValueError, Cardinals, 'One') self.assertRaises(SimpleFacetValueError, Cardinals, 'four') if sys.version_info[:2] >= (2, 7): with self.assertRaises(SimpleFacetValueError) as cm: Cardinals('four') self.assertEqual(cm.exception.facet, Cardinals._CF_enumeration)
def testComplex (self): canonicalt = six.u('<complex xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>') canonicald = canonicalt.encode('utf-8') for xmlt in ( canonicalt, six.u('<complex xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"></complex>'), six.u('<complex xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"><!-- comment --></complex>')) : doc = pyxb.utils.domutils.StringToDOM(xmlt) instance = CreateFromDOM(doc.documentElement) self.assertTrue(instance._isNil()) self.assertEqual(instance.toDOM().documentElement.toxml("utf-8"), canonicald) instance.validateBinding()
def testMakeIdentifier (self): self.assertEqual('id', MakeIdentifier('id')) self.assertEqual('id', MakeIdentifier(six.u('id'))) self.assertEqual('id_sep', MakeIdentifier(six.u('id_sep'))) self.assertEqual('id_sep', MakeIdentifier(six.u('id sep'))) self.assertEqual('id_sep_too', MakeIdentifier(six.u('id-sep too'))) self.assertEqual('idid', MakeIdentifier(six.u('id&id'))) self.assertEqual('id', MakeIdentifier('_id')) self.assertEqual('id_', MakeIdentifier('_id_')) self.assertEqual('emptyString', MakeIdentifier('')) self.assertEqual('emptyString', MakeIdentifier('_'))
def testReplace (self): self.assertEqual("test", self.__Replace.normalizeString("test")) self.assertEqual(" test", self.__Replace.normalizeString(" test")) self.assertEqual(" test", self.__Replace.normalizeString("\ttest")) self.assertEqual(" test ", self.__Replace.normalizeString("\ttest\n\r")) self.assertEqual(" test too ", self.__Replace.normalizeString("\ttest\n\rtoo\n")) self.assertEqual("test", self.__Replace.normalizeString(six.u("test"))) self.assertEqual(" test", self.__Replace.normalizeString(six.u(" test"))) self.assertEqual(" test", self.__Replace.normalizeString(six.u("\ttest"))) self.assertEqual(" test ", self.__Replace.normalizeString(six.u("\ttest\n\r"))) self.assertEqual(" test too ", self.__Replace.normalizeString(six.u("\ttest\n\rtoo\n")))
def testCollapse (self): self.assertEqual("test", self.__Collapse.normalizeString("test")) self.assertEqual("test", self.__Collapse.normalizeString(" test")) self.assertEqual("test", self.__Collapse.normalizeString("\ttest")) self.assertEqual("test", self.__Collapse.normalizeString("\ttest\n\r")) self.assertEqual("test too", self.__Collapse.normalizeString("\ttest\n\rtoo\n")) self.assertEqual("test", self.__Collapse.normalizeString(six.u("test"))) self.assertEqual("test", self.__Collapse.normalizeString(six.u(" test"))) self.assertEqual("test", self.__Collapse.normalizeString(six.u("\ttest"))) self.assertEqual("test", self.__Collapse.normalizeString(six.u("\ttest\n\r"))) self.assertEqual("test too", self.__Collapse.normalizeString(six.u("\ttest\n\rtoo\n")))
def testCtorMixed (self): instance = Mixed() self.assertRaises(pyxb.AttributeValidationError, instance.validateBinding) instance = Mixed(units='m') self.assertTrue(instance.validateBinding()) instance = Mixed(4, units='m') self.assertTrue(instance.validateBinding()) self.assertEqual(six.u('4'), instance.orderedContent()[0].value) instance = Mixed(xs.int(4), units='m') self.assertTrue(instance.validateBinding()) self.assertEqual(six.u('4'), instance.orderedContent()[0].value)
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 test(self): self.assertEqual(Cardinals.one, Cardinals('one')) self.assertEqual(Cardinals.one, Cardinals(six.u('one'))) self.assertEqual(Cardinals.three, Cardinals('three')) self.assertEqual(Cardinals.three, Cardinals(six.u('three'))) self.assertRaises(SimpleFacetValueError, Cardinals, 'One') self.assertRaises(SimpleFacetValueError, Cardinals, 'four') if sys.version_info[:2] >= (2, 7): with self.assertRaises(SimpleFacetValueError) as cm: Cardinals('four') self.assertEqual(cm.exception.facet, Cardinals._CF_enumeration)
def testCollapseString (self): # The way it will work if from DOM content: self.assertEqual("test", CollapseString("test", _from_xml=True)) self.assertEqual("test", CollapseString(" test", _from_xml=True)) self.assertEqual("test", CollapseString("\ttest", _from_xml=True)) self.assertEqual("test", CollapseString("\ttest\n\r", _from_xml=True)) self.assertEqual("test too", CollapseString("\ttest\n\rtoo\n", _from_xml=True)) self.assertEqual("test", CollapseString(six.u("test"), _from_xml=True)) self.assertEqual("test", CollapseString(six.u(" test"), _from_xml=True)) self.assertEqual("test", CollapseString(six.u("\ttest"), _from_xml=True)) self.assertEqual("test", CollapseString(six.u("\ttest\n\r"), _from_xml=True)) self.assertEqual("test too", CollapseString(six.u("\ttest\n\rtoo\n"), _from_xml=True))
def testDirect(self): v = po2(8) self.assertEqual(po2._elementForValue(8).value(), v) self.assertTrue(isinstance(v, po2)) v = po2(six.u('8')) self.assertEqual(po2._elementForValue(8).value(), v) self.assertTrue(isinstance(v, po2)) self.assertRaises(SimpleFacetValueError, po2, 9) v = english(six.u('b@d')) self.assertEqual(english.bd, v) self.assertRaises(SimpleFacetValueError, eng, six.u('bd'))
def testCtorMixed(self): instance = Mixed() self.assertRaises(pyxb.AttributeValidationError, instance.validateBinding) instance = Mixed(units='m') self.assertTrue(instance.validateBinding()) instance = Mixed(4, units='m') self.assertTrue(instance.validateBinding()) self.assertEqual(six.u('4'), instance.orderedContent()[0].value) instance = Mixed(xs.int(4), units='m') self.assertTrue(instance.validateBinding()) self.assertEqual(six.u('4'), instance.orderedContent()[0].value)
def testEmptyWithAttr (self): self.assertEqual(5, len(emptyWithAttr.typeDefinition()._AttributeMap)) self.assertRaises(MissingAttributeError, CreateFromDocument, '<emptyWithAttr xmlns="URN:testCTD"/>') instance = CreateFromDocument('<emptyWithAttr capitalized="false" xmlns="URN:testCTD"/>') self.assertEqual('irish', instance.language) self.assertTrue(not instance.capitalized) self.assertEqual(5432, instance.port) self.assertEqual('top default', instance.tlAttr) self.assertEqual('stone', instance.immutable) instance.tlAttr = 'new value' self.assertEqual('new value', instance.tlAttr) # Can't change immutable attributes self.assertRaises(AttributeChangeError, self.setImmutable, instance, 'water') self.assertRaises(AttributeChangeError, CreateFromDocument, '<emptyWithAttr capitalized="true" immutable="water" xmlns="URN:testCTD"/>') instance = CreateFromDocument('<emptyWithAttr capitalized="true" language="hebrew" xmlns="URN:testCTD"/>') self.assertEqual('hebrew', instance.language) self.assertTrue(instance.capitalized) self.assertEqual(5432, instance.port) # Raw constructor generates default everything; optional # attributes may have value None. instance = emptyWithAttr() self.assertEqual('irish', instance.language) self.assertTrue(instance.capitalized is None) self.assertEqual(5432, instance.port) self.assertRaises(pyxb.MissingAttributeError, ToDOM, instance) instance.capitalized = False xmlt = six.u('<tca:emptyWithAttr capitalized="false" xmlns:tca="URN:testCTD"/>') xmld = xmlt.encode('utf-8') self.assertEqual(ToDOM(instance).toxml("utf-8"), xmld) # Test reference attribute self.assertEqual('top default', instance.tlAttr) # Create another instance, to make sure the attributes are different instance2 = emptyWithAttr() self.assertEqual('irish', instance2.language) instance2.language = 'french' instance2.capitalized = False xmlt = six.u('<tca:emptyWithAttr capitalized="false" language="french" xmlns:tca="URN:testCTD"/>') xmld = xmlt.encode('utf-8') self.assertEqual(ToDOM(instance2).toxml("utf-8"), xmld) self.assertNotEqual(instance.language, instance2.language) # Verify the use. Note reference through CTD not element. au = emptyWithAttr_._AttributeMap['language'] self.assertFalse(au.required()) self.assertFalse(au.prohibited()) au = emptyWithAttr_._AttributeMap['capitalized'] self.assertTrue(au.required()) self.assertFalse(au.prohibited())
def testElementForValue (self): e1 = english._elementForValue(six.u('one')) self.assertEqual(english.one, e1.value()) self.assertEqual('one', e1.tag()) self.assertRaises(KeyError, english._elementForValue, six.u('no such value')) ev = english._elementForValue(six.u('b@d')) self.assertEqual(english.bd, ev.value()) v2 = po2._elementForValue(2) self.assertEqual(2, v2.value()) self.assertIsNone(v2.tag()) self.assertRaises(KeyError, po2._elementForValue, six.u('2'))
def testDirect (self): v = po2(8) self.assertEqual(po2._elementForValue(8).value(), v) self.assertTrue(isinstance(v, po2)) v = po2(six.u('8')) self.assertEqual(po2._elementForValue(8).value(), v) self.assertTrue(isinstance(v, po2)) self.assertRaises(SimpleFacetValueError, po2, 9) v = english(six.u('b@d')) self.assertEqual(english.bd, v) self.assertRaises(SimpleFacetValueError, eng, six.u('bd'))
class TestUnrecognizedAttributeError(unittest.TestCase): Good_xmlt = six.u('<eAttributes aReq="4"/>') Good_xmld = Good_xmlt.encode('utf-8') Bad_xmlt = six.u('<eAttributes aReq="4" aBad="1"/>') Bad_xmld = Bad_xmlt.encode('utf-8') def testSchemaSupport(self): dom = pyxb.utils.domutils.StringToDOM(self.Good_xmlt) instance = trac26.CreateFromDOM(dom) self.assertEqual(self.Good_xmld, instance.toxml('utf-8', root_only=True)) def testDOM(self): dom = pyxb.utils.domutils.StringToDOM(self.Bad_xmlt) with self.assertRaises(pyxb.UnrecognizedAttributeError) as cm: instance = trac26.CreateFromDOM(dom) e = cm.exception # The code path for this is creating a map from attribute tags # to values in isolation of the specific instance. A # partially-constructed instance is available, but the # location is not available. self.assertEqual(e.type, trac26.tAttributes) self.assertEqual(e.tag, 'aBad') self.assertTrue(e.instance is not None) self.assertTrue(isinstance(e.instance, e.type)) self.assertTrue(e.location is None) def testDocument(self): instance = None with self.assertRaises(pyxb.UnrecognizedAttributeError) as cm: instance = trac26.CreateFromDocument(self.Bad_xmlt) self.assertTrue(instance is None) e = cm.exception self.assertEqual(e.type, trac26.tAttributes) self.assertEqual(e.tag, 'aBad') # In this case we were given an instance, which provides a # location. Note that initialization of the instance was left # incomplete. self.assertFalse(e.instance is None) self.assertFalse((e.location is None) and (pyxb.XMLStyle_saxer == pyxb._XMLStyle)) if e.location is not None: self.assertEqual(1, e.location.lineNumber) self.assertEqual(0, e.location.columnNumber) def testDisplayDOM(self): if DisplayException: trac26.CreateFromDOM(pyxb.utils.domutils.StringToDOM( self.Bad_xmlt)) def testDisplayDoc(self): if DisplayException: trac26.CreateFromDocument(self.Bad_xmlt)
class TestAbstractInstantiationError(unittest.TestCase): Good_xmlt = six.u( '<eUseAbstract xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><eAbstract xsi:type="tConcSubCymru"><welsh>un</welsh></eAbstract></eUseAbstract>' ) Good_xmld = Good_xmlt.encode('utf-8') Bad_xmlt = six.u( '<eUseAbstract xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><eAbstract><welsh>un</welsh></eAbstract></eUseAbstract>' ) Bad_xmld = Bad_xmlt.encode('utf-8') def testSchemaSupport(self): cym1 = trac26.tConcSubCymru('un') eng3 = trac26.tConcSubEnglish('three') # Direct generation works instance = trac26.eUseAbstract(cym1) # So does from documents with xsi:type i2 = trac26.CreateFromDocument(self.Good_xmlt) self.assertTrue(isinstance(i2.eAbstract, trac26.tConcSubCymru)) def testException(self): scym1 = trac26.tCardCymru('un') instance = None with self.assertRaises(pyxb.AbstractInstantiationError) as cm: instance = trac26.eAbstract(scym1) e = cm.exception self.assertTrue(instance is None) self.assertEqual( str(e), 'Cannot instantiate abstract type tAbstract directly') def testFromDocument(self): instance = None with self.assertRaises(pyxb.AbstractInstantiationError) as cm: instance = trac26.CreateFromDocument(self.Bad_xmlt) e = cm.exception self.assertTrue(instance is None) # Location within Bad_xmlt where error occurred self.assertFalse((e.location is None) and (pyxb.XMLStyle_saxer == pyxb._XMLStyle)) if e.location is not None: self.assertEqual(1, e.location.lineNumber) self.assertEqual(68, e.location.columnNumber) def testDisplayException(self): if DisplayException: scym1 = trac26.tCardCymru('un') trac26.eAbstract(scym1) def testDisplayExceptionDoc(self): if DisplayException: instance = trac26.CreateFromDocument(self.Bad_xmlt)
def _MatchCharClassExpr(text, position): '''Parse a U{charClassExpr<http://www.w3.org/TR/xmlschema-2/#nt-charClassExpr>}. These are XML regular expression classes such as C{[abc]}, C{[a-c]}, C{[^abc]}, or C{[a-z-[q]]}. @param text: The complete text of the regular expression being translated. The first character must be the C{[} starting a character class. @param position: The offset of the start of the character group. @return: A pair C{(cps, p)} where C{cps} is a L{pyxb.utils.unicode.CodePointSet} containing the code points associated with the property, and C{p} is the text offset immediately following the closing brace. @raise RegularExpressionError: if the expression is syntactically invalid. ''' if position >= len(text): raise RegularExpressionError(position, 'Missing character class expression') if six.u('[') != text[position]: raise RegularExpressionError( position, "Expected start of character class expression, got '%s'" % (text[position], )) position = position + 1 if position >= len(text): raise RegularExpressionError(position, 'Missing character class expression') negated = (text[position] == '^') if negated: position = position + 1 result_cps, has_following_subtraction, position = _MatchPosCharGroup( text, position) if negated: result_cps = result_cps.negate() if has_following_subtraction: assert text[position] == six.u('-') assert text[position + 1] == six.u('[') position = position + 1 sub_cps, position = _MatchCharClassExpr(text, position) result_cps.subtract(sub_cps) if position >= len(text) or text[position] != six.u(']'): raise RegularExpressionError(position, "Expected ']' to end character class") return result_cps, position + 1
def testBasic (self): instance = color(color_.red, color_=color_.green) xmlt = six.u('<color color="green"><color>red</color></color>') xmld = xmlt.encode('utf-8') self.assertEqual(instance.toxml("utf-8", root_only=True), xmld) instance.color = color_.blue xmlt = six.u('<color color="green"><color>blue</color></color>') xmld = xmlt.encode('utf-8') self.assertEqual(instance.toxml("utf-8", root_only=True), xmld) instance.color_ = color_.red xmlt = six.u('<color color="red"><color>blue</color></color>') xmld = xmlt.encode('utf-8') self.assertEqual(instance.toxml("utf-8", root_only=True), xmld)
def testElementForValue(self): e1 = english._elementForValue(six.u('one')) self.assertEqual(english.one, e1.value()) self.assertEqual('one', e1.tag()) self.assertRaises(KeyError, english._elementForValue, six.u('no such value')) ev = english._elementForValue(six.u('b@d')) self.assertEqual(english.bd, ev.value()) v2 = po2._elementForValue(2) self.assertEqual(2, v2.value()) self.assertIsNone(v2.tag()) self.assertRaises(KeyError, po2._elementForValue, six.u('2'))
def testMixedOnly (self): xmlt = six.u('<anything>mixed</anything>') instance = CreateFromDocument(xmlt) self.assertEqual(0, len(instance.wildcardElements())) oc = instance.orderedContent() self.assertEqual(1, len(oc)) self.assertTrue(isinstance(oc[0], pyxb.binding.basis.NonElementContent)) i = anything() i.append('mixed') i.validateBinding() xmlt = six.u('<anything>mixed</anything>') xmld = xmlt.encode('utf-8') self.assertEqual(xmld, i.toxml('utf-8', root_only=True))
def testAddAttributes(self): x = wildcard() self.assertEqual(six.u('<wildcard/>'), x.toxml('utf-8', root_only=True).decode('utf-8')) x.attr = False self.assertEqual( six.u('<wildcard attr="false"/>').encode('utf-8'), x.toxml('utf-8', root_only=True)) x._setAttribute(ns1.createExpandedName('w1'), 'val') self.assertEqual( six.u( '<wildcard attr="false" n1:w1="val" xmlns:n1="urn:issue14.1"/>' ).encode('utf-8'), x.toxml('utf-8', root_only=True))
def testBasic(self): instance = color(color_.red, color_=color_.green) xmlt = six.u('<color color="green"><color>red</color></color>') xmld = xmlt.encode('utf-8') self.assertEqual(instance.toxml("utf-8", root_only=True), xmld) instance.color = color_.blue xmlt = six.u('<color color="green"><color>blue</color></color>') xmld = xmlt.encode('utf-8') self.assertEqual(instance.toxml("utf-8", root_only=True), xmld) instance.color_ = color_.red xmlt = six.u('<color color="red"><color>blue</color></color>') xmld = xmlt.encode('utf-8') self.assertEqual(instance.toxml("utf-8", root_only=True), xmld)
def testElement(self): xmlt = six.u('<anything><text>eltcontent</text></anything>') instance = CreateFromDocument(xmlt) self.assertEqual(1, len(instance.wildcardElements())) oc = instance.orderedContent() self.assertEqual(1, len(oc)) self.assertTrue(isinstance(oc[0], pyxb.binding.basis.ElementContent)) i = anything() i.append(text('eltcontent')) i.validateBinding() xmlt = six.u('<anything><text>eltcontent</text></anything>') xmld = xmlt.encode('utf-8') self.assertEqual(xmld, i.toxml('utf-8', root_only=True))
def testMultilevel (self): xmlt = six.u('<concreteBase><basement>dirt floor</basement></concreteBase>') doc = pyxb.utils.domutils.StringToDOM(xmlt) instance = CreateFromDOM(doc.documentElement) self.assertEqual('dirt floor', instance.basement) xmlt = six.u('<oneFloor xsi:type="restaurant" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><basement>concrete</basement><lobby>tiled</lobby><room>eats</room></oneFloor>') doc = pyxb.utils.domutils.StringToDOM(xmlt) instance = CreateFromDOM(doc.documentElement) self.assertEqual(concreteBase_.basement, instance.__class__.basement) self.assertEqual(oneFloor_.lobby, instance.__class__.lobby) self.assertEqual(restaurant_.room, instance.__class__.room) self.assertEqual('tiled', instance.lobby) self.assertEqual('eats', instance.room)
def testTooManySingle(self): xmlt = six.u( '<ns1:choice xmlns:ns1="URN:test-mg-choice"><first/><second/></ns1:choice>' ) dom = pyxb.utils.domutils.StringToDOM(xmlt) self.assertRaises(UnrecognizedContentError, choice.createFromDOM, dom.documentElement) xmlt = six.u( '<ns1:choice xmlns:ns1="URN:test-mg-choice"><second/><third/></ns1:choice>' ) dom = pyxb.utils.domutils.StringToDOM(xmlt) self.assertRaises(UnrecognizedContentError, choice.createFromDOM, dom.documentElement)
class TestMixedContentError(unittest.TestCase): Good_xmlt = six.u('<eCTwSCSequence><eCTwSC>2</eCTwSC></eCTwSCSequence>') Good_xmld = Good_xmlt.encode('utf-8') Bad_xmlt = six.u( '<eCTwSCSequence><eCTwSC>2</eCTwSC>noise</eCTwSCSequence>') Bad_xmld = Bad_xmlt.encode('utf-8') def testSchemaSupport(self): instance = trac26.eCTwSCSequence() instance.append(trac26.eCTwSC(2)) instance = trac26.CreateFromDocument(self.Good_xmlt) self.assertEqual(self.Good_xmld, instance.toxml('utf-8', root_only=True)) def testException(self): instance = trac26.eCTwSCSequence() instance.append(trac26.eCTwSC(2)) with self.assertRaises(pyxb.MixedContentError) as cm: instance.append('noise') e = cm.exception self.assertTrue(e.location is None) self.assertEqual(e.instance, instance) self.assertEqual(e.value, 'noise') self.assertEqual(str(e), 'Invalid non-element content') def testDocument(self): instance = None with self.assertRaises(pyxb.MixedContentError) as cm: instance = trac26.CreateFromDocument(self.Bad_xmlt) e = cm.exception self.assertFalse((e.location is None) and (pyxb.XMLStyle_saxer == pyxb._XMLStyle)) loctext = '' if e.location is not None: self.assertEqual(1, e.location.lineNumber) self.assertEqual(34, e.location.columnNumber) loctext = ' at <unknown>[1:34]' self.assertEqual(e.value, 'noise') self.assertEqual(str(e), 'Invalid non-element content{}'.format(loctext)) def testDisplay(self): if DisplayException: instance = trac26.eCTwSCSequence() instance.append(trac26.eCTwSC(2)) instance.append('noise') def testDisplayDoc(self): if DisplayException: instance = trac26.CreateFromDocument(self.Bad_xmlt)