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, sys, os.path 
   9   
  10  this_dir = os.path.dirname(__file__) 
  11  if this_dir not in sys.path: 
  12      sys.path.insert(0, this_dir) # needed for Py3 
  13   
  14  from common_imports import etree, HelperTestCase, fileInTestDir 
  15  from common_imports import SillyFileLike, canonicalize, doctest, make_doctest 
  16  from common_imports import _bytes, _str, StringIO, BytesIO 
  17   
  18  from lxml import objectify 
  19   
  20  PYTYPE_NAMESPACE = "http://codespeak.net/lxml/objectify/pytype" 
  21  XML_SCHEMA_NS = "http://www.w3.org/2001/XMLSchema" 
  22  XML_SCHEMA_INSTANCE_NS = "http://www.w3.org/2001/XMLSchema-instance" 
  23  XML_SCHEMA_INSTANCE_TYPE_ATTR = "{%s}type" % XML_SCHEMA_INSTANCE_NS 
  24  XML_SCHEMA_NIL_ATTR = "{%s}nil" % XML_SCHEMA_INSTANCE_NS 
  25  TREE_PYTYPE = "TREE" 
  26  DEFAULT_NSMAP = { "py"  : PYTYPE_NAMESPACE, 
  27                    "xsi" : XML_SCHEMA_INSTANCE_NS, 
  28                    "xsd" : XML_SCHEMA_NS} 
  29   
  30  objectclass2xsitype = { 
  31      # objectify built-in 
  32      objectify.IntElement: ("int", "short", "byte", "unsignedShort", 
  33                             "unsignedByte", "integer", "nonPositiveInteger", 
  34                             "negativeInteger", "long", "nonNegativeInteger", 
  35                             "unsignedLong", "unsignedInt", "positiveInteger",), 
  36      objectify.FloatElement: ("float", "double"), 
  37      objectify.BoolElement: ("boolean",), 
  38      objectify.StringElement: ("string", "normalizedString", "token", "language", 
  39                                "Name", "NCName", "ID", "IDREF", "ENTITY", 
  40                                "NMTOKEN", ), 
  41      # None: xsi:nil="true" 
  42      } 
  43   
  44  xsitype2objclass = dict([ (v, k) for k in objectclass2xsitype 
  45                            for v in objectclass2xsitype[k] ]) 
  46   
  47  objectclass2pytype = { 
  48      # objectify built-in 
  49      objectify.IntElement: "int", 
  50      objectify.FloatElement: "float", 
  51      objectify.BoolElement: "bool", 
  52      objectify.StringElement: "str", 
  53      # None: xsi:nil="true" 
  54      } 
  55   
  56  pytype2objclass = dict([ (objectclass2pytype[k], k) 
  57                           for k in objectclass2pytype]) 
  58   
  59  xml_str = '''\ 
  60  <obj:root xmlns:obj="objectified" xmlns:other="otherNS"> 
  61    <obj:c1 a1="A1" a2="A2" other:a3="A3"> 
  62      <obj:c2>0</obj:c2> 
  63      <obj:c2>1</obj:c2> 
  64      <obj:c2>2</obj:c2> 
  65      <other:c2>3</other:c2> 
  66      <c2>4</c2> 
  67    </obj:c1> 
  68  </obj:root>''' 
  69   
70 -class ObjectifyTestCase(HelperTestCase):
71 """Test cases for lxml.objectify 72 """ 73 etree = etree 74
75 - def XML(self, xml):
76 return self.etree.XML(xml, self.parser)
77
78 - def setUp(self):
79 super(ObjectifyTestCase, self).setUp() 80 self.parser = self.etree.XMLParser(remove_blank_text=True) 81 self.lookup = etree.ElementNamespaceClassLookup( 82 objectify.ObjectifyElementClassLookup() ) 83 self.parser.set_element_class_lookup(self.lookup) 84 85 self.Element = self.parser.makeelement 86 87 ns = self.lookup.get_namespace("otherNS") 88 ns[None] = self.etree.ElementBase 89 90 self._orig_types = objectify.getRegisteredTypes()
91
92 - def tearDown(self):
93 self.lookup.get_namespace("otherNS").clear() 94 objectify.set_pytype_attribute_tag() 95 del self.lookup 96 del self.parser 97 98 for pytype in objectify.getRegisteredTypes(): 99 pytype.unregister() 100 for pytype in self._orig_types: 101 pytype.register() 102 del self._orig_types 103 104 super(ObjectifyTestCase, self).tearDown()
105 106
107 - def test_element_nsmap_default(self):
108 elt = objectify.Element("test") 109 self.assertEquals(elt.nsmap, DEFAULT_NSMAP)
110
111 - def test_element_nsmap_empty(self):
112 nsmap = {} 113 elt = objectify.Element("test", nsmap=nsmap) 114 self.assertEquals(list(elt.nsmap.values()), [PYTYPE_NAMESPACE])
115
117 nsmap = {"mypy": PYTYPE_NAMESPACE, 118 "myxsi": XML_SCHEMA_INSTANCE_NS, 119 "myxsd": XML_SCHEMA_NS} 120 elt = objectify.Element("test", nsmap=nsmap) 121 self.assertEquals(elt.nsmap, nsmap)
122
123 - def test_element_nsmap_custom(self):
124 nsmap = {"my": "someNS", 125 "myother": "someOtherNS", 126 "myxsd": XML_SCHEMA_NS} 127 elt = objectify.Element("test", nsmap=nsmap) 128 self.assert_(PYTYPE_NAMESPACE in elt.nsmap.values()) 129 for prefix, ns in nsmap.items(): 130 self.assert_(prefix in elt.nsmap) 131 self.assertEquals(nsmap[prefix], elt.nsmap[prefix])
132
134 root = objectify.Element("root") 135 root.sub = objectify.Element("test") 136 self.assertEquals(root.sub.nsmap, DEFAULT_NSMAP)
137
139 root = objectify.Element("root") 140 nsmap = {} 141 root.sub = objectify.Element("test", nsmap=nsmap) 142 self.assertEquals(root.sub.nsmap, DEFAULT_NSMAP)
143
145 root = objectify.Element("root") 146 nsmap = {"mypy": PYTYPE_NAMESPACE, 147 "myxsi": XML_SCHEMA_INSTANCE_NS, 148 "myxsd": XML_SCHEMA_NS} 149 root.sub = objectify.Element("test", nsmap=nsmap) 150 self.assertEquals(root.sub.nsmap, DEFAULT_NSMAP)
151
153 root = objectify.Element("root") 154 nsmap = {"my": "someNS", 155 "myother": "someOtherNS", 156 "myxsd": XML_SCHEMA_NS,} 157 root.sub = objectify.Element("test", nsmap=nsmap) 158 expected = nsmap.copy() 159 del expected["myxsd"] 160 expected.update(DEFAULT_NSMAP) 161 self.assertEquals(root.sub.nsmap, expected)
162
164 value = objectify.DataElement("test this") 165 self.assertEquals(value.nsmap, DEFAULT_NSMAP)
166
168 nsmap = {} 169 value = objectify.DataElement("test this", nsmap=nsmap) 170 self.assertEquals(list(value.nsmap.values()), [PYTYPE_NAMESPACE])
171
173 nsmap = {"mypy": PYTYPE_NAMESPACE, 174 "myxsi": XML_SCHEMA_INSTANCE_NS, 175 "myxsd": XML_SCHEMA_NS} 176 value = objectify.DataElement("test this", nsmap=nsmap) 177 self.assertEquals(value.nsmap, nsmap)
178
180 nsmap = {"my": "someNS", 181 "myother": "someOtherNS", 182 "myxsd": XML_SCHEMA_NS,} 183 value = objectify.DataElement("test", nsmap=nsmap) 184 self.assert_(PYTYPE_NAMESPACE in value.nsmap.values()) 185 for prefix, ns in nsmap.items(): 186 self.assert_(prefix in value.nsmap) 187 self.assertEquals(nsmap[prefix], value.nsmap[prefix])
188
190 root = objectify.Element("root") 191 root.value = objectify.DataElement("test this") 192 self.assertEquals(root.value.nsmap, DEFAULT_NSMAP)
193
195 root = objectify.Element("root") 196 nsmap = {} 197 root.value = objectify.DataElement("test this", nsmap=nsmap) 198 self.assertEquals(root.value.nsmap, DEFAULT_NSMAP)
199
201 root = objectify.Element("root") 202 nsmap = {"mypy": PYTYPE_NAMESPACE, 203 "myxsi": XML_SCHEMA_INSTANCE_NS, 204 "myxsd": XML_SCHEMA_NS} 205 root.value = objectify.DataElement("test this", nsmap=nsmap) 206 self.assertEquals(root.value.nsmap, DEFAULT_NSMAP)
207
209 root = objectify.Element("root") 210 nsmap = {"my": "someNS", 211 "myother": "someOtherNS", 212 "myxsd": XML_SCHEMA_NS} 213 root.value = objectify.DataElement("test", nsmap=nsmap) 214 expected = nsmap.copy() 215 del expected["myxsd"] 216 expected.update(DEFAULT_NSMAP) 217 self.assertEquals(root.value.nsmap, expected)
218
220 # ObjectifiedDataElement can also be used as E-Factory 221 value = objectify.ObjectifiedDataElement('test', 'toast') 222 self.assertEquals(value.text, 'testtoast')
223
225 # ObjectifiedDataElement can also be used as E-Factory 226 value = objectify.ObjectifiedElement(objectify.ObjectifiedDataElement(), 'test', 'toast') 227 self.assertEquals(value.ObjectifiedDataElement.tail, 'testtoast')
228
230 # keyword arguments override attrib entries 231 value = objectify.DataElement(23, _pytype="str", _xsi="foobar", 232 attrib={"gnu": "muh", "cat": "meeow", 233 "dog": "wuff"}, 234 bird="tchilp", dog="grrr") 235 self.assertEquals(value.get("gnu"), "muh") 236 self.assertEquals(value.get("cat"), "meeow") 237 self.assertEquals(value.get("dog"), "grrr") 238 self.assertEquals(value.get("bird"), "tchilp")
239
241 # Check that DataElement preserves all attributes ObjectifiedDataElement 242 # arguments 243 arg = objectify.DataElement(23, _pytype="str", _xsi="foobar", 244 attrib={"gnu": "muh", "cat": "meeow", 245 "dog": "wuff"}, 246 bird="tchilp", dog="grrr") 247 value = objectify.DataElement(arg) 248 self.assert_(isinstance(value, objectify.StringElement)) 249 for attr in arg.attrib: 250 self.assertEquals(value.get(attr), arg.get(attr))
251
253 # Check that _pytype arg overrides original py:pytype of 254 # ObjectifiedDataElement 255 arg = objectify.DataElement(23, _pytype="str", _xsi="foobar", 256 attrib={"gnu": "muh", "cat": "meeow", 257 "dog": "wuff"}, 258 bird="tchilp", dog="grrr") 259 value = objectify.DataElement(arg, _pytype="NoneType") 260 self.assert_(isinstance(value, objectify.NoneElement)) 261 self.assertEquals(value.get(XML_SCHEMA_NIL_ATTR), "true") 262 self.assertEquals(value.text, None) 263 self.assertEquals(value.pyval, None) 264 for attr in arg.attrib: 265 #if not attr == objectify.PYTYPE_ATTRIBUTE: 266 self.assertEquals(value.get(attr), arg.get(attr))
267
269 # Check that _pytype arg overrides original py:pytype of 270 # ObjectifiedDataElement 271 arg = objectify.DataElement(23, _pytype="str", _xsi="foobar", 272 attrib={"gnu": "muh", "cat": "meeow", 273 "dog": "wuff"}, 274 bird="tchilp", dog="grrr") 275 value = objectify.DataElement(arg, _pytype="int") 276 self.assert_(isinstance(value, objectify.IntElement)) 277 self.assertEquals(value.get(objectify.PYTYPE_ATTRIBUTE), "int") 278 for attr in arg.attrib: 279 if not attr == objectify.PYTYPE_ATTRIBUTE: 280 self.assertEquals(value.get(attr), arg.get(attr))
281
283 # Check that _xsi arg overrides original xsi:type of given 284 # ObjectifiedDataElement 285 arg = objectify.DataElement(23, _pytype="str", _xsi="foobar", 286 attrib={"gnu": "muh", "cat": "meeow", 287 "dog": "wuff"}, 288 bird="tchilp", dog="grrr") 289 value = objectify.DataElement(arg, _xsi="xsd:int") 290 self.assert_(isinstance(value, objectify.IntElement)) 291 self.assertEquals(value.get(XML_SCHEMA_INSTANCE_TYPE_ATTR), "xsd:int") 292 self.assertEquals(value.get(objectify.PYTYPE_ATTRIBUTE), "int") 293 for attr in arg.attrib: 294 if not attr in [objectify.PYTYPE_ATTRIBUTE, 295 XML_SCHEMA_INSTANCE_TYPE_ATTR]: 296 self.assertEquals(value.get(attr), arg.get(attr))
297
299 # Check that _pytype and _xsi args override original py:pytype and 300 # xsi:type attributes of given ObjectifiedDataElement 301 arg = objectify.DataElement(23, _pytype="str", _xsi="foobar", 302 attrib={"gnu": "muh", "cat": "meeow", 303 "dog": "wuff"}, 304 bird="tchilp", dog="grrr") 305 value = objectify.DataElement(arg, _pytype="int", _xsi="xsd:int") 306 self.assert_(isinstance(value, objectify.IntElement)) 307 self.assertEquals(value.get(objectify.PYTYPE_ATTRIBUTE), "int") 308 self.assertEquals(value.get(XML_SCHEMA_INSTANCE_TYPE_ATTR), "xsd:int") 309 for attr in arg.attrib: 310 if not attr in [objectify.PYTYPE_ATTRIBUTE, 311 XML_SCHEMA_INSTANCE_TYPE_ATTR]: 312 self.assertEquals(value.get(attr), arg.get(attr))
313
315 self.assertRaises(ValueError, objectify.DataElement, 3.1415, 316 _pytype="int")
317
319 self.assertRaises(ValueError, objectify.DataElement, 3.1415, 320 _xsi="xsd:int")
321
323 arg = objectify.DataElement(3.1415) 324 self.assertRaises(ValueError, objectify.DataElement, arg, 325 _pytype="int")
326
328 arg = objectify.DataElement(3.1415) 329 self.assertRaises(ValueError, objectify.DataElement, arg, 330 _xsi="xsd:int")
331
333 arg = objectify.Element('arg') 334 value = objectify.DataElement(arg) 335 self.assert_(isinstance(value, objectify.ObjectifiedElement)) 336 for attr in arg.attrib: 337 self.assertEquals(value.get(attr), arg.get(attr))
338
339 - def test_root(self):
340 root = self.Element("test") 341 self.assert_(isinstance(root, objectify.ObjectifiedElement))
342
343 - def test_str(self):
344 root = self.Element("test") 345 self.assertEquals('', str(root))
346
347 - def test_child(self):
348 root = self.XML(xml_str) 349 self.assertEquals("0", root.c1.c2.text)
350
351 - def test_countchildren(self):
352 root = self.XML(xml_str) 353 self.assertEquals(1, root.countchildren()) 354 self.assertEquals(5, root.c1.countchildren())
355
356 - def test_child_getattr(self):
357 root = self.XML(xml_str) 358 self.assertEquals("0", getattr(root.c1, "{objectified}c2").text) 359 self.assertEquals("3", getattr(root.c1, "{otherNS}c2").text)
360
361 - def test_child_nonexistant(self):
362 root = self.XML(xml_str) 363 self.assertRaises(AttributeError, getattr, root.c1, "NOT_THERE") 364 self.assertRaises(AttributeError, getattr, root.c1, "{unknownNS}c2")
365
367 root = self.XML(xml_str) 368 self.assertEquals("4", getattr(root.c1, "{}c2").text) 369 self.assertEquals("0", getattr(root.c1, "c2").text)
370
371 - def test_setattr(self):
372 for val in [ 373 2, 2**32, 1.2, "Won't get fooled again", 374 _str("W\xf6n't get f\xf6\xf6led \xe4g\xe4in", 'ISO-8859-1'), True, 375 False, None]: 376 root = self.Element('root') 377 attrname = 'val' 378 setattr(root, attrname, val) 379 result = getattr(root, attrname) 380 self.assertEquals(val, result) 381 self.assertEquals(type(val), type(result.pyval))
382
383 - def test_setattr_nonunicode(self):
384 root = self.Element('root') 385 attrname = 'val' 386 val = _bytes("W\xf6n't get f\xf6\xf6led \xe4g\xe4in", 'ISO-8859-1') 387 self.assertRaises(ValueError, setattr, root, attrname, val) 388 self.assertRaises(AttributeError, getattr, root, attrname)
389
390 - def test_addattr(self):
391 root = self.XML(xml_str) 392 self.assertEquals(1, len(root.c1)) 393 root.addattr("c1", "test") 394 self.assertEquals(2, len(root.c1)) 395 self.assertEquals("test", root.c1[1].text)
396
397 - def test_addattr_element(self):
398 root = self.XML(xml_str) 399 self.assertEquals(1, len(root.c1)) 400 401 new_el = self.Element("test", myattr="5") 402 root.addattr("c1", new_el) 403 self.assertEquals(2, len(root.c1)) 404 self.assertEquals(None, root.c1[0].get("myattr")) 405 self.assertEquals("5", root.c1[1].get("myattr"))
406
407 - def test_addattr_list(self):
408 root = self.XML(xml_str) 409 self.assertEquals(1, len(root.c1)) 410 411 new_el = self.Element("test") 412 self.etree.SubElement(new_el, "a", myattr="A") 413 self.etree.SubElement(new_el, "a", myattr="B") 414 415 root.addattr("c1", list(new_el.a)) 416 self.assertEquals(3, len(root.c1)) 417 self.assertEquals(None, root.c1[0].get("myattr")) 418 self.assertEquals("A", root.c1[1].get("myattr")) 419 self.assertEquals("B", root.c1[2].get("myattr"))
420
421 - def test_child_addattr(self):
422 root = self.XML(xml_str) 423 self.assertEquals(3, len(root.c1.c2)) 424 root.c1.addattr("c2", 3) 425 self.assertEquals(4, len(root.c1.c2)) 426 self.assertEquals("3", root.c1.c2[3].text)
427
428 - def test_child_index(self):
429 root = self.XML(xml_str) 430 self.assertEquals("0", root.c1.c2[0].text) 431 self.assertEquals("1", root.c1.c2[1].text) 432 self.assertEquals("2", root.c1.c2[2].text) 433 self.assertRaises(IndexError, operator.getitem, root.c1.c2, 3)
434
435 - def test_child_index_neg(self):
436 root = self.XML(xml_str) 437 self.assertEquals("0", root.c1.c2[0].text) 438 self.assertEquals("0", root.c1.c2[-3].text) 439 self.assertEquals("1", root.c1.c2[-2].text) 440 self.assertEquals("2", root.c1.c2[-1].text) 441 self.assertRaises(IndexError, operator.getitem, root.c1.c2, -4)
442
443 - def test_child_len(self):
444 root = self.XML(xml_str) 445 self.assertEquals(1, len(root)) 446 self.assertEquals(1, len(root.c1)) 447 self.assertEquals(3, len(root.c1.c2))
448
449 - def test_child_iter(self):
450 root = self.XML(xml_str) 451 self.assertEquals([root], 452 list(iter(root))) 453 self.assertEquals([root.c1], 454 list(iter(root.c1))) 455 self.assertEquals([root.c1.c2[0], root.c1.c2[1], root.c1.c2[2]], 456 list(iter((root.c1.c2))))
457
458 - def test_class_lookup(self):
459 root = self.XML(xml_str) 460 self.assert_(isinstance(root.c1.c2, objectify.ObjectifiedElement)) 461 self.assertFalse(isinstance(getattr(root.c1, "{otherNS}c2"), 462 objectify.ObjectifiedElement))
463
464 - def test_dir(self):
465 root = self.XML(xml_str) 466 dir_c1 = dir(objectify.ObjectifiedElement) + ['c1'] 467 dir_c1.sort() 468 dir_c2 = dir(objectify.ObjectifiedElement) + ['c2'] 469 dir_c2.sort() 470 471 self.assertEquals(dir_c1, dir(root)) 472 self.assertEquals(dir_c2, dir(root.c1))
473
474 - def test_vars(self):
475 root = self.XML(xml_str) 476 self.assertEquals({'c1' : root.c1}, vars(root)) 477 self.assertEquals({'c2' : root.c1.c2}, vars(root.c1))
478
479 - def test_child_set_ro(self):
480 root = self.XML(xml_str) 481 self.assertRaises(TypeError, setattr, root.c1.c2, 'text', "test") 482 self.assertRaises(TypeError, setattr, root.c1.c2, 'pyval', "test")
483 484 # slicing 485
486 - def test_getslice_complete(self):
487 root = self.XML("<root><c>c1</c><c>c2</c></root>") 488 self.assertEquals(["c1", "c2"], 489 [ c.text for c in root.c[:] ])
490
491 - def test_getslice_partial(self):
492 root = self.XML("<root><c>c1</c><c>c2</c><c>c3</c><c>c4</c></root>") 493 test_list = ["c1", "c2", "c3", "c4"] 494 495 self.assertEquals(test_list, 496 [ c.text for c in root.c[:] ]) 497 self.assertEquals(test_list[1:2], 498 [ c.text for c in root.c[1:2] ]) 499 self.assertEquals(test_list[-3:-1], 500 [ c.text for c in root.c[-3:-1] ]) 501 self.assertEquals(test_list[-3:3], 502 [ c.text for c in root.c[-3:3] ]) 503 self.assertEquals(test_list[-3000:3], 504 [ c.text for c in root.c[-3000:3] ]) 505 self.assertEquals(test_list[-3:3000], 506 [ c.text for c in root.c[-3:3000] ])
507
508 - def test_getslice_partial_neg(self):
509 root = self.XML("<root><c>c1</c><c>c2</c><c>c3</c><c>c4</c></root>") 510 test_list = ["c1", "c2", "c3", "c4"] 511 512 self.assertEquals(test_list, 513 [ c.text for c in root.c[:] ]) 514 self.assertEquals(test_list[2:1:-1], 515 [ c.text for c in root.c[2:1:-1] ]) 516 self.assertEquals(test_list[-1:-3:-1], 517 [ c.text for c in root.c[-1:-3:-1] ]) 518 self.assertEquals(test_list[2:-3:-1], 519 [ c.text for c in root.c[2:-3:-1] ]) 520 self.assertEquals(test_list[2:-3000:-1], 521 [ c.text for c in root.c[2:-3000:-1] ])
522 523 # slice assignment 524
525 - def test_setslice_complete(self):
526 Element = self.Element 527 root = Element("root") 528 root.c = ["c1", "c2"] 529 530 c1 = root.c[0] 531 c2 = root.c[1] 532 533 self.assertEquals([c1,c2], list(root.c)) 534 self.assertEquals(["c1", "c2"], 535 [ c.text for c in root.c ])
536
537 - def test_setslice_elements(self):
538 Element = self.Element 539 root = Element("root") 540 root.c = ["c1", "c2"] 541 542 c1 = root.c[0] 543 c2 = root.c[1] 544 545 self.assertEquals([c1,c2], list(root.c)) 546 self.assertEquals(["c1", "c2"], 547 [ c.text for c in root.c ]) 548 549 root2 = Element("root2") 550 root2.el = [ "test", "test" ] 551 self.assertEquals(["test", "test"], 552 [ el.text for el in root2.el ]) 553 554 root.c = [ root2.el, root2.el ] 555 self.assertEquals(["test", "test"], 556 [ c.text for c in root.c ]) 557 self.assertEquals(["test", "test"], 558 [ el.text for el in root2.el ]) 559 560 root.c[:] = [ c1, c2, c2, c1 ] 561 self.assertEquals(["c1", "c2", "c2", "c1"], 562 [ c.text for c in root.c ])
563
564 - def test_setslice_partial(self):
565 Element = self.Element 566 root = Element("root") 567 l = ["c1", "c2", "c3", "c4"] 568 root.c = l 569 570 self.assertEquals(["c1", "c2", "c3", "c4"], 571 [ c.text for c in root.c ]) 572 self.assertEquals(l, 573 [ c.text for c in root.c ]) 574 575 new_slice = ["cA", "cB"] 576 l[1:2] = new_slice 577 root.c[1:2] = new_slice 578 579 self.assertEquals(["c1", "cA", "cB", "c3", "c4"], l) 580 self.assertEquals(["c1", "cA", "cB", "c3", "c4"], 581 [ c.text for c in root.c ]) 582 self.assertEquals(l, 583 [ c.text for c in root.c ])
584
585 - def test_setslice_insert(self):
586 Element = self.Element 587 root = Element("root") 588 l = ["c1", "c2", "c3", "c4"] 589 root.c = l 590 591 self.assertEquals(["c1", "c2", "c3", "c4"], 592 [ c.text for c in root.c ]) 593 self.assertEquals(l, 594 [ c.text for c in root.c ]) 595 596 new_slice = ["cA", "cB"] 597 l[1:1] = new_slice 598 root.c[1:1] = new_slice 599 600 self.assertEquals(["c1", "cA", "cB", "c2", "c3", "c4"], l) 601 self.assertEquals(["c1", "cA", "cB", "c2", "c3", "c4"], 602 [ c.text for c in root.c ]) 603 self.assertEquals(l, 604 [ c.text for c in root.c ])
605
606 - def test_setslice_insert_neg(self):
607 Element = self.Element 608 root = Element("root") 609 l = ["c1", "c2", "c3", "c4"] 610 root.c = l 611 612 self.assertEquals(["c1", "c2", "c3", "c4"], 613 [ c.text for c in root.c ]) 614 self.assertEquals(l, 615 [ c.text for c in root.c ]) 616 617 new_slice = ["cA", "cB"] 618 l[-2:-2] = new_slice 619 root.c[-2:-2] = new_slice 620 621 self.assertEquals(["c1", "c2", "cA", "cB", "c3", "c4"], l) 622 self.assertEquals(["c1", "c2", "cA", "cB", "c3", "c4"], 623 [ c.text for c in root.c ]) 624 self.assertEquals(l, 625 [ c.text for c in root.c ])
626
627 - def test_setslice_empty(self):
628 Element = self.Element 629 root = Element("root") 630 631 root.c = [] 632 self.assertRaises( 633 AttributeError, getattr, root, 'c')
634
636 Element = self.Element 637 root = Element("root") 638 l = ["c1", "c2", "c3", "c4"] 639 root.c = l 640 641 self.assertEquals(["c1", "c2", "c3", "c4"], 642 [ c.text for c in root.c ]) 643 self.assertEquals(l, 644 [ c.text for c in root.c ]) 645 646 new_slice = ["cA", "cB", "cC"] 647 self.assertRaises( 648 ValueError, operator.setitem, 649 l, slice(1,2,-1), new_slice) 650 self.assertRaises( 651 ValueError, operator.setitem, 652 root.c, slice(1,2,-1), new_slice)
653
654 - def test_setslice_partial_neg(self):
655 Element = self.Element 656 root = Element("root") 657 l = ["c1", "c2", "c3", "c4"] 658 root.c = l 659 660 self.assertEquals(["c1", "c2", "c3", "c4"], 661 [ c.text for c in root.c ]) 662 self.assertEquals(l, 663 [ c.text for c in root.c ]) 664 665 new_slice = ["cA", "cB"] 666 l[-1:1:-1] = new_slice 667 root.c[-1:1:-1] = new_slice 668 669 self.assertEquals(["c1", "c2", "cB", "cA"], l) 670 self.assertEquals(["c1", "c2", "cB", "cA"], 671 [ c.text for c in root.c ]) 672 self.assertEquals(l, 673 [ c.text for c in root.c ])
674
676 Element = self.Element 677 root = Element("root") 678 l = ["c1", "c2", "c3", "c4"] 679 root.c = l 680 681 self.assertEquals(["c1", "c2", "c3", "c4"], 682 [ c.text for c in root.c ]) 683 self.assertEquals(l, 684 [ c.text for c in root.c ]) 685 686 new_slice = ["cA", "cB"] 687 l[-1:-4:-2] = new_slice 688 root.c[-1:-4:-2] = new_slice 689 690 self.assertEquals(["c1", "cB", "c3", "cA"], l) 691 self.assertEquals(["c1", "cB", "c3", "cA"], 692 [ c.text for c in root.c ]) 693 self.assertEquals(l, 694 [ c.text for c in root.c ])
695 696 # other stuff 697
698 - def test_set_string(self):
699 # make sure strings are not handled as sequences 700 Element = self.Element 701 root = Element("root") 702 root.c = "TEST" 703 self.assertEquals(["TEST"], 704 [ c.text for c in root.c ])
705
706 - def test_setitem_string(self):
707 # make sure strings are set as children 708 Element = self.Element 709 root = Element("root") 710 root["c"] = "TEST" 711 self.assertEquals(["TEST"], 712 [ c.text for c in root.c ])
713
715 # make sure 'text' etc. are set as children 716 Element = self.Element 717 root = Element("root") 718 719 root["text"] = "TEST" 720 self.assertEquals(["TEST"], 721 [ c.text for c in root["text"] ]) 722 723 root["tail"] = "TEST" 724 self.assertEquals(["TEST"], 725 [ c.text for c in root["tail"] ]) 726 727 root["pyval"] = "TEST" 728 self.assertEquals(["TEST"], 729 [ c.text for c in root["pyval"] ]) 730 731 root["tag"] = "TEST" 732 self.assertEquals(["TEST"], 733 [ c.text for c in root["tag"] ])
734
735 - def test_findall(self):
736 XML = self.XML 737 root = XML('<a><b><c/></b><b/><c><b/></c></a>') 738 self.assertEquals(1, len(root.findall("c"))) 739 self.assertEquals(2, len(root.findall(".//c"))) 740 self.assertEquals(3, len(root.findall(".//b"))) 741 self.assert_(root.findall(".//b")[1] is root.getchildren()[1])
742
743 - def test_findall_ns(self):
744 XML = self.XML 745 root = XML('<a xmlns:x="X" xmlns:y="Y"><x:b><c/></x:b><b/><c><x:b/><b/></c><b/></a>') 746 self.assertEquals(2, len(root.findall(".//{X}b"))) 747 self.assertEquals(3, len(root.findall(".//b"))) 748 self.assertEquals(2, len(root.findall("b")))
749
750 - def test_build_tree(self):
751 root = self.Element('root') 752 root.a = 5 753 root.b = 6 754 self.assert_(isinstance(root, objectify.ObjectifiedElement)) 755 self.assert_(isinstance(root.a, objectify.IntElement)) 756 self.assert_(isinstance(root.b, objectify.IntElement))
757
758 - def test_type_NoneType(self):
759 Element = self.Element 760 SubElement = self.etree.SubElement 761 762 nil_attr = XML_SCHEMA_NIL_ATTR 763 root = Element("{objectified}root") 764 SubElement(root, "{objectified}none") 765 SubElement(root, "{objectified}none", {nil_attr : "true"}) 766 self.assertFalse(isinstance(root.none, objectify.NoneElement)) 767 self.assertFalse(isinstance(root.none[0], objectify.NoneElement)) 768 self.assert_(isinstance(root.none[1], objectify.NoneElement)) 769 self.assertEquals(hash(root.none[1]), hash(None)) 770 self.assertEquals(root.none[1], None) 771 self.assertFalse(root.none[1])
772
773 - def test_data_element_NoneType(self):
774 value = objectify.DataElement(None) 775 self.assert_(isinstance(value, objectify.NoneElement)) 776 self.assertEquals(value, None) 777 self.assertEquals(value.get(XML_SCHEMA_NIL_ATTR), "true")
778
779 - def test_type_bool(self):
780 Element = self.Element 781 SubElement = self.etree.SubElement 782 root = Element("{objectified}root") 783 root.bool = True 784 self.assertEquals(root.bool, True) 785 self.assertEquals(root.bool + root.bool, True + True) 786 self.assertEquals(True + root.bool, True + root.bool) 787 self.assertEquals(root.bool * root.bool, True * True) 788 self.assertEquals(int(root.bool), int(True)) 789 self.assertEquals(hash(root.bool), hash(True)) 790 self.assertEquals(complex(root.bool), complex(True)) 791 self.assert_(isinstance(root.bool, objectify.BoolElement)) 792 793 root.bool = False 794 self.assertEquals(root.bool, False) 795 self.assertEquals(root.bool + root.bool, False + False) 796 self.assertEquals(False + root.bool, False + root.bool) 797 self.assertEquals(root.bool * root.bool, False * False) 798 self.assertEquals(int(root.bool), int(False)) 799 self.assertEquals(hash(root.bool), hash(False)) 800 self.assertEquals(complex(root.bool), complex(False)) 801 self.assert_(isinstance(root.bool, objectify.BoolElement))
802
803 - def test_data_element_bool(self):
804 value = objectify.DataElement(True) 805 self.assert_(isinstance(value, objectify.BoolElement)) 806 self.assertEquals(value, True) 807 808 value = objectify.DataElement(False) 809 self.assert_(isinstance(value, objectify.BoolElement)) 810 self.assertEquals(value, False)
811
812 - def test_type_str(self):
813 Element = self.Element 814 SubElement = self.etree.SubElement 815 root = Element("{objectified}root") 816 root.s = "test" 817 self.assert_(isinstance(root.s, objectify.StringElement))
818
819 - def test_type_str_intliteral(self):
820 Element = self.Element 821 SubElement = self.etree.SubElement 822 root = Element("{objectified}root") 823 root.s = "3" 824 self.assert_(isinstance(root.s, objectify.StringElement))
825
826 - def test_type_str_floatliteral(self):
827 Element = self.Element 828 SubElement = self.etree.SubElement 829 root = Element("{objectified}root") 830 root.s = "3.72" 831 self.assert_(isinstance(root.s, objectify.StringElement))
832
833 - def test_type_str_mul(self):
834 Element = self.Element 835 SubElement = self.etree.SubElement 836 root = Element("{objectified}root") 837 root.s = "test" 838 839 self.assertEquals("test" * 5, root.s * 5) 840 self.assertEquals(5 * "test", 5 * root.s) 841 842 self.assertRaises(TypeError, operator.mul, root.s, "honk") 843 self.assertRaises(TypeError, operator.mul, "honk", root.s)
844
845 - def test_type_str_add(self):
846 Element = self.Element 847 SubElement = self.etree.SubElement 848 root = Element("{objectified}root") 849 root.s = "test" 850 851 s = "toast" 852 self.assertEquals("test" + s, root.s + s) 853 self.assertEquals(s + "test", s + root.s)
854
855 - def test_type_str_mod(self):
856 s = "%d %f %s %r" 857 el = objectify.DataElement(s) 858 values = (1, 7.0, "abcd", None) 859 self.assertEquals(s % values, el % values) 860 861 s = "%d" 862 el = objectify.DataElement(s) 863 val = 5 864 self.assertEquals(s % val, el % val) 865 866 s = "%d %s" 867 el = objectify.DataElement(s) 868 val = 5 869 self.assertRaises(TypeError, el.__mod__, val) 870 871 s = "" 872 el = objectify.DataElement(s) 873 val = 5 874 self.assertRaises(TypeError, el.__mod__, val)
875
876 - def test_type_str_hash(self):
877 v = "1" 878 el = objectify.DataElement(v) 879 self.assertEquals(hash(el), hash("1"))
880
881 - def test_type_str_as_int(self):
882 v = "1" 883 el = objectify.DataElement(v) 884 self.assertEquals(int(el), 1)
885
886 - def test_type_str_as_float(self):
887 v = "1" 888 el = objectify.DataElement(v) 889 self.assertEquals(float(el), 1)
890
891 - def test_type_str_as_complex(self):
892 v = "1" 893 el = objectify.DataElement(v) 894 self.assertEquals(complex(el), 1)
895
897 s = "%d %f %s %r" 898 el = objectify.DataElement(s) 899 values = (objectify.DataElement(1), 900 objectify.DataElement(7.0), 901 objectify.DataElement("abcd"), 902 objectify.DataElement(None)) 903 self.assertEquals(s % values, el % values)
904
905 - def test_data_element_str(self):
906 value = objectify.DataElement("test") 907 self.assert_(isinstance(value, objectify.StringElement)) 908 self.assertEquals(value, "test")
909
911 value = objectify.DataElement("3") 912 self.assert_(isinstance(value, objectify.StringElement)) 913 self.assertEquals(value, "3")
914
916 value = objectify.DataElement("3.20") 917 self.assert_(isinstance(value, objectify.StringElement)) 918 self.assertEquals(value, "3.20")
919
920 - def test_type_ustr(self):
921 Element = self.Element 922 SubElement = self.etree.SubElement 923 root = Element("{objectified}root") 924 root.s = _str("test") 925 self.assert_(isinstance(root.s, objectify.StringElement))
926
927 - def test_type_ustr_intliteral(self):
928 Element = self.Element 929 SubElement = self.etree.SubElement 930 root = Element("{objectified}root") 931 root.s = _str("3") 932 self.assert_(isinstance(root.s, objectify.StringElement))
933
935 Element = self.Element 936 SubElement = self.etree.SubElement 937 root = Element("{objectified}root") 938 root.s = _str("3.72") 939 self.assert_(isinstance(root.s, objectify.StringElement))
940
941 - def test_type_ustr_mul(self):
942 Element = self.Element 943 SubElement = self.etree.SubElement 944 root = Element("{objectified}root") 945 root.s = _str("test") 946 947 self.assertEquals(_str("test") * 5, root.s * 5) 948 self.assertEquals(5 * _str("test"), 5 * root.s) 949 950 self.assertRaises(TypeError, operator.mul, root.s, _str("honk")) 951 self.assertRaises(TypeError, operator.mul, _str("honk"), root.s)
952
953 - def test_type_ustr_add(self):
954 Element = self.Element 955 SubElement = self.etree.SubElement 956 root = Element("{objectified}root") 957 root.s = _str("test") 958 959 s = _str("toast") 960 self.assertEquals(_str("test") + s, root.s + s) 961 self.assertEquals(s + _str("test"), s + root.s)
962
963 - def test_data_element_ustr(self):
964 value = objectify.DataElement(_str("test")) 965 self.assert_(isinstance(value, objectify.StringElement)) 966 self.assertEquals(value, _str("test"))
967
969 value = objectify.DataElement("3") 970 self.assert_(isinstance(value, objectify.StringElement)) 971 self.assertEquals(value, _str("3"))
972
974 value = objectify.DataElement(_str("3.20")) 975 self.assert_(isinstance(value, objectify.StringElement)) 976 self.assertEquals(value, _str("3.20"))
977
978 - def test_type_int(self):
979 Element = self.Element 980 SubElement = self.etree.SubElement 981 root = Element("{objectified}root") 982 root.none = 5 983 self.assert_(isinstance(root.none, objectify.IntElement))
984
985 - def test_data_element_int(self):
986 value = objectify.DataElement(5) 987 self.assert_(isinstance(value, objectify.IntElement)) 988 self.assertEquals(value, 5)
989
990 - def test_data_element_int_hash(self):
991 value = objectify.DataElement(123) 992 self.assertEquals(hash(value), hash(123))
993
994 - def test_type_float(self):
995 Element = self.Element 996 SubElement = self.etree.SubElement 997 root = Element("{objectified}root") 998 root.none = 5.5 999 self.assert_(isinstance(root.none, objectify.FloatElement))
1000
1001 - def test_data_element_float(self):
1002 value = objectify.DataElement(5.5) 1003 self.assert_(isinstance(value, objectify.FloatElement)) 1004 self.assertEquals(value, 5.5)
1005
1007 value = objectify.DataElement(5.5) 1008 self.assertEquals(hash(value), hash(5.5))
1009
1010 - def test_data_element_xsitypes(self):
1011 for xsi, objclass in xsitype2objclass.items(): 1012 # 1 is a valid value for all ObjectifiedDataElement classes 1013 pyval = 1 1014 value = objectify.DataElement(pyval, _xsi=xsi) 1015 self.assert_(isinstance(value, objclass), 1016 "DataElement(%s, _xsi='%s') returns %s, expected %s" 1017 % (pyval, xsi, type(value), objclass))
1018
1020 for xsi, objclass in xsitype2objclass.items(): 1021 # 1 is a valid value for all ObjectifiedDataElement classes 1022 pyval = 1 1023 value = objectify.DataElement(pyval, _xsi="xsd:%s" % xsi) 1024 self.assert_(isinstance(value, objclass), 1025 "DataElement(%s, _xsi='%s') returns %s, expected %s" 1026 % (pyval, xsi, type(value), objclass))
1027
1029 for xsi, objclass in xsitype2objclass.items(): 1030 # 1 is a valid value for all ObjectifiedDataElement classes 1031 self.assertRaises(ValueError, objectify.DataElement, 1, 1032 _xsi="foo:%s" % xsi)
1033
1034 - def test_data_element_pytypes(self):
1035 for pytype, objclass in pytype2objclass.items(): 1036 # 1 is a valid value for all ObjectifiedDataElement classes 1037 pyval = 1 1038 value = objectify.DataElement(pyval, _pytype=pytype) 1039 self.assert_(isinstance(value, objclass), 1040 "DataElement(%s, _pytype='%s') returns %s, expected %s" 1041 % (pyval, pytype, type(value), objclass))
1042
1044 pyval = 1 1045 pytype = "NoneType" 1046 objclass = objectify.NoneElement 1047 value = objectify.DataElement(pyval, _pytype=pytype) 1048 self.assert_(isinstance(value, objclass), 1049 "DataElement(%s, _pytype='%s') returns %s, expected %s" 1050 % (pyval, pytype, type(value), objclass)) 1051 self.assertEquals(value.text, None) 1052 self.assertEquals(value.pyval, None)
1053
1055 # pre-2.0 lxml called NoneElement "none" 1056 pyval = 1 1057 pytype = "none" 1058 objclass = objectify.NoneElement 1059 value = objectify.DataElement(pyval, _pytype=pytype) 1060 self.assert_(isinstance(value, objclass), 1061 "DataElement(%s, _pytype='%s') returns %s, expected %s" 1062 % (pyval, pytype, type(value), objclass)) 1063 self.assertEquals(value.text, None) 1064 self.assertEquals(value.pyval, None)
1065
1066 - def test_type_unregistered(self):
1067 Element = self.Element 1068 SubElement = self.etree.SubElement 1069 class MyFloat(float): 1070 pass
1071 root = Element("{objectified}root") 1072 root.myfloat = MyFloat(5.5) 1073 self.assert_(isinstance(root.myfloat, objectify.FloatElement)) 1074 self.assertEquals(root.myfloat.get(objectify.PYTYPE_ATTRIBUTE), None)
1075
1076 - def test_data_element_unregistered(self):
1077 class MyFloat(float): 1078 pass
1079 value = objectify.DataElement(MyFloat(5.5)) 1080 self.assert_(isinstance(value, objectify.FloatElement)) 1081 self.assertEquals(value, 5.5) 1082 self.assertEquals(value.get(objectify.PYTYPE_ATTRIBUTE), None) 1083
1084 - def test_schema_types(self):
1085 XML = self.XML 1086 root = XML('''\ 1087 <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 1088 <b xsi:type="boolean">true</b> 1089 <b xsi:type="boolean">false</b> 1090 <b xsi:type="boolean">1</b> 1091 <b xsi:type="boolean">0</b> 1092 1093 <f xsi:type="float">5</f> 1094 <f xsi:type="double">5</f> 1095 1096 <s xsi:type="string">5</s> 1097 <s xsi:type="normalizedString">5</s> 1098 <s xsi:type="token">5</s> 1099 <s xsi:type="language">5</s> 1100 <s xsi:type="Name">5</s> 1101 <s xsi:type="NCName">5</s> 1102 <s xsi:type="ID">5</s> 1103 <s xsi:type="IDREF">5</s> 1104 <s xsi:type="ENTITY">5</s> 1105 <s xsi:type="NMTOKEN">5</s> 1106 1107 <l xsi:type="integer">5</l> 1108 <l xsi:type="nonPositiveInteger">5</l> 1109 <l xsi:type="negativeInteger">5</l> 1110 <l xsi:type="long">5</l> 1111 <l xsi:type="nonNegativeInteger">5</l> 1112 <l xsi:type="unsignedLong">5</l> 1113 <l xsi:type="unsignedInt">5</l> 1114 <l xsi:type="positiveInteger">5</l> 1115 1116 <i xsi:type="int">5</i> 1117 <i xsi:type="short">5</i> 1118 <i xsi:type="byte">5</i> 1119 <i xsi:type="unsignedShort">5</i> 1120 <i xsi:type="unsignedByte">5</i> 1121 1122 <n xsi:nil="true"/> 1123 </root> 1124 ''') 1125 1126 for b in root.b: 1127 self.assert_(isinstance(b, objectify.BoolElement)) 1128 self.assertEquals(True, root.b[0]) 1129 self.assertEquals(False, root.b[1]) 1130 self.assertEquals(True, root.b[2]) 1131 self.assertEquals(False, root.b[3]) 1132 1133 for f in root.f: 1134 self.assert_(isinstance(f, objectify.FloatElement)) 1135 self.assertEquals(5, f) 1136 1137 for s in root.s: 1138 self.assert_(isinstance(s, objectify.StringElement)) 1139 self.assertEquals("5", s) 1140 1141 for i in root.i: 1142 self.assert_(isinstance(i, objectify.IntElement)) 1143 self.assertEquals(5, i) 1144 1145 for l in root.l: 1146 self.assert_(isinstance(l, objectify.IntElement)) 1147 self.assertEquals(5, i) 1148 1149 self.assert_(isinstance(root.n, objectify.NoneElement)) 1150 self.assertEquals(None, root.n)
1151
1152 - def test_schema_types_prefixed(self):
1153 XML = self.XML 1154 root = XML('''\ 1155 <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 1156 xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 1157 <b xsi:type="xsd:boolean">true</b> 1158 <b xsi:type="xsd:boolean">false</b> 1159 <b xsi:type="xsd:boolean">1</b> 1160 <b xsi:type="xsd:boolean">0</b> 1161 1162 <f xsi:type="xsd:float">5</f> 1163 <f xsi:type="xsd:double">5</f> 1164 1165 <s xsi:type="xsd:string">5</s> 1166 <s xsi:type="xsd:normalizedString">5</s> 1167 <s xsi:type="xsd:token">5</s> 1168 <s xsi:type="xsd:language">5</s> 1169 <s xsi:type="xsd:Name">5</s> 1170 <s xsi:type="xsd:NCName">5</s> 1171 <s xsi:type="xsd:ID">5</s> 1172 <s xsi:type="xsd:IDREF">5</s> 1173 <s xsi:type="xsd:ENTITY">5</s> 1174 <s xsi:type="xsd:NMTOKEN">5</s> 1175 1176 <l xsi:type="xsd:integer">5</l> 1177 <l xsi:type="xsd:nonPositiveInteger">5</l> 1178 <l xsi:type="xsd:negativeInteger">5</l> 1179 <l xsi:type="xsd:long">5</l> 1180 <l xsi:type="xsd:nonNegativeInteger">5</l> 1181 <l xsi:type="xsd:unsignedLong">5</l> 1182 <l xsi:type="xsd:unsignedInt">5</l> 1183 <l xsi:type="xsd:positiveInteger">5</l> 1184 1185 <i xsi:type="xsd:int">5</i> 1186 <i xsi:type="xsd:short">5</i> 1187 <i xsi:type="xsd:byte">5</i> 1188 <i xsi:type="xsd:unsignedShort">5</i> 1189 <i xsi:type="xsd:unsignedByte">5</i> 1190 1191 <n xsi:nil="true"/> 1192 </root> 1193 ''') 1194 1195 for b in root.b: 1196 self.assert_(isinstance(b, objectify.BoolElement)) 1197 self.assertEquals(True, root.b[0]) 1198 self.assertEquals(False, root.b[1]) 1199 self.assertEquals(True, root.b[2]) 1200 self.assertEquals(False, root.b[3]) 1201 1202 for f in root.f: 1203 self.assert_(isinstance(f, objectify.FloatElement)) 1204 self.assertEquals(5, f) 1205 1206 for s in root.s: 1207 self.assert_(isinstance(s, objectify.StringElement)) 1208 self.assertEquals("5", s) 1209 1210 for i in root.i: 1211 self.assert_(isinstance(i, objectify.IntElement)) 1212 self.assertEquals(5, i) 1213 1214 for l in root.l: 1215 self.assert_(isinstance(l, objectify.IntElement)) 1216 self.assertEquals(5, l) 1217 1218 self.assert_(isinstance(root.n, objectify.NoneElement)) 1219 self.assertEquals(None, root.n)
1220
1221 - def test_type_str_sequence(self):
1222 XML = self.XML 1223 root = XML(_bytes('<root><b>why</b><b>try</b></root>')) 1224 strs = [ str(s) for s in root.b ] 1225 self.assertEquals(["why", "try"], 1226 strs)
1227
1228 - def test_type_str_cmp(self):
1229 XML = self.XML 1230 root = XML(_bytes('<root><b>test</b><b>taste</b><b></b><b/></root>')) 1231 self.assertFalse(root.b[0] < root.b[1]) 1232 self.assertFalse(root.b[0] <= root.b[1]) 1233 self.assertFalse(root.b[0] == root.b[1]) 1234 1235 self.assert_(root.b[0] != root.b[1]) 1236 self.assert_(root.b[0] >= root.b[1]) 1237 self.assert_(root.b[0] > root.b[1]) 1238 1239 self.assertEquals(root.b[0], "test") 1240 self.assertEquals("test", root.b[0]) 1241 1242 self.assertEquals("", root.b[2]) 1243 self.assertEquals(root.b[2], "") 1244 self.assertEquals("", root.b[3]) 1245 self.assertEquals(root.b[3], "") 1246 self.assertEquals(root.b[2], root.b[3]) 1247 1248 root.b = "test" 1249 self.assert_(root.b) 1250 root.b = "" 1251 self.assertFalse(root.b) 1252 self.assertEquals(root.b, "") 1253 self.assertEquals("", root.b)
1254
1255 - def test_type_int_cmp(self):
1256 XML = self.XML 1257 root = XML(_bytes('<root><b>5</b><b>6</b></root>')) 1258 self.assert_(root.b[0] < root.b[1]) 1259 self.assert_(root.b[0] <= root.b[1]) 1260 self.assert_(root.b[0] != root.b[1]) 1261 1262 self.assertFalse(root.b[0] == root.b[1]) 1263 self.assertFalse(root.b[0] >= root.b[1]) 1264 self.assertFalse(root.b[0] > root.b[1]) 1265 1266 self.assertEquals(root.b[0], 5) 1267 self.assertEquals(5, root.b[0]) 1268 self.assertNotEquals(root.b[0], "5") 1269 1270 root.b = 5 1271 self.assert_(root.b) 1272 root.b = 0 1273 self.assertFalse(root.b)
1274 1275 # float + long share the NumberElement implementation with int 1276
1277 - def test_type_bool_cmp(self):
1278 XML = self.XML 1279 root = XML(_bytes('<root><b>false</b><b>true</b></root>')) 1280 self.assert_(root.b[0] < root.b[1]) 1281 self.assert_(root.b[0] <= root.b[1]) 1282 self.assert_(root.b[0] != root.b[1]) 1283 1284 self.assertFalse(root.b[0] == root.b[1]) 1285 self.assertFalse(root.b[0] >= root.b[1]) 1286 self.assertFalse(root.b[0] > root.b[1]) 1287 1288 self.assertFalse(root.b[0]) 1289 self.assert_(root.b[1]) 1290 1291 self.assertEquals(root.b[0], False) 1292 self.assertEquals(False, root.b[0]) 1293 self.assert_(root.b[0] < 5) 1294 self.assert_(5 > root.b[0]) 1295 1296 root.b = True 1297 self.assert_(root.b) 1298 root.b = False 1299 self.assertFalse(root.b)
1300
1301 - def test_type_none_cmp(self):
1302 XML = self.XML 1303 root = XML(_bytes(""" 1304 <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 1305 <b xsi:nil="true"></b><b xsi:nil="true"/> 1306 </root>""")) 1307 self.assert_(root.b[0] == root.b[1]) 1308 self.assertFalse(root.b[0]) 1309 self.assertEquals(root.b[0], None) 1310 self.assertEquals(None, root.b[0])
1311 1312 # doesn't work in Py3: 1313 1314 #for comparison in ["abc", 5, 7.3, True, [], ()]: 1315 # none = root.b[1] 1316 # self.assert_(none < comparison, "%s (%s) should be < %s" % 1317 # (none, type(none), comparison) ) 1318 # self.assert_(comparison > none, "%s should be > %s (%s)" % 1319 # (comparison, none, type(none)) ) 1320
1321 - def test_dataelement_xsi(self):
1322 el = objectify.DataElement(1, _xsi="string") 1323 self.assertEquals( 1324 el.get(XML_SCHEMA_INSTANCE_TYPE_ATTR), 1325 'xsd:string')
1326
1327 - def test_dataelement_xsi_nsmap(self):
1328 el = objectify.DataElement(1, _xsi="string", 1329 nsmap={'schema': XML_SCHEMA_NS}) 1330 self.assertEquals( 1331 el.get(XML_SCHEMA_INSTANCE_TYPE_ATTR), 1332 'schema:string')
1333
1334 - def test_dataelement_xsi_prefix_error(self):
1335 self.assertRaises(ValueError, objectify.DataElement, 1, 1336 _xsi="foo:string")
1337
1338 - def test_pytype_annotation(self):
1339 XML = self.XML 1340 root = XML(_bytes('''\ 1341 <a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 1342 xmlns:py="http://codespeak.net/lxml/objectify/pytype"> 1343 <b>5</b> 1344 <b>test</b> 1345 <c>1.1</c> 1346 <c>\uF8D2</c> 1347 <x>true</x> 1348 <n xsi:nil="true" /> 1349 <n></n> 1350 <b xsi:type="double">5</b> 1351 <b xsi:type="float">5</b> 1352 <s xsi:type="string">23</s> 1353 <s py:pytype="str">42</s> 1354 <f py:pytype="float">300</f> 1355 <l py:pytype="long">2</l> 1356 <t py:pytype="TREE"></t> 1357 </a> 1358 ''')) 1359 objectify.annotate(root) 1360 1361 child_types = [ c.get(objectify.PYTYPE_ATTRIBUTE) 1362 for c in root.iterchildren() ] 1363 self.assertEquals("int", child_types[ 0]) 1364 self.assertEquals("str", child_types[ 1]) 1365 self.assertEquals("float", child_types[ 2]) 1366 self.assertEquals("str", child_types[ 3]) 1367 self.assertEquals("bool", child_types[ 4]) 1368 self.assertEquals("NoneType", child_types[ 5]) 1369 self.assertEquals(None, child_types[ 6]) 1370 self.assertEquals("float", child_types[ 7]) 1371 self.assertEquals("float", child_types[ 8]) 1372 self.assertEquals("str", child_types[ 9]) 1373 self.assertEquals("int", child_types[10]) 1374 self.assertEquals("int", child_types[11]) 1375 self.assertEquals("int", child_types[12]) 1376 self.assertEquals(None, child_types[13]) 1377 1378 self.assertEquals("true", root.n.get(XML_SCHEMA_NIL_ATTR))
1379
1380 - def test_pytype_annotation_empty(self):
1381 XML = self.XML 1382 root = XML(_bytes('''\ 1383 <a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 1384 xmlns:py="http://codespeak.net/lxml/objectify/pytype"> 1385 <n></n> 1386 </a> 1387 ''')) 1388 objectify.annotate(root) 1389 1390 child_types = [ c.get(objectify.PYTYPE_ATTRIBUTE) 1391 for c in root.iterchildren() ] 1392 self.assertEquals(None, child_types[0]) 1393 1394 objectify.annotate(root, empty_pytype="str") 1395 1396 child_types = [ c.get(objectify.PYTYPE_ATTRIBUTE) 1397 for c in root.iterchildren() ] 1398 self.assertEquals("str", child_types[0])
1399
1400 - def test_pytype_annotation_use_old(self):
1401 XML = self.XML 1402 root = XML(_bytes('''\ 1403 <a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 1404 xmlns:py="http://codespeak.net/lxml/objectify/pytype"> 1405 <b>5</b> 1406 <b>test</b> 1407 <c>1.1</c> 1408 <c>\uF8D2</c> 1409 <x>true</x> 1410 <n xsi:nil="true" /> 1411 <n></n> 1412 <b xsi:type="double">5</b> 1413 <b xsi:type="float">5</b> 1414 <s xsi:type="string">23</s> 1415 <s py:pytype="str">42</s> 1416 <f py:pytype="float">300</f> 1417 <l py:pytype="long">2</l> 1418 <t py:pytype="TREE"></t> 1419 </a> 1420 ''')) 1421 objectify.annotate(root, ignore_old=False) 1422 1423 child_types = [ c.get(objectify.PYTYPE_ATTRIBUTE) 1424 for c in root.iterchildren() ] 1425 self.assertEquals("int", child_types[ 0]) 1426 self.assertEquals("str", child_types[ 1]) 1427 self.assertEquals("float", child_types[ 2]) 1428 self.assertEquals("str", child_types[ 3]) 1429 self.assertEquals("bool", child_types[ 4]) 1430 self.assertEquals("NoneType", child_types[ 5]) 1431 self.assertEquals(None, child_types[ 6]) 1432 self.assertEquals("float", child_types[ 7]) 1433 self.assertEquals("float", child_types[ 8]) 1434 self.assertEquals("str", child_types[ 9]) 1435 self.assertEquals("str", child_types[10]) 1436 self.assertEquals("float", child_types[11]) 1437 self.assertEquals("int", child_types[12]) 1438 self.assertEquals(TREE_PYTYPE, child_types[13]) 1439 1440 self.assertEquals("true", root.n.get(XML_SCHEMA_NIL_ATTR))
1441
1442 - def test_pytype_xsitype_annotation(self):
1443 XML = self.XML 1444 root = XML(_bytes('''\ 1445 <a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 1446 xmlns:py="http://codespeak.net/lxml/objectify/pytype"> 1447 <b>5</b> 1448 <b>test</b> 1449 <c>1.1</c> 1450 <c>\uF8D2</c> 1451 <x>true</x> 1452 <n xsi:nil="true" /> 1453 <n></n> 1454 <b xsi:type="double">5</b> 1455 <b xsi:type="float">5</b> 1456 <s xsi:type="string">23</s> 1457 <s py:pytype="str">42</s> 1458 <f py:pytype="float">300</f> 1459 <l py:pytype="long">2</l> 1460 <t py:pytype="TREE"></t> 1461 </a> 1462 ''')) 1463 objectify.annotate(root, ignore_old=False, ignore_xsi=False, 1464 annotate_xsi=1, annotate_pytype=1) 1465 1466 # check py annotations 1467 child_types = [ c.get(objectify.PYTYPE_ATTRIBUTE) 1468 for c in root.iterchildren() ] 1469 self.assertEquals("int", child_types[ 0]) 1470 self.assertEquals("str", child_types[ 1]) 1471 self.assertEquals("float", child_types[ 2]) 1472 self.assertEquals("str", child_types[ 3]) 1473 self.assertEquals("bool", child_types[ 4]) 1474 self.assertEquals("NoneType", child_types[ 5]) 1475 self.assertEquals(None, child_types[ 6]) 1476 self.assertEquals("float", child_types[ 7]) 1477 self.assertEquals("float", child_types[ 8]) 1478 self.assertEquals("str", child_types[ 9]) 1479 self.assertEquals("str", child_types[10]) 1480 self.assertEquals("float", child_types[11]) 1481 self.assertEquals("int", child_types[12]) 1482 self.assertEquals(TREE_PYTYPE, child_types[13]) 1483 1484 self.assertEquals("true", root.n.get(XML_SCHEMA_NIL_ATTR)) 1485 1486 child_xsitypes = [ c.get(XML_SCHEMA_INSTANCE_TYPE_ATTR) 1487 for c in root.iterchildren() ] 1488 1489 # check xsi annotations 1490 child_types = [ c.get(XML_SCHEMA_INSTANCE_TYPE_ATTR) 1491 for c in root.iterchildren() ] 1492 self.assertEquals("xsd:integer", child_types[ 0]) 1493 self.assertEquals("xsd:string", child_types[ 1]) 1494 self.assertEquals("xsd:double", child_types[ 2]) 1495 self.assertEquals("xsd:string", child_types[ 3]) 1496 self.assertEquals("xsd:boolean", child_types[ 4]) 1497 self.assertEquals(None, child_types[ 5]) 1498 self.assertEquals(None, child_types[ 6]) 1499 self.assertEquals("xsd:double", child_types[ 7]) 1500 self.assertEquals("xsd:float", child_types[ 8]) 1501 self.assertEquals("xsd:string", child_types[ 9]) 1502 self.assertEquals("xsd:string", child_types[10]) 1503 self.assertEquals("xsd:double", child_types[11]) 1504 self.assertEquals("xsd:integer", child_types[12]) 1505 self.assertEquals(None, child_types[13]) 1506 1507 self.assertEquals("true", root.n.get(XML_SCHEMA_NIL_ATTR))
1508
1509 - def test_xsiannotate_use_old(self):
1510 XML = self.XML 1511 root = XML(_bytes('''\ 1512 <a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 1513 xmlns:py="http://codespeak.net/lxml/objectify/pytype"> 1514 <b>5</b> 1515 <b>test</b> 1516 <c>1.1</c> 1517 <c>\uF8D2</c> 1518 <x>true</x> 1519 <n xsi:nil="true" /> 1520 <n></n> 1521 <b xsi:type="double">5</b> 1522 <b xsi:type="float">5</b> 1523 <s xsi:type="string">23</s> 1524 <s py:pytype="str">42</s> 1525 <f py:pytype="float">300</f> 1526 <l py:pytype="long">2</l> 1527 <t py:pytype="TREE"></t> 1528 </a> 1529 ''')) 1530 objectify.xsiannotate(root, ignore_old=False) 1531 1532 child_types = [ c.get(XML_SCHEMA_INSTANCE_TYPE_ATTR) 1533 for c in root.iterchildren() ] 1534 self.assertEquals("xsd:integer", child_types[ 0]) 1535 self.assertEquals("xsd:string", child_types[ 1]) 1536 self.assertEquals("xsd:double", child_types[ 2]) 1537 self.assertEquals("xsd:string", child_types[ 3]) 1538 self.assertEquals("xsd:boolean", child_types[ 4]) 1539 self.assertEquals(None, child_types[ 5]) 1540 self.assertEquals(None, child_types[ 6]) 1541 self.assertEquals("xsd:double", child_types[ 7]) 1542 self.assertEquals("xsd:float", child_types[ 8]) 1543 self.assertEquals("xsd:string", child_types[ 9]) 1544 self.assertEquals("xsd:string", child_types[10]) 1545 self.assertEquals("xsd:double", child_types[11]) 1546 self.assertEquals("xsd:integer", child_types[12]) 1547 self.assertEquals(None, child_types[13])
1548
1549 - def test_pyannotate_ignore_old(self):
1550 XML = self.XML 1551 root = XML(_bytes('''\ 1552 <a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 1553 xmlns:py="http://codespeak.net/lxml/objectify/pytype"> 1554 <b>5</b> 1555 <b>test</b> 1556 <c>1.1</c> 1557 <c>\uF8D2</c> 1558 <x>true</x> 1559 <n xsi:nil="true" /> 1560 <n></n> 1561 <b xsi:type="double">5</b> 1562 <b xsi:type="float">5</b> 1563 <s xsi:type="string">23</s> 1564 <s py:pytype="str">42</s> 1565 <f py:pytype="float">300</f> 1566 <l py:pytype="long">2</l> 1567 <t py:pytype="TREE"></t> 1568 </a> 1569 ''')) 1570 objectify.pyannotate(root, ignore_old=True) 1571 1572 child_types = [ c.get(objectify.PYTYPE_ATTRIBUTE) 1573 for c in root.iterchildren() ] 1574 self.assertEquals("int", child_types[ 0]) 1575 self.assertEquals("str", child_types[ 1]) 1576 self.assertEquals("float", child_types[ 2]) 1577 self.assertEquals("str", child_types[ 3]) 1578 self.assertEquals("bool", child_types[ 4]) 1579 self.assertEquals("NoneType", child_types[ 5]) 1580 self.assertEquals(None, child_types[ 6]) 1581 self.assertEquals("float", child_types[ 7]) 1582 self.assertEquals("float", child_types[ 8]) 1583 self.assertEquals("str", child_types[ 9]) 1584 self.assertEquals("int", child_types[10]) 1585 self.assertEquals("int", child_types[11]) 1586 self.assertEquals("int", child_types[12]) 1587 self.assertEquals(None, child_types[13]) 1588 1589 self.assertEquals("true", root.n.get(XML_SCHEMA_NIL_ATTR))
1590
1591 - def test_pyannotate_empty(self):
1592 XML = self.XML 1593 root = XML('''\ 1594 <a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 1595 xmlns:py="http://codespeak.net/lxml/objectify/pytype"> 1596 <n></n> 1597 </a> 1598 ''') 1599 objectify.pyannotate(root) 1600 1601 child_types = [ c.get(objectify.PYTYPE_ATTRIBUTE) 1602 for c in root.iterchildren() ] 1603 self.assertEquals(None, child_types[0]) 1604 1605 objectify.annotate(root, empty_pytype="str") 1606 1607 child_types = [ c.get(objectify.PYTYPE_ATTRIBUTE) 1608 for c in root.iterchildren() ] 1609 self.assertEquals("str", child_types[0])
1610
1611 - def test_pyannotate_use_old(self):
1612 XML = self.XML 1613 root = XML('''\ 1614 <a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 1615 xmlns:py="http://codespeak.net/lxml/objectify/pytype"> 1616 <b>5</b> 1617 <b>test</b> 1618 <c>1.1</c> 1619 <c>\uF8D2</c> 1620 <x>true</x> 1621 <n xsi:nil="true" /> 1622 <n></n> 1623 <b xsi:type="double">5</b> 1624 <b xsi:type="float">5</b> 1625 <s xsi:type="string">23</s> 1626 <s py:pytype="str">42</s> 1627 <f py:pytype="float">300</f> 1628 <l py:pytype="long">2</l> 1629 <t py:pytype="TREE"></t> 1630 </a> 1631 ''') 1632 objectify.pyannotate(root) 1633 1634 child_types = [ c.get(objectify.PYTYPE_ATTRIBUTE) 1635 for c in root.iterchildren() ] 1636 self.assertEquals("int", child_types[ 0]) 1637 self.assertEquals("str", child_types[ 1]) 1638 self.assertEquals("float", child_types[ 2]) 1639 self.assertEquals("str", child_types[ 3]) 1640 self.assertEquals("bool", child_types[ 4]) 1641 self.assertEquals("NoneType", child_types[ 5]) 1642 self.assertEquals(None, child_types[ 6]) 1643 self.assertEquals("float", child_types[ 7]) 1644 self.assertEquals("float", child_types[ 8]) 1645 self.assertEquals("str", child_types[ 9]) 1646 self.assertEquals("str", child_types[10]) 1647 self.assertEquals("float", child_types[11]) 1648 self.assertEquals("int", child_types[12]) 1649 self.assertEquals(TREE_PYTYPE, child_types[13]) 1650 1651 self.assertEquals("true", root.n.get(XML_SCHEMA_NIL_ATTR))
1652
1653 - def test_xsiannotate_ignore_old(self):
1654 XML = self.XML 1655 root = XML(_bytes('''\ 1656 <a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 1657 xmlns:py="http://codespeak.net/lxml/objectify/pytype"> 1658 <b>5</b> 1659 <b>test</b> 1660 <c>1.1</c> 1661 <c>\uF8D2</c> 1662 <x>true</x> 1663 <n xsi:nil="true" /> 1664 <n></n> 1665 <b xsi:type="double">5</b> 1666 <b xsi:type="float">5</b> 1667 <s xsi:type="string">23</s> 1668 <s py:pytype="str">42</s> 1669 <f py:pytype="float">300</f> 1670 <l py:pytype="long">2</l> 1671 <t py:pytype="TREE"></t> 1672 </a> 1673 ''')) 1674 objectify.xsiannotate(root, ignore_old=True) 1675 1676 child_types = [ c.get(XML_SCHEMA_INSTANCE_TYPE_ATTR) 1677 for c in root.iterchildren() ] 1678 self.assertEquals("xsd:integer", child_types[ 0]) 1679 self.assertEquals("xsd:string", child_types[ 1]) 1680 self.assertEquals("xsd:double", child_types[ 2]) 1681 self.assertEquals("xsd:string", child_types[ 3]) 1682 self.assertEquals("xsd:boolean", child_types[ 4]) 1683 self.assertEquals(None, child_types[ 5]) 1684 self.assertEquals(None, child_types[ 6]) 1685 self.assertEquals("xsd:integer", child_types[ 7]) 1686 self.assertEquals("xsd:integer", child_types[ 8]) 1687 self.assertEquals("xsd:integer", child_types[ 9]) 1688 self.assertEquals("xsd:string", child_types[10]) 1689 self.assertEquals("xsd:double", child_types[11]) 1690 self.assertEquals("xsd:integer", child_types[12]) 1691 self.assertEquals(None, child_types[13]) 1692 1693 self.assertEquals("true", root.n.get(XML_SCHEMA_NIL_ATTR))
1694
1695 - def test_deannotate(self):
1696 XML = self.XML 1697 root = XML(_bytes('''\ 1698 <a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 1699 xmlns:py="http://codespeak.net/lxml/objectify/pytype"> 1700 <b>5</b> 1701 <b>test</b> 1702 <c>1.1</c> 1703 <c>\uF8D2</c> 1704 <x>true</x> 1705 <n xsi:nil="true" /> 1706 <n></n> 1707 <b xsi:type="double">5</b> 1708 <b xsi:type="float">5</b> 1709 <s xsi:type="string">23</s> 1710 <s py:pytype="str">42</s> 1711 <f py:pytype="float">300</f> 1712 <l py:pytype="long">2</l> 1713 <t py:pytype="TREE"></t> 1714 </a> 1715 ''')) 1716 objectify.deannotate(root) 1717 1718 for c in root.getiterator(): 1719 self.assertEquals(None, c.get(XML_SCHEMA_INSTANCE_TYPE_ATTR)) 1720 self.assertEquals(None, c.get(objectify.PYTYPE_ATTRIBUTE)) 1721 1722 self.assertEquals("true", root.n.get(XML_SCHEMA_NIL_ATTR))
1723
1724 - def test_xsinil_deannotate(self):
1725 XML = self.XML 1726 root = XML(_bytes('''\ 1727 <a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 1728 xmlns:py="http://codespeak.net/lxml/objectify/pytype"> 1729 <b>5</b> 1730 <b>test</b> 1731 <c>1.1</c> 1732 <c>\uF8D2</c> 1733 <x>true</x> 1734 <n xsi:nil="true" /> 1735 <n></n> 1736 <b xsi:type="double">5</b> 1737 <b xsi:type="float">5</b> 1738 <s xsi:type="string">23</s> 1739 <s py:pytype="str">42</s> 1740 <f py:pytype="float">300</f> 1741 <l py:pytype="long">2</l> 1742 <t py:pytype="TREE"></t> 1743 </a> 1744 ''')) 1745 objectify.annotate( 1746 root, ignore_old=False, ignore_xsi=False, annotate_xsi=True, 1747 empty_pytype='str', empty_type='string') 1748 objectify.deannotate(root, pytype=False, xsi=False, xsi_nil=True) 1749 1750 child_types = [ c.get(XML_SCHEMA_INSTANCE_TYPE_ATTR) 1751 for c in root.iterchildren() ] 1752 self.assertEquals("xsd:integer", child_types[ 0]) 1753 self.assertEquals("xsd:string", child_types[ 1]) 1754 self.assertEquals("xsd:double", child_types[ 2]) 1755 self.assertEquals("xsd:string", child_types[ 3]) 1756 self.assertEquals("xsd:boolean", child_types[ 4]) 1757 self.assertEquals(None, child_types[ 5]) 1758 self.assertEquals("xsd:string", child_types[ 6]) 1759 self.assertEquals("xsd:double", child_types[ 7]) 1760 self.assertEquals("xsd:float", child_types[ 8]) 1761 self.assertEquals("xsd:string", child_types[ 9]) 1762 self.assertEquals("xsd:string", child_types[10]) 1763 self.assertEquals("xsd:double", child_types[11]) 1764 self.assertEquals("xsd:integer", child_types[12]) 1765 self.assertEquals(None, child_types[13]) 1766 1767 self.assertEquals(None, root.n.get(XML_SCHEMA_NIL_ATTR)) 1768 1769 for c in root.iterchildren(): 1770 self.assertNotEquals(None, c.get(objectify.PYTYPE_ATTRIBUTE)) 1771 # these have no equivalent in xsi:type 1772 if (c.get(objectify.PYTYPE_ATTRIBUTE) not in [TREE_PYTYPE, 1773 "NoneType"]): 1774 self.assertNotEquals( 1775 None, c.get(XML_SCHEMA_INSTANCE_TYPE_ATTR))
1776
1777 - def test_xsitype_deannotate(self):
1778 XML = self.XML 1779 root = XML(_bytes('''\ 1780 <a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 1781 xmlns:py="http://codespeak.net/lxml/objectify/pytype" 1782 xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 1783 <b>5</b> 1784 <b>test</b> 1785 <c>1.1</c> 1786 <c>\uF8D2</c> 1787 <x>true</x> 1788 <n xsi:nil="true" /> 1789 <n></n> 1790 <b xsi:type="xsd:double">5</b> 1791 <b xsi:type="xsd:float">5</b> 1792 <s xsi:type="xsd:string">23</s> 1793 <s py:pytype="str">42</s> 1794 <f py:pytype="float">300</f> 1795 <l py:pytype="long">2</l> 1796 <t py:pytype="TREE"></t> 1797 </a> 1798 ''')) 1799 objectify.annotate(root) 1800 objectify.deannotate(root, pytype=False) 1801 1802 child_types = [ c.get(objectify.PYTYPE_ATTRIBUTE) 1803 for c in root.iterchildren() ] 1804 self.assertEquals("int", child_types[ 0]) 1805 self.assertEquals("str", child_types[ 1]) 1806 self.assertEquals("float", child_types[ 2]) 1807 self.assertEquals("str", child_types[ 3]) 1808 self.assertEquals("bool", child_types[ 4]) 1809 self.assertEquals("NoneType", child_types[ 5]) 1810 self.assertEquals(None, child_types[ 6]) 1811 self.assertEquals("float", child_types[ 7]) 1812 self.assertEquals("float", child_types[ 8]) 1813 self.assertEquals("str", child_types[ 9]) 1814 self.assertEquals("int", child_types[10]) 1815 self.assertEquals("int", child_types[11]) 1816 self.assertEquals("int", child_types[12]) 1817 self.assertEquals(None, child_types[13]) 1818 1819 self.assertEquals("true", root.n.get(XML_SCHEMA_NIL_ATTR)) 1820 1821 for c in root.getiterator(): 1822 self.assertEquals(None, c.get(XML_SCHEMA_INSTANCE_TYPE_ATTR))
1823
1824 - def test_pytype_deannotate(self):
1825 XML = self.XML 1826 root = XML(_bytes('''\ 1827 <a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 1828 xmlns:py="http://codespeak.net/lxml/objectify/pytype" 1829 xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 1830 <b xsi:type="xsd:int">5</b> 1831 <b xsi:type="xsd:string">test</b> 1832 <c xsi:type="xsd:float">1.1</c> 1833 <c xsi:type="xsd:string">\uF8D2</c> 1834 <x xsi:type="xsd:boolean">true</x> 1835 <n xsi:nil="true" /> 1836 <n></n> 1837 <b xsi:type="xsd:double">5</b> 1838 <b xsi:type="xsd:float">5</b> 1839 <s xsi:type="xsd:string">23</s> 1840 <s xsi:type="xsd:string">42</s> 1841 <f xsi:type="xsd:float">300</f> 1842 <l xsi:type="xsd:long">2</l> 1843 <t py:pytype="TREE"></t> 1844 </a> 1845 ''')) 1846 objectify.annotate(root) 1847 objectify.deannotate(root, xsi=False) 1848 1849 child_types = [ c.get(XML_SCHEMA_INSTANCE_TYPE_ATTR) 1850 for c in root.iterchildren() ] 1851 self.assertEquals("xsd:int", child_types[ 0]) 1852 self.assertEquals("xsd:string", child_types[ 1]) 1853 self.assertEquals("xsd:float", child_types[ 2]) 1854 self.assertEquals("xsd:string", child_types[ 3]) 1855 self.assertEquals("xsd:boolean", child_types[ 4]) 1856 self.assertEquals(None, child_types[ 5]) 1857 self.assertEquals(None, child_types[ 6]) 1858 self.assertEquals("xsd:double", child_types[ 7]) 1859 self.assertEquals("xsd:float", child_types[ 8]) 1860 self.assertEquals("xsd:string", child_types[ 9]) 1861 self.assertEquals("xsd:string", child_types[10]) 1862 self.assertEquals("xsd:float", child_types[11]) 1863 self.assertEquals("xsd:long", child_types[12]) 1864 self.assertEquals(None, child_types[13]) 1865 1866 self.assertEquals("true", root.n.get(XML_SCHEMA_NIL_ATTR)) 1867 1868 for c in root.getiterator(): 1869 self.assertEquals(None, c.get(objectify.PYTYPE_ATTRIBUTE))
1870
1871 - def test_change_pytype_attribute(self):
1872 XML = self.XML 1873 1874 xml = _bytes('''\ 1875 <a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 1876 <b>5</b> 1877 <b>test</b> 1878 <c>1.1</c> 1879 <c>\uF8D2</c> 1880 <x>true</x> 1881 <n xsi:nil="true" /> 1882 <n></n> 1883 <b xsi:type="double">5</b> 1884 </a> 1885 ''') 1886 1887 pytype_ns, pytype_name = objectify.PYTYPE_ATTRIBUTE[1:].split('}') 1888 objectify.set_pytype_attribute_tag("{TEST}test") 1889 1890 root = XML(xml) 1891 objectify.annotate(root) 1892 1893 attribs = root.xpath("//@py:%s" % pytype_name, 1894 namespaces={"py" : pytype_ns}) 1895 self.assertEquals(0, len(attribs)) 1896 attribs = root.xpath("//@py:test", 1897 namespaces={"py" : "TEST"}) 1898 self.assertEquals(7, len(attribs)) 1899 1900 objectify.set_pytype_attribute_tag() 1901 pytype_ns, pytype_name = objectify.PYTYPE_ATTRIBUTE[1:].split('}') 1902 1903 self.assertNotEqual("test", pytype_ns.lower()) 1904 self.assertNotEqual("test", pytype_name.lower()) 1905 1906 root = XML(xml) 1907 attribs = root.xpath("//@py:%s" % pytype_name, 1908 namespaces={"py" : pytype_ns}) 1909 self.assertEquals(0, len(attribs)) 1910 1911 objectify.annotate(root) 1912 attribs = root.xpath("//@py:%s" % pytype_name, 1913 namespaces={"py" : pytype_ns}) 1914 self.assertEquals(7, len(attribs))
1915
1916 - def test_registered_types(self):
1917 orig_types = objectify.getRegisteredTypes() 1918 orig_types[0].unregister() 1919 self.assertEquals(orig_types[1:], objectify.getRegisteredTypes()) 1920 1921 class NewType(objectify.ObjectifiedDataElement): 1922 pass
1923 1924 def checkMyType(s): 1925 return True 1926 1927 pytype = objectify.PyType("mytype", checkMyType, NewType) 1928 self.assert_(pytype not in objectify.getRegisteredTypes()) 1929 pytype.register() 1930 self.assert_(pytype in objectify.getRegisteredTypes()) 1931 pytype.unregister() 1932 self.assert_(pytype not in objectify.getRegisteredTypes()) 1933 1934 pytype.register(before = [objectify.getRegisteredTypes()[0].name]) 1935 self.assertEquals(pytype, objectify.getRegisteredTypes()[0]) 1936 pytype.unregister() 1937 1938 pytype.register(after = [objectify.getRegisteredTypes()[0].name]) 1939 self.assertNotEqual(pytype, objectify.getRegisteredTypes()[0]) 1940 pytype.unregister() 1941 1942 self.assertRaises(ValueError, pytype.register, 1943 before = [objectify.getRegisteredTypes()[0].name], 1944 after = [objectify.getRegisteredTypes()[1].name]) 1945
1946 - def test_registered_type_stringify(self):
1947 from datetime import datetime 1948 def parse_date(value): 1949 if len(value) != 14: 1950 raise ValueError(value) 1951 Y = int(value[0:4]) 1952 M = int(value[4:6]) 1953 D = int(value[6:8]) 1954 h = int(value[8:10]) 1955 m = int(value[10:12]) 1956 s = int(value[12:14]) 1957 return datetime(Y, M, D, h, m, s)
1958 1959 def stringify_date(date): 1960 return date.strftime("%Y%m%d%H%M%S") 1961 1962 class DatetimeElement(objectify.ObjectifiedDataElement): 1963 def pyval(self): 1964 return parse_date(self.text) 1965 pyval = property(pyval) 1966 1967 datetime_type = objectify.PyType( 1968 "datetime", parse_date, DatetimeElement, stringify_date) 1969 datetime_type.xmlSchemaTypes = "dateTime" 1970 datetime_type.register() 1971 1972 NAMESPACE = "http://foo.net/xmlns" 1973 NAMESPACE_MAP = {'ns': NAMESPACE} 1974 1975 r = objectify.Element("{%s}root" % NAMESPACE, nsmap=NAMESPACE_MAP) 1976 time = datetime.now() 1977 r.date = time 1978 1979 self.assert_(isinstance(r.date, DatetimeElement)) 1980 self.assert_(isinstance(r.date.pyval, datetime)) 1981 1982 self.assertEquals(r.date.pyval, parse_date(stringify_date(time))) 1983 self.assertEquals(r.date.text, stringify_date(time)) 1984 1985 r.date = objectify.E.date(time) 1986 1987 self.assert_(isinstance(r.date, DatetimeElement)) 1988 self.assert_(isinstance(r.date.pyval, datetime)) 1989 1990 self.assertEquals(r.date.pyval, parse_date(stringify_date(time))) 1991 self.assertEquals(r.date.text, stringify_date(time)) 1992 1993 date = objectify.DataElement(time) 1994 1995 self.assert_(isinstance(date, DatetimeElement)) 1996 self.assert_(isinstance(date.pyval, datetime)) 1997 1998 self.assertEquals(date.pyval, parse_date(stringify_date(time))) 1999 self.assertEquals(date.text, stringify_date(time)) 2000
2001 - def test_object_path(self):
2002 root = self.XML(xml_str) 2003 path = objectify.ObjectPath( "root.c1.c2" ) 2004 self.assertEquals(root.c1.c2.text, path.find(root).text) 2005 self.assertEquals(root.c1.c2.text, path(root).text)
2006
2007 - def test_object_path_list(self):
2008 root = self.XML(xml_str) 2009 path = objectify.ObjectPath( ['root', 'c1', 'c2'] ) 2010 self.assertEquals(root.c1.c2.text, path.find(root).text) 2011 self.assertEquals(root.c1.c2.text, path(root).text)
2012
2013 - def test_object_path_fail(self):
2014 root = self.XML(xml_str) 2015 path = objectify.ObjectPath( "root.c1.c99" ) 2016 self.assertRaises(AttributeError, path, root)
2017
2018 - def test_object_path_default_absolute(self):
2019 root = self.XML(xml_str) 2020 path = objectify.ObjectPath( "root.c1.c99" ) 2021 self.assertEquals(None, path(root, None)) 2022 path = objectify.ObjectPath( "root.c99.c2" ) 2023 self.assertEquals(None, path(root, None)) 2024 path = objectify.ObjectPath( "notroot.c99.c2" ) 2025 self.assertEquals(None, path(root, None))
2026
2027 - def test_object_path_default_relative(self):
2028 root = self.XML(xml_str) 2029 path = objectify.ObjectPath( ".c1.c99" ) 2030 self.assertEquals(None, path(root, None)) 2031 path = objectify.ObjectPath( ".c99.c2" ) 2032 self.assertEquals(None, path(root, None))
2033
2034 - def test_object_path_syntax(self):
2035 root = self.XML(xml_str) 2036 path = objectify.ObjectPath("root . {objectified}c1. c2") 2037 self.assertEquals(root.c1.c2.text, path(root).text) 2038 2039 path = objectify.ObjectPath(" root.{objectified} c1.c2 [ 0 ] ") 2040 self.assertEquals(root.c1.c2.text, path(root).text)
2041
2042 - def test_object_path_fail_parse_empty(self):
2043 self.assertRaises(ValueError, objectify.ObjectPath, "")
2044
2045 - def test_object_path_fail_parse_empty_list(self):
2046 self.assertRaises(ValueError, objectify.ObjectPath, [])
2047
2048 - def test_object_path_hasattr(self):
2049 root = self.XML(xml_str) 2050 path = objectify.ObjectPath( "root" ) 2051 self.assert_(path.hasattr(root)) 2052 path = objectify.ObjectPath( "root.c1" ) 2053 self.assert_(path.hasattr(root)) 2054 path = objectify.ObjectPath( "root.c1.c2" ) 2055 self.assert_(path.hasattr(root)) 2056 path = objectify.ObjectPath( "root.c1.{otherNS}c2" ) 2057 self.assert_(path.hasattr(root)) 2058 path = objectify.ObjectPath( "root.c1.c2[1]" ) 2059 self.assert_(path.hasattr(root)) 2060 path = objectify.ObjectPath( "root.c1.c2[2]" ) 2061 self.assert_(path.hasattr(root)) 2062 path = objectify.ObjectPath( "root.c1.c2[3]" ) 2063 self.assertFalse(path.hasattr(root)) 2064 path = objectify.ObjectPath( "root.c1[1].c2" ) 2065 self.assertFalse(path.hasattr(root))
2066
2067 - def test_object_path_dot(self):
2068 root = self.XML(xml_str) 2069 path = objectify.ObjectPath( "." ) 2070 self.assertEquals(root.c1.c2.text, path(root).c1.c2.text)
2071
2072 - def test_object_path_dot_list(self):
2073 root = self.XML(xml_str) 2074 path = objectify.ObjectPath( [''] ) 2075 self.assertEquals(root.c1.c2.text, path(root).c1.c2.text)
2076
2077 - def test_object_path_dot_root(self):
2078 root = self.XML(xml_str) 2079 path = objectify.ObjectPath( ".c1.c2" ) 2080 self.assertEquals(root.c1.c2.text, path(root).text)
2081
2082 - def test_object_path_dot_root_list(self):
2083 root = self.XML(xml_str) 2084 path = objectify.ObjectPath( ['', 'c1', 'c2'] ) 2085 self.assertEquals(root.c1.c2.text, path(root).text)
2086
2087 - def test_object_path_index(self):
2088 root = self.XML(xml_str) 2089 path = objectify.ObjectPath( "root.c1[0].c2[0]" ) 2090 self.assertEquals(root.c1.c2.text, path(root).text) 2091 2092 path = objectify.ObjectPath( "root.c1[0].c2" ) 2093 self.assertEquals(root.c1.c2.text, path(root).text) 2094 2095 path = objectify.ObjectPath( "root.c1[0].c2[1]" ) 2096 self.assertEquals(root.c1.c2[1].text, path(root).text) 2097 2098 path = objectify.ObjectPath( "root.c1.c2[2]" ) 2099 self.assertEquals(root.c1.c2[2].text, path(root).text) 2100 2101 path = objectify.ObjectPath( "root.c1.c2[-1]" ) 2102 self.assertEquals(root.c1.c2[-1].text, path(root).text) 2103 2104 path = objectify.ObjectPath( "root.c1.c2[-3]" ) 2105 self.assertEquals(root.c1.c2[-3].text, path(root).text)
2106
2107 - def test_object_path_index_list(self):
2108 root = self.XML(xml_str) 2109 path = objectify.ObjectPath( ['root', 'c1[0]', 'c2[0]'] ) 2110 self.assertEquals(root.c1.c2.text, path(root).text) 2111 2112 path = objectify.ObjectPath( ['root', 'c1[0]', 'c2[2]'] ) 2113 self.assertEquals(root.c1.c2[2].text, path(root).text) 2114 2115 path = objectify.ObjectPath( ['root', 'c1', 'c2[2]'] ) 2116 self.assertEquals(root.c1.c2[2].text, path(root).text) 2117 2118 path = objectify.ObjectPath( ['root', 'c1', 'c2[-1]'] ) 2119 self.assertEquals(root.c1.c2[-1].text, path(root).text) 2120 2121 path = objectify.ObjectPath( ['root', 'c1', 'c2[-3]'] ) 2122 self.assertEquals(root.c1.c2[-3].text, path(root).text)
2123
2124 - def test_object_path_index_fail_parse(self):
2125 self.assertRaises(ValueError, objectify.ObjectPath, 2126 "root.c1[0].c2[-1-2]") 2127 self.assertRaises(ValueError, objectify.ObjectPath, 2128 ['root', 'c1[0]', 'c2[-1-2]']) 2129 2130 self.assertRaises(ValueError, objectify.ObjectPath, 2131 "root[2].c1.c2") 2132 self.assertRaises(ValueError, objectify.ObjectPath, 2133 ['root[2]', 'c1', 'c2']) 2134 2135 self.assertRaises(ValueError, objectify.ObjectPath, 2136 []) 2137 self.assertRaises(ValueError, objectify.ObjectPath, 2138 ['', '', ''])
2139
2140 - def test_object_path_index_fail_lookup(self):
2141 root = self.XML(xml_str) 2142 path = objectify.ObjectPath("root.c1[9999].c2") 2143 self.assertRaises(AttributeError, path, root) 2144 2145 path = objectify.ObjectPath("root.c1[0].c2[9999]") 2146 self.assertRaises(AttributeError, path, root) 2147 2148 path = objectify.ObjectPath(".c1[9999].c2[0]") 2149 self.assertRaises(AttributeError, path, root) 2150 2151 path = objectify.ObjectPath("root.c1[-2].c2") 2152 self.assertRaises(AttributeError, path, root) 2153 2154 path = objectify.ObjectPath("root.c1[0].c2[-4]") 2155 self.assertRaises(AttributeError, path, root)
2156
2157 - def test_object_path_ns(self):
2158 root = self.XML(xml_str) 2159 path = objectify.ObjectPath( "{objectified}root.c1.c2" ) 2160 self.assertEquals(root.c1.c2.text, path.find(root).text) 2161 path = objectify.ObjectPath( "{objectified}root.{objectified}c1.c2" ) 2162 self.assertEquals(root.c1.c2.text, path.find(root).text) 2163 path = objectify.ObjectPath( "root.{objectified}c1.{objectified}c2" ) 2164 self.assertEquals(root.c1.c2.text, path.find(root).text) 2165 path = objectify.ObjectPath( "root.c1.{objectified}c2" ) 2166 self.assertEquals(root.c1.c2.text, path.find(root).text) 2167 path = objectify.ObjectPath( "root.c1.{otherNS}c2" ) 2168 self.assertEquals(getattr(root.c1, '{otherNS}c2').text, 2169 path.find(root).text)
2170
2171 - def test_object_path_ns_list(self):
2172 root = self.XML(xml_str) 2173 path = objectify.ObjectPath( ['{objectified}root', 'c1', 'c2'] ) 2174 self.assertEquals(root.c1.c2.text, path.find(root).text) 2175 path = objectify.ObjectPath( ['{objectified}root', '{objectified}c1', 'c2'] ) 2176 self.assertEquals(root.c1.c2.text, path.find(root).text) 2177 path = objectify.ObjectPath( ['root', '{objectified}c1', '{objectified}c2'] ) 2178 self.assertEquals(root.c1.c2.text, path.find(root).text) 2179 path = objectify.ObjectPath( ['root', '{objectified}c1', '{objectified}c2[2]'] ) 2180 self.assertEquals(root.c1.c2[2].text, path.find(root).text) 2181 path = objectify.ObjectPath( ['root', 'c1', '{objectified}c2'] ) 2182 self.assertEquals(root.c1.c2.text, path.find(root).text) 2183 path = objectify.ObjectPath( ['root', 'c1', '{objectified}c2[2]'] ) 2184 self.assertEquals(root.c1.c2[2].text, path.find(root).text) 2185 path = objectify.ObjectPath( ['root', 'c1', '{otherNS}c2'] ) 2186 self.assertEquals(getattr(root.c1, '{otherNS}c2').text, 2187 path.find(root).text)
2188
2189 - def test_object_path_set(self):
2190 root = self.XML(xml_str) 2191 path = objectify.ObjectPath( "root.c1.c2" ) 2192 self.assertEquals(root.c1.c2.text, path.find(root).text) 2193 self.assertEquals("1", root.c1.c2[1].text) 2194 2195 new_value = "my new value" 2196 path.setattr(root, new_value) 2197 2198 self.assertEquals(new_value, root.c1.c2.text) 2199 self.assertEquals(new_value, path(root).text) 2200 self.assertEquals("1", root.c1.c2[1].text)
2201
2202 - def test_object_path_set_element(self):
2203 root = self.XML(xml_str) 2204 path = objectify.ObjectPath( "root.c1.c2" ) 2205 self.assertEquals(root.c1.c2.text, path.find(root).text) 2206 self.assertEquals("1", root.c1.c2[1].text) 2207 2208 new_el = self.Element("{objectified}test") 2209 etree.SubElement(new_el, "{objectified}sub", myattr="ATTR").a = "TEST" 2210 path.setattr(root, new_el.sub) 2211 2212 self.assertEquals("ATTR", root.c1.c2.get("myattr")) 2213 self.assertEquals("TEST", root.c1.c2.a.text) 2214 self.assertEquals("TEST", path(root).a.text) 2215 self.assertEquals("1", root.c1.c2[1].text)
2216
2217 - def test_object_path_set_create(self):
2218 root = self.XML(xml_str) 2219 path = objectify.ObjectPath( "root.c1.c99" ) 2220 self.assertRaises(AttributeError, path.find, root) 2221 2222 new_value = "my new value" 2223 path.setattr(root, new_value) 2224 2225 self.assertEquals(1, len(root.c1.c99)) 2226 self.assertEquals(new_value, root.c1.c99.text) 2227 self.assertEquals(new_value, path(root).text)
2228
2229 - def test_object_path_set_create_element(self):
2230 root = self.XML(xml_str) 2231 path = objectify.ObjectPath( "root.c1.c99" ) 2232 self.assertRaises(AttributeError, path.find, root) 2233 2234 new_el = self.Element("{objectified}test") 2235 etree.SubElement(new_el, "{objectified}sub", myattr="ATTR").a = "TEST" 2236 path.setattr(root, new_el.sub) 2237 2238 self.assertEquals(1, len(root.c1.c99)) 2239 self.assertEquals("ATTR", root.c1.c99.get("myattr")) 2240 self.assertEquals("TEST", root.c1.c99.a.text) 2241 self.assertEquals("TEST", path(root).a.text)
2242
2243 - def test_object_path_set_create_list(self):
2244 root = self.XML(xml_str) 2245 path = objectify.ObjectPath( "root.c1.c99" ) 2246 self.assertRaises(AttributeError, path.find, root) 2247 2248 new_el = self.Element("{objectified}test") 2249 new_el.a = ["TEST1", "TEST2"] 2250 new_el.a[0].set("myattr", "ATTR1") 2251 new_el.a[1].set("myattr", "ATTR2") 2252 2253 path.setattr(root, list(new_el.a)) 2254 2255 self.assertEquals(2, len(root.c1.c99)) 2256 self.assertEquals("ATTR1", root.c1.c99[0].get("myattr")) 2257 self.assertEquals("TEST1", root.c1.c99[0].text) 2258 self.assertEquals("ATTR2", root.c1.c99[1].get("myattr")) 2259 self.assertEquals("TEST2", root.c1.c99[1].text) 2260 self.assertEquals("TEST1", path(root).text)
2261
2262 - def test_object_path_addattr(self):
2263 root = self.XML(xml_str) 2264 path = objectify.ObjectPath( "root.c1.c2" ) 2265 self.assertEquals(3, len(root.c1.c2)) 2266 path.addattr(root, "test") 2267 self.assertEquals(4, len(root.c1.c2)) 2268 self.assertEquals(["0", "1", "2", "test"], 2269 [el.text for el in root.c1.c2])
2270
2271 - def test_object_path_addattr_element(self):
2272 root = self.XML(xml_str) 2273 path = objectify.ObjectPath( "root.c1.c2" ) 2274 self.assertEquals(3, len(root.c1.c2)) 2275 2276 new_el = self.Element("{objectified}test") 2277 etree.SubElement(new_el, "{objectified}sub").a = "TEST" 2278 2279 path.addattr(root, new_el.sub) 2280 self.assertEquals(4, len(root.c1.c2)) 2281 self.assertEquals("TEST", root.c1.c2[3].a.text) 2282 self.assertEquals(["0", "1", "2"], 2283 [el.text for el in root.c1.c2[:3]])
2284
2285 - def test_object_path_addattr_create(self):
2286 root = self.XML(xml_str) 2287 path = objectify.ObjectPath( "root.c1.c99" ) 2288 self.assertRaises(AttributeError, path.find, root) 2289 2290 new_value = "my new value" 2291 path.addattr(root, new_value) 2292 2293 self.assertEquals(1, len(root.c1.c99)) 2294 self.assertEquals(new_value, root.c1.c99.text) 2295 self.assertEquals(new_value, path(root).text)
2296
2297 - def test_object_path_addattr_create_element(self):
2298 root = self.XML(xml_str) 2299 path = objectify.ObjectPath( "root.c1.c99" ) 2300 self.assertRaises(AttributeError, path.find, root) 2301 2302 new_el = self.Element("{objectified}test") 2303 etree.SubElement(new_el, "{objectified}sub", myattr="ATTR").a = "TEST" 2304 2305 path.addattr(root, new_el.sub) 2306 self.assertEquals(1, len(root.c1.c99)) 2307 self.assertEquals("TEST", root.c1.c99.a.text) 2308 self.assertEquals("TEST", path(root).a.text) 2309 self.assertEquals("ATTR", root.c1.c99.get("myattr"))
2310
2311 - def test_object_path_addattr_create_list(self):
2312 root = self.XML(xml_str) 2313 path = objectify.ObjectPath( "root.c1.c99" ) 2314 self.assertRaises(AttributeError, path.find, root) 2315 2316 new_el = self.Element("{objectified}test") 2317 new_el.a = ["TEST1", "TEST2"] 2318 2319 self.assertEquals(2, len(new_el.a)) 2320 2321 path.addattr(root, list(new_el.a)) 2322 self.assertEquals(2, len(root.c1.c99)) 2323 self.assertEquals("TEST1", root.c1.c99.text) 2324 self.assertEquals("TEST2", path(root)[1].text)
2325
2326 - def test_descendant_paths(self):
2327 root = self.XML(xml_str) 2328 self.assertEquals( 2329 ['{objectified}root', '{objectified}root.c1', 2330 '{objectified}root.c1.c2', 2331 '{objectified}root.c1.c2[1]', '{objectified}root.c1.c2[2]', 2332 '{objectified}root.c1.{otherNS}c2', '{objectified}root.c1.{}c2'], 2333 root.descendantpaths())
2334
2335 - def test_descendant_paths_child(self):
2336 root = self.XML(xml_str) 2337 self.assertEquals( 2338 ['{objectified}c1', '{objectified}c1.c2', 2339 '{objectified}c1.c2[1]', '{objectified}c1.c2[2]', 2340 '{objectified}c1.{otherNS}c2', '{objectified}c1.{}c2'], 2341 root.c1.descendantpaths())
2342
2343 - def test_descendant_paths_prefix(self):
2344 root = self.XML(xml_str) 2345 self.assertEquals( 2346 ['root.{objectified}c1', 'root.{objectified}c1.c2', 2347 'root.{objectified}c1.c2[1]', 'root.{objectified}c1.c2[2]', 2348 'root.{objectified}c1.{otherNS}c2', 2349 'root.{objectified}c1.{}c2'], 2350 root.c1.descendantpaths('root'))
2351
2352 - def test_pickle(self):
2353 import pickle 2354 2355 root = self.XML(xml_str) 2356 out = BytesIO() 2357 pickle.dump(root, out) 2358 2359 new_root = pickle.loads(out.getvalue()) 2360 self.assertEquals( 2361 etree.tostring(new_root), 2362 etree.tostring(root))
2363
2364 - def test_pickle_elementtree(self):
2365 import pickle 2366 2367 tree = etree.ElementTree(self.XML(xml_str + "<?my pi?>")) 2368 out = BytesIO() 2369 pickle.dump(tree, out) 2370 2371 new_tree = pickle.loads(out.getvalue()) 2372 self.assert_(isinstance(new_tree, etree._ElementTree)) 2373 self.assertEquals( 2374 etree.tostring(new_tree), 2375 etree.tostring(tree))
2376
2377 - def test_pickle_intelement(self):
2378 self._test_pickle('<x>42</x>') 2379 self._test_pickle(objectify.DataElement(42))
2380
2381 - def test_pickle_floattelement(self):
2382 self._test_pickle('<x>42.0</x>') 2383 self._test_pickle(objectify.DataElement(42.0))
2384
2385 - def test_pickle_strelement(self):
2386 self._test_pickle('<x>Pickle me!</x>') 2387 self._test_pickle(objectify.DataElement('Pickle me!'))
2388
2389 - def test_pickle_boolelement(self):
2390 self._test_pickle('<x>true</x>') 2391 self._test_pickle('<x>false</x>') 2392 self._test_pickle(objectify.DataElement(True)) 2393 self._test_pickle(objectify.DataElement(False))
2394
2395 - def test_pickle_noneelement(self):
2396 self._test_pickle(''' 2397 <x xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>''') 2398 self._test_pickle(objectify.DataElement(None))
2399
2400 - def _test_pickle(self, stringOrElt):
2401 import pickle 2402 if isinstance(stringOrElt, (etree._Element, etree._ElementTree)): 2403 elt = stringOrElt 2404 else: 2405 elt = self.XML(stringOrElt) 2406 out = BytesIO() 2407 pickle.dump(elt, out) 2408 2409 new_elt = pickle.loads(out.getvalue()) 2410 self.assertEquals( 2411 etree.tostring(new_elt), 2412 etree.tostring(elt))
2413 2414 # E-Factory tests, need to use sub-elements as root element is always 2415 # type-looked-up as ObjectifiedElement (no annotations)
2416 - def test_efactory_int(self):
2417 E = objectify.E 2418 root = E.root(E.val(23)) 2419 self.assert_(isinstance(root.val, objectify.IntElement))
2420
2421 - def test_efactory_float(self):
2422 E = objectify.E 2423 root = E.root(E.val(233.23)) 2424 self.assert_(isinstance(root.val, objectify.FloatElement))
2425
2426 - def test_efactory_str(self):
2427 E = objectify.E 2428 root = E.root(E.val("what?")) 2429 self.assert_(isinstance(root.val, objectify.StringElement))
2430
2431 - def test_efactory_unicode(self):
2432 E = objectify.E 2433 root = E.root(E.val(_str("blöödy häll", encoding="ISO-8859-1"))) 2434 self.assert_(isinstance(root.val, objectify.StringElement))
2435
2436 - def test_efactory_bool(self):
2437 E = objectify.E 2438 root = E.root(E.val(True)) 2439 self.assert_(isinstance(root.val, objectify.BoolElement))
2440
2441 - def test_efactory_none(self):
2442 E = objectify.E 2443 root = E.root(E.val(None)) 2444 self.assert_(isinstance(root.val, objectify.NoneElement))
2445
2446 - def test_efactory_value_concatenation(self):
2447 E = objectify.E 2448 root = E.root(E.val(1, "foo", 2.0, "bar ", True, None)) 2449 self.assert_(isinstance(root.val, objectify.StringElement))
2450
2451 - def test_efactory_attrib(self):
2452 E = objectify.E 2453 root = E.root(foo="bar") 2454 self.assertEquals(root.get("foo"), "bar")
2455
2456 - def test_efactory_nested(self):
2457 E = objectify.E 2458 DataElement = objectify.DataElement 2459 root = E.root("text", E.sub(E.subsub()), "tail", DataElement(1), 2460 DataElement(2.0)) 2461 self.assert_(isinstance(root, objectify.ObjectifiedElement)) 2462 self.assertEquals(root.text, "text") 2463 self.assert_(isinstance(root.sub, objectify.ObjectifiedElement)) 2464 self.assertEquals(root.sub.tail, "tail") 2465 self.assert_(isinstance(root.sub.subsub, objectify.StringElement)) 2466 self.assertEquals(len(root.value), 2) 2467 self.assert_(isinstance(root.value[0], objectify.IntElement)) 2468 self.assert_(isinstance(root.value[1], objectify.FloatElement))
2469
2470 - def test_efactory_subtype(self):
2471 class Attribute(objectify.ObjectifiedDataElement): 2472 def __init__(self): 2473 objectify.ObjectifiedDataElement.__init__(self) 2474 self.set("datatype", "TYPE") 2475 self.set("range", "0.,1.")
2476 2477 attr = Attribute() 2478 self.assertEquals(attr.text, None) 2479 self.assertEquals(attr.get("datatype"), "TYPE") 2480 self.assertEquals(attr.get("range"), "0.,1.") 2481
2482 - def test_XML_base_url_docinfo(self):
2483 root = objectify.XML(_bytes("<root/>"), base_url="http://no/such/url") 2484 docinfo = root.getroottree().docinfo 2485 self.assertEquals(docinfo.URL, "http://no/such/url")
2486
2487 - def test_XML_set_base_url_docinfo(self):
2488 root = objectify.XML(_bytes("<root/>"), base_url="http://no/such/url") 2489 docinfo = root.getroottree().docinfo 2490 self.assertEquals(docinfo.URL, "http://no/such/url") 2491 docinfo.URL = "https://secret/url" 2492 self.assertEquals(docinfo.URL, "https://secret/url")
2493
2494 - def test_parse_stringio_base_url(self):
2495 tree = objectify.parse(BytesIO("<root/>"), base_url="http://no/such/url") 2496 docinfo = tree.docinfo 2497 self.assertEquals(docinfo.URL, "http://no/such/url")
2498
2499 - def test_parse_base_url_docinfo(self):
2500 tree = objectify.parse(fileInTestDir('include/test_xinclude.xml'), 2501 base_url="http://no/such/url") 2502 docinfo = tree.docinfo 2503 self.assertEquals(docinfo.URL, "http://no/such/url")
2504
2505 - def test_xml_base(self):
2506 root = objectify.XML(_bytes("<root/>"), base_url="http://no/such/url") 2507 self.assertEquals(root.base, "http://no/such/url") 2508 self.assertEquals( 2509 root.get('{http://www.w3.org/XML/1998/namespace}base'), None) 2510 root.base = "https://secret/url" 2511 self.assertEquals(root.base, "https://secret/url") 2512 self.assertEquals( 2513 root.get('{http://www.w3.org/XML/1998/namespace}base'), 2514 "https://secret/url")
2515
2516 - def test_xml_base_attribute(self):
2517 root = objectify.XML(_bytes("<root/>"), base_url="http://no/such/url") 2518 self.assertEquals(root.base, "http://no/such/url") 2519 self.assertEquals( 2520 root.get('{http://www.w3.org/XML/1998/namespace}base'), None) 2521 root.set('{http://www.w3.org/XML/1998/namespace}base', 2522 "https://secret/url") 2523 self.assertEquals(root.base, "https://secret/url") 2524 self.assertEquals( 2525 root.get('{http://www.w3.org/XML/1998/namespace}base'), 2526 "https://secret/url")
2527
2528 - def test_standard_lookup(self):
2529 XML = self.XML 2530 2531 xml = _bytes('''\ 2532 <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 2533 <i>5</i> 2534 <i>-5</i> 2535 <l>4294967296</l> 2536 <l>-4294967296</l> 2537 <f>1.1</f> 2538 <b>true</b> 2539 <b>false</b> 2540 <s>Strange things happen, where strings collide</s> 2541 <s>True</s> 2542 <s>False</s> 2543 <s>t</s> 2544 <s>f</s> 2545 <s></s> 2546 <s>None</s> 2547 <n xsi:nil="true" /> 2548 </root> 2549 ''') 2550 root = XML(xml) 2551 2552 for i in root.i: 2553 self.assert_(isinstance(i, objectify.IntElement)) 2554 for l in root.l: 2555 self.assert_(isinstance(l, objectify.IntElement)) 2556 for f in root.f: 2557 self.assert_(isinstance(f, objectify.FloatElement)) 2558 for b in root.b: 2559 self.assert_(isinstance(b, objectify.BoolElement)) 2560 self.assertEquals(True, root.b[0]) 2561 self.assertEquals(False, root.b[1]) 2562 for s in root.s: 2563 self.assert_(isinstance(s, objectify.StringElement)) 2564 self.assert_(isinstance(root.n, objectify.NoneElement)) 2565 self.assertEquals(None, root.n)
2566
2567 -def test_suite():
2568 suite = unittest.TestSuite() 2569 suite.addTests([unittest.makeSuite(ObjectifyTestCase)]) 2570 suite.addTests(doctest.DocTestSuite(objectify)) 2571 if sys.version_info >= (2,4): 2572 suite.addTests( 2573 [make_doctest('../../../doc/objectify.txt')]) 2574 return suite
2575 2576 if __name__ == '__main__': 2577 print('to test use test.py %s' % __file__) 2578