| Home | Trees | Indices | Help |
|
|---|
|
|
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>3</c2>
67 </obj:c1>
68 </obj:root>'''
69
71 """Test cases for lxml.objectify
72 """
73 etree = etree
74
77
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
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
110
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
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
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 # keyword arguments override attrib entries
221 value = objectify.DataElement(23, _pytype="str", _xsi="foobar",
222 attrib={"gnu": "muh", "cat": "meeow",
223 "dog": "wuff"},
224 bird="tchilp", dog="grrr")
225 self.assertEquals(value.get("gnu"), "muh")
226 self.assertEquals(value.get("cat"), "meeow")
227 self.assertEquals(value.get("dog"), "grrr")
228 self.assertEquals(value.get("bird"), "tchilp")
229
231 # Check that DataElement preserves all attributes ObjectifiedDataElement
232 # arguments
233 arg = objectify.DataElement(23, _pytype="str", _xsi="foobar",
234 attrib={"gnu": "muh", "cat": "meeow",
235 "dog": "wuff"},
236 bird="tchilp", dog="grrr")
237 value = objectify.DataElement(arg)
238 self.assert_(isinstance(value, objectify.StringElement))
239 for attr in arg.attrib:
240 self.assertEquals(value.get(attr), arg.get(attr))
241
243 # Check that _pytype arg overrides original py:pytype of
244 # ObjectifiedDataElement
245 arg = objectify.DataElement(23, _pytype="str", _xsi="foobar",
246 attrib={"gnu": "muh", "cat": "meeow",
247 "dog": "wuff"},
248 bird="tchilp", dog="grrr")
249 value = objectify.DataElement(arg, _pytype="NoneType")
250 self.assert_(isinstance(value, objectify.NoneElement))
251 self.assertEquals(value.get(XML_SCHEMA_NIL_ATTR), "true")
252 self.assertEquals(value.text, None)
253 self.assertEquals(value.pyval, None)
254 for attr in arg.attrib:
255 #if not attr == objectify.PYTYPE_ATTRIBUTE:
256 self.assertEquals(value.get(attr), arg.get(attr))
257
259 # Check that _pytype arg overrides original py:pytype of
260 # ObjectifiedDataElement
261 arg = objectify.DataElement(23, _pytype="str", _xsi="foobar",
262 attrib={"gnu": "muh", "cat": "meeow",
263 "dog": "wuff"},
264 bird="tchilp", dog="grrr")
265 value = objectify.DataElement(arg, _pytype="int")
266 self.assert_(isinstance(value, objectify.IntElement))
267 self.assertEquals(value.get(objectify.PYTYPE_ATTRIBUTE), "int")
268 for attr in arg.attrib:
269 if not attr == objectify.PYTYPE_ATTRIBUTE:
270 self.assertEquals(value.get(attr), arg.get(attr))
271
273 # Check that _xsi arg overrides original xsi:type of given
274 # ObjectifiedDataElement
275 arg = objectify.DataElement(23, _pytype="str", _xsi="foobar",
276 attrib={"gnu": "muh", "cat": "meeow",
277 "dog": "wuff"},
278 bird="tchilp", dog="grrr")
279 value = objectify.DataElement(arg, _xsi="xsd:int")
280 self.assert_(isinstance(value, objectify.IntElement))
281 self.assertEquals(value.get(XML_SCHEMA_INSTANCE_TYPE_ATTR), "xsd:int")
282 self.assertEquals(value.get(objectify.PYTYPE_ATTRIBUTE), "int")
283 for attr in arg.attrib:
284 if not attr in [objectify.PYTYPE_ATTRIBUTE,
285 XML_SCHEMA_INSTANCE_TYPE_ATTR]:
286 self.assertEquals(value.get(attr), arg.get(attr))
287
289 # Check that _pytype and _xsi args override original py:pytype and
290 # xsi:type attributes of given ObjectifiedDataElement
291 arg = objectify.DataElement(23, _pytype="str", _xsi="foobar",
292 attrib={"gnu": "muh", "cat": "meeow",
293 "dog": "wuff"},
294 bird="tchilp", dog="grrr")
295 value = objectify.DataElement(arg, _pytype="int", _xsi="xsd:int")
296 self.assert_(isinstance(value, objectify.IntElement))
297 self.assertEquals(value.get(objectify.PYTYPE_ATTRIBUTE), "int")
298 self.assertEquals(value.get(XML_SCHEMA_INSTANCE_TYPE_ATTR), "xsd:int")
299 for attr in arg.attrib:
300 if not attr in [objectify.PYTYPE_ATTRIBUTE,
301 XML_SCHEMA_INSTANCE_TYPE_ATTR]:
302 self.assertEquals(value.get(attr), arg.get(attr))
303
307
311
313 arg = objectify.DataElement(3.1415)
314 self.assertRaises(ValueError, objectify.DataElement, arg,
315 _pytype="int")
316
318 arg = objectify.DataElement(3.1415)
319 self.assertRaises(ValueError, objectify.DataElement, arg,
320 _xsi="xsd:int")
321
325
329
333
335 root = self.XML(xml_str)
336 self.assertEquals(1, root.countchildren())
337 self.assertEquals(5, root.c1.countchildren())
338
340 root = self.XML(xml_str)
341 self.assertEquals("0", getattr(root.c1, "{objectified}c2").text)
342 self.assertEquals("3", getattr(root.c1, "{otherNS}c2").text)
343
345 root = self.XML(xml_str)
346 self.assertRaises(AttributeError, getattr, root.c1, "NOT_THERE")
347 self.assertRaises(AttributeError, getattr, root.c1, "{unknownNS}c2")
348
350 root = self.XML(xml_str)
351 self.assertEquals(1, len(root.c1))
352 root.addattr("c1", "test")
353 self.assertEquals(2, len(root.c1))
354 self.assertEquals("test", root.c1[1].text)
355
357 root = self.XML(xml_str)
358 self.assertEquals(1, len(root.c1))
359
360 new_el = self.Element("test", myattr="5")
361 root.addattr("c1", new_el)
362 self.assertEquals(2, len(root.c1))
363 self.assertEquals(None, root.c1[0].get("myattr"))
364 self.assertEquals("5", root.c1[1].get("myattr"))
365
367 root = self.XML(xml_str)
368 self.assertEquals(1, len(root.c1))
369
370 new_el = self.Element("test")
371 self.etree.SubElement(new_el, "a", myattr="A")
372 self.etree.SubElement(new_el, "a", myattr="B")
373
374 root.addattr("c1", list(new_el.a))
375 self.assertEquals(3, len(root.c1))
376 self.assertEquals(None, root.c1[0].get("myattr"))
377 self.assertEquals("A", root.c1[1].get("myattr"))
378 self.assertEquals("B", root.c1[2].get("myattr"))
379
381 root = self.XML(xml_str)
382 self.assertEquals(3, len(root.c1.c2))
383 root.c1.addattr("c2", 3)
384 self.assertEquals(4, len(root.c1.c2))
385 self.assertEquals("3", root.c1.c2[3].text)
386
388 root = self.XML(xml_str)
389 self.assertEquals("0", root.c1.c2[0].text)
390 self.assertEquals("1", root.c1.c2[1].text)
391 self.assertEquals("2", root.c1.c2[2].text)
392 self.assertRaises(IndexError, operator.getitem, root.c1.c2, 3)
393
395 root = self.XML(xml_str)
396 self.assertEquals("0", root.c1.c2[0].text)
397 self.assertEquals("0", root.c1.c2[-3].text)
398 self.assertEquals("1", root.c1.c2[-2].text)
399 self.assertEquals("2", root.c1.c2[-1].text)
400 self.assertRaises(IndexError, operator.getitem, root.c1.c2, -4)
401
403 root = self.XML(xml_str)
404 self.assertEquals(1, len(root))
405 self.assertEquals(1, len(root.c1))
406 self.assertEquals(3, len(root.c1.c2))
407
409 root = self.XML(xml_str)
410 self.assertEquals([root],
411 list(iter(root)))
412 self.assertEquals([root.c1],
413 list(iter(root.c1)))
414 self.assertEquals([root.c1.c2[0], root.c1.c2[1], root.c1.c2[2]],
415 list(iter((root.c1.c2))))
416
418 root = self.XML(xml_str)
419 self.assert_(isinstance(root.c1.c2, objectify.ObjectifiedElement))
420 self.assertFalse(isinstance(getattr(root.c1, "{otherNS}c2"),
421 objectify.ObjectifiedElement))
422
424 root = self.XML(xml_str)
425 dir_c1 = dir(objectify.ObjectifiedElement) + ['c1']
426 dir_c1.sort()
427 dir_c2 = dir(objectify.ObjectifiedElement) + ['c2']
428 dir_c2.sort()
429
430 self.assertEquals(dir_c1, dir(root))
431 self.assertEquals(dir_c2, dir(root.c1))
432
434 root = self.XML(xml_str)
435 self.assertEquals({'c1' : root.c1}, vars(root))
436 self.assertEquals({'c2' : root.c1.c2}, vars(root.c1))
437
439 root = self.XML(xml_str)
440 self.assertRaises(TypeError, setattr, root.c1.c2, 'text', "test")
441 self.assertRaises(TypeError, setattr, root.c1.c2, 'pyval', "test")
442
443 # slicing
444
446 root = self.XML("<root><c>c1</c><c>c2</c></root>")
447 self.assertEquals(["c1", "c2"],
448 [ c.text for c in root.c[:] ])
449
451 root = self.XML("<root><c>c1</c><c>c2</c><c>c3</c><c>c4</c></root>")
452 test_list = ["c1", "c2", "c3", "c4"]
453
454 self.assertEquals(test_list,
455 [ c.text for c in root.c[:] ])
456 self.assertEquals(test_list[1:2],
457 [ c.text for c in root.c[1:2] ])
458 self.assertEquals(test_list[-3:-1],
459 [ c.text for c in root.c[-3:-1] ])
460 self.assertEquals(test_list[-3:3],
461 [ c.text for c in root.c[-3:3] ])
462 self.assertEquals(test_list[-3000:3],
463 [ c.text for c in root.c[-3000:3] ])
464 self.assertEquals(test_list[-3:3000],
465 [ c.text for c in root.c[-3:3000] ])
466
468 root = self.XML("<root><c>c1</c><c>c2</c><c>c3</c><c>c4</c></root>")
469 test_list = ["c1", "c2", "c3", "c4"]
470
471 self.assertEquals(test_list,
472 [ c.text for c in root.c[:] ])
473 self.assertEquals(test_list[2:1:-1],
474 [ c.text for c in root.c[2:1:-1] ])
475 self.assertEquals(test_list[-1:-3:-1],
476 [ c.text for c in root.c[-1:-3:-1] ])
477 self.assertEquals(test_list[2:-3:-1],
478 [ c.text for c in root.c[2:-3:-1] ])
479 self.assertEquals(test_list[2:-3000:-1],
480 [ c.text for c in root.c[2:-3000:-1] ])
481
482 # slice assignment
483
485 Element = self.Element
486 root = Element("root")
487 root.c = ["c1", "c2"]
488
489 c1 = root.c[0]
490 c2 = root.c[1]
491
492 self.assertEquals([c1,c2], list(root.c))
493 self.assertEquals(["c1", "c2"],
494 [ c.text for c in root.c ])
495
497 Element = self.Element
498 root = Element("root")
499 root.c = ["c1", "c2"]
500
501 c1 = root.c[0]
502 c2 = root.c[1]
503
504 self.assertEquals([c1,c2], list(root.c))
505 self.assertEquals(["c1", "c2"],
506 [ c.text for c in root.c ])
507
508 root2 = Element("root2")
509 root2.el = [ "test", "test" ]
510 self.assertEquals(["test", "test"],
511 [ el.text for el in root2.el ])
512
513 root.c = [ root2.el, root2.el ]
514 self.assertEquals(["test", "test"],
515 [ c.text for c in root.c ])
516 self.assertEquals(["test", "test"],
517 [ el.text for el in root2.el ])
518
519 root.c[:] = [ c1, c2, c2, c1 ]
520 self.assertEquals(["c1", "c2", "c2", "c1"],
521 [ c.text for c in root.c ])
522
524 Element = self.Element
525 root = Element("root")
526 l = ["c1", "c2", "c3", "c4"]
527 root.c = l
528
529 self.assertEquals(["c1", "c2", "c3", "c4"],
530 [ c.text for c in root.c ])
531 self.assertEquals(l,
532 [ c.text for c in root.c ])
533
534 new_slice = ["cA", "cB"]
535 l[1:2] = new_slice
536 root.c[1:2] = new_slice
537
538 self.assertEquals(["c1", "cA", "cB", "c3", "c4"], l)
539 self.assertEquals(["c1", "cA", "cB", "c3", "c4"],
540 [ c.text for c in root.c ])
541 self.assertEquals(l,
542 [ c.text for c in root.c ])
543
545 Element = self.Element
546 root = Element("root")
547 l = ["c1", "c2", "c3", "c4"]
548 root.c = l
549
550 self.assertEquals(["c1", "c2", "c3", "c4"],
551 [ c.text for c in root.c ])
552 self.assertEquals(l,
553 [ c.text for c in root.c ])
554
555 new_slice = ["cA", "cB"]
556 l[1:1] = new_slice
557 root.c[1:1] = new_slice
558
559 self.assertEquals(["c1", "cA", "cB", "c2", "c3", "c4"], l)
560 self.assertEquals(["c1", "cA", "cB", "c2", "c3", "c4"],
561 [ c.text for c in root.c ])
562 self.assertEquals(l,
563 [ c.text for c in root.c ])
564
566 Element = self.Element
567 root = Element("root")
568 l = ["c1", "c2", "c3", "c4"]
569 root.c = l
570
571 self.assertEquals(["c1", "c2", "c3", "c4"],
572 [ c.text for c in root.c ])
573 self.assertEquals(l,
574 [ c.text for c in root.c ])
575
576 new_slice = ["cA", "cB"]
577 l[-2:-2] = new_slice
578 root.c[-2:-2] = new_slice
579
580 self.assertEquals(["c1", "c2", "cA", "cB", "c3", "c4"], l)
581 self.assertEquals(["c1", "c2", "cA", "cB", "c3", "c4"],
582 [ c.text for c in root.c ])
583 self.assertEquals(l,
584 [ c.text for c in root.c ])
585
587 Element = self.Element
588 root = Element("root")
589
590 root.c = []
591 self.assertRaises(
592 AttributeError, getattr, root, 'c')
593
595 Element = self.Element
596 root = Element("root")
597 l = ["c1", "c2", "c3", "c4"]
598 root.c = l
599
600 self.assertEquals(["c1", "c2", "c3", "c4"],
601 [ c.text for c in root.c ])
602 self.assertEquals(l,
603 [ c.text for c in root.c ])
604
605 new_slice = ["cA", "cB", "cC"]
606 self.assertRaises(
607 ValueError, operator.setitem,
608 l, slice(1,2,-1), new_slice)
609 self.assertRaises(
610 ValueError, operator.setitem,
611 root.c, slice(1,2,-1), new_slice)
612
614 Element = self.Element
615 root = Element("root")
616 l = ["c1", "c2", "c3", "c4"]
617 root.c = l
618
619 self.assertEquals(["c1", "c2", "c3", "c4"],
620 [ c.text for c in root.c ])
621 self.assertEquals(l,
622 [ c.text for c in root.c ])
623
624 new_slice = ["cA", "cB"]
625 l[-1:1:-1] = new_slice
626 root.c[-1:1:-1] = new_slice
627
628 self.assertEquals(["c1", "c2", "cB", "cA"], l)
629 self.assertEquals(["c1", "c2", "cB", "cA"],
630 [ c.text for c in root.c ])
631 self.assertEquals(l,
632 [ c.text for c in root.c ])
633
635 Element = self.Element
636 root = Element("root")
637 l = ["c1", "c2", "c3", "c4"]
638 root.c = l
639
640 self.assertEquals(["c1", "c2", "c3", "c4"],
641 [ c.text for c in root.c ])
642 self.assertEquals(l,
643 [ c.text for c in root.c ])
644
645 new_slice = ["cA", "cB"]
646 l[-1:-4:-2] = new_slice
647 root.c[-1:-4:-2] = new_slice
648
649 self.assertEquals(["c1", "cB", "c3", "cA"], l)
650 self.assertEquals(["c1", "cB", "c3", "cA"],
651 [ c.text for c in root.c ])
652 self.assertEquals(l,
653 [ c.text for c in root.c ])
654
655 # other stuff
656
658 # make sure strings are not handled as sequences
659 Element = self.Element
660 root = Element("root")
661 root.c = "TEST"
662 self.assertEquals(["TEST"],
663 [ c.text for c in root.c ])
664
666 # make sure strings are set as children
667 Element = self.Element
668 root = Element("root")
669 root["c"] = "TEST"
670 self.assertEquals(["TEST"],
671 [ c.text for c in root.c ])
672
674 # make sure 'text' etc. are set as children
675 Element = self.Element
676 root = Element("root")
677
678 root["text"] = "TEST"
679 self.assertEquals(["TEST"],
680 [ c.text for c in root["text"] ])
681
682 root["tail"] = "TEST"
683 self.assertEquals(["TEST"],
684 [ c.text for c in root["tail"] ])
685
686 root["pyval"] = "TEST"
687 self.assertEquals(["TEST"],
688 [ c.text for c in root["pyval"] ])
689
690 root["tag"] = "TEST"
691 self.assertEquals(["TEST"],
692 [ c.text for c in root["tag"] ])
693
695 XML = self.XML
696 root = XML('<a><b><c/></b><b/><c><b/></c></a>')
697 self.assertEquals(1, len(root.findall("c")))
698 self.assertEquals(2, len(root.findall(".//c")))
699 self.assertEquals(3, len(root.findall(".//b")))
700 self.assert_(root.findall(".//b")[1] is root.getchildren()[1])
701
703 XML = self.XML
704 root = XML('<a xmlns:x="X" xmlns:y="Y"><x:b><c/></x:b><b/><c><x:b/><b/></c><b/></a>')
705 self.assertEquals(2, len(root.findall(".//{X}b")))
706 self.assertEquals(3, len(root.findall(".//b")))
707 self.assertEquals(2, len(root.findall("b")))
708
710 root = self.Element('root')
711 root.a = 5
712 root.b = 6
713 self.assert_(isinstance(root, objectify.ObjectifiedElement))
714 self.assert_(isinstance(root.a, objectify.IntElement))
715 self.assert_(isinstance(root.b, objectify.IntElement))
716
718 Element = self.Element
719 SubElement = self.etree.SubElement
720
721 nil_attr = XML_SCHEMA_NIL_ATTR
722 root = Element("{objectified}root")
723 SubElement(root, "{objectified}none")
724 SubElement(root, "{objectified}none", {nil_attr : "true"})
725 self.assertFalse(isinstance(root.none, objectify.NoneElement))
726 self.assertFalse(isinstance(root.none[0], objectify.NoneElement))
727 self.assert_(isinstance(root.none[1], objectify.NoneElement))
728 self.assertEquals(root.none[1], None)
729 self.assertFalse(root.none[1])
730
732 value = objectify.DataElement(None)
733 self.assert_(isinstance(value, objectify.NoneElement))
734 self.assertEquals(value, None)
735 self.assertEquals(value.get(XML_SCHEMA_NIL_ATTR), "true")
736
738 Element = self.Element
739 SubElement = self.etree.SubElement
740 root = Element("{objectified}root")
741 root.bool = True
742 self.assertEquals(root.bool, True)
743 self.assertEquals(root.bool + root.bool, True + True)
744 self.assertEquals(True + root.bool, True + root.bool)
745 self.assertEquals(root.bool * root.bool, True * True)
746 self.assertEquals(int(root.bool), int(True))
747 self.assertEquals(complex(root.bool), complex(True))
748 self.assert_(isinstance(root.bool, objectify.BoolElement))
749
750 root.bool = False
751 self.assertEquals(root.bool, False)
752 self.assertEquals(root.bool + root.bool, False + False)
753 self.assertEquals(False + root.bool, False + root.bool)
754 self.assertEquals(root.bool * root.bool, False * False)
755 self.assertEquals(int(root.bool), int(False))
756 self.assertEquals(complex(root.bool), complex(False))
757 self.assert_(isinstance(root.bool, objectify.BoolElement))
758
760 value = objectify.DataElement(True)
761 self.assert_(isinstance(value, objectify.BoolElement))
762 self.assertEquals(value, True)
763
764 value = objectify.DataElement(False)
765 self.assert_(isinstance(value, objectify.BoolElement))
766 self.assertEquals(value, False)
767
769 Element = self.Element
770 SubElement = self.etree.SubElement
771 root = Element("{objectified}root")
772 root.s = "test"
773 self.assert_(isinstance(root.s, objectify.StringElement))
774
776 Element = self.Element
777 SubElement = self.etree.SubElement
778 root = Element("{objectified}root")
779 root.s = "3"
780 self.assert_(isinstance(root.s, objectify.StringElement))
781
783 Element = self.Element
784 SubElement = self.etree.SubElement
785 root = Element("{objectified}root")
786 root.s = "3.72"
787 self.assert_(isinstance(root.s, objectify.StringElement))
788
790 Element = self.Element
791 SubElement = self.etree.SubElement
792 root = Element("{objectified}root")
793 root.s = "test"
794
795 self.assertEquals("test" * 5, root.s * 5)
796 self.assertEquals(5 * "test", 5 * root.s)
797
798 self.assertRaises(TypeError, operator.mul, root.s, "honk")
799 self.assertRaises(TypeError, operator.mul, "honk", root.s)
800
802 Element = self.Element
803 SubElement = self.etree.SubElement
804 root = Element("{objectified}root")
805 root.s = "test"
806
807 s = "toast"
808 self.assertEquals("test" + s, root.s + s)
809 self.assertEquals(s + "test", s + root.s)
810
812 s = "%d %f %s %r"
813 el = objectify.DataElement(s)
814 values = (1, 7.0, "abcd", None)
815 self.assertEquals(s % values, el % values)
816
817 s = "%d"
818 el = objectify.DataElement(s)
819 val = 5
820 self.assertEquals(s % val, el % val)
821
822 s = "%d %s"
823 el = objectify.DataElement(s)
824 val = 5
825 self.assertRaises(TypeError, el.__mod__, val)
826
827 s = ""
828 el = objectify.DataElement(s)
829 val = 5
830 self.assertRaises(TypeError, el.__mod__, val)
831
836
841
846
848 s = "%d %f %s %r"
849 el = objectify.DataElement(s)
850 values = (objectify.DataElement(1),
851 objectify.DataElement(7.0),
852 objectify.DataElement("abcd"),
853 objectify.DataElement(None))
854 self.assertEquals(s % values, el % values)
855
857 value = objectify.DataElement("test")
858 self.assert_(isinstance(value, objectify.StringElement))
859 self.assertEquals(value, "test")
860
862 value = objectify.DataElement("3")
863 self.assert_(isinstance(value, objectify.StringElement))
864 self.assertEquals(value, "3")
865
867 value = objectify.DataElement("3.20")
868 self.assert_(isinstance(value, objectify.StringElement))
869 self.assertEquals(value, "3.20")
870
872 Element = self.Element
873 SubElement = self.etree.SubElement
874 root = Element("{objectified}root")
875 root.s = _str("test")
876 self.assert_(isinstance(root.s, objectify.StringElement))
877
879 Element = self.Element
880 SubElement = self.etree.SubElement
881 root = Element("{objectified}root")
882 root.s = _str("3")
883 self.assert_(isinstance(root.s, objectify.StringElement))
884
886 Element = self.Element
887 SubElement = self.etree.SubElement
888 root = Element("{objectified}root")
889 root.s = _str("3.72")
890 self.assert_(isinstance(root.s, objectify.StringElement))
891
893 Element = self.Element
894 SubElement = self.etree.SubElement
895 root = Element("{objectified}root")
896 root.s = _str("test")
897
898 self.assertEquals(_str("test") * 5, root.s * 5)
899 self.assertEquals(5 * _str("test"), 5 * root.s)
900
901 self.assertRaises(TypeError, operator.mul, root.s, _str("honk"))
902 self.assertRaises(TypeError, operator.mul, _str("honk"), root.s)
903
905 Element = self.Element
906 SubElement = self.etree.SubElement
907 root = Element("{objectified}root")
908 root.s = _str("test")
909
910 s = _str("toast")
911 self.assertEquals(_str("test") + s, root.s + s)
912 self.assertEquals(s + _str("test"), s + root.s)
913
915 value = objectify.DataElement(_str("test"))
916 self.assert_(isinstance(value, objectify.StringElement))
917 self.assertEquals(value, _str("test"))
918
920 value = objectify.DataElement("3")
921 self.assert_(isinstance(value, objectify.StringElement))
922 self.assertEquals(value, _str("3"))
923
925 value = objectify.DataElement(_str("3.20"))
926 self.assert_(isinstance(value, objectify.StringElement))
927 self.assertEquals(value, _str("3.20"))
928
930 Element = self.Element
931 SubElement = self.etree.SubElement
932 root = Element("{objectified}root")
933 root.none = 5
934 self.assert_(isinstance(root.none, objectify.IntElement))
935
937 value = objectify.DataElement(5)
938 self.assert_(isinstance(value, objectify.IntElement))
939 self.assertEquals(value, 5)
940
942 Element = self.Element
943 SubElement = self.etree.SubElement
944 root = Element("{objectified}root")
945 root.none = 5.5
946 self.assert_(isinstance(root.none, objectify.FloatElement))
947
949 value = objectify.DataElement(5.5)
950 self.assert_(isinstance(value, objectify.FloatElement))
951 self.assertEquals(value, 5.5)
952
954 for xsi, objclass in xsitype2objclass.items():
955 # 1 is a valid value for all ObjectifiedDataElement classes
956 pyval = 1
957 value = objectify.DataElement(pyval, _xsi=xsi)
958 self.assert_(isinstance(value, objclass),
959 "DataElement(%s, _xsi='%s') returns %s, expected %s"
960 % (pyval, xsi, type(value), objclass))
961
963 for xsi, objclass in xsitype2objclass.items():
964 # 1 is a valid value for all ObjectifiedDataElement classes
965 pyval = 1
966 value = objectify.DataElement(pyval, _xsi="xsd:%s" % xsi)
967 self.assert_(isinstance(value, objclass),
968 "DataElement(%s, _xsi='%s') returns %s, expected %s"
969 % (pyval, xsi, type(value), objclass))
970
972 for xsi, objclass in xsitype2objclass.items():
973 # 1 is a valid value for all ObjectifiedDataElement classes
974 self.assertRaises(ValueError, objectify.DataElement, 1,
975 _xsi="foo:%s" % xsi)
976
978 for pytype, objclass in pytype2objclass.items():
979 # 1 is a valid value for all ObjectifiedDataElement classes
980 pyval = 1
981 value = objectify.DataElement(pyval, _pytype=pytype)
982 self.assert_(isinstance(value, objclass),
983 "DataElement(%s, _pytype='%s') returns %s, expected %s"
984 % (pyval, pytype, type(value), objclass))
985
987 pyval = 1
988 pytype = "NoneType"
989 objclass = objectify.NoneElement
990 value = objectify.DataElement(pyval, _pytype=pytype)
991 self.assert_(isinstance(value, objclass),
992 "DataElement(%s, _pytype='%s') returns %s, expected %s"
993 % (pyval, pytype, type(value), objclass))
994 self.assertEquals(value.text, None)
995 self.assertEquals(value.pyval, None)
996
998 # pre-2.0 lxml called NoneElement "none"
999 pyval = 1
1000 pytype = "none"
1001 objclass = objectify.NoneElement
1002 value = objectify.DataElement(pyval, _pytype=pytype)
1003 self.assert_(isinstance(value, objclass),
1004 "DataElement(%s, _pytype='%s') returns %s, expected %s"
1005 % (pyval, pytype, type(value), objclass))
1006 self.assertEquals(value.text, None)
1007 self.assertEquals(value.pyval, None)
1008
1010 Element = self.Element
1011 SubElement = self.etree.SubElement
1012 class MyFloat(float):
1013 pass
1014 root = Element("{objectified}root")
1015 root.myfloat = MyFloat(5.5)
1016 self.assert_(isinstance(root.myfloat, objectify.FloatElement))
1017 self.assertEquals(root.myfloat.get(objectify.PYTYPE_ATTRIBUTE), None)
1018
1022 value = objectify.DataElement(MyFloat(5.5))
1023 self.assert_(isinstance(value, objectify.FloatElement))
1024 self.assertEquals(value, 5.5)
1025 self.assertEquals(value.get(objectify.PYTYPE_ATTRIBUTE), None)
1026
1028 XML = self.XML
1029 root = XML('''\
1030 <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
1031 <b xsi:type="boolean">true</b>
1032 <b xsi:type="boolean">false</b>
1033 <b xsi:type="boolean">1</b>
1034 <b xsi:type="boolean">0</b>
1035
1036 <f xsi:type="float">5</f>
1037 <f xsi:type="double">5</f>
1038
1039 <s xsi:type="string">5</s>
1040 <s xsi:type="normalizedString">5</s>
1041 <s xsi:type="token">5</s>
1042 <s xsi:type="language">5</s>
1043 <s xsi:type="Name">5</s>
1044 <s xsi:type="NCName">5</s>
1045 <s xsi:type="ID">5</s>
1046 <s xsi:type="IDREF">5</s>
1047 <s xsi:type="ENTITY">5</s>
1048 <s xsi:type="NMTOKEN">5</s>
1049
1050 <l xsi:type="integer">5</l>
1051 <l xsi:type="nonPositiveInteger">5</l>
1052 <l xsi:type="negativeInteger">5</l>
1053 <l xsi:type="long">5</l>
1054 <l xsi:type="nonNegativeInteger">5</l>
1055 <l xsi:type="unsignedLong">5</l>
1056 <l xsi:type="unsignedInt">5</l>
1057 <l xsi:type="positiveInteger">5</l>
1058
1059 <i xsi:type="int">5</i>
1060 <i xsi:type="short">5</i>
1061 <i xsi:type="byte">5</i>
1062 <i xsi:type="unsignedShort">5</i>
1063 <i xsi:type="unsignedByte">5</i>
1064
1065 <n xsi:nil="true"/>
1066 </root>
1067 ''')
1068
1069 for b in root.b:
1070 self.assert_(isinstance(b, objectify.BoolElement))
1071 self.assertEquals(True, root.b[0])
1072 self.assertEquals(False, root.b[1])
1073 self.assertEquals(True, root.b[2])
1074 self.assertEquals(False, root.b[3])
1075
1076 for f in root.f:
1077 self.assert_(isinstance(f, objectify.FloatElement))
1078 self.assertEquals(5, f)
1079
1080 for s in root.s:
1081 self.assert_(isinstance(s, objectify.StringElement))
1082 self.assertEquals("5", s)
1083
1084 for i in root.i:
1085 self.assert_(isinstance(i, objectify.IntElement))
1086 self.assertEquals(5, i)
1087
1088 for l in root.l:
1089 self.assert_(isinstance(l, objectify.IntElement))
1090 self.assertEquals(5, i)
1091
1092 self.assert_(isinstance(root.n, objectify.NoneElement))
1093 self.assertEquals(None, root.n)
1094
1096 XML = self.XML
1097 root = XML('''\
1098 <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
1099 xmlns:xsd="http://www.w3.org/2001/XMLSchema">
1100 <b xsi:type="xsd:boolean">true</b>
1101 <b xsi:type="xsd:boolean">false</b>
1102 <b xsi:type="xsd:boolean">1</b>
1103 <b xsi:type="xsd:boolean">0</b>
1104
1105 <f xsi:type="xsd:float">5</f>
1106 <f xsi:type="xsd:double">5</f>
1107
1108 <s xsi:type="xsd:string">5</s>
1109 <s xsi:type="xsd:normalizedString">5</s>
1110 <s xsi:type="xsd:token">5</s>
1111 <s xsi:type="xsd:language">5</s>
1112 <s xsi:type="xsd:Name">5</s>
1113 <s xsi:type="xsd:NCName">5</s>
1114 <s xsi:type="xsd:ID">5</s>
1115 <s xsi:type="xsd:IDREF">5</s>
1116 <s xsi:type="xsd:ENTITY">5</s>
1117 <s xsi:type="xsd:NMTOKEN">5</s>
1118
1119 <l xsi:type="xsd:integer">5</l>
1120 <l xsi:type="xsd:nonPositiveInteger">5</l>
1121 <l xsi:type="xsd:negativeInteger">5</l>
1122 <l xsi:type="xsd:long">5</l>
1123 <l xsi:type="xsd:nonNegativeInteger">5</l>
1124 <l xsi:type="xsd:unsignedLong">5</l>
1125 <l xsi:type="xsd:unsignedInt">5</l>
1126 <l xsi:type="xsd:positiveInteger">5</l>
1127
1128 <i xsi:type="xsd:int">5</i>
1129 <i xsi:type="xsd:short">5</i>
1130 <i xsi:type="xsd:byte">5</i>
1131 <i xsi:type="xsd:unsignedShort">5</i>
1132 <i xsi:type="xsd:unsignedByte">5</i>
1133
1134 <n xsi:nil="true"/>
1135 </root>
1136 ''')
1137
1138 for b in root.b:
1139 self.assert_(isinstance(b, objectify.BoolElement))
1140 self.assertEquals(True, root.b[0])
1141 self.assertEquals(False, root.b[1])
1142 self.assertEquals(True, root.b[2])
1143 self.assertEquals(False, root.b[3])
1144
1145 for f in root.f:
1146 self.assert_(isinstance(f, objectify.FloatElement))
1147 self.assertEquals(5, f)
1148
1149 for s in root.s:
1150 self.assert_(isinstance(s, objectify.StringElement))
1151 self.assertEquals("5", s)
1152
1153 for i in root.i:
1154 self.assert_(isinstance(i, objectify.IntElement))
1155 self.assertEquals(5, i)
1156
1157 for l in root.l:
1158 self.assert_(isinstance(l, objectify.IntElement))
1159 self.assertEquals(5, l)
1160
1161 self.assert_(isinstance(root.n, objectify.NoneElement))
1162 self.assertEquals(None, root.n)
1163
1165 XML = self.XML
1166 root = XML(_bytes('<root><b>why</b><b>try</b></root>'))
1167 strs = [ str(s) for s in root.b ]
1168 self.assertEquals(["why", "try"],
1169 strs)
1170
1172 XML = self.XML
1173 root = XML(_bytes('<root><b>test</b><b>taste</b><b></b><b/></root>'))
1174 self.assertFalse(root.b[0] < root.b[1])
1175 self.assertFalse(root.b[0] <= root.b[1])
1176 self.assertFalse(root.b[0] == root.b[1])
1177
1178 self.assert_(root.b[0] != root.b[1])
1179 self.assert_(root.b[0] >= root.b[1])
1180 self.assert_(root.b[0] > root.b[1])
1181
1182 self.assertEquals(root.b[0], "test")
1183 self.assertEquals("test", root.b[0])
1184
1185 self.assertEquals("", root.b[2])
1186 self.assertEquals(root.b[2], "")
1187 self.assertEquals("", root.b[3])
1188 self.assertEquals(root.b[3], "")
1189 self.assertEquals(root.b[2], root.b[3])
1190
1191 root.b = "test"
1192 self.assert_(root.b)
1193 root.b = ""
1194 self.assertFalse(root.b)
1195 self.assertEquals(root.b, "")
1196 self.assertEquals("", root.b)
1197
1199 XML = self.XML
1200 root = XML(_bytes('<root><b>5</b><b>6</b></root>'))
1201 self.assert_(root.b[0] < root.b[1])
1202 self.assert_(root.b[0] <= root.b[1])
1203 self.assert_(root.b[0] != root.b[1])
1204
1205 self.assertFalse(root.b[0] == root.b[1])
1206 self.assertFalse(root.b[0] >= root.b[1])
1207 self.assertFalse(root.b[0] > root.b[1])
1208
1209 self.assertEquals(root.b[0], 5)
1210 self.assertEquals(5, root.b[0])
1211 self.assertNotEquals(root.b[0], "5")
1212
1213 root.b = 5
1214 self.assert_(root.b)
1215 root.b = 0
1216 self.assertFalse(root.b)
1217
1218 # float + long share the NumberElement implementation with int
1219
1221 XML = self.XML
1222 root = XML(_bytes('<root><b>false</b><b>true</b></root>'))
1223 self.assert_(root.b[0] < root.b[1])
1224 self.assert_(root.b[0] <= root.b[1])
1225 self.assert_(root.b[0] != root.b[1])
1226
1227 self.assertFalse(root.b[0] == root.b[1])
1228 self.assertFalse(root.b[0] >= root.b[1])
1229 self.assertFalse(root.b[0] > root.b[1])
1230
1231 self.assertFalse(root.b[0])
1232 self.assert_(root.b[1])
1233
1234 self.assertEquals(root.b[0], False)
1235 self.assertEquals(False, root.b[0])
1236 self.assert_(root.b[0] < 5)
1237 self.assert_(5 > root.b[0])
1238
1239 root.b = True
1240 self.assert_(root.b)
1241 root.b = False
1242 self.assertFalse(root.b)
1243
1245 XML = self.XML
1246 root = XML(_bytes("""
1247 <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
1248 <b xsi:nil="true"></b><b xsi:nil="true"/>
1249 </root>"""))
1250 self.assert_(root.b[0] == root.b[1])
1251 self.assertFalse(root.b[0])
1252 self.assertEquals(root.b[0], None)
1253 self.assertEquals(None, root.b[0])
1254
1255 # doesn't work in Py3:
1256
1257 #for comparison in ["abc", 5, 7.3, True, [], ()]:
1258 # none = root.b[1]
1259 # self.assert_(none < comparison, "%s (%s) should be < %s" %
1260 # (none, type(none), comparison) )
1261 # self.assert_(comparison > none, "%s should be > %s (%s)" %
1262 # (comparison, none, type(none)) )
1263
1265 el = objectify.DataElement(1, _xsi="string")
1266 self.assertEquals(
1267 el.get(XML_SCHEMA_INSTANCE_TYPE_ATTR),
1268 'xsd:string')
1269
1271 el = objectify.DataElement(1, _xsi="string",
1272 nsmap={'schema': XML_SCHEMA_NS})
1273 self.assertEquals(
1274 el.get(XML_SCHEMA_INSTANCE_TYPE_ATTR),
1275 'schema:string')
1276
1280
1282 XML = self.XML
1283 root = XML(_bytes('''\
1284 <a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
1285 xmlns:py="http://codespeak.net/lxml/objectify/pytype">
1286 <b>5</b>
1287 <b>test</b>
1288 <c>1.1</c>
1289 <c>\uF8D2</c>
1290 <x>true</x>
1291 <n xsi:nil="true" />
1292 <n></n>
1293 <b xsi:type="double">5</b>
1294 <b xsi:type="float">5</b>
1295 <s xsi:type="string">23</s>
1296 <s py:pytype="str">42</s>
1297 <f py:pytype="float">300</f>
1298 <l py:pytype="long">2</l>
1299 <t py:pytype="TREE"></t>
1300 </a>
1301 '''))
1302 objectify.annotate(root)
1303
1304 child_types = [ c.get(objectify.PYTYPE_ATTRIBUTE)
1305 for c in root.iterchildren() ]
1306 self.assertEquals("int", child_types[ 0])
1307 self.assertEquals("str", child_types[ 1])
1308 self.assertEquals("float", child_types[ 2])
1309 self.assertEquals("str", child_types[ 3])
1310 self.assertEquals("bool", child_types[ 4])
1311 self.assertEquals("NoneType", child_types[ 5])
1312 self.assertEquals(None, child_types[ 6])
1313 self.assertEquals("float", child_types[ 7])
1314 self.assertEquals("float", child_types[ 8])
1315 self.assertEquals("str", child_types[ 9])
1316 self.assertEquals("int", child_types[10])
1317 self.assertEquals("int", child_types[11])
1318 self.assertEquals("int", child_types[12])
1319 self.assertEquals(None, child_types[13])
1320
1321 self.assertEquals("true", root.n.get(XML_SCHEMA_NIL_ATTR))
1322
1324 XML = self.XML
1325 root = XML(_bytes('''\
1326 <a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
1327 xmlns:py="http://codespeak.net/lxml/objectify/pytype">
1328 <n></n>
1329 </a>
1330 '''))
1331 objectify.annotate(root)
1332
1333 child_types = [ c.get(objectify.PYTYPE_ATTRIBUTE)
1334 for c in root.iterchildren() ]
1335 self.assertEquals(None, child_types[0])
1336
1337 objectify.annotate(root, empty_pytype="str")
1338
1339 child_types = [ c.get(objectify.PYTYPE_ATTRIBUTE)
1340 for c in root.iterchildren() ]
1341 self.assertEquals("str", child_types[0])
1342
1344 XML = self.XML
1345 root = XML(_bytes('''\
1346 <a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
1347 xmlns:py="http://codespeak.net/lxml/objectify/pytype">
1348 <b>5</b>
1349 <b>test</b>
1350 <c>1.1</c>
1351 <c>\uF8D2</c>
1352 <x>true</x>
1353 <n xsi:nil="true" />
1354 <n></n>
1355 <b xsi:type="double">5</b>
1356 <b xsi:type="float">5</b>
1357 <s xsi:type="string">23</s>
1358 <s py:pytype="str">42</s>
1359 <f py:pytype="float">300</f>
1360 <l py:pytype="long">2</l>
1361 <t py:pytype="TREE"></t>
1362 </a>
1363 '''))
1364 objectify.annotate(root, ignore_old=False)
1365
1366 child_types = [ c.get(objectify.PYTYPE_ATTRIBUTE)
1367 for c in root.iterchildren() ]
1368 self.assertEquals("int", child_types[ 0])
1369 self.assertEquals("str", child_types[ 1])
1370 self.assertEquals("float", child_types[ 2])
1371 self.assertEquals("str", child_types[ 3])
1372 self.assertEquals("bool", child_types[ 4])
1373 self.assertEquals("NoneType", child_types[ 5])
1374 self.assertEquals(None, child_types[ 6])
1375 self.assertEquals("float", child_types[ 7])
1376 self.assertEquals("float", child_types[ 8])
1377 self.assertEquals("str", child_types[ 9])
1378 self.assertEquals("str", child_types[10])
1379 self.assertEquals("float", child_types[11])
1380 self.assertEquals("int", child_types[12])
1381 self.assertEquals(TREE_PYTYPE, child_types[13])
1382
1383 self.assertEquals("true", root.n.get(XML_SCHEMA_NIL_ATTR))
1384
1386 XML = self.XML
1387 root = XML(_bytes('''\
1388 <a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
1389 xmlns:py="http://codespeak.net/lxml/objectify/pytype">
1390 <b>5</b>
1391 <b>test</b>
1392 <c>1.1</c>
1393 <c>\uF8D2</c>
1394 <x>true</x>
1395 <n xsi:nil="true" />
1396 <n></n>
1397 <b xsi:type="double">5</b>
1398 <b xsi:type="float">5</b>
1399 <s xsi:type="string">23</s>
1400 <s py:pytype="str">42</s>
1401 <f py:pytype="float">300</f>
1402 <l py:pytype="long">2</l>
1403 <t py:pytype="TREE"></t>
1404 </a>
1405 '''))
1406 objectify.annotate(root, ignore_old=False, ignore_xsi=False,
1407 annotate_xsi=1, annotate_pytype=1)
1408
1409 # check py annotations
1410 child_types = [ c.get(objectify.PYTYPE_ATTRIBUTE)
1411 for c in root.iterchildren() ]
1412 self.assertEquals("int", child_types[ 0])
1413 self.assertEquals("str", child_types[ 1])
1414 self.assertEquals("float", child_types[ 2])
1415 self.assertEquals("str", child_types[ 3])
1416 self.assertEquals("bool", child_types[ 4])
1417 self.assertEquals("NoneType", child_types[ 5])
1418 self.assertEquals(None, child_types[ 6])
1419 self.assertEquals("float", child_types[ 7])
1420 self.assertEquals("float", child_types[ 8])
1421 self.assertEquals("str", child_types[ 9])
1422 self.assertEquals("str", child_types[10])
1423 self.assertEquals("float", child_types[11])
1424 self.assertEquals("int", child_types[12])
1425 self.assertEquals(TREE_PYTYPE, child_types[13])
1426
1427 self.assertEquals("true", root.n.get(XML_SCHEMA_NIL_ATTR))
1428
1429 child_xsitypes = [ c.get(XML_SCHEMA_INSTANCE_TYPE_ATTR)
1430 for c in root.iterchildren() ]
1431
1432 # check xsi annotations
1433 child_types = [ c.get(XML_SCHEMA_INSTANCE_TYPE_ATTR)
1434 for c in root.iterchildren() ]
1435 self.assertEquals("xsd:integer", child_types[ 0])
1436 self.assertEquals("xsd:string", child_types[ 1])
1437 self.assertEquals("xsd:double", child_types[ 2])
1438 self.assertEquals("xsd:string", child_types[ 3])
1439 self.assertEquals("xsd:boolean", child_types[ 4])
1440 self.assertEquals(None, child_types[ 5])
1441 self.assertEquals(None, child_types[ 6])
1442 self.assertEquals("xsd:double", child_types[ 7])
1443 self.assertEquals("xsd:float", child_types[ 8])
1444 self.assertEquals("xsd:string", child_types[ 9])
1445 self.assertEquals("xsd:string", child_types[10])
1446 self.assertEquals("xsd:double", child_types[11])
1447 self.assertEquals("xsd:integer", child_types[12])
1448 self.assertEquals(None, child_types[13])
1449
1450 self.assertEquals("true", root.n.get(XML_SCHEMA_NIL_ATTR))
1451
1453 XML = self.XML
1454 root = XML(_bytes('''\
1455 <a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
1456 xmlns:py="http://codespeak.net/lxml/objectify/pytype">
1457 <b>5</b>
1458 <b>test</b>
1459 <c>1.1</c>
1460 <c>\uF8D2</c>
1461 <x>true</x>
1462 <n xsi:nil="true" />
1463 <n></n>
1464 <b xsi:type="double">5</b>
1465 <b xsi:type="float">5</b>
1466 <s xsi:type="string">23</s>
1467 <s py:pytype="str">42</s>
1468 <f py:pytype="float">300</f>
1469 <l py:pytype="long">2</l>
1470 <t py:pytype="TREE"></t>
1471 </a>
1472 '''))
1473 objectify.xsiannotate(root, ignore_old=False)
1474
1475 child_types = [ c.get(XML_SCHEMA_INSTANCE_TYPE_ATTR)
1476 for c in root.iterchildren() ]
1477 self.assertEquals("xsd:integer", child_types[ 0])
1478 self.assertEquals("xsd:string", child_types[ 1])
1479 self.assertEquals("xsd:double", child_types[ 2])
1480 self.assertEquals("xsd:string", child_types[ 3])
1481 self.assertEquals("xsd:boolean", child_types[ 4])
1482 self.assertEquals(None, child_types[ 5])
1483 self.assertEquals(None, child_types[ 6])
1484 self.assertEquals("xsd:double", child_types[ 7])
1485 self.assertEquals("xsd:float", child_types[ 8])
1486 self.assertEquals("xsd:string", child_types[ 9])
1487 self.assertEquals("xsd:string", child_types[10])
1488 self.assertEquals("xsd:double", child_types[11])
1489 self.assertEquals("xsd:integer", child_types[12])
1490 self.assertEquals(None, child_types[13])
1491
1493 XML = self.XML
1494 root = XML(_bytes('''\
1495 <a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
1496 xmlns:py="http://codespeak.net/lxml/objectify/pytype">
1497 <b>5</b>
1498 <b>test</b>
1499 <c>1.1</c>
1500 <c>\uF8D2</c>
1501 <x>true</x>
1502 <n xsi:nil="true" />
1503 <n></n>
1504 <b xsi:type="double">5</b>
1505 <b xsi:type="float">5</b>
1506 <s xsi:type="string">23</s>
1507 <s py:pytype="str">42</s>
1508 <f py:pytype="float">300</f>
1509 <l py:pytype="long">2</l>
1510 <t py:pytype="TREE"></t>
1511 </a>
1512 '''))
1513 objectify.pyannotate(root, ignore_old=True)
1514
1515 child_types = [ c.get(objectify.PYTYPE_ATTRIBUTE)
1516 for c in root.iterchildren() ]
1517 self.assertEquals("int", child_types[ 0])
1518 self.assertEquals("str", child_types[ 1])
1519 self.assertEquals("float", child_types[ 2])
1520 self.assertEquals("str", child_types[ 3])
1521 self.assertEquals("bool", child_types[ 4])
1522 self.assertEquals("NoneType", child_types[ 5])
1523 self.assertEquals(None, child_types[ 6])
1524 self.assertEquals("float", child_types[ 7])
1525 self.assertEquals("float", child_types[ 8])
1526 self.assertEquals("str", child_types[ 9])
1527 self.assertEquals("int", child_types[10])
1528 self.assertEquals("int", child_types[11])
1529 self.assertEquals("int", child_types[12])
1530 self.assertEquals(None, child_types[13])
1531
1532 self.assertEquals("true", root.n.get(XML_SCHEMA_NIL_ATTR))
1533
1535 XML = self.XML
1536 root = XML('''\
1537 <a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
1538 xmlns:py="http://codespeak.net/lxml/objectify/pytype">
1539 <n></n>
1540 </a>
1541 ''')
1542 objectify.pyannotate(root)
1543
1544 child_types = [ c.get(objectify.PYTYPE_ATTRIBUTE)
1545 for c in root.iterchildren() ]
1546 self.assertEquals(None, child_types[0])
1547
1548 objectify.annotate(root, empty_pytype="str")
1549
1550 child_types = [ c.get(objectify.PYTYPE_ATTRIBUTE)
1551 for c in root.iterchildren() ]
1552 self.assertEquals("str", child_types[0])
1553
1555 XML = self.XML
1556 root = XML('''\
1557 <a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
1558 xmlns:py="http://codespeak.net/lxml/objectify/pytype">
1559 <b>5</b>
1560 <b>test</b>
1561 <c>1.1</c>
1562 <c>\uF8D2</c>
1563 <x>true</x>
1564 <n xsi:nil="true" />
1565 <n></n>
1566 <b xsi:type="double">5</b>
1567 <b xsi:type="float">5</b>
1568 <s xsi:type="string">23</s>
1569 <s py:pytype="str">42</s>
1570 <f py:pytype="float">300</f>
1571 <l py:pytype="long">2</l>
1572 <t py:pytype="TREE"></t>
1573 </a>
1574 ''')
1575 objectify.pyannotate(root)
1576
1577 child_types = [ c.get(objectify.PYTYPE_ATTRIBUTE)
1578 for c in root.iterchildren() ]
1579 self.assertEquals("int", child_types[ 0])
1580 self.assertEquals("str", child_types[ 1])
1581 self.assertEquals("float", child_types[ 2])
1582 self.assertEquals("str", child_types[ 3])
1583 self.assertEquals("bool", child_types[ 4])
1584 self.assertEquals("NoneType", child_types[ 5])
1585 self.assertEquals(None, child_types[ 6])
1586 self.assertEquals("float", child_types[ 7])
1587 self.assertEquals("float", child_types[ 8])
1588 self.assertEquals("str", child_types[ 9])
1589 self.assertEquals("str", child_types[10])
1590 self.assertEquals("float", child_types[11])
1591 self.assertEquals("int", child_types[12])
1592 self.assertEquals(TREE_PYTYPE, child_types[13])
1593
1594 self.assertEquals("true", root.n.get(XML_SCHEMA_NIL_ATTR))
1595
1597 XML = self.XML
1598 root = XML(_bytes('''\
1599 <a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
1600 xmlns:py="http://codespeak.net/lxml/objectify/pytype">
1601 <b>5</b>
1602 <b>test</b>
1603 <c>1.1</c>
1604 <c>\uF8D2</c>
1605 <x>true</x>
1606 <n xsi:nil="true" />
1607 <n></n>
1608 <b xsi:type="double">5</b>
1609 <b xsi:type="float">5</b>
1610 <s xsi:type="string">23</s>
1611 <s py:pytype="str">42</s>
1612 <f py:pytype="float">300</f>
1613 <l py:pytype="long">2</l>
1614 <t py:pytype="TREE"></t>
1615 </a>
1616 '''))
1617 objectify.xsiannotate(root, ignore_old=True)
1618
1619 child_types = [ c.get(XML_SCHEMA_INSTANCE_TYPE_ATTR)
1620 for c in root.iterchildren() ]
1621 self.assertEquals("xsd:integer", child_types[ 0])
1622 self.assertEquals("xsd:string", child_types[ 1])
1623 self.assertEquals("xsd:double", child_types[ 2])
1624 self.assertEquals("xsd:string", child_types[ 3])
1625 self.assertEquals("xsd:boolean", child_types[ 4])
1626 self.assertEquals(None, child_types[ 5])
1627 self.assertEquals(None, child_types[ 6])
1628 self.assertEquals("xsd:integer", child_types[ 7])
1629 self.assertEquals("xsd:integer", child_types[ 8])
1630 self.assertEquals("xsd:integer", child_types[ 9])
1631 self.assertEquals("xsd:string", child_types[10])
1632 self.assertEquals("xsd:double", child_types[11])
1633 self.assertEquals("xsd:integer", child_types[12])
1634 self.assertEquals(None, child_types[13])
1635
1636 self.assertEquals("true", root.n.get(XML_SCHEMA_NIL_ATTR))
1637
1639 XML = self.XML
1640 root = XML(_bytes('''\
1641 <a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
1642 xmlns:py="http://codespeak.net/lxml/objectify/pytype">
1643 <b>5</b>
1644 <b>test</b>
1645 <c>1.1</c>
1646 <c>\uF8D2</c>
1647 <x>true</x>
1648 <n xsi:nil="true" />
1649 <n></n>
1650 <b xsi:type="double">5</b>
1651 <b xsi:type="float">5</b>
1652 <s xsi:type="string">23</s>
1653 <s py:pytype="str">42</s>
1654 <f py:pytype="float">300</f>
1655 <l py:pytype="long">2</l>
1656 <t py:pytype="TREE"></t>
1657 </a>
1658 '''))
1659 objectify.deannotate(root)
1660
1661 for c in root.getiterator():
1662 self.assertEquals(None, c.get(XML_SCHEMA_INSTANCE_TYPE_ATTR))
1663 self.assertEquals(None, c.get(objectify.PYTYPE_ATTRIBUTE))
1664
1665 self.assertEquals("true", root.n.get(XML_SCHEMA_NIL_ATTR))
1666
1668 XML = self.XML
1669 root = XML(_bytes('''\
1670 <a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
1671 xmlns:py="http://codespeak.net/lxml/objectify/pytype">
1672 <b>5</b>
1673 <b>test</b>
1674 <c>1.1</c>
1675 <c>\uF8D2</c>
1676 <x>true</x>
1677 <n xsi:nil="true" />
1678 <n></n>
1679 <b xsi:type="double">5</b>
1680 <b xsi:type="float">5</b>
1681 <s xsi:type="string">23</s>
1682 <s py:pytype="str">42</s>
1683 <f py:pytype="float">300</f>
1684 <l py:pytype="long">2</l>
1685 <t py:pytype="TREE"></t>
1686 </a>
1687 '''))
1688 objectify.annotate(
1689 root, ignore_old=False, ignore_xsi=False, annotate_xsi=True,
1690 empty_pytype='str', empty_type='string')
1691 objectify.deannotate(root, pytype=False, xsi=False, xsi_nil=True)
1692
1693 child_types = [ c.get(XML_SCHEMA_INSTANCE_TYPE_ATTR)
1694 for c in root.iterchildren() ]
1695 self.assertEquals("xsd:integer", child_types[ 0])
1696 self.assertEquals("xsd:string", child_types[ 1])
1697 self.assertEquals("xsd:double", child_types[ 2])
1698 self.assertEquals("xsd:string", child_types[ 3])
1699 self.assertEquals("xsd:boolean", child_types[ 4])
1700 self.assertEquals(None, child_types[ 5])
1701 self.assertEquals("xsd:string", child_types[ 6])
1702 self.assertEquals("xsd:double", child_types[ 7])
1703 self.assertEquals("xsd:float", child_types[ 8])
1704 self.assertEquals("xsd:string", child_types[ 9])
1705 self.assertEquals("xsd:string", child_types[10])
1706 self.assertEquals("xsd:double", child_types[11])
1707 self.assertEquals("xsd:integer", child_types[12])
1708 self.assertEquals(None, child_types[13])
1709
1710 self.assertEquals(None, root.n.get(XML_SCHEMA_NIL_ATTR))
1711
1712 for c in root.iterchildren():
1713 self.assertNotEquals(None, c.get(objectify.PYTYPE_ATTRIBUTE))
1714 # these have no equivalent in xsi:type
1715 if (c.get(objectify.PYTYPE_ATTRIBUTE) not in [TREE_PYTYPE,
1716 "NoneType"]):
1717 self.assertNotEquals(
1718 None, c.get(XML_SCHEMA_INSTANCE_TYPE_ATTR))
1719
1721 XML = self.XML
1722 root = XML(_bytes('''\
1723 <a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
1724 xmlns:py="http://codespeak.net/lxml/objectify/pytype"
1725 xmlns:xsd="http://www.w3.org/2001/XMLSchema">
1726 <b>5</b>
1727 <b>test</b>
1728 <c>1.1</c>
1729 <c>\uF8D2</c>
1730 <x>true</x>
1731 <n xsi:nil="true" />
1732 <n></n>
1733 <b xsi:type="xsd:double">5</b>
1734 <b xsi:type="xsd:float">5</b>
1735 <s xsi:type="xsd:string">23</s>
1736 <s py:pytype="str">42</s>
1737 <f py:pytype="float">300</f>
1738 <l py:pytype="long">2</l>
1739 <t py:pytype="TREE"></t>
1740 </a>
1741 '''))
1742 objectify.annotate(root)
1743 objectify.deannotate(root, pytype=False)
1744
1745 child_types = [ c.get(objectify.PYTYPE_ATTRIBUTE)
1746 for c in root.iterchildren() ]
1747 self.assertEquals("int", child_types[ 0])
1748 self.assertEquals("str", child_types[ 1])
1749 self.assertEquals("float", child_types[ 2])
1750 self.assertEquals("str", child_types[ 3])
1751 self.assertEquals("bool", child_types[ 4])
1752 self.assertEquals("NoneType", child_types[ 5])
1753 self.assertEquals(None, child_types[ 6])
1754 self.assertEquals("float", child_types[ 7])
1755 self.assertEquals("float", child_types[ 8])
1756 self.assertEquals("str", child_types[ 9])
1757 self.assertEquals("int", child_types[10])
1758 self.assertEquals("int", child_types[11])
1759 self.assertEquals("int", child_types[12])
1760 self.assertEquals(None, child_types[13])
1761
1762 self.assertEquals("true", root.n.get(XML_SCHEMA_NIL_ATTR))
1763
1764 for c in root.getiterator():
1765 self.assertEquals(None, c.get(XML_SCHEMA_INSTANCE_TYPE_ATTR))
1766
1768 XML = self.XML
1769 root = XML(_bytes('''\
1770 <a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
1771 xmlns:py="http://codespeak.net/lxml/objectify/pytype"
1772 xmlns:xsd="http://www.w3.org/2001/XMLSchema">
1773 <b xsi:type="xsd:int">5</b>
1774 <b xsi:type="xsd:string">test</b>
1775 <c xsi:type="xsd:float">1.1</c>
1776 <c xsi:type="xsd:string">\uF8D2</c>
1777 <x xsi:type="xsd:boolean">true</x>
1778 <n xsi:nil="true" />
1779 <n></n>
1780 <b xsi:type="xsd:double">5</b>
1781 <b xsi:type="xsd:float">5</b>
1782 <s xsi:type="xsd:string">23</s>
1783 <s xsi:type="xsd:string">42</s>
1784 <f xsi:type="xsd:float">300</f>
1785 <l xsi:type="xsd:long">2</l>
1786 <t py:pytype="TREE"></t>
1787 </a>
1788 '''))
1789 objectify.annotate(root)
1790 objectify.deannotate(root, xsi=False)
1791
1792 child_types = [ c.get(XML_SCHEMA_INSTANCE_TYPE_ATTR)
1793 for c in root.iterchildren() ]
1794 self.assertEquals("xsd:int", child_types[ 0])
1795 self.assertEquals("xsd:string", child_types[ 1])
1796 self.assertEquals("xsd:float", child_types[ 2])
1797 self.assertEquals("xsd:string", child_types[ 3])
1798 self.assertEquals("xsd:boolean", child_types[ 4])
1799 self.assertEquals(None, child_types[ 5])
1800 self.assertEquals(None, child_types[ 6])
1801 self.assertEquals("xsd:double", child_types[ 7])
1802 self.assertEquals("xsd:float", child_types[ 8])
1803 self.assertEquals("xsd:string", child_types[ 9])
1804 self.assertEquals("xsd:string", child_types[10])
1805 self.assertEquals("xsd:float", child_types[11])
1806 self.assertEquals("xsd:long", child_types[12])
1807 self.assertEquals(None, child_types[13])
1808
1809 self.assertEquals("true", root.n.get(XML_SCHEMA_NIL_ATTR))
1810
1811 for c in root.getiterator():
1812 self.assertEquals(None, c.get(objectify.PYTYPE_ATTRIBUTE))
1813
1815 XML = self.XML
1816
1817 xml = _bytes('''\
1818 <a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
1819 <b>5</b>
1820 <b>test</b>
1821 <c>1.1</c>
1822 <c>\uF8D2</c>
1823 <x>true</x>
1824 <n xsi:nil="true" />
1825 <n></n>
1826 <b xsi:type="double">5</b>
1827 </a>
1828 ''')
1829
1830 pytype_ns, pytype_name = objectify.PYTYPE_ATTRIBUTE[1:].split('}')
1831 objectify.set_pytype_attribute_tag("{TEST}test")
1832
1833 root = XML(xml)
1834 objectify.annotate(root)
1835
1836 attribs = root.xpath("//@py:%s" % pytype_name,
1837 namespaces={"py" : pytype_ns})
1838 self.assertEquals(0, len(attribs))
1839 attribs = root.xpath("//@py:test",
1840 namespaces={"py" : "TEST"})
1841 self.assertEquals(7, len(attribs))
1842
1843 objectify.set_pytype_attribute_tag()
1844 pytype_ns, pytype_name = objectify.PYTYPE_ATTRIBUTE[1:].split('}')
1845
1846 self.assertNotEqual("test", pytype_ns.lower())
1847 self.assertNotEqual("test", pytype_name.lower())
1848
1849 root = XML(xml)
1850 attribs = root.xpath("//@py:%s" % pytype_name,
1851 namespaces={"py" : pytype_ns})
1852 self.assertEquals(0, len(attribs))
1853
1854 objectify.annotate(root)
1855 attribs = root.xpath("//@py:%s" % pytype_name,
1856 namespaces={"py" : pytype_ns})
1857 self.assertEquals(7, len(attribs))
1858
1860 orig_types = objectify.getRegisteredTypes()
1861 orig_types[0].unregister()
1862 self.assertEquals(orig_types[1:], objectify.getRegisteredTypes())
1863
1864 class NewType(objectify.ObjectifiedDataElement):
1865 pass
1866
1867 def checkMyType(s):
1868 return True
1869
1870 pytype = objectify.PyType("mytype", checkMyType, NewType)
1871 self.assert_(pytype not in objectify.getRegisteredTypes())
1872 pytype.register()
1873 self.assert_(pytype in objectify.getRegisteredTypes())
1874 pytype.unregister()
1875 self.assert_(pytype not in objectify.getRegisteredTypes())
1876
1877 pytype.register(before = [objectify.getRegisteredTypes()[0].name])
1878 self.assertEquals(pytype, objectify.getRegisteredTypes()[0])
1879 pytype.unregister()
1880
1881 pytype.register(after = [objectify.getRegisteredTypes()[0].name])
1882 self.assertNotEqual(pytype, objectify.getRegisteredTypes()[0])
1883 pytype.unregister()
1884
1885 self.assertRaises(ValueError, pytype.register,
1886 before = [objectify.getRegisteredTypes()[0].name],
1887 after = [objectify.getRegisteredTypes()[1].name])
1888
1890 from datetime import datetime
1891 def parse_date(value):
1892 if len(value) != 14:
1893 raise ValueError(value)
1894 Y = int(value[0:4])
1895 M = int(value[4:6])
1896 D = int(value[6:8])
1897 h = int(value[8:10])
1898 m = int(value[10:12])
1899 s = int(value[12:14])
1900 return datetime(Y, M, D, h, m, s)
1901
1902 def stringify_date(date):
1903 return date.strftime("%Y%m%d%H%M%S")
1904
1905 class DatetimeElement(objectify.ObjectifiedDataElement):
1906 def pyval(self):
1907 return parse_date(self.text)
1908 pyval = property(pyval)
1909
1910 datetime_type = objectify.PyType(
1911 "datetime", parse_date, DatetimeElement, stringify_date)
1912 datetime_type.xmlSchemaTypes = "dateTime"
1913 datetime_type.register()
1914
1915 NAMESPACE = "http://foo.net/xmlns"
1916 NAMESPACE_MAP = {'ns': NAMESPACE}
1917
1918 r = objectify.Element("{%s}root" % NAMESPACE, nsmap=NAMESPACE_MAP)
1919 time = datetime.now()
1920 r.date = time
1921
1922 self.assert_(isinstance(r.date, DatetimeElement))
1923 self.assert_(isinstance(r.date.pyval, datetime))
1924
1925 self.assertEquals(r.date.pyval, parse_date(stringify_date(time)))
1926 self.assertEquals(r.date.text, stringify_date(time))
1927
1928 r.date = objectify.E.date(time)
1929
1930 self.assert_(isinstance(r.date, DatetimeElement))
1931 self.assert_(isinstance(r.date.pyval, datetime))
1932
1933 self.assertEquals(r.date.pyval, parse_date(stringify_date(time)))
1934 self.assertEquals(r.date.text, stringify_date(time))
1935
1937 root = self.XML(xml_str)
1938 path = objectify.ObjectPath( "root.c1.c2" )
1939 self.assertEquals(root.c1.c2.text, path.find(root).text)
1940 self.assertEquals(root.c1.c2.text, path(root).text)
1941
1943 root = self.XML(xml_str)
1944 path = objectify.ObjectPath( ['root', 'c1', 'c2'] )
1945 self.assertEquals(root.c1.c2.text, path.find(root).text)
1946 self.assertEquals(root.c1.c2.text, path(root).text)
1947
1949 root = self.XML(xml_str)
1950 path = objectify.ObjectPath( "root.c1.c99" )
1951 self.assertRaises(AttributeError, path, root)
1952
1954 root = self.XML(xml_str)
1955 path = objectify.ObjectPath( "root.c1.c99" )
1956 self.assertEquals(None, path(root, None))
1957 path = objectify.ObjectPath( "root.c99.c2" )
1958 self.assertEquals(None, path(root, None))
1959 path = objectify.ObjectPath( "notroot.c99.c2" )
1960 self.assertEquals(None, path(root, None))
1961
1963 root = self.XML(xml_str)
1964 path = objectify.ObjectPath( ".c1.c99" )
1965 self.assertEquals(None, path(root, None))
1966 path = objectify.ObjectPath( ".c99.c2" )
1967 self.assertEquals(None, path(root, None))
1968
1970 root = self.XML(xml_str)
1971 path = objectify.ObjectPath("root . {objectified}c1. c2")
1972 self.assertEquals(root.c1.c2.text, path(root).text)
1973
1974 path = objectify.ObjectPath(" root.{objectified} c1.c2 [ 0 ] ")
1975 self.assertEquals(root.c1.c2.text, path(root).text)
1976
1979
1982
1984 root = self.XML(xml_str)
1985 path = objectify.ObjectPath( "root" )
1986 self.assert_(path.hasattr(root))
1987 path = objectify.ObjectPath( "root.c1" )
1988 self.assert_(path.hasattr(root))
1989 path = objectify.ObjectPath( "root.c1.c2" )
1990 self.assert_(path.hasattr(root))
1991 path = objectify.ObjectPath( "root.c1.{otherNS}c2" )
1992 self.assert_(path.hasattr(root))
1993 path = objectify.ObjectPath( "root.c1.c2[1]" )
1994 self.assert_(path.hasattr(root))
1995 path = objectify.ObjectPath( "root.c1.c2[2]" )
1996 self.assert_(path.hasattr(root))
1997 path = objectify.ObjectPath( "root.c1.c2[3]" )
1998 self.assertFalse(path.hasattr(root))
1999 path = objectify.ObjectPath( "root.c1[1].c2" )
2000 self.assertFalse(path.hasattr(root))
2001
2003 root = self.XML(xml_str)
2004 path = objectify.ObjectPath( "." )
2005 self.assertEquals(root.c1.c2.text, path(root).c1.c2.text)
2006
2008 root = self.XML(xml_str)
2009 path = objectify.ObjectPath( [''] )
2010 self.assertEquals(root.c1.c2.text, path(root).c1.c2.text)
2011
2013 root = self.XML(xml_str)
2014 path = objectify.ObjectPath( ".c1.c2" )
2015 self.assertEquals(root.c1.c2.text, path(root).text)
2016
2018 root = self.XML(xml_str)
2019 path = objectify.ObjectPath( ['', 'c1', 'c2'] )
2020 self.assertEquals(root.c1.c2.text, path(root).text)
2021
2023 root = self.XML(xml_str)
2024 path = objectify.ObjectPath( "root.c1[0].c2[0]" )
2025 self.assertEquals(root.c1.c2.text, path(root).text)
2026
2027 path = objectify.ObjectPath( "root.c1[0].c2" )
2028 self.assertEquals(root.c1.c2.text, path(root).text)
2029
2030 path = objectify.ObjectPath( "root.c1[0].c2[1]" )
2031 self.assertEquals(root.c1.c2[1].text, path(root).text)
2032
2033 path = objectify.ObjectPath( "root.c1.c2[2]" )
2034 self.assertEquals(root.c1.c2[2].text, path(root).text)
2035
2036 path = objectify.ObjectPath( "root.c1.c2[-1]" )
2037 self.assertEquals(root.c1.c2[-1].text, path(root).text)
2038
2039 path = objectify.ObjectPath( "root.c1.c2[-3]" )
2040 self.assertEquals(root.c1.c2[-3].text, path(root).text)
2041
2043 root = self.XML(xml_str)
2044 path = objectify.ObjectPath( ['root', 'c1[0]', 'c2[0]'] )
2045 self.assertEquals(root.c1.c2.text, path(root).text)
2046
2047 path = objectify.ObjectPath( ['root', 'c1[0]', 'c2[2]'] )
2048 self.assertEquals(root.c1.c2[2].text, path(root).text)
2049
2050 path = objectify.ObjectPath( ['root', 'c1', 'c2[2]'] )
2051 self.assertEquals(root.c1.c2[2].text, path(root).text)
2052
2053 path = objectify.ObjectPath( ['root', 'c1', 'c2[-1]'] )
2054 self.assertEquals(root.c1.c2[-1].text, path(root).text)
2055
2056 path = objectify.ObjectPath( ['root', 'c1', 'c2[-3]'] )
2057 self.assertEquals(root.c1.c2[-3].text, path(root).text)
2058
2060 self.assertRaises(ValueError, objectify.ObjectPath,
2061 "root.c1[0].c2[-1-2]")
2062 self.assertRaises(ValueError, objectify.ObjectPath,
2063 ['root', 'c1[0]', 'c2[-1-2]'])
2064
2065 self.assertRaises(ValueError, objectify.ObjectPath,
2066 "root[2].c1.c2")
2067 self.assertRaises(ValueError, objectify.ObjectPath,
2068 ['root[2]', 'c1', 'c2'])
2069
2070 self.assertRaises(ValueError, objectify.ObjectPath,
2071 [])
2072 self.assertRaises(ValueError, objectify.ObjectPath,
2073 ['', '', ''])
2074
2076 root = self.XML(xml_str)
2077 path = objectify.ObjectPath("root.c1[9999].c2")
2078 self.assertRaises(AttributeError, path, root)
2079
2080 path = objectify.ObjectPath("root.c1[0].c2[9999]")
2081 self.assertRaises(AttributeError, path, root)
2082
2083 path = objectify.ObjectPath(".c1[9999].c2[0]")
2084 self.assertRaises(AttributeError, path, root)
2085
2086 path = objectify.ObjectPath("root.c1[-2].c2")
2087 self.assertRaises(AttributeError, path, root)
2088
2089 path = objectify.ObjectPath("root.c1[0].c2[-4]")
2090 self.assertRaises(AttributeError, path, root)
2091
2093 root = self.XML(xml_str)
2094 path = objectify.ObjectPath( "{objectified}root.c1.c2" )
2095 self.assertEquals(root.c1.c2.text, path.find(root).text)
2096 path = objectify.ObjectPath( "{objectified}root.{objectified}c1.c2" )
2097 self.assertEquals(root.c1.c2.text, path.find(root).text)
2098 path = objectify.ObjectPath( "root.{objectified}c1.{objectified}c2" )
2099 self.assertEquals(root.c1.c2.text, path.find(root).text)
2100 path = objectify.ObjectPath( "root.c1.{objectified}c2" )
2101 self.assertEquals(root.c1.c2.text, path.find(root).text)
2102 path = objectify.ObjectPath( "root.c1.{otherNS}c2" )
2103 self.assertEquals(getattr(root.c1, '{otherNS}c2').text,
2104 path.find(root).text)
2105
2107 root = self.XML(xml_str)
2108 path = objectify.ObjectPath( ['{objectified}root', 'c1', 'c2'] )
2109 self.assertEquals(root.c1.c2.text, path.find(root).text)
2110 path = objectify.ObjectPath( ['{objectified}root', '{objectified}c1', 'c2'] )
2111 self.assertEquals(root.c1.c2.text, path.find(root).text)
2112 path = objectify.ObjectPath( ['root', '{objectified}c1', '{objectified}c2'] )
2113 self.assertEquals(root.c1.c2.text, path.find(root).text)
2114 path = objectify.ObjectPath( ['root', '{objectified}c1', '{objectified}c2[2]'] )
2115 self.assertEquals(root.c1.c2[2].text, path.find(root).text)
2116 path = objectify.ObjectPath( ['root', 'c1', '{objectified}c2'] )
2117 self.assertEquals(root.c1.c2.text, path.find(root).text)
2118 path = objectify.ObjectPath( ['root', 'c1', '{objectified}c2[2]'] )
2119 self.assertEquals(root.c1.c2[2].text, path.find(root).text)
2120 path = objectify.ObjectPath( ['root', 'c1', '{otherNS}c2'] )
2121 self.assertEquals(getattr(root.c1, '{otherNS}c2').text,
2122 path.find(root).text)
2123
2125 root = self.XML(xml_str)
2126 path = objectify.ObjectPath( "root.c1.c2" )
2127 self.assertEquals(root.c1.c2.text, path.find(root).text)
2128 self.assertEquals("1", root.c1.c2[1].text)
2129
2130 new_value = "my new value"
2131 path.setattr(root, new_value)
2132
2133 self.assertEquals(new_value, root.c1.c2.text)
2134 self.assertEquals(new_value, path(root).text)
2135 self.assertEquals("1", root.c1.c2[1].text)
2136
2138 root = self.XML(xml_str)
2139 path = objectify.ObjectPath( "root.c1.c2" )
2140 self.assertEquals(root.c1.c2.text, path.find(root).text)
2141 self.assertEquals("1", root.c1.c2[1].text)
2142
2143 new_el = self.Element("{objectified}test")
2144 etree.SubElement(new_el, "{objectified}sub", myattr="ATTR").a = "TEST"
2145 path.setattr(root, new_el.sub)
2146
2147 self.assertEquals("ATTR", root.c1.c2.get("myattr"))
2148 self.assertEquals("TEST", root.c1.c2.a.text)
2149 self.assertEquals("TEST", path(root).a.text)
2150 self.assertEquals("1", root.c1.c2[1].text)
2151
2153 root = self.XML(xml_str)
2154 path = objectify.ObjectPath( "root.c1.c99" )
2155 self.assertRaises(AttributeError, path.find, root)
2156
2157 new_value = "my new value"
2158 path.setattr(root, new_value)
2159
2160 self.assertEquals(1, len(root.c1.c99))
2161 self.assertEquals(new_value, root.c1.c99.text)
2162 self.assertEquals(new_value, path(root).text)
2163
2165 root = self.XML(xml_str)
2166 path = objectify.ObjectPath( "root.c1.c99" )
2167 self.assertRaises(AttributeError, path.find, root)
2168
2169 new_el = self.Element("{objectified}test")
2170 etree.SubElement(new_el, "{objectified}sub", myattr="ATTR").a = "TEST"
2171 path.setattr(root, new_el.sub)
2172
2173 self.assertEquals(1, len(root.c1.c99))
2174 self.assertEquals("ATTR", root.c1.c99.get("myattr"))
2175 self.assertEquals("TEST", root.c1.c99.a.text)
2176 self.assertEquals("TEST", path(root).a.text)
2177
2179 root = self.XML(xml_str)
2180 path = objectify.ObjectPath( "root.c1.c99" )
2181 self.assertRaises(AttributeError, path.find, root)
2182
2183 new_el = self.Element("{objectified}test")
2184 new_el.a = ["TEST1", "TEST2"]
2185 new_el.a[0].set("myattr", "ATTR1")
2186 new_el.a[1].set("myattr", "ATTR2")
2187
2188 path.setattr(root, list(new_el.a))
2189
2190 self.assertEquals(2, len(root.c1.c99))
2191 self.assertEquals("ATTR1", root.c1.c99[0].get("myattr"))
2192 self.assertEquals("TEST1", root.c1.c99[0].text)
2193 self.assertEquals("ATTR2", root.c1.c99[1].get("myattr"))
2194 self.assertEquals("TEST2", root.c1.c99[1].text)
2195 self.assertEquals("TEST1", path(root).text)
2196
2198 root = self.XML(xml_str)
2199 path = objectify.ObjectPath( "root.c1.c2" )
2200 self.assertEquals(3, len(root.c1.c2))
2201 path.addattr(root, "test")
2202 self.assertEquals(4, len(root.c1.c2))
2203 self.assertEquals(["0", "1", "2", "test"],
2204 [el.text for el in root.c1.c2])
2205
2207 root = self.XML(xml_str)
2208 path = objectify.ObjectPath( "root.c1.c2" )
2209 self.assertEquals(3, len(root.c1.c2))
2210
2211 new_el = self.Element("{objectified}test")
2212 etree.SubElement(new_el, "{objectified}sub").a = "TEST"
2213
2214 path.addattr(root, new_el.sub)
2215 self.assertEquals(4, len(root.c1.c2))
2216 self.assertEquals("TEST", root.c1.c2[3].a.text)
2217 self.assertEquals(["0", "1", "2"],
2218 [el.text for el in root.c1.c2[:3]])
2219
2221 root = self.XML(xml_str)
2222 path = objectify.ObjectPath( "root.c1.c99" )
2223 self.assertRaises(AttributeError, path.find, root)
2224
2225 new_value = "my new value"
2226 path.addattr(root, new_value)
2227
2228 self.assertEquals(1, len(root.c1.c99))
2229 self.assertEquals(new_value, root.c1.c99.text)
2230 self.assertEquals(new_value, path(root).text)
2231
2233 root = self.XML(xml_str)
2234 path = objectify.ObjectPath( "root.c1.c99" )
2235 self.assertRaises(AttributeError, path.find, root)
2236
2237 new_el = self.Element("{objectified}test")
2238 etree.SubElement(new_el, "{objectified}sub", myattr="ATTR").a = "TEST"
2239
2240 path.addattr(root, new_el.sub)
2241 self.assertEquals(1, len(root.c1.c99))
2242 self.assertEquals("TEST", root.c1.c99.a.text)
2243 self.assertEquals("TEST", path(root).a.text)
2244 self.assertEquals("ATTR", root.c1.c99.get("myattr"))
2245
2247 root = self.XML(xml_str)
2248 path = objectify.ObjectPath( "root.c1.c99" )
2249 self.assertRaises(AttributeError, path.find, root)
2250
2251 new_el = self.Element("{objectified}test")
2252 new_el.a = ["TEST1", "TEST2"]
2253
2254 self.assertEquals(2, len(new_el.a))
2255
2256 path.addattr(root, list(new_el.a))
2257 self.assertEquals(2, len(root.c1.c99))
2258 self.assertEquals("TEST1", root.c1.c99.text)
2259 self.assertEquals("TEST2", path(root)[1].text)
2260
2262 root = self.XML(xml_str)
2263 self.assertEquals(
2264 ['{objectified}root', '{objectified}root.c1',
2265 '{objectified}root.c1.c2',
2266 '{objectified}root.c1.c2[1]', '{objectified}root.c1.c2[2]',
2267 '{objectified}root.c1.{otherNS}c2', '{objectified}root.c1.{}c2'],
2268 root.descendantpaths())
2269
2271 root = self.XML(xml_str)
2272 self.assertEquals(
2273 ['{objectified}c1', '{objectified}c1.c2',
2274 '{objectified}c1.c2[1]', '{objectified}c1.c2[2]',
2275 '{objectified}c1.{otherNS}c2', '{objectified}c1.{}c2'],
2276 root.c1.descendantpaths())
2277
2279 root = self.XML(xml_str)
2280 self.assertEquals(
2281 ['root.{objectified}c1', 'root.{objectified}c1.c2',
2282 'root.{objectified}c1.c2[1]', 'root.{objectified}c1.c2[2]',
2283 'root.{objectified}c1.{otherNS}c2',
2284 'root.{objectified}c1.{}c2'],
2285 root.c1.descendantpaths('root'))
2286
2288 import pickle
2289
2290 root = self.XML(xml_str)
2291 out = BytesIO()
2292 pickle.dump(root, out)
2293
2294 new_root = pickle.loads(out.getvalue())
2295 self.assertEquals(
2296 etree.tostring(new_root),
2297 etree.tostring(root))
2298
2300 import pickle
2301
2302 tree = etree.ElementTree(self.XML(xml_str + "<?my pi?>"))
2303 out = BytesIO()
2304 pickle.dump(tree, out)
2305
2306 new_tree = pickle.loads(out.getvalue())
2307 self.assert_(isinstance(new_tree, etree._ElementTree))
2308 self.assertEquals(
2309 etree.tostring(new_tree),
2310 etree.tostring(tree))
2311
2312 # E-Factory tests, need to use sub-elements as root element is always
2313 # type-looked-up as ObjectifiedElement (no annotations)
2315 E = objectify.E
2316 root = E.root(E.val(23))
2317 self.assert_(isinstance(root.val, objectify.IntElement))
2318
2320 E = objectify.E
2321 root = E.root(E.val(233.23))
2322 self.assert_(isinstance(root.val, objectify.FloatElement))
2323
2325 E = objectify.E
2326 root = E.root(E.val("what?"))
2327 self.assert_(isinstance(root.val, objectify.StringElement))
2328
2330 E = objectify.E
2331 root = E.root(E.val(_str("blöödy häll", encoding="ISO-8859-1")))
2332 self.assert_(isinstance(root.val, objectify.StringElement))
2333
2335 E = objectify.E
2336 root = E.root(E.val(True))
2337 self.assert_(isinstance(root.val, objectify.BoolElement))
2338
2340 E = objectify.E
2341 root = E.root(E.val(None))
2342 self.assert_(isinstance(root.val, objectify.NoneElement))
2343
2345 E = objectify.E
2346 root = E.root(E.val(1, "foo", 2.0, "bar ", True, None))
2347 self.assert_(isinstance(root.val, objectify.StringElement))
2348
2353
2355 E = objectify.E
2356 DataElement = objectify.DataElement
2357 root = E.root("text", E.sub(E.subsub()), "tail", DataElement(1),
2358 DataElement(2.0))
2359 self.assert_(isinstance(root, objectify.ObjectifiedElement))
2360 self.assertEquals(root.text, "text")
2361 self.assert_(isinstance(root.sub, objectify.ObjectifiedElement))
2362 self.assertEquals(root.sub.tail, "tail")
2363 self.assert_(isinstance(root.sub.subsub, objectify.StringElement))
2364 self.assertEquals(len(root.value), 2)
2365 self.assert_(isinstance(root.value[0], objectify.IntElement))
2366 self.assert_(isinstance(root.value[1], objectify.FloatElement))
2367
2369 root = objectify.XML(_bytes("<root/>"), base_url="http://no/such/url")
2370 docinfo = root.getroottree().docinfo
2371 self.assertEquals(docinfo.URL, "http://no/such/url")
2372
2374 root = objectify.XML(_bytes("<root/>"), base_url="http://no/such/url")
2375 docinfo = root.getroottree().docinfo
2376 self.assertEquals(docinfo.URL, "http://no/such/url")
2377 docinfo.URL = "https://secret/url"
2378 self.assertEquals(docinfo.URL, "https://secret/url")
2379
2381 tree = objectify.parse(BytesIO("<root/>"), base_url="http://no/such/url")
2382 docinfo = tree.docinfo
2383 self.assertEquals(docinfo.URL, "http://no/such/url")
2384
2386 tree = objectify.parse(fileInTestDir('include/test_xinclude.xml'),
2387 base_url="http://no/such/url")
2388 docinfo = tree.docinfo
2389 self.assertEquals(docinfo.URL, "http://no/such/url")
2390
2392 root = objectify.XML(_bytes("<root/>"), base_url="http://no/such/url")
2393 self.assertEquals(root.base, "http://no/such/url")
2394 self.assertEquals(
2395 root.get('{http://www.w3.org/XML/1998/namespace}base'), None)
2396 root.base = "https://secret/url"
2397 self.assertEquals(root.base, "https://secret/url")
2398 self.assertEquals(
2399 root.get('{http://www.w3.org/XML/1998/namespace}base'),
2400 "https://secret/url")
2401
2403 root = objectify.XML(_bytes("<root/>"), base_url="http://no/such/url")
2404 self.assertEquals(root.base, "http://no/such/url")
2405 self.assertEquals(
2406 root.get('{http://www.w3.org/XML/1998/namespace}base'), None)
2407 root.set('{http://www.w3.org/XML/1998/namespace}base',
2408 "https://secret/url")
2409 self.assertEquals(root.base, "https://secret/url")
2410 self.assertEquals(
2411 root.get('{http://www.w3.org/XML/1998/namespace}base'),
2412 "https://secret/url")
2413
2415 XML = self.XML
2416
2417 xml = _bytes('''\
2418 <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
2419 <i>5</i>
2420 <i>-5</i>
2421 <l>4294967296</l>
2422 <l>-4294967296</l>
2423 <f>1.1</f>
2424 <b>true</b>
2425 <b>false</b>
2426 <s>Strange things happen, where strings collide</s>
2427 <s>True</s>
2428 <s>False</s>
2429 <s>t</s>
2430 <s>f</s>
2431 <s></s>
2432 <s>None</s>
2433 <n xsi:nil="true" />
2434 </root>
2435 ''')
2436 root = XML(xml)
2437
2438 for i in root.i:
2439 self.assert_(isinstance(i, objectify.IntElement))
2440 for l in root.l:
2441 self.assert_(isinstance(l, objectify.IntElement))
2442 for f in root.f:
2443 self.assert_(isinstance(f, objectify.FloatElement))
2444 for b in root.b:
2445 self.assert_(isinstance(b, objectify.BoolElement))
2446 self.assertEquals(True, root.b[0])
2447 self.assertEquals(False, root.b[1])
2448 for s in root.s:
2449 self.assert_(isinstance(s, objectify.StringElement))
2450 self.assert_(isinstance(root.n, objectify.NoneElement))
2451 self.assertEquals(None, root.n)
2452
2454 suite = unittest.TestSuite()
2455 suite.addTests([unittest.makeSuite(ObjectifyTestCase)])
2456 if sys.version_info >= (2,4):
2457 suite.addTests(
2458 [make_doctest('../../../doc/objectify.txt')])
2459 return suite
2460
2461 if __name__ == '__main__':
2462 print('to test use test.py %s' % __file__)
2463
| Home | Trees | Indices | Help |
|
|---|
| Generated by Epydoc 3.0 on Sun Jun 21 09:44:49 2009 | http://epydoc.sourceforge.net |