Package lxml :: Package tests :: Module test_objectify
[hide private]
[frames] | no frames]

Source Code for Module lxml.tests.test_objectify

   1  # -*- coding: utf-8 -*- 
   2   
   3  """ 
   4  Tests specific to the lxml.objectify API 
   5  """ 
   6   
   7   
   8  import unittest, operator 
   9   
  10  from common_imports import etree, StringIO, HelperTestCase, fileInTestDir 
  11  from common_imports import SillyFileLike, canonicalize, doctest 
  12  from common_imports import itemgetter 
  13   
  14  from lxml import objectify 
  15   
  16  PYTYPE_NAMESPACE = "http://codespeak.net/lxml/objectify/pytype" 
  17  XML_SCHEMA_NS = "http://www.w3.org/2001/XMLSchema" 
  18  XML_SCHEMA_INSTANCE_NS = "http://www.w3.org/2001/XMLSchema-instance" 
  19  XML_SCHEMA_INSTANCE_TYPE_ATTR = "{%s}type" % XML_SCHEMA_INSTANCE_NS 
  20  XML_SCHEMA_NIL_ATTR = "{%s}nil" % XML_SCHEMA_INSTANCE_NS 
  21  DEFAULT_NSMAP = { "py" : PYTYPE_NAMESPACE, 
  22                    "xsi" : XML_SCHEMA_INSTANCE_NS, 
  23                    "xsd" : XML_SCHEMA_NS} 
  24   
  25  objectclass2xsitype = { 
  26      # objectify built-in 
  27      objectify.IntElement: ("int", "short", "byte", "unsignedShort", 
  28                             "unsignedByte",), 
  29      objectify.LongElement: ("integer", "nonPositiveInteger", "negativeInteger", 
  30                              "long", "nonNegativeInteger", "unsignedLong", 
  31                              "unsignedInt", "positiveInteger",), 
  32      objectify.FloatElement: ("float", "double"), 
  33      objectify.BoolElement: ("boolean",), 
  34      objectify.StringElement: ("string", "normalizedString", "token", "language", 
  35                                "Name", "NCName", "ID", "IDREF", "ENTITY", 
  36                                "NMTOKEN", ), 
  37      # None: xsi:nil="true" 
  38      } 
  39   
  40  xsitype2objclass = dict(( (v, k) for k in objectclass2xsitype 
  41                            for v in objectclass2xsitype[k] )) 
  42   
  43  xml_str = '''\ 
  44  <obj:root xmlns:obj="objectified" xmlns:other="otherNS"> 
  45    <obj:c1 a1="A1" a2="A2" other:a3="A3"> 
  46      <obj:c2>0</obj:c2> 
  47      <obj:c2>1</obj:c2> 
  48      <obj:c2>2</obj:c2> 
  49      <other:c2>3</other:c2> 
  50      <c2>3</c2> 
  51    </obj:c1> 
  52  </obj:root>''' 
  53   
54 -class ObjectifyTestCase(HelperTestCase):
55 """Test cases for lxml.objectify 56 """ 57 etree = etree 58
59 - def XML(self, xml):
60 return self.etree.XML(xml, self.parser)
61
62 - def setUp(self):
63 super(ObjectifyTestCase, self).setUp() 64 self.parser = self.etree.XMLParser(remove_blank_text=True) 65 lookup = etree.ElementNamespaceClassLookup( 66 objectify.ObjectifyElementClassLookup() ) 67 self.parser.setElementClassLookup(lookup) 68 69 self.Element = self.parser.makeelement 70 71 ns = self.etree.Namespace("otherNS") 72 ns[None] = self.etree.ElementBase
73
74 - def tearDown(self):
75 self.etree.Namespace("otherNS").clear() 76 objectify.setPytypeAttributeTag() 77 super(ObjectifyTestCase, self).tearDown()
78
80 elt = objectify.Element("test") 81 self.assertEquals(elt.nsmap, DEFAULT_NSMAP)
82
83 - def test_element_nsmap_empty(self):
84 nsmap = {} 85 elt = objectify.Element("test", nsmap=nsmap) 86 self.assertEquals(elt.nsmap.values(), [PYTYPE_NAMESPACE])
87
89 nsmap = {"mypy": PYTYPE_NAMESPACE, 90 "myxsi": XML_SCHEMA_INSTANCE_NS, 91 "myxsd": XML_SCHEMA_NS} 92 elt = objectify.Element("test", nsmap=nsmap) 93 self.assertEquals(elt.nsmap, nsmap)
94
96 nsmap = {"my": "someNS", 97 "myother": "someOtherNS", 98 "myxsd": XML_SCHEMA_NS} 99 elt = objectify.Element("test", nsmap=nsmap) 100 self.assert_(PYTYPE_NAMESPACE in elt.nsmap.values()) 101 for prefix, ns in nsmap.items(): 102 self.assert_(prefix in elt.nsmap) 103 self.assertEquals(nsmap[prefix], elt.nsmap[prefix])
104
106 root = objectify.Element("root") 107 root.sub = objectify.Element("test") 108 self.assertEquals(root.sub.nsmap, DEFAULT_NSMAP)
109
111 root = objectify.Element("root") 112 nsmap = {} 113 root.sub = objectify.Element("test", nsmap=nsmap) 114 self.assertEquals(root.sub.nsmap, DEFAULT_NSMAP)
115
117 root = objectify.Element("root") 118 nsmap = {"mypy": PYTYPE_NAMESPACE, 119 "myxsi": XML_SCHEMA_INSTANCE_NS, 120 "myxsd": XML_SCHEMA_NS} 121 root.sub = objectify.Element("test", nsmap=nsmap) 122 self.assertEquals(root.sub.nsmap, DEFAULT_NSMAP)
123
125 root = objectify.Element("root") 126 nsmap = {"my": "someNS", 127 "myother": "someOtherNS", 128 "myxsd": XML_SCHEMA_NS,} 129 root.sub = objectify.Element("test", nsmap=nsmap) 130 expected = nsmap.copy() 131 del expected["myxsd"] 132 expected.update(DEFAULT_NSMAP) 133 self.assertEquals(root.sub.nsmap, expected)
134
136 value = objectify.DataElement("test this") 137 self.assertEquals(value.nsmap, DEFAULT_NSMAP)
138
140 nsmap = {} 141 value = objectify.DataElement("test this", nsmap=nsmap) 142 self.assertEquals(value.nsmap.values(), [PYTYPE_NAMESPACE])
143
145 nsmap = {"mypy": PYTYPE_NAMESPACE, 146 "myxsi": XML_SCHEMA_INSTANCE_NS, 147 "myxsd": XML_SCHEMA_NS} 148 value = objectify.DataElement("test this", nsmap=nsmap) 149 self.assertEquals(value.nsmap, nsmap)
150
152 nsmap = {"my": "someNS", 153 "myother": "someOtherNS", 154 "myxsd": XML_SCHEMA_NS,} 155 value = objectify.DataElement("test", nsmap=nsmap) 156 self.assert_(PYTYPE_NAMESPACE in value.nsmap.values()) 157 for prefix, ns in nsmap.items(): 158 self.assert_(prefix in value.nsmap) 159 self.assertEquals(nsmap[prefix], value.nsmap[prefix])
160
162 root = objectify.Element("root") 163 root.value = objectify.DataElement("test this") 164 self.assertEquals(root.value.nsmap, DEFAULT_NSMAP)
165
167 root = objectify.Element("root") 168 nsmap = {} 169 root.value = objectify.DataElement("test this", nsmap=nsmap) 170 self.assertEquals(root.value.nsmap, DEFAULT_NSMAP)
171
173 root = objectify.Element("root") 174 nsmap = {"mypy": PYTYPE_NAMESPACE, 175 "myxsi": XML_SCHEMA_INSTANCE_NS, 176 "myxsd": XML_SCHEMA_NS} 177 root.value = objectify.DataElement("test this", nsmap=nsmap) 178 self.assertEquals(root.value.nsmap, DEFAULT_NSMAP)
179
181 root = objectify.Element("root") 182 nsmap = {"my": "someNS", 183 "myother": "someOtherNS", 184 "myxsd": XML_SCHEMA_NS} 185 root.value = objectify.DataElement("test", nsmap=nsmap) 186 expected = nsmap.copy() 187 del expected["myxsd"] 188 expected.update(DEFAULT_NSMAP) 189 self.assertEquals(root.value.nsmap, expected)
190
192 # keyword arguments override attrib entries 193 value = objectify.DataElement(23, _pytype="str", _xsi="foobar", 194 attrib={"gnu": "muh", "cat": "meeow", 195 "dog": "wuff"}, 196 bird="tchilp", dog="grrr") 197 self.assertEquals(value.get("gnu"), "muh") 198 self.assertEquals(value.get("cat"), "meeow") 199 self.assertEquals(value.get("dog"), "grrr") 200 self.assertEquals(value.get("bird"), "tchilp")
201
203 # Check that DataElement preserves all attributes ObjectifiedDataElement 204 # arguments 205 arg = objectify.DataElement(23, _pytype="str", _xsi="foobar", 206 attrib={"gnu": "muh", "cat": "meeow", 207 "dog": "wuff"}, 208 bird="tchilp", dog="grrr") 209 value = objectify.DataElement(arg) 210 self.assert_(isinstance(value, objectify.StringElement)) 211 for attr in arg.attrib: 212 self.assertEquals(value.get(attr), arg.get(attr))
213
215 # Check that _pytype arg overrides original py:pytype of 216 # ObjectifiedDataElement 217 arg = objectify.DataElement(23, _pytype="str", _xsi="foobar", 218 attrib={"gnu": "muh", "cat": "meeow", 219 "dog": "wuff"}, 220 bird="tchilp", dog="grrr") 221 value = objectify.DataElement(arg, _pytype="int") 222 self.assert_(isinstance(value, objectify.IntElement)) 223 self.assertEquals(value.get(objectify.PYTYPE_ATTRIBUTE), "int") 224 for attr in arg.attrib: 225 if not attr == objectify.PYTYPE_ATTRIBUTE: 226 self.assertEquals(value.get(attr), arg.get(attr))
227
229 # Check that _xsi arg overrides original xsi:type of given 230 # ObjectifiedDataElement 231 arg = objectify.DataElement(23, _pytype="str", _xsi="foobar", 232 attrib={"gnu": "muh", "cat": "meeow", 233 "dog": "wuff"}, 234 bird="tchilp", dog="grrr") 235 value = objectify.DataElement(arg, _xsi="xsd:int") 236 self.assert_(isinstance(value, objectify.IntElement)) 237 self.assertEquals(value.get(XML_SCHEMA_INSTANCE_TYPE_ATTR), "xsd:int") 238 self.assertEquals(value.get(objectify.PYTYPE_ATTRIBUTE), "int") 239 for attr in arg.attrib: 240 if not attr in [objectify.PYTYPE_ATTRIBUTE, 241 XML_SCHEMA_INSTANCE_TYPE_ATTR]: 242 self.assertEquals(value.get(attr), arg.get(attr))
243
245 # Check that _pytype and _xsi args override original py:pytype and 246 # xsi:type attributes of given ObjectifiedDataElement 247 arg = objectify.DataElement(23, _pytype="str", _xsi="foobar", 248 attrib={"gnu": "muh", "cat": "meeow", 249 "dog": "wuff"}, 250 bird="tchilp", dog="grrr") 251 value = objectify.DataElement(arg, _pytype="int", _xsi="xsd:int") 252 self.assert_(isinstance(value, objectify.IntElement)) 253 self.assertEquals(value.get(objectify.PYTYPE_ATTRIBUTE), "int") 254 self.assertEquals(value.get(XML_SCHEMA_INSTANCE_TYPE_ATTR), "xsd:int") 255 for attr in arg.attrib: 256 if not attr in [objectify.PYTYPE_ATTRIBUTE, 257 XML_SCHEMA_INSTANCE_TYPE_ATTR]: 258 self.assertEquals(value.get(attr), arg.get(attr))
259
261 self.assertRaises(ValueError, objectify.DataElement, 3.1415, 262 _pytype="int")
263
265 self.assertRaises(ValueError, objectify.DataElement, 3.1415, 266 _xsi="xsd:int")
267
269 arg = objectify.DataElement(3.1415) 270 self.assertRaises(ValueError, objectify.DataElement, arg, 271 _pytype="int")
272
274 arg = objectify.DataElement(3.1415) 275 self.assertRaises(ValueError, objectify.DataElement, arg, 276 _xsi="xsd:int")
277
278 - def test_root(self):
279 root = self.Element("test") 280 self.assert_(isinstance(root, objectify.ObjectifiedElement))
281
282 - def test_str(self):
283 root = self.Element("test") 284 self.assertEquals('', str(root))
285
286 - def test_child(self):
287 root = self.XML(xml_str) 288 self.assertEquals("0", root.c1.c2.text)
289
290 - def test_countchildren(self):
291 root = self.XML(xml_str) 292 self.assertEquals(1, root.countchildren()) 293 self.assertEquals(5, root.c1.countchildren())
294
295 - def test_child_getattr(self):
296 root = self.XML(xml_str) 297 self.assertEquals("0", getattr(root.c1, "{objectified}c2").text) 298 self.assertEquals("3", getattr(root.c1, "{otherNS}c2").text)
299
300 - def test_child_nonexistant(self):
301 root = self.XML(xml_str) 302 self.assertRaises(AttributeError, getattr, root.c1, "NOT_THERE") 303 self.assertRaises(AttributeError, getattr, root.c1, "{unknownNS}c2")
304
305 - def test_addattr(self):
306 root = self.XML(xml_str) 307 self.assertEquals(1, len(root.c1)) 308 root.addattr("c1", "test") 309 self.assertEquals(2, len(root.c1)) 310 self.assertEquals("test", root.c1[1].text)
311
312 - def test_addattr_element(self):
313 root = self.XML(xml_str) 314 self.assertEquals(1, len(root.c1)) 315 316 new_el = self.Element("test", myattr="5") 317 root.addattr("c1", new_el) 318 self.assertEquals(2, len(root.c1)) 319 self.assertEquals(None, root.c1[0].get("myattr")) 320 self.assertEquals("5", root.c1[1].get("myattr"))
321
322 - def test_addattr_list(self):
323 root = self.XML(xml_str) 324 self.assertEquals(1, len(root.c1)) 325 326 new_el = self.Element("test") 327 self.etree.SubElement(new_el, "a", myattr="A") 328 self.etree.SubElement(new_el, "a", myattr="B") 329 330 root.addattr("c1", list(new_el.a)) 331 self.assertEquals(3, len(root.c1)) 332 self.assertEquals(None, root.c1[0].get("myattr")) 333 self.assertEquals("A", root.c1[1].get("myattr")) 334 self.assertEquals("B", root.c1[2].get("myattr"))
335
336 - def test_child_addattr(self):
337 root = self.XML(xml_str) 338 self.assertEquals(3, len(root.c1.c2)) 339 root.c1.addattr("c2", 3) 340 self.assertEquals(4, len(root.c1.c2)) 341 self.assertEquals("3", root.c1.c2[3].text)
342
343 - def test_child_index(self):
344 root = self.XML(xml_str) 345 self.assertEquals("0", root.c1.c2[0].text) 346 self.assertEquals("1", root.c1.c2[1].text) 347 self.assertEquals("2", root.c1.c2[2].text) 348 self.assertRaises(IndexError, itemgetter(3), root.c1.c2)
349
350 - def test_child_index_neg(self):
351 root = self.XML(xml_str) 352 self.assertEquals("0", root.c1.c2[0].text) 353 self.assertEquals("0", root.c1.c2[-3].text) 354 self.assertEquals("1", root.c1.c2[-2].text) 355 self.assertEquals("2", root.c1.c2[-1].text) 356 self.assertRaises(IndexError, itemgetter(-4), root.c1.c2)
357
358 - def test_child_len(self):
359 root = self.XML(xml_str) 360 self.assertEquals(1, len(root)) 361 self.assertEquals(1, len(root.c1)) 362 self.assertEquals(3, len(root.c1.c2))
363
364 - def test_child_iter(self):
365 root = self.XML(xml_str) 366 self.assertEquals([root], 367 list(iter(root))) 368 self.assertEquals([root.c1], 369 list(iter(root.c1))) 370 self.assertEquals([root.c1.c2[0], root.c1.c2[1], root.c1.c2[2]], 371 list(iter((root.c1.c2))))
372
373 - def test_class_lookup(self):
374 root = self.XML(xml_str) 375 self.assert_(isinstance(root.c1.c2, objectify.ObjectifiedElement)) 376 self.assertFalse(isinstance(getattr(root.c1, "{otherNS}c2"), 377 objectify.ObjectifiedElement))
378
379 - def test_dir(self):
380 root = self.XML(xml_str) 381 dir_c1 = dir(objectify.ObjectifiedElement) + ['c1'] 382 dir_c1.sort() 383 dir_c2 = dir(objectify.ObjectifiedElement) + ['c2'] 384 dir_c2.sort() 385 386 self.assertEquals(dir_c1, dir(root)) 387 self.assertEquals(dir_c2, dir(root.c1))
388
389 - def test_vars(self):
390 root = self.XML(xml_str) 391 self.assertEquals({'c1' : root.c1}, vars(root)) 392 self.assertEquals({'c2' : root.c1.c2}, vars(root.c1))
393
394 - def test_child_set_ro(self):
395 root = self.XML(xml_str) 396 self.assertRaises(TypeError, setattr, root.c1.c2, 'text', "test") 397 self.assertRaises(TypeError, setattr, root.c1.c2, 'pyval', "test")
398
399 - def test_setslice(self):
400 Element = self.Element 401 SubElement = self.etree.SubElement 402 root = Element("root") 403 root.c = ["c1", "c2"] 404 405 c1 = root.c[0] 406 c2 = root.c[1] 407 408 self.assertEquals([c1,c2], list(root.c)) 409 self.assertEquals(["c1", "c2"], 410 [ c.text for c in root.c ]) 411 412 root2 = Element("root2") 413 root2.el = [ "test", "test" ] 414 self.assertEquals(["test", "test"], 415 [ el.text for el in root2.el ]) 416 417 root.c = [ root2.el, root2.el ] 418 self.assertEquals(["test", "test"], 419 [ c.text for c in root.c ]) 420 self.assertEquals(["test", "test"], 421 [ el.text for el in root2.el ]) 422 423 root.c[:] = [ c1, c2, c2, c1 ] 424 self.assertEquals(["c1", "c2", "c2", "c1"], 425 [ c.text for c in root.c ])
426
427 - def test_set_string(self):
428 # make sure strings are not handled as sequences 429 Element = self.Element 430 SubElement = self.etree.SubElement 431 root = Element("root") 432 root.c = "TEST" 433 self.assertEquals(["TEST"], 434 [ c.text for c in root.c ])
435
436 - def test_setitem_string(self):
437 # make sure strings are set as children 438 Element = self.Element 439 SubElement = self.etree.SubElement 440 root = Element("root") 441 root["c"] = "TEST" 442 self.assertEquals(["TEST"], 443 [ c.text for c in root.c ])
444
446 # make sure 'text' etc. are set as children 447 Element = self.Element 448 SubElement = self.etree.SubElement 449 root = Element("root") 450 451 root["text"] = "TEST" 452 self.assertEquals(["TEST"], 453 [ c.text for c in root["text"] ]) 454 455 root["tail"] = "TEST" 456 self.assertEquals(["TEST"], 457 [ c.text for c in root["tail"] ]) 458 459 root["pyval"] = "TEST" 460 self.assertEquals(["TEST"], 461 [ c.text for c in root["pyval"] ]) 462 463 root["tag"] = "TEST" 464 self.assertEquals(["TEST"], 465 [ c.text for c in root["tag"] ])
466
467 - def test_findall(self):
468 XML = self.XML 469 root = XML('<a><b><c/></b><b/><c><b/></c></a>') 470 self.assertEquals(1, len(root.findall("c"))) 471 self.assertEquals(2, len(root.findall(".//c"))) 472 self.assertEquals(3, len(root.findall(".//b"))) 473 self.assert_(root.findall(".//b")[1] is root.getchildren()[1])
474
475 - def test_findall_ns(self):
476 XML = self.XML 477 root = XML('<a xmlns:x="X" xmlns:y="Y"><x:b><c/></x:b><b/><c><x:b/><b/></c><b/></a>') 478 self.assertEquals(2, len(root.findall(".//{X}b"))) 479 self.assertEquals(3, len(root.findall(".//b"))) 480 self.assertEquals(2, len(root.findall("b")))
481
482 - def test_build_tree(self):
483 root = self.Element('root') 484 root.a = 5 485 root.b = 6 486 self.assert_(isinstance(root, objectify.ObjectifiedElement)) 487 self.assert_(isinstance(root.a, objectify.IntElement)) 488 self.assert_(isinstance(root.b, objectify.IntElement))
489
490 - def test_type_none(self):
491 Element = self.Element 492 SubElement = self.etree.SubElement 493 494 nil_attr = XML_SCHEMA_NIL_ATTR 495 root = Element("{objectified}root") 496 SubElement(root, "{objectified}none") 497 SubElement(root, "{objectified}none", {nil_attr : "true"}) 498 self.assertFalse(isinstance(root.none, objectify.NoneElement)) 499 self.assertFalse(isinstance(root.none[0], objectify.NoneElement)) 500 self.assert_(isinstance(root.none[1], objectify.NoneElement)) 501 self.assertEquals(root.none[1], None) 502 self.assertFalse(root.none[1])
503
504 - def test_data_element_none(self):
505 value = objectify.DataElement(None) 506 self.assert_(isinstance(value, objectify.NoneElement)) 507 self.assertEquals(value, None) 508 self.assertEquals(value.get(XML_SCHEMA_NIL_ATTR), "true")
509
510 - def test_type_bool(self):
511 Element = self.Element 512 SubElement = self.etree.SubElement 513 root = Element("{objectified}root") 514 root.bool = 'true' 515 self.assert_(isinstance(root.bool, objectify.BoolElement)) 516 self.assertEquals(root.bool, True) 517 518 root.bool = 'false' 519 self.assert_(isinstance(root.bool, objectify.BoolElement)) 520 self.assertEquals(root.bool, False)
521
522 - def test_data_element_bool(self):
523 value = objectify.DataElement(True) 524 self.assert_(isinstance(value, objectify.BoolElement)) 525 self.assertEquals(value, True) 526 527 value = objectify.DataElement(False) 528 self.assert_(isinstance(value, objectify.BoolElement)) 529 self.assertEquals(value, False)
530
531 - def test_type_str(self):
532 Element = self.Element 533 SubElement = self.etree.SubElement 534 root = Element("{objectified}root") 535 root.none = "test" 536 self.assert_(isinstance(root.none, objectify.StringElement))
537
538 - def test_type_str_mul(self):
539 Element = self.Element 540 SubElement = self.etree.SubElement 541 root = Element("{objectified}root") 542 root.none = "test" 543 544 self.assertEquals("test" * 5, root.none * 5) 545 self.assertEquals(5 * "test", 5 * root.none) 546 547 self.assertRaises(TypeError, operator.mul, root.none, "honk") 548 self.assertRaises(TypeError, operator.mul, "honk", root.none)
549
550 - def test_type_str_add(self):
551 Element = self.Element 552 SubElement = self.etree.SubElement 553 root = Element("{objectified}root") 554 root.none = "test" 555 556 s = "toast" 557 self.assertEquals("test" + s, root.none + s) 558 self.assertEquals(s + "test", s + root.none)
559
560 - def test_data_element_str(self):
561 value = objectify.DataElement("test") 562 self.assert_(isinstance(value, objectify.StringElement)) 563 self.assertEquals(value, "test")
564
565 - def test_type_int(self):
566 Element = self.Element 567 SubElement = self.etree.SubElement 568 root = Element("{objectified}root") 569 root.none = 5 570 self.assert_(isinstance(root.none, objectify.IntElement))
571
572 - def test_data_element_int(self):
573 value = objectify.DataElement(5) 574 self.assert_(isinstance(value, objectify.IntElement)) 575 self.assertEquals(value, 5)
576
577 - def test_type_float(self):
578 Element = self.Element 579 SubElement = self.etree.SubElement 580 root = Element("{objectified}root") 581 root.none = 5.5 582 self.assert_(isinstance(root.none, objectify.FloatElement))
583
584 - def test_data_element_float(self):
585 value = objectify.DataElement(5.5) 586 self.assert_(isinstance(value, objectify.FloatElement)) 587 self.assertEquals(value, 5.5)
588
589 - def test_data_element_xsitypes(self):
590 for xsi, objclass in xsitype2objclass.iteritems(): 591 # 1 is a valid value for all ObjectifiedDataElement classes 592 value = objectify.DataElement(1, _xsi=xsi) 593 self.assert_(isinstance(value, objclass))
594
596 for xsi, objclass in xsitype2objclass.iteritems(): 597 # 1 is a valid value for all ObjectifiedDataElement classes 598 value = objectify.DataElement(1, _xsi="xsd:%s" % xsi) 599 self.assert_(isinstance(value, objclass))
600
602 for xsi, objclass in xsitype2objclass.iteritems(): 603 # 1 is a valid value for all ObjectifiedDataElement classes 604 self.assertRaises(ValueError, objectify.DataElement, 1, 605 _xsi="foo:%s" % xsi)
606
607 - def test_schema_types(self):
608 XML = self.XML 609 root = XML('''\ 610 <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 611 <b xsi:type="boolean">true</b> 612 <b xsi:type="boolean">false</b> 613 <b xsi:type="boolean">1</b> 614 <b xsi:type="boolean">0</b> 615 616 <f xsi:type="float">5</f> 617 <f xsi:type="double">5</f> 618 619 <s xsi:type="string">5</s> 620 <s xsi:type="normalizedString">5</s> 621 <s xsi:type="token">5</s> 622 <s xsi:type="language">5</s> 623 <s xsi:type="Name">5</s> 624 <s xsi:type="NCName">5</s> 625 <s xsi:type="ID">5</s> 626 <s xsi:type="IDREF">5</s> 627 <s xsi:type="ENTITY">5</s> 628 <s xsi:type="NMTOKEN">5</s> 629 630 <l xsi:type="integer">5</l> 631 <l xsi:type="nonPositiveInteger">5</l> 632 <l xsi:type="negativeInteger">5</l> 633 <l xsi:type="long">5</l> 634 <l xsi:type="nonNegativeInteger">5</l> 635 <l xsi:type="unsignedLong">5</l> 636 <l xsi:type="unsignedInt">5</l> 637 <l xsi:type="positiveInteger">5</l> 638 639 <i xsi:type="int">5</i> 640 <i xsi:type="short">5</i> 641 <i xsi:type="byte">5</i> 642 <i xsi:type="unsignedShort">5</i> 643 <i xsi:type="unsignedByte">5</i> 644 645 <n xsi:nil="true"/> 646 </root> 647 ''') 648 649 for b in root.b: 650 self.assert_(isinstance(b, objectify.BoolElement)) 651 self.assertEquals(True, root.b[0]) 652 self.assertEquals(False, root.b[1]) 653 self.assertEquals(True, root.b[2]) 654 self.assertEquals(False, root.b[3]) 655 656 for f in root.f: 657 self.assert_(isinstance(f, objectify.FloatElement)) 658 self.assertEquals(5, f) 659 660 for s in root.s: 661 self.assert_(isinstance(s, objectify.StringElement)) 662 self.assertEquals("5", s) 663 664 for l in root.l: 665 self.assert_(isinstance(l, objectify.LongElement)) 666 self.assertEquals(5L, l) 667 668 for i in root.i: 669 self.assert_(isinstance(i, objectify.IntElement)) 670 self.assertEquals(5, i) 671 672 self.assert_(isinstance(root.n, objectify.NoneElement)) 673 self.assertEquals(None, root.n)
674
675 - def test_schema_types_prefixed(self):
676 XML = self.XML 677 root = XML('''\ 678 <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 679 xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 680 <b xsi:type="xsd:boolean">true</b> 681 <b xsi:type="xsd:boolean">false</b> 682 <b xsi:type="xsd:boolean">1</b> 683 <b xsi:type="xsd:boolean">0</b> 684 685 <f xsi:type="xsd:float">5</f> 686 <f xsi:type="xsd:double">5</f> 687 688 <s xsi:type="xsd:string">5</s> 689 <s xsi:type="xsd:normalizedString">5</s> 690 <s xsi:type="xsd:token">5</s> 691 <s xsi:type="xsd:language">5</s> 692 <s xsi:type="xsd:Name">5</s> 693 <s xsi:type="xsd:NCName">5</s> 694 <s xsi:type="xsd:ID">5</s> 695 <s xsi:type="xsd:IDREF">5</s> 696 <s xsi:type="xsd:ENTITY">5</s> 697 <s xsi:type="xsd:NMTOKEN">5</s> 698 699 <l xsi:type="xsd:integer">5</l> 700 <l xsi:type="xsd:nonPositiveInteger">5</l> 701 <l xsi:type="xsd:negativeInteger">5</l> 702 <l xsi:type="xsd:long">5</l> 703 <l xsi:type="xsd:nonNegativeInteger">5</l> 704 <l xsi:type="xsd:unsignedLong">5</l> 705 <l xsi:type="xsd:unsignedInt">5</l> 706 <l xsi:type="xsd:positiveInteger">5</l> 707 708 <i xsi:type="xsd:int">5</i> 709 <i xsi:type="xsd:short">5</i> 710 <i xsi:type="xsd:byte">5</i> 711 <i xsi:type="xsd:unsignedShort">5</i> 712 <i xsi:type="xsd:unsignedByte">5</i> 713 714 <n xsi:nil="true"/> 715 </root> 716 ''') 717 718 for b in root.b: 719 self.assert_(isinstance(b, objectify.BoolElement)) 720 self.assertEquals(True, root.b[0]) 721 self.assertEquals(False, root.b[1]) 722 self.assertEquals(True, root.b[2]) 723 self.assertEquals(False, root.b[3]) 724 725 for f in root.f: 726 self.assert_(isinstance(f, objectify.FloatElement)) 727 self.assertEquals(5, f) 728 729 for s in root.s: 730 self.assert_(isinstance(s, objectify.StringElement)) 731 self.assertEquals("5", s) 732 733 for l in root.l: 734 self.assert_(isinstance(l, objectify.LongElement)) 735 self.assertEquals(5L, l) 736 737 for i in root.i: 738 self.assert_(isinstance(i, objectify.IntElement)) 739 self.assertEquals(5, i) 740 741 self.assert_(isinstance(root.n, objectify.NoneElement)) 742 self.assertEquals(None, root.n)
743
744 - def test_type_str_sequence(self):
745 XML = self.XML 746 root = XML(u'<root><b>why</b><b>try</b></root>') 747 strs = [ str(s) for s in root.b ] 748 self.assertEquals(["why", "try"], 749 strs)
750
751 - def test_type_str_cmp(self):
752 XML = self.XML 753 root = XML(u'<root><b>test</b><b>taste</b><b></b><b/></root>') 754 self.assertFalse(root.b[0] < root.b[1]) 755 self.assertFalse(root.b[0] <= root.b[1]) 756 self.assertFalse(root.b[0] == root.b[1]) 757 758 self.assert_(root.b[0] != root.b[1]) 759 self.assert_(root.b[0] >= root.b[1]) 760 self.assert_(root.b[0] > root.b[1]) 761 762 self.assertEquals(root.b[0], "test") 763 self.assertEquals("test", root.b[0]) 764 self.assert_(root.b[0] > 5) 765 self.assert_(5 < root.b[0]) 766 767 self.assertEquals("", root.b[2]) 768 self.assertEquals(root.b[2], "") 769 self.assertEquals("", root.b[3]) 770 self.assertEquals(root.b[3], "") 771 self.assertEquals(root.b[2], root.b[3]) 772 773 root.b = "test" 774 self.assert_(root.b) 775 root.b = "" 776 self.assertFalse(root.b) 777 self.assertEquals(root.b, "") 778 self.assertEquals("", root.b)
779
780 - def test_type_int_cmp(self):
781 XML = self.XML 782 root = XML(u'<root><b>5</b><b>6</b></root>') 783 self.assert_(root.b[0] < root.b[1]) 784 self.assert_(root.b[0] <= root.b[1]) 785 self.assert_(root.b[0] != root.b[1]) 786 787 self.assertFalse(root.b[0] == root.b[1]) 788 self.assertFalse(root.b[0] >= root.b[1]) 789 self.assertFalse(root.b[0] > root.b[1]) 790 791 self.assertEquals(root.b[0], 5) 792 self.assertEquals(5, root.b[0]) 793 self.assert_(root.b[0] < "5") 794 self.assert_("5" > root.b[0]) 795 796 root.b = 5 797 self.assert_(root.b) 798 root.b = 0 799 self.assertFalse(root.b)
800 801 # float + long share the NumberElement implementation with int 802
803 - def test_type_bool_cmp(self):
804 XML = self.XML 805 root = XML(u'<root><b>false</b><b>true</b></root>') 806 self.assert_(root.b[0] < root.b[1]) 807 self.assert_(root.b[0] <= root.b[1]) 808 self.assert_(root.b[0] != root.b[1]) 809 810 self.assertFalse(root.b[0] == root.b[1]) 811 self.assertFalse(root.b[0] >= root.b[1]) 812 self.assertFalse(root.b[0] > root.b[1]) 813 814 self.assertFalse(root.b[0]) 815 self.assert_(root.b[1]) 816 817 self.assertEquals(root.b[0], False) 818 self.assertEquals(False, root.b[0]) 819 self.assert_(root.b[0] < 5) 820 self.assert_(5 > root.b[0]) 821 822 root.b = True 823 self.assert_(root.b) 824 root.b = False 825 self.assertFalse(root.b)
826
827 - def test_type_none_cmp(self):
828 XML = self.XML 829 root = XML(u""" 830 <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 831 <b xsi:nil="true"></b><b xsi:nil="true"/> 832 </root>""") 833 self.assert_(root.b[0] == root.b[1]) 834 self.assertFalse(root.b[0]) 835 self.assertEquals(root.b[0], None) 836 self.assertEquals(None, root.b[0]) 837 838 for comparison in ["abc", 5, 7.3, True, [], ()]: 839 none = root.b[1] 840 self.assert_(none < comparison, "%s (%s) should be < %s" % 841 (none, type(none), comparison) ) 842 self.assert_(comparison > none, "%s should be > %s (%s)" % 843 (comparison, none, type(none)))
844
845 - def test_type_str_mod(self):
846 s = "%d %f %s %r" 847 el = objectify.DataElement(s) 848 values = (1, 7.0, "abcd", None) 849 self.assertEquals(s % values, el % values) 850 851 s = "%d" 852 el = objectify.DataElement(s) 853 val = 5 854 self.assertEquals(s % val, el % val) 855 856 s = "%d %s" 857 el = objectify.DataElement(s) 858 val = 5 859 self.assertRaises(TypeError, el.__mod__, val) 860 861 s = "" 862 el = objectify.DataElement(s) 863 val = 5 864 self.assertRaises(TypeError, el.__mod__, val)
865
866 - def test_pytype_annotation(self):
867 XML = self.XML 868 root = XML(u'''\ 869 <a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 870 xmlns:py="http://codespeak.net/lxml/objectify/pytype"> 871 <b>5</b> 872 <b>test</b> 873 <c>1.1</c> 874 <c>\uF8D2</c> 875 <x>true</x> 876 <n xsi:nil="true" /> 877 <n></n> 878 <b xsi:type="double">5</b> 879 <b xsi:type="float">5</b> 880 <s xsi:type="string">23</s> 881 <s py:pytype="str">42</s> 882 <f py:pytype="float">300</f> 883 <l py:pytype="long">2</l> 884 </a> 885 ''') 886 objectify.annotate(root) 887 888 child_types = [ c.get(objectify.PYTYPE_ATTRIBUTE) 889 for c in root.iterchildren() ] 890 self.assertEquals("int", child_types[ 0]) 891 self.assertEquals("str", child_types[ 1]) 892 self.assertEquals("float", child_types[ 2]) 893 self.assertEquals("str", child_types[ 3]) 894 self.assertEquals("bool", child_types[ 4]) 895 self.assertEquals("none", child_types[ 5]) 896 self.assertEquals(None, child_types[ 6]) 897 self.assertEquals("float", child_types[ 7]) 898 self.assertEquals("float", child_types[ 8]) 899 self.assertEquals("str", child_types[ 9]) 900 self.assertEquals("int", child_types[10]) 901 self.assertEquals("int", child_types[11]) 902 self.assertEquals("int", child_types[12]) 903 904 self.assertEquals("true", root.n.get(XML_SCHEMA_NIL_ATTR))
905
907 XML = self.XML 908 root = XML(u'''\ 909 <a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 910 xmlns:py="http://codespeak.net/lxml/objectify/pytype"> 911 <b>5</b> 912 <b>test</b> 913 <c>1.1</c> 914 <c>\uF8D2</c> 915 <x>true</x> 916 <n xsi:nil="true" /> 917 <n></n> 918 <b xsi:type="double">5</b> 919 <b xsi:type="float">5</b> 920 <s xsi:type="string">23</s> 921 <s py:pytype="str">42</s> 922 <f py:pytype="float">300</f> 923 <l py:pytype="long">2</l> 924 </a> 925 ''') 926 objectify.annotate(root, ignore_old=False) 927 928 child_types = [ c.get(objectify.PYTYPE_ATTRIBUTE) 929 for c in root.iterchildren() ] 930 self.assertEquals("int", child_types[ 0]) 931 self.assertEquals("str", child_types[ 1]) 932 self.assertEquals("float", child_types[ 2]) 933 self.assertEquals("str", child_types[ 3]) 934 self.assertEquals("bool", child_types[ 4]) 935 self.assertEquals("none", child_types[ 5]) 936 self.assertEquals(None, child_types[ 6]) 937 self.assertEquals("float", child_types[ 7]) 938 self.assertEquals("float", child_types[ 8]) 939 self.assertEquals("str", child_types[ 9]) 940 self.assertEquals("str", child_types[10]) 941 self.assertEquals("float", child_types[11]) 942 self.assertEquals("long", child_types[12]) 943 944 self.assertEquals("true", root.n.get(XML_SCHEMA_NIL_ATTR))
945
946 - def test_deannotate(self):
947 XML = self.XML 948 root = XML(u'''\ 949 <a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 950 xmlns:py="http://codespeak.net/lxml/objectify/pytype"> 951 <b>5</b> 952 <b>test</b> 953 <c>1.1</c> 954 <c>\uF8D2</c> 955 <x>true</x> 956 <n xsi:nil="true" /> 957 <n></n> 958 <b xsi:type="double">5</b> 959 <b xsi:type="float">5</b> 960 <s xsi:type="string">23</s> 961 <s py:pytype="str">42</s> 962 <f py:pytype="float">300</f> 963 <l py:pytype="long">2</l> 964 </a> 965 ''') 966 objectify.deannotate(root) 967 968 for c in root.getiterator(): 969 self.assertEquals(None, c.get(XML_SCHEMA_INSTANCE_TYPE_ATTR)) 970 self.assertEquals(None, c.get(objectify.PYTYPE_ATTRIBUTE)) 971 972 self.assertEquals("true", root.n.get(XML_SCHEMA_NIL_ATTR))
973
974 - def test_xsitype_deannotate(self):
975 XML = self.XML 976 root = XML(u'''\ 977 <a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 978 xmlns:py="http://codespeak.net/lxml/objectify/pytype" 979 xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 980 <b>5</b> 981 <b>test</b> 982 <c>1.1</c> 983 <c>\uF8D2</c> 984 <x>true</x> 985 <n xsi:nil="true" /> 986 <n></n> 987 <b xsi:type="xsd:double">5</b> 988 <b xsi:type="xsd:float">5</b> 989 <s xsi:type="xsd:string">23</s> 990 <s py:pytype="str">42</s> 991 <f py:pytype="float">300</f> 992 <l py:pytype="long">2</l> 993 </a> 994 ''') 995 objectify.annotate(root) 996 objectify.deannotate(root, pytype=False) 997 998 child_types = [ c.get(objectify.PYTYPE_ATTRIBUTE) 999 for c in root.iterchildren() ] 1000 self.assertEquals("int", child_types[ 0]) 1001 self.assertEquals("str", child_types[ 1]) 1002 self.assertEquals("float", child_types[ 2]) 1003 self.assertEquals("str", child_types[ 3]) 1004 self.assertEquals("bool", child_types[ 4]) 1005 self.assertEquals("none", child_types[ 5]) 1006 self.assertEquals(None, child_types[ 6]) 1007 self.assertEquals("float", child_types[ 7]) 1008 self.assertEquals("float", child_types[ 8]) 1009 self.assertEquals("str", child_types[ 9]) 1010 self.assertEquals("int", child_types[10]) 1011 self.assertEquals("int", child_types[11]) 1012 self.assertEquals("int", child_types[12]) 1013 1014 self.assertEquals("true", root.n.get(XML_SCHEMA_NIL_ATTR)) 1015 1016 for c in root.getiterator(): 1017 self.assertEquals(None, c.get(XML_SCHEMA_INSTANCE_TYPE_ATTR))
1018
1019 - def test_pytype_deannotate(self):
1020 XML = self.XML 1021 root = XML(u'''\ 1022 <a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 1023 xmlns:py="http://codespeak.net/lxml/objectify/pytype" 1024 xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 1025 <b xsi:type="xsd:int">5</b> 1026 <b xsi:type="xsd:string">test</b> 1027 <c xsi:type="xsd:float">1.1</c> 1028 <c xsi:type="xsd:string">\uF8D2</c> 1029 <x xsi:type="xsd:boolean">true</x> 1030 <n xsi:nil="true" /> 1031 <n></n> 1032 <b xsi:type="xsd:double">5</b> 1033 <b xsi:type="xsd:float">5</b> 1034 <s xsi:type="xsd:string">23</s> 1035 <s xsi:type="xsd:string">42</s> 1036 <f xsi:type="xsd:float">300</f> 1037 <l xsi:type="xsd:long">2</l> 1038 </a> 1039 ''') 1040 objectify.annotate(root) 1041 objectify.deannotate(root, xsi=False) 1042 1043 child_types = [ c.get(XML_SCHEMA_INSTANCE_TYPE_ATTR) 1044 for c in root.iterchildren() ] 1045 self.assertEquals("xsd:int", child_types[ 0]) 1046 self.assertEquals("xsd:string", child_types[ 1]) 1047 self.assertEquals("xsd:float", child_types[ 2]) 1048 self.assertEquals("xsd:string", child_types[ 3]) 1049 self.assertEquals("xsd:boolean", child_types[ 4]) 1050 self.assertEquals(None, child_types[ 5]) 1051 self.assertEquals(None, child_types[ 6]) 1052 self.assertEquals("xsd:double", child_types[ 7]) 1053 self.assertEquals("xsd:float", child_types[ 8]) 1054 self.assertEquals("xsd:string", child_types[ 9]) 1055 self.assertEquals("xsd:string", child_types[10]) 1056 self.assertEquals("xsd:float", child_types[11]) 1057 self.assertEquals("xsd:long", child_types[12]) 1058 1059 self.assertEquals("true", root.n.get(XML_SCHEMA_NIL_ATTR)) 1060 1061 for c in root.getiterator(): 1062 self.assertEquals(None, c.get(objectify.PYTYPE_ATTRIBUTE))
1063
1065 XML = self.XML 1066 1067 xml = u'''\ 1068 <a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 1069 <b>5</b> 1070 <b>test</b> 1071 <c>1.1</c> 1072 <c>\uF8D2</c> 1073 <x>true</x> 1074 <n xsi:nil="true" /> 1075 <n></n> 1076 <b xsi:type="double">5</b> 1077 </a> 1078 ''' 1079 1080 pytype_ns, pytype_name = objectify.PYTYPE_ATTRIBUTE[1:].split('}') 1081 objectify.setPytypeAttributeTag("{TEST}test") 1082 1083 root = XML(xml) 1084 objectify.annotate(root) 1085 1086 attribs = root.xpath("//@py:%s" % pytype_name, {"py" : pytype_ns}) 1087 self.assertEquals(0, len(attribs)) 1088 attribs = root.xpath("//@py:test", {"py" : "TEST"}) 1089 self.assertEquals(7, len(attribs)) 1090 1091 objectify.setPytypeAttributeTag() 1092 pytype_ns, pytype_name = objectify.PYTYPE_ATTRIBUTE[1:].split('}') 1093 1094 self.assertNotEqual("test", pytype_ns.lower()) 1095 self.assertNotEqual("test", pytype_name.lower()) 1096 1097 root = XML(xml) 1098 attribs = root.xpath("//@py:%s" % pytype_name, {"py" : pytype_ns}) 1099 self.assertEquals(0, len(attribs)) 1100 1101 objectify.annotate(root) 1102 attribs = root.xpath("//@py:%s" % pytype_name, {"py" : pytype_ns}) 1103 self.assertEquals(7, len(attribs))
1104
1105 - def test_registered_types(self):
1106 orig_types = objectify.getRegisteredTypes() 1107 1108 try: 1109 orig_types[0].unregister() 1110 self.assertEquals(orig_types[1:], objectify.getRegisteredTypes()) 1111 1112 class NewType(objectify.ObjectifiedDataElement): 1113 pass
1114 1115 def checkMyType(s): 1116 return True
1117 1118 pytype = objectify.PyType("mytype", checkMyType, NewType) 1119 pytype.register() 1120 self.assert_(pytype in objectify.getRegisteredTypes()) 1121 pytype.unregister() 1122 1123 pytype.register(before = [objectify.getRegisteredTypes()[0].name]) 1124 self.assertEquals(pytype, objectify.getRegisteredTypes()[0]) 1125 pytype.unregister() 1126 1127 pytype.register(after = [objectify.getRegisteredTypes()[0].name]) 1128 self.assertNotEqual(pytype, objectify.getRegisteredTypes()[0]) 1129 pytype.unregister() 1130 1131 self.assertRaises(ValueError, pytype.register, 1132 before = [objectify.getRegisteredTypes()[0].name], 1133 after = [objectify.getRegisteredTypes()[1].name]) 1134 1135 finally: 1136 for pytype in objectify.getRegisteredTypes(): 1137 pytype.unregister() 1138 for pytype in orig_types: 1139 pytype.register() 1140
1141 - def test_object_path(self):
1142 root = self.XML(xml_str) 1143 path = objectify.ObjectPath( "root.c1.c2" ) 1144 self.assertEquals(root.c1.c2.text, path.find(root).text) 1145 self.assertEquals(root.c1.c2.text, path(root).text)
1146
1147 - def test_object_path_list(self):
1148 root = self.XML(xml_str) 1149 path = objectify.ObjectPath( ['root', 'c1', 'c2'] ) 1150 self.assertEquals(root.c1.c2.text, path.find(root).text) 1151 self.assertEquals(root.c1.c2.text, path(root).text)
1152
1153 - def test_object_path_fail(self):
1154 root = self.XML(xml_str) 1155 path = objectify.ObjectPath( "root.c1.c99" ) 1156 self.assertRaises(AttributeError, path, root) 1157 self.assertEquals(None, path(root, None))
1158
1159 - def test_object_path_syntax(self):
1160 root = self.XML(xml_str) 1161 path = objectify.ObjectPath("root . {objectified}c1. c2") 1162 self.assertEquals(root.c1.c2.text, path(root).text) 1163 1164 path = objectify.ObjectPath(" root.{objectified} c1.c2 [ 0 ] ") 1165 self.assertEquals(root.c1.c2.text, path(root).text)
1166
1167 - def test_object_path_hasattr(self):
1168 root = self.XML(xml_str) 1169 path = objectify.ObjectPath( "root" ) 1170 self.assert_(path.hasattr(root)) 1171 path = objectify.ObjectPath( "root.c1" ) 1172 self.assert_(path.hasattr(root)) 1173 path = objectify.ObjectPath( "root.c1.c2" ) 1174 self.assert_(path.hasattr(root)) 1175 path = objectify.ObjectPath( "root.c1.{otherNS}c2" ) 1176 self.assert_(path.hasattr(root)) 1177 path = objectify.ObjectPath( "root.c1.c2[1]" ) 1178 self.assert_(path.hasattr(root)) 1179 path = objectify.ObjectPath( "root.c1.c2[2]" ) 1180 self.assert_(path.hasattr(root)) 1181 path = objectify.ObjectPath( "root.c1.c2[3]" ) 1182 self.assertFalse(path.hasattr(root)) 1183 path = objectify.ObjectPath( "root.c1[1].c2" ) 1184 self.assertFalse(path.hasattr(root))
1185
1186 - def test_object_path_dot(self):
1187 root = self.XML(xml_str) 1188 path = objectify.ObjectPath( "." ) 1189 self.assertEquals(root.c1.c2.text, path(root).c1.c2.text)
1190
1191 - def test_object_path_dot_list(self):
1192 root = self.XML(xml_str) 1193 path = objectify.ObjectPath( [''] ) 1194 self.assertEquals(root.c1.c2.text, path(root).c1.c2.text)
1195
1196 - def test_object_path_dot_root(self):
1197 root = self.XML(xml_str) 1198 path = objectify.ObjectPath( ".c1.c2" ) 1199 self.assertEquals(root.c1.c2.text, path(root).text)
1200
1201 - def test_object_path_dot_root_list(self):
1202 root = self.XML(xml_str) 1203 path = objectify.ObjectPath( ['', 'c1', 'c2'] ) 1204 self.assertEquals(root.c1.c2.text, path(root).text)
1205
1206 - def test_object_path_index(self):
1207 root = self.XML(xml_str) 1208 path = objectify.ObjectPath( "root.c1[0].c2[0]" ) 1209 self.assertEquals(root.c1.c2.text, path(root).text) 1210 1211 path = objectify.ObjectPath( "root.c1[0].c2" ) 1212 self.assertEquals(root.c1.c2.text, path(root).text) 1213 1214 path = objectify.ObjectPath( "root.c1[0].c2[1]" ) 1215 self.assertEquals(root.c1.c2[1].text, path(root).text) 1216 1217 path = objectify.ObjectPath( "root.c1.c2[2]" ) 1218 self.assertEquals(root.c1.c2[2].text, path(root).text) 1219 1220 path = objectify.ObjectPath( "root.c1.c2[-1]" ) 1221 self.assertEquals(root.c1.c2[-1].text, path(root).text) 1222 1223 path = objectify.ObjectPath( "root.c1.c2[-3]" ) 1224 self.assertEquals(root.c1.c2[-3].text, path(root).text)
1225
1226 - def test_object_path_index_list(self):
1227 root = self.XML(xml_str) 1228 path = objectify.ObjectPath( ['root', 'c1[0]', 'c2[0]'] ) 1229 self.assertEquals(root.c1.c2.text, path(root).text) 1230 1231 path = objectify.ObjectPath( ['root', 'c1[0]', 'c2[2]'] ) 1232 self.assertEquals(root.c1.c2[2].text, path(root).text) 1233 1234 path = objectify.ObjectPath( ['root', 'c1', 'c2[2]'] ) 1235 self.assertEquals(root.c1.c2[2].text, path(root).text) 1236 1237 path = objectify.ObjectPath( ['root', 'c1', 'c2[-1]'] ) 1238 self.assertEquals(root.c1.c2[-1].text, path(root).text) 1239 1240 path = objectify.ObjectPath( ['root', 'c1', 'c2[-3]'] ) 1241 self.assertEquals(root.c1.c2[-3].text, path(root).text)
1242
1243 - def test_object_path_index_fail_parse(self):
1244 self.assertRaises(ValueError, objectify.ObjectPath, 1245 "root.c1[0].c2[-1-2]") 1246 self.assertRaises(ValueError, objectify.ObjectPath, 1247 ['root', 'c1[0]', 'c2[-1-2]']) 1248 1249 self.assertRaises(ValueError, objectify.ObjectPath, 1250 "root[2].c1.c2") 1251 self.assertRaises(ValueError, objectify.ObjectPath, 1252 ['root[2]', 'c1', 'c2']) 1253 1254 self.assertRaises(ValueError, objectify.ObjectPath, 1255 []) 1256 self.assertRaises(ValueError, objectify.ObjectPath, 1257 ['', '', ''])
1258
1259 - def test_object_path_index_fail_lookup(self):
1260 root = self.XML(xml_str) 1261 path = objectify.ObjectPath("root.c1[9999].c2") 1262 self.assertRaises(AttributeError, path, root) 1263 1264 path = objectify.ObjectPath("root.c1[0].c2[9999]") 1265 self.assertRaises(AttributeError, path, root) 1266 1267 path = objectify.ObjectPath(".c1[9999].c2[0]") 1268 self.assertRaises(AttributeError, path, root) 1269 1270 path = objectify.ObjectPath("root.c1[-2].c2") 1271 self.assertRaises(AttributeError, path, root) 1272 1273 path = objectify.ObjectPath("root.c1[0].c2[-4]") 1274 self.assertRaises(AttributeError, path, root)
1275
1276 - def test_object_path_ns(self):
1277 root = self.XML(xml_str) 1278 path = objectify.ObjectPath( "{objectified}root.c1.c2" ) 1279 self.assertEquals(root.c1.c2.text, path.find(root).text) 1280 path = objectify.ObjectPath( "{objectified}root.{objectified}c1.c2" ) 1281 self.assertEquals(root.c1.c2.text, path.find(root).text) 1282 path = objectify.ObjectPath( "root.{objectified}c1.{objectified}c2" ) 1283 self.assertEquals(root.c1.c2.text, path.find(root).text) 1284 path = objectify.ObjectPath( "root.c1.{objectified}c2" ) 1285 self.assertEquals(root.c1.c2.text, path.find(root).text) 1286 path = objectify.ObjectPath( "root.c1.{otherNS}c2" ) 1287 self.assertEquals(getattr(root.c1, '{otherNS}c2').text, 1288 path.find(root).text)
1289
1290 - def test_object_path_ns_list(self):
1291 root = self.XML(xml_str) 1292 path = objectify.ObjectPath( ['{objectified}root', 'c1', 'c2'] ) 1293 self.assertEquals(root.c1.c2.text, path.find(root).text) 1294 path = objectify.ObjectPath( ['{objectified}root', '{objectified}c1', 'c2'] ) 1295 self.assertEquals(root.c1.c2.text, path.find(root).text) 1296 path = objectify.ObjectPath( ['root', '{objectified}c1', '{objectified}c2'] ) 1297 self.assertEquals(root.c1.c2.text, path.find(root).text) 1298 path = objectify.ObjectPath( ['root', '{objectified}c1', '{objectified}c2[2]'] ) 1299 self.assertEquals(root.c1.c2[2].text, path.find(root).text) 1300 path = objectify.ObjectPath( ['root', 'c1', '{objectified}c2'] ) 1301 self.assertEquals(root.c1.c2.text, path.find(root).text) 1302 path = objectify.ObjectPath( ['root', 'c1', '{objectified}c2[2]'] ) 1303 self.assertEquals(root.c1.c2[2].text, path.find(root).text) 1304 path = objectify.ObjectPath( ['root', 'c1', '{otherNS}c2'] ) 1305 self.assertEquals(getattr(root.c1, '{otherNS}c2').text, 1306 path.find(root).text)
1307
1308 - def test_object_path_set(self):
1309 root = self.XML(xml_str) 1310 path = objectify.ObjectPath( "root.c1.c2" ) 1311 self.assertEquals(root.c1.c2.text, path.find(root).text) 1312 self.assertEquals("1", root.c1.c2[1].text) 1313 1314 new_value = "my new value" 1315 path.setattr(root, new_value) 1316 1317 self.assertEquals(new_value, root.c1.c2.text) 1318 self.assertEquals(new_value, path(root).text) 1319 self.assertEquals("1", root.c1.c2[1].text)
1320
1321 - def test_object_path_set_element(self):
1322 root = self.XML(xml_str) 1323 path = objectify.ObjectPath( "root.c1.c2" ) 1324 self.assertEquals(root.c1.c2.text, path.find(root).text) 1325 self.assertEquals("1", root.c1.c2[1].text) 1326 1327 new_el = self.Element("{objectified}test") 1328 etree.SubElement(new_el, "{objectified}sub", myattr="ATTR").a = "TEST" 1329 path.setattr(root, new_el.sub) 1330 1331 self.assertEquals("ATTR", root.c1.c2.get("myattr")) 1332 self.assertEquals("TEST", root.c1.c2.a.text) 1333 self.assertEquals("TEST", path(root).a.text) 1334 self.assertEquals("1", root.c1.c2[1].text)
1335
1336 - def test_object_path_set_create(self):
1337 root = self.XML(xml_str) 1338 path = objectify.ObjectPath( "root.c1.c99" ) 1339 self.assertRaises(AttributeError, path.find, root) 1340 1341 new_value = "my new value" 1342 path.setattr(root, new_value) 1343 1344 self.assertEquals(1, len(root.c1.c99)) 1345 self.assertEquals(new_value, root.c1.c99.text) 1346 self.assertEquals(new_value, path(root).text)
1347
1348 - def test_object_path_set_create_element(self):
1349 root = self.XML(xml_str) 1350 path = objectify.ObjectPath( "root.c1.c99" ) 1351 self.assertRaises(AttributeError, path.find, root) 1352 1353 new_el = self.Element("{objectified}test") 1354 etree.SubElement(new_el, "{objectified}sub", myattr="ATTR").a = "TEST" 1355 path.setattr(root, new_el.sub) 1356 1357 self.assertEquals(1, len(root.c1.c99)) 1358 self.assertEquals("ATTR", root.c1.c99.get("myattr")) 1359 self.assertEquals("TEST", root.c1.c99.a.text) 1360 self.assertEquals("TEST", path(root).a.text)
1361
1362 - def test_object_path_set_create_list(self):
1363 root = self.XML(xml_str) 1364 path = objectify.ObjectPath( "root.c1.c99" ) 1365 self.assertRaises(AttributeError, path.find, root) 1366 1367 new_el = self.Element("{objectified}test") 1368 new_el.a = ["TEST1", "TEST2"] 1369 new_el.a[0].set("myattr", "ATTR1") 1370 new_el.a[1].set("myattr", "ATTR2") 1371 1372 path.setattr(root, list(new_el.a)) 1373 1374 self.assertEquals(2, len(root.c1.c99)) 1375 self.assertEquals("ATTR1", root.c1.c99[0].get("myattr")) 1376 self.assertEquals("TEST1", root.c1.c99[0].text) 1377 self.assertEquals("ATTR2", root.c1.c99[1].get("myattr")) 1378 self.assertEquals("TEST2", root.c1.c99[1].text) 1379 self.assertEquals("TEST1", path(root).text)
1380
1381 - def test_object_path_addattr(self):
1382 root = self.XML(xml_str) 1383 path = objectify.ObjectPath( "root.c1.c2" ) 1384 self.assertEquals(3, len(root.c1.c2)) 1385 path.addattr(root, "test") 1386 self.assertEquals(4, len(root.c1.c2)) 1387 self.assertEquals(["0", "1", "2", "test"], 1388 [el.text for el in root.c1.c2])
1389
1390 - def test_object_path_addattr_element(self):
1391 root = self.XML(xml_str) 1392 path = objectify.ObjectPath( "root.c1.c2" ) 1393 self.assertEquals(3, len(root.c1.c2)) 1394 1395 new_el = self.Element("{objectified}test") 1396 etree.SubElement(new_el, "{objectified}sub").a = "TEST" 1397 1398 path.addattr(root, new_el.sub) 1399 self.assertEquals(4, len(root.c1.c2)) 1400 self.assertEquals("TEST", root.c1.c2[3].a.text) 1401 self.assertEquals(["0", "1", "2"], 1402 [el.text for el in root.c1.c2[:3]])
1403
1404 - def test_object_path_addattr_create(self):
1405 root = self.XML(xml_str) 1406 path = objectify.ObjectPath( "root.c1.c99" ) 1407 self.assertRaises(AttributeError, path.find, root) 1408 1409 new_value = "my new value" 1410 path.addattr(root, new_value) 1411 1412 self.assertEquals(1, len(root.c1.c99)) 1413 self.assertEquals(new_value, root.c1.c99.text) 1414 self.assertEquals(new_value, path(root).text)
1415
1416 - def test_object_path_addattr_create_element(self):
1417 root = self.XML(xml_str) 1418 path = objectify.ObjectPath( "root.c1.c99" ) 1419 self.assertRaises(AttributeError, path.find, root) 1420 1421 new_el = self.Element("{objectified}test") 1422 etree.SubElement(new_el, "{objectified}sub", myattr="ATTR").a = "TEST" 1423 1424 path.addattr(root, new_el.sub) 1425 self.assertEquals(1, len(root.c1.c99)) 1426 self.assertEquals("TEST", root.c1.c99.a.text) 1427 self.assertEquals("TEST", path(root).a.text) 1428 self.assertEquals("ATTR", root.c1.c99.get("myattr"))
1429
1430 - def test_object_path_addattr_create_list(self):
1431 root = self.XML(xml_str) 1432 path = objectify.ObjectPath( "root.c1.c99" ) 1433 self.assertRaises(AttributeError, path.find, root) 1434 1435 new_el = self.Element("{objectified}test") 1436 new_el.a = ["TEST1", "TEST2"] 1437 1438 self.assertEquals(2, len(new_el.a)) 1439 1440 path.addattr(root, list(new_el.a)) 1441 self.assertEquals(2, len(root.c1.c99)) 1442 self.assertEquals("TEST1", root.c1.c99.text) 1443 self.assertEquals("TEST2", path(root)[1].text)
1444
1445 - def test_descendant_paths(self):
1446 root = self.XML(xml_str) 1447 self.assertEquals( 1448 ['{objectified}root', '{objectified}root.c1', 1449 '{objectified}root.c1.c2', 1450 '{objectified}root.c1.c2[1]', '{objectified}root.c1.c2[2]', 1451 '{objectified}root.c1.{otherNS}c2', '{objectified}root.c1.{}c2'], 1452 root.descendantpaths())
1453
1454 - def test_descendant_paths_child(self):
1455 root = self.XML(xml_str) 1456 self.assertEquals( 1457 ['{objectified}c1', '{objectified}c1.c2', 1458 '{objectified}c1.c2[1]', '{objectified}c1.c2[2]', 1459 '{objectified}c1.{otherNS}c2', '{objectified}c1.{}c2'], 1460 root.c1.descendantpaths())
1461
1462 - def test_descendant_paths_prefix(self):
1463 root = self.XML(xml_str) 1464 self.assertEquals( 1465 ['root.{objectified}c1', 'root.{objectified}c1.c2', 1466 'root.{objectified}c1.c2[1]', 'root.{objectified}c1.c2[2]', 1467 'root.{objectified}c1.{otherNS}c2', 1468 'root.{objectified}c1.{}c2'], 1469 root.c1.descendantpaths('root'))
1470
1471 - def test_pickle(self):
1472 import pickle 1473 1474 root = self.XML(xml_str) 1475 out = StringIO() 1476 pickle.dump(root, out) 1477 1478 new_root = pickle.loads(out.getvalue()) 1479 self.assertEquals( 1480 etree.tostring(new_root), 1481 etree.tostring(root))
1482
1483 -def test_suite():
1484 suite = unittest.TestSuite() 1485 suite.addTests([unittest.makeSuite(ObjectifyTestCase)]) 1486 suite.addTests( 1487 [doctest.DocFileSuite('../../../doc/objectify.txt')]) 1488 return suite
1489 1490 if __name__ == '__main__': 1491 unittest.main() 1492