/usr/lib/python2.7/dist-packages/code_saturne/Base/XMLengine.py is in code-saturne-data 4.2.0+repack-1build1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 | # -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# This file is part of Code_Saturne, a general-purpose CFD tool.
#
# Copyright (C) 1998-2015 EDF S.A.
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
# Street, Fifth Floor, Boston, MA 02110-1301, USA.
#-------------------------------------------------------------------------------
"""
This module defines a Lightweight XML constructor and reader.
It provides a management of the XML document, which reflets the treated case.
This module defines the following classes:
- Dico
- XMLElement
- XMLDocument
- Case
- XMLDocumentTestCase
"""
#-------------------------------------------------------------------------------
# Library modules import
#-------------------------------------------------------------------------------
import os, sys, string, unittest, logging
from xml.dom.minidom import Document, parse, parseString, Node
from xml.sax.handler import ContentHandler
from xml.sax import make_parser
#-------------------------------------------------------------------------------
# Application modules import
#-------------------------------------------------------------------------------
from code_saturne.Base.Toolbox import GuiParam
#-------------------------------------------------------------------------------
# Third-party modules
#-------------------------------------------------------------------------------
from PyQt4.QtCore import QObject, SIGNAL
#-------------------------------------------------------------------------------
# log config
#-------------------------------------------------------------------------------
logging.basicConfig()
log = logging.getLogger("XMLengine")
#log.setLevel(logging.NOTSET)
log.setLevel(GuiParam.DEBUG)
#-------------------------------------------------------------------------------
# Checker of XML file syntax
#-------------------------------------------------------------------------------
def xmlChecker(filename):
"""Try to open the xml file, and return a message if an error occurs.
@param filename name of the file of parameters ith its absolute path
@return m error message
"""
m = ""
try:
p = make_parser()
p.setContentHandler(ContentHandler())
p.parse(filename)
except Exception as e:
f = os.path.basename(filename)
m = "%s file reading error. \n\n"\
"This file is not in accordance with XML specifications.\n\n"\
"The parsing syntax error is:\n\n%s" % (f, e)
return m
#-------------------------------------------------------------------------------
# Simple class wich emulate a basic dictionary, but allows to make
# everytimes verification on values and keys
#-------------------------------------------------------------------------------
class Dico:
"""
This define a simple class in order to store informations about the case.
These informations are useful only for the current session, and are
forgotten for the next one.
"""
def __init__(self):
"""
Create a dictionary and the associated key.
"""
self.data = {}
self.data['new'] = ""
self.data['saved'] = "yes"
self.data['prepro'] = True
self.data['xmlfile'] = ""
self.data['mesh_path'] = ""
self.data['user_src_path'] = ""
self.data['data_path'] = ""
self.data['resu_path'] = ""
self.data['scripts_path'] = ""
self.data['relevant_subdir'] = "no"
self.data['case_path'] = ""
self.data['runcase'] = False
self.data['batch'] = None
self.data['no_boundary_conditions'] = False
self.data['salome'] = False
self.data['package'] = None
self.data['current_page'] = ""
self.data['current_index'] = None
self.data['current_tab'] = -1
self.data['undo'] = []
self.data['redo'] = []
self.data['probes'] = None
def _errorExit(self, msg):
"""
"""
print('CASE DICO ERROR')
raise ValueError(msg)
def __setitem__(self, key, name):
"""
Store values in the data dictionary when the key exists
in the dictionary.
"""
if hasattr(self, 'data'):
if key in self.data:
self.data[key] = name
else:
msg = "There is an error in the use of the dictionary "+ \
"with the key named: " + key + ". \n" + \
"The application will finish.\n" \
"Please contact the development team."
print(self._errorExit(msg))
def __getitem__(self, key):
"""
Extraction of informations from the data dictionary.
"""
if hasattr(self, 'data'):
if key in self.data:
return self.data[key]
else:
return None
def printDico(self):
"""
Simple tool wich prints the dictionary contents on the current terminal.
"""
if hasattr(self, 'data'):
for i in list(self.data.keys()):
print("%s -> %s" % (i, self.data[i]))
#-------------------------------------------------------------------------------
# Lightweight XML constructor and reader
#-------------------------------------------------------------------------------
if sys.version[0] == '2':
from types import UnicodeType
def _encode(v):
"""
return a byte string. This function handles the Unicode encoding.
minidom handles only byte strings, see: http://evanjones.ca/python-utf8.html
"""
if isinstance(v, UnicodeType):
v = v.encode("utf-8")
return v
else:
def _encode(v):
"""
return an utf-8 byte string. In Python 3, this is a No-op.
"""
return v
class XMLElement:
"""
"""
def __init__(self, doc, el, case):
"""
Constructor.
"""
self.doc = doc
self.el = el
self.ca = case
def _errorExit(self, msg):
"""
"""
print('XML ERROR')
raise ValueError(msg)
if sys.version[0] == '2':
def toString(self):
"""
Print the XMLElement node to a simple string (without \n and \t).
Unicode characters are encoded.
"""
return self.el.toxml("utf-8")
else:
def toString(self):
"""
Print the XMLElement node to a simple string (without \n and \t).
Unicode characters are encoded.
"""
# self.el.toxml() would be enough, except for the root node,
# where the encoding type is written only where specified.
return self.el.toxml("utf-8").decode()
if sys.version[0] == '2':
def toUnicodeString(self):
"""
Print the XMLElement node to an unicode string (without \n and \t).
Unicode string are decoded if it's possible by the standard output,
if not unicode characters are replaced by '?' character.
Warning: do not use this method for comparison purposes!
"""
unicode_obj = self.el.toxml()
try:
return unicode_obj.encode("utf-8", 'replace')
except:
return unicode_obj.encode(sys.stdout.encoding, 'replace')
else:
def toUnicodeString(self):
"""
Print the XMLElement node to an unicode string (without \n and \t).
Unicode string are decoded if it's possible by the standard output,
if not unicode characters are replaced by '?' character.
Warning: do not use this method for comparison purposes!
"""
try:
# self.el.toxml() would be enough, except for the root node,
# where the encoding type is written only where specified.
return self.el.toxml("utf-8").decode()
except:
unicode_obj = self.toxml(encoding=sys.stdout.encoding)
return unicode_obj.decode()
if sys.version[0] == '2':
def __str__(self):
"""
Print the XMLElement node with \n and \t.
Unicode string are decoded if it's possible by the standard output,
if not unicode characters are replaced by '?' character.
Warning: do not use this method for comparison purpose!
"""
unicode_obj = self.el.toprettyxml()
try:
return unicode_obj.encode("utf-8", 'replace')
except:
return unicode_obj.encode(sys.stdout.encoding, 'replace')
else:
def __str__(self):
"""
Print the XMLElement node with \n and \t.
Unicode string are decoded if it's possible by the standard output,
if not unicode characters are replaced by '?' character.
Warning: do not use this method for comparison purpose!
"""
try:
# self.el.toprettyxml() would be enough, except for the root,
# where the encoding type is written only where specified.
return self.el.toprettyxml("utf-8").decode()
except:
unicode_obj = self.el.toprettyxml(encoding=sys.stdout.encoding)
return unicode_obj.decode()
def __xmlLog(self):
"""Convenient method for log"""
if self.el.hasChildNodes() and len(self.el.childNodes) > 1:
return "\n" + self.__str__()
else:
return self.toUnicodeString()
def _inst(self, el):
"""
Transform a Element node to an instance of the XMLElement class.
"""
return XMLElement(self.doc, el, self.ca)
def xmlCreateAttribute(self, **kwargs):
"""
Set attributes to a XMLElement node, only if these attributes
does not allready exist.
"""
if self.ca: self.ca.modified()
for attr, value in list(kwargs.items()):
if not self.el.hasAttribute(attr):
self.el.setAttribute(attr, _encode(str(value)))
log.debug("xmlCreateAttribute-> %s" % self.__xmlLog())
def xmlGetAttributeDictionary(self):
"""
Return the dictionary of the XMLElement node attributes.
"""
d = {}
if self.el.nodeType == Node.ELEMENT_NODE:
if self.el.hasAttributes():
attrs = self.el._get_attributes()
a_names = list(attrs.keys())
a_names.sort()
for a_name in a_names:
d[a_name] = attrs[a_name].value
return d
def xmlGetAttribute(self, attr):
"""
Return the value of the XMLElement node attribute.
Crash if the searched attribute does not exist.
"""
if not self.el.hasAttribute(attr):
node = self.__str__()
attr = attr.encode(sys.stdout.encoding,'replace')
msg = "There is an error in with the elementNode: \n\n" \
+ node + "\n\nand the searching attribute: \n\n" \
+ attr + "\n\nThe application will finish."
self._errorExit(msg)
else:
a = self.el.getAttributeNode(attr)
return _encode(a.value)
def xmlSetAttribute(self, **kwargs):
"""
Set several attribute (key=value) to a node
"""
if self.ca: self.ca.modified()
for attr, value in list(kwargs.items()):
self.el.setAttribute(attr, _encode(str(value)))
log.debug("xmlSetAttribute-> %s" % self.__xmlLog())
def xmlDelAttribute(self, attr):
"""
Delete the XMLElement node attribute
"""
if self.ca: self.ca.modified()
if self.el.hasAttribute(attr):
self.el.removeAttribute(attr)
log.debug("xmlDelAttribute-> %s %s" % (attr, self.__xmlLog()))
def __getitem__(self, attr):
"""
Return the XMLElement attribute's value
with a dictionary syntaxe: node['attr']
Return None if the searched attribute does not exist.
"""
a = self.el.getAttributeNode(attr)
if a:
return _encode(a.value)
return None
def __setitem__(self, attr, value):
"""
Set a XMLElement attribute an its value
with a dictionary syntaxe: node['attr'] = value
"""
if self.ca: self.ca.modified()
self.el.setAttribute(attr, _encode(str(value)))
log.debug("__setitem__-> %s" % self.__xmlLog())
def __delitem__(self, name):
"""
Delete a XMLElement attribute with a dictionary syntaxe: del node['attr']
"""
if self.ca: self.ca.modified()
self.xmlDelAttribute(name)
#log.debug("__delitem__-> %s" % self.__xmlLog())
def xmlSortByTagName(self):
"""
Return a dictionary which keys are the name of the node.
"""
d = {}
for node in self.el.childNodes:
if node.nodeType == Node.ELEMENT_NODE:
dd = self._inst(node).xmlGetAttributeDictionary()
key = node.tagName
for k in list(dd.keys()): key = key + (k+dd[k])
d[key] = self._inst(node)
elif node.nodeType == Node.TEXT_NODE:
try:
k = float(node.data)
except:
k = node.data
d[k] = self._inst(node)
return d
def __cmp__(self, other):
"""
Return 0 if two XMLElement are the same, return 1 otherwise.
"""
if not other:
return 1
if not isinstance(other, XMLElement):
return 1
if self.el.nodeType == Node.ELEMENT_NODE:
if self.el.tagName != other.el.tagName:
return 1
elif self.el.nodeType == Node.TEXT_NODE:
try:
a = float(self.el.data)
b = float(other.el.data)
except:
a = self.el.data
b = other.el.data
if a != b:
return 1
if self.xmlGetAttributeDictionary() != other.xmlGetAttributeDictionary():
return 1
d1 = self.xmlSortByTagName()
d2 = other.xmlSortByTagName()
l1 = list(d1.keys())
l2 = list(d2.keys())
l1.sort()
l2.sort()
if l1 != l2:
return 1
if self.el.childNodes and other.el.childNodes:
for key in list(d1.keys()):
if d1[key] != d2[key]:
return 1
return 0
if sys.version[0] > '2':
def __eq__(self, other):
"""
Compare two XMLDocument nodes equivalence.
"""
if self.__cmp__(other) == 1:
return False
else:
return True
def __ne__(self, other):
"""
Compare two XMLDocument nodes equivalence.
"""
if self.__cmp__(other) == 1:
return True
else:
return False
def _nodeList(self, tag, *attrList, **kwargs):
"""
Return a list of Element (and not XMLElement)!
"""
nodeList = []
# Get the nodes list
#
nodeL = self.el.getElementsByTagName(tag)
# If there is a precision for the selection
#
#TRYME
## for attr in attrList:
## for node in nodeL:
## if node.hasAttribute(attr) and node not in nodeList:
## nodeList.append(node)
## if attrList and kwargs:
## nodeL = nodeList
## nodeList = []
## for k, v in kwargs.items():
## for node in nodeL:
## if node.getAttribute(k) == v and node not in nodeList:
## nodeList.append(node)
for node in nodeL:
iok = 0
for attr in attrList:
if node.hasAttribute(str(attr)):
iok = 1
else:
iok = 0
break
if iok: nodeList.append(node)
if attrList and kwargs:
nodeL = nodeList
nodeList = []
for node in nodeL:
iok = 0
for k, v in list(kwargs.items()):
if node.getAttribute(str(k)) == str(v):
iok = 1
else:
iok = 0
break
if iok: nodeList.append(node)
#TRYME
if not attrList and not kwargs:
nodeList = nodeL
return nodeList
def _childNodeList(self, tag, *attrList, **kwargs):
"""
Return a list of first child Element node from the explored XMLElement node.
"""
nodeList = self._nodeList(tag, *attrList, **kwargs)
childNodeList = []
if self.el.hasChildNodes():
for node in self.el.childNodes:
if node.nodeType == Node.ELEMENT_NODE:
if node.nodeName == tag and node in nodeList:
childNodeList.append(node)
return childNodeList
def xmlAddChild(self, tag, *attrList, **kwargs):
"""
Add a new XMLElement node as a child of the current
XMLElement node (i.e. self), with attributes and value.
"""
if self.ca: self.ca.modified()
el = self.doc.createElement(tag)
for k in attrList:
el.setAttribute(k, "")
for k, v in list(kwargs.items()):
el.setAttribute(k, _encode(str(v)))
nn = None
for n in self.el.childNodes:
if n.nodeType == self.doc.ELEMENT_NODE:
if sorted([n.nodeName, tag]) != [n.nodeName, tag]:
nn = n
break
if tag == "variable" and n.nodeName == "variable":
name1 = n.getAttributeNode("name").value
name2 = el.getAttributeNode("name").value
if sorted([name1, name2]) != [name1, name2]:
nn = n
break
if tag == "property" and n.nodeName == "property":
name1 = n.getAttributeNode("name").value
name2 = el.getAttributeNode("name").value
if sorted([name1, name2]) != [name1, name2]:
nn = n
break
log.debug("xmlAddChild-> %s %s" % (tag, self.__xmlLog()))
return self._inst(self.el.insertBefore(el, nn))
def xmlSetTextNode(self, newTextNode):
"""
Replace old text value of a TEXT_NODE by the new one.
If the elementNode 'node' has no TEXT_NODE as childNodes,
it will be created.
"""
if self.ca: self.ca.modified()
if newTextNode == "" or newTextNode == None : return
if type(newTextNode) != str: newTextNode = str(newTextNode)
if self.el.hasChildNodes():
for n in self.el.childNodes:
if n.nodeType == Node.TEXT_NODE:
n.data = _encode(newTextNode)
else:
self._inst(
self.el.appendChild(
self.doc.createTextNode(_encode(newTextNode))))
log.debug("xmlSetTextNode-> %s" % self.__xmlLog())
def xmlSetData(self, tag, textNode, *attrList, **kwargs):
"""
Set the textNode in an elementNode, which is a single node.
If the searched 'tag' doesn't exist, it is create
and textNode is added as a child TEXT_NODE nodeType.
Return a XMLElement list of the created Node.
"""
# First we convert textNode in string, if necessary.
# About the precision display read :
# "B. Floating Point Arithmetic: Issues and Limitations
# http://www.python.org/doc/current/tut/node14.html"
#
if type(textNode) == float: textNode = str("%.12g" % (textNode))
nodeList = self._childNodeList(tag, *attrList, **kwargs)
elementList = []
# Add a new ELEMENT_NODE and a new TEXT_NODE
# or replace an existing TEXT_NODE
#
if not nodeList:
child = self.xmlAddChild(tag, *attrList, **kwargs)
child.xmlSetTextNode(textNode)
elementList.append(child)
else:
for node in nodeList:
child = self._inst(node)
child.xmlSetTextNode(textNode)
elementList.append(child)
return elementList
def xmlGetTextNode(self, sep=" "):
"""
"""
rc = []
if self.el.hasChildNodes():
for node in self.el.childNodes:
if node.nodeType == node.TEXT_NODE:
rc.append(node.data)
return _encode(sep.join(rc))
else:
return None
def xmlGetStringList(self, tag, *attrList, **kwargs):
"""
Return a list of TEXT_NODE associed to the tagName elements
from the explored elementNode.
"""
stringList = []
nodeList = self._nodeList(tag, *attrList, **kwargs)
if nodeList:
for node in nodeList:
data = self._inst(node).xmlGetTextNode()
if data:
stringList.append(data)
return stringList
def xmlGetChildStringList(self, tag, *attrList, **kwargs):
"""
Return a list of TEXT_NODE associed to the tagName elements
from the explored elementNode.
"""
stringList = []
nodeList = self._childNodeList(tag, *attrList, **kwargs)
if nodeList:
for node in nodeList:
data = self._inst(node).xmlGetTextNode()
if data:
stringList.append(data)
return stringList
def xmlGetIntList(self, tag, *attrList, **kwargs):
"""
Return a list of integer insteed of a list of one string.
"""
intList = []
stringList = self.xmlGetStringList(tag, *attrList, **kwargs)
for s in stringList:
try:
intList.append(int(s))
except:
pass
return intList
def xmlGetString(self, tag, *attrList, **kwargs):
"""
Just verify that te returned list contains only one string variable.
Return a string and not a list of one string.
"""
stringList = self.xmlGetStringList(tag, *attrList, **kwargs)
if stringList:
if len(stringList) == 1:
string = stringList[0]
else:
msg = "There is an error in with the use of the xmlGetString method. "\
"There is more than one occurence of the tagName: " + tag
self._errorExit(msg)
else:
string = ""
return string
def xmlGetChildString(self, tag, *attrList, **kwargs):
"""
Just verify that te returned list contains only one string variable.
Return a string and not a list of one string.
"""
stringList = self.xmlGetChildStringList(tag, *attrList, **kwargs)
if stringList:
if len(stringList) == 1:
string = stringList[0]
else:
msg = "There is an error in with the use of the xmlGetChildString method. "\
"There is more than one occurence of the tagName: " + tag
self._errorExit(msg)
else:
string = ""
return string
def xmlGetInt(self, tag, *attrList, **kwargs):
"""
Just verify that te returned list contains only one string variable.
Return an integer and not a list of one string.
"""
stringList = self.xmlGetStringList(tag, *attrList, **kwargs)
if stringList:
if len(stringList) == 1:
try:
integer = int(stringList[0])
except:
integer = None
else:
msg = "There is an error in with the use of the xmlGetInt method. "\
"There is more than one occurence of the tagName: " + tag
self._errorExit(msg)
else:
integer = None
return integer
def xmlGetDouble(self, tag, *attrList, **kwargs):
"""
Just verify that the returned list contains only one string variable.
Return a float and not a list of one string.
"""
stringList = self.xmlGetStringList(tag, *attrList, **kwargs)
if stringList:
if len(stringList) == 1:
try:
double = float(stringList[0])
except:
double = None
else:
msg = "There is an error in with the use of the xmlGetDouble method. "\
"There is more than one occurence of the tagName: " + tag
self._errorExit(msg)
else:
double = None
return double
def xmlGetChildDouble(self, tag, *attrList, **kwargs):
"""
Just verify that te returned list contains only one string variable.
Return a float and not a list of one string.
"""
stringList = self.xmlGetChildStringList(tag, *attrList, **kwargs)
if stringList:
if len(stringList) == 1:
try:
double = float(stringList[0])
except:
double = None
else:
msg = "There is an error in with the use of the xmlGetChildDouble method. "\
"There is more than one occurence of the tagName: " + tag
self._errorExit(msg)
else:
double = None
return double
def xmlAddComment(self, data):
"""
Create a comment XMLElement node.
"""
if self.ca: self.ca.modified()
elt = self._inst( self.el.appendChild(self.doc.createComment(data)) )
log.debug("xmlAddComment-> %s" % self.__xmlLog())
return elt
def xmlGetNodeList(self, tag, *attrList, **kwargs):
"""
Return a list of XMLElement nodes from the explored
XMLElement node (i.e. self).
"""
return list(map(self._inst, self._nodeList(tag, *attrList, **kwargs)))
def xmlGetNode(self, tag, *attrList, **kwargs):
"""
Return a single XMLElement node from the explored elementNode.
The returned element is an instance of the XMLElement class.
"""
nodeList = self._nodeList(tag, *attrList, **kwargs)
if len(nodeList) > 1:
msg = "There is an error in with the use of the xmlGetNode method. "\
"There is more than one occurence of the tag: " + tag
for n in nodeList: msg += "\n" + self._inst(n).__str__()
self._errorExit(msg)
elif len(nodeList) == 1:
return self._inst(nodeList[0])
else:
return None
def xmlGetChildNodeList(self, tag, *attrList, **kwargs):
"""
Return a list of XMLElement nodes from the explored elementNode.
Each element of the returned list is an instance of the XMLElement
class.
"""
return list(map(self._inst, self._childNodeList(tag, *attrList, **kwargs)))
def xmlGetChildNode(self, tag, *attrList, **kwargs):
"""
Return a single XMLElement node from the explored elementNode.
The returned element is an instance of the XMLElement class.
"""
nodeList = self._childNodeList(tag, *attrList, **kwargs)
if len(nodeList) > 1:
msg = "There is an error in with the use of the xmlGetChildNode method. "\
"There is more than one occurence of the tag: " + tag
for n in nodeList: msg += "\n" + self._inst(n).__str__()
self._errorExit(msg)
elif len(nodeList) == 1:
return self._inst(nodeList[0])
else:
return None
def xmlInitNodeList(self, tag, *attrList, **kwargs):
"""
Each element of the returned list is an instance
of the XMLElement class.
"""
nodeList = self._nodeList(tag, *attrList, **kwargs)
if not nodeList:
child = self.xmlAddChild(tag, *attrList, **kwargs)
for k in attrList: child.el.setAttribute(k, "")
for k, v in list(kwargs.items()): child.el.setAttribute(k, _encode(str(v)))
nodeList.append(child)
else:
l = []
for node in nodeList: l.append(self._inst(node))
nodeList = l
return nodeList
def xmlInitChildNodeList(self, tag, *attrList, **kwargs):
"""
Each element of the returned list is an instance
of the XMLElement class.
"""
nodeList = self._childNodeList(tag, *attrList, **kwargs)
if not nodeList:
child = self.xmlAddChild(tag, *attrList, **kwargs)
for k in attrList: child.el.setAttribute(k, "")
for k, v in list(kwargs.items()): child.el.setAttribute(k, _encode(str(v)))
nodeList.append(child)
else:
l = []
for node in nodeList: l.append(self._inst(node))
nodeList = l
return nodeList
def xmlInitNode(self, tag, *attrList, **kwargs):
"""
Return a single XMLElement node from the explored elementNode.
If the tag does not exist, it will be created.
The returned element is an instance of the XMLElement class.
"""
nodeList = self._nodeList(tag, *attrList, **kwargs)
if not nodeList:
child = self.xmlAddChild(tag, *attrList, **kwargs)
for k in attrList: child.el.setAttribute(k, "")
for k, v in list(kwargs.items()): child.el.setAttribute(k, _encode(str(v)))
else:
if len(nodeList) > 1:
msg = "There is an error in with the use of the xmlInitNode method. "\
"There is more than one occurence of the tag: " + tag
for n in nodeList: msg += "\n" + self._inst(n).__str__()
self._errorExit(msg)
else:
child = self._inst(nodeList[0])
return child
def xmlInitChildNode(self, tag, *attrList, **kwargs):
"""
Return a single XMLElement child node from the explored elementNode.
If the tag does not exist, it will be created.
The returned element is an instance of the XMLElement class.
"""
nodeList = self._childNodeList(tag, *attrList, **kwargs)
if not nodeList:
child = self.xmlAddChild(tag, *attrList, **kwargs)
for k in attrList: child.el.setAttribute(k, "")
for k, v in list(kwargs.items()): child.el.setAttribute(k, _encode(str(v)))
else:
if len(nodeList) > 1:
msg = "There is an error in with the use of the xmlInitChildNode method. "\
"There is more than one occurence of the tag: " + tag
for n in nodeList: msg += "\n" + self._inst(n).__str__()
self._errorExit(msg)
else:
child = self._inst(nodeList[0])
return child
def xmlChildsCopy(self, oldNode, deep=1000):
"""
Copy all childsNode of oldNode to the node newNode.
'deep' is the childs and little-childs level of the copy.
"""
if self.ca: self.ca.modified()
if oldNode.el.hasChildNodes():
for n in oldNode.el.childNodes:
self._inst(self.el.appendChild(n.cloneNode(deep)))
log.debug("xmlChildsCopy-> %s" % self.__xmlLog())
def xmlRemoveNode(self):
"""
Destroy a single node.
"""
if self.ca: self.ca.modified()
oldChild = self.el.parentNode.removeChild(self.el)
oldChild.unlink()
def xmlRemoveChild(self, tag, *attrList, **kwargs):
"""
Destroy the nodeList found with 'tag' and
'attrList'/'kwargs' if they exist.
"""
for node in self._nodeList(tag, *attrList, **kwargs):
self._inst(node).xmlRemoveNode()
log.debug("xmlRemoveChild-> %s %s" % (tag, self.__xmlLog()))
def xmlNormalizeWhitespace(self, text):
"""
return a string without redundant whitespace.
"""
# This function is important even if it is single line.
# XML treats whitespace very flexibly; you can
# include extra spaces or newlines wherever you like. This means that
# you must normalize the whitespace before comparing attribute values or
# element content; otherwise the comparison might produce a wrong
# result due to the content of two elements having different amounts of
# whitespace.
return " ".join(text.split())
class XMLDocument(XMLElement):
"""
"""
def __init__(self, case=None, tag=None, *attrList, **kwargs):
"""
"""
self.doc = Document()
self.case = case
XMLElement.__init__(self, self.doc, self.doc, self.case)
if tag:
self.el = self.xmlAddChild(tag, *attrList, **kwargs).el
def root(self):
"""
This function return the only one root element of the document
(higher level of ELEMENT_NODE after the <?xml version="2.0" ?> markup).
"""
return self._inst(self.doc.documentElement)
if sys.version[0] == '2':
def toPrettyString(self):
"""
Return the XMLDocument to a byte string with \n and \t.
Unicode characters are encoded.
"""
return self.doc.toprettyxml(encoding = "utf-8")
else:
def toPrettyString(self):
"""
Return the XMLDocument to a string with \n and \t.
"""
return self.doc.toprettyxml(encoding = "utf-8").decode()
if sys.version[0] == '2':
def toPrettyUnicodeString(self):
"""
Return the XMLDocument node to a byte string with \n and \t.
Unicode string are decoded if it's possible by the standard output,
if not unicode characters are replaced by '?' character.
Warning: the returned XMLDocument do not show the encoding in the
header, because it is already encoded!
Warning: do not use this method for comparison purpose!
"""
unicode_obj = self.el.toprettyxml()
try:
return unicode_obj.encode("utf-8",'replace')
except:
return unicode_obj.encode(sys.stdout.encoding,'replace')
else:
def toPrettyUnicodeString(self):
"""
Return the XMLDocument node to a byte string with \n and \t.
Unicode string are decoded if it's possible by the standard output,
if not unicode characters are replaced by '?' character.
Warning: the returned XMLDocument do not show the encoding in the
header, because it is already encoded!
Warning: do not use this method for comparison purposes!
"""
try:
return self.el.toprettyxml("utf-8").decode()
except:
unicode_obj = self.el.toprettyxml(encoding=sys.stdout.encoding)
return unicode_obj.decode()
def __str__(self):
"""
Print the XMLDocument node with \n and \t.
Unicode string are decoded if it's possible by the standard output,
if not unicode characters are replaced by '?' character.
Warning: the returned XMLDocument do not show the encoding in the
header, because it is already encoded!
Warning: do not use this method for comparison purpose!
"""
return self.toPrettyUnicodeString()
def parse(self, d):
"""
return a xml doc from a file
"""
self.doc = self.el = parse(d)
return self
def parseString(self, d):
"""
return a xml doc from a string
"""
self.doc = self.el = parseString(_encode(d))
return self
def xmlCleanAllBlank(self, node):
"""
Clean a previous XMLElement file. The purpose of this method
is to delete all TEXT_NODE which are "\n" or "\t".
It is a recursive method.
"""
if isinstance(node, XMLElement):
node = node.el
if 'formula' not in node.tagName:
for n in node.childNodes:
if n.nodeType == Node.TEXT_NODE:
n.data = self.xmlNormalizeWhitespace(n.data)
else:
for n in node.childNodes:
if n.nodeType == Node.TEXT_NODE:
while n.data[0] in (" ", "\n", "\t"):
n.data = n.data[1:]
while n.data[-1] in (" ", "\n", "\t"):
n.data = n.data[:-1]
node.normalize()
for n in node.childNodes:
if n.nodeType == Node.TEXT_NODE:
if n.data == "":
old_child = node.removeChild(n)
old_child.unlink()
for n in node.childNodes:
if n.nodeType == Node.ELEMENT_NODE:
if n.hasChildNodes(): self.xmlCleanAllBlank(n)
def xmlCleanHightLevelBlank(self, node):
"""
This method deletes TEXT_NODE which are "\n" or "\t" in the
hight level of the ELEMENT_NODE nodes. It is a recursive method.
"""
if isinstance(node, XMLElement):
node = node.el
elementNode = 0
for n in node.childNodes:
if n.nodeType == Node.ELEMENT_NODE:
elementNode = 1
if n.hasChildNodes():
self.xmlCleanHightLevelBlank(n)
if 'formula' not in node.tagName:
for n in node.childNodes:
if n.nodeType == Node.TEXT_NODE and not elementNode:
self.xmlCleanAllBlank(n.parentNode)
else:
for n in node.childNodes:
if n.nodeType == Node.TEXT_NODE:
while n.data[0] in (" ", "\n", "\t"):
n.data = n.data[1:]
while n.data[-1] in (" ", "\n", "\t"):
n.data = n.data[:-1]
#-------------------------------------------------------------------------------
# XML utility functions
#-------------------------------------------------------------------------------
class Case(Dico, XMLDocument, QObject):
def __init__(self, package=None, file_name=""):
"""
Instantiate a new dico and a new xml doc
"""
Dico.__init__(self)
XMLDocument.__init__(self, case=self)
QObject.__init__(self)
if package:
self['package'] = package
rootNode = '<' + self['package'].code_name +'_GUI study="" case="" version="2.0"/>'
else:
rootNode = '<' + '_GUI study="" case="" version="2.0"/>'
if file_name:
self.parse(file_name)
self['new'] = "no"
self['saved'] = "yes"
else:
self.parseString(rootNode)
self['new'] = "yes"
self['saved'] = "yes"
self.record_func_prev = None
self.record_argument_prev = None
self.record_local = False
self.record_global = True
self.xml_prev = ""
def xmlRootNode(self):
"""
This function return the only one root element of the document
(higher level of ELEMENT_NODE).
"""
return self.doc.documentElement
def modified(self):
"""
Return if the xml doc is modified.
"""
self['saved'] = "no"
def isModified(self):
"""
Return True if the xml doc is modified.
"""
return self['saved'] == "no"
def __del__(self):
"""
What to do when the instance of Case is deleted.
"""
if hasattr(self, 'data'):
delattr(self, 'data')
if hasattr(self, 'doc'):
self.doc.unlink()
delattr(self, 'doc')
def __str__(self):
"""
Print on the current terminal the contents of the case.
"""
self.printDico()
return self.toPrettyUnicodeString()
def xmlSaveDocument(self):
"""
This method writes the associated xml file.
See saveCase and saveCaseAs methods in the Main module.
"""
try:
d = XMLDocument().parseString(self.toPrettyString())
d.xmlCleanHightLevelBlank(d.root())
file = open(self['xmlfile'], 'w')
file.write(d.toString())
file.close()
self['new'] = "no"
self['saved'] = "yes"
d.doc.unlink()
except IOError:
msg = "Error: unable to save the XML document file." ,
"(XMLengine module, Case class, xmlSaveDocument method)"
print(msg)
def undoStop(self):
self.record_local = True
def undoStart(self):
self.record_local = False
def undoStopGlobal(self):
self.record_global = False
def undoStartGlobal(self):
self.record_global = True
def undoGlobal(self, f, c):
if self['current_page'] != '' and self.record_local == False and self.record_global == True:
if self.xml_prev != self.toString() or self.xml_prev == "":
# control if function have same arguments
# last argument is value
same = True
if self.record_argument_prev == None:
same = False
elif (len(c) == len(self.record_argument_prev) and len(c) >= 2):
for i in range(0, len(c)-1):
if c[i] != self.record_argument_prev[i]:
same = False
if same:
pass
else:
self['undo'].append([self['current_page'], self.toString(), self['current_index'], self['current_tab']])
self.xml_prev = self.toString()
self.record_func_prev = None
self.record_argument_prev = c
self.emit(SIGNAL("undo"))
def undo(self, f, c):
if self['current_page'] != '' and self.record_local == False and self.record_global == True:
if self.xml_prev != self.toString():
# control if function have same arguments
# last argument is value
same = True
if self.record_argument_prev == None:
same = False
elif (len(c) == len(self.record_argument_prev) and len(c) >= 2):
for i in range(0, len(c)-1):
if c[i] != self.record_argument_prev[i]:
same = False
if self.record_func_prev == f and same:
pass
else:
self.record_func_prev = f
self.record_argument_prev = c
self['undo'].append([self['current_page'], self.toString(), self['current_index'], self['current_tab']])
self.xml_prev = self.toString()
self.emit(SIGNAL("undo"))
#-------------------------------------------------------------------------------
# XMLengine test case
#-------------------------------------------------------------------------------
class XMLengineTestCase(unittest.TestCase):
def setUp(self):
"""This method is executed before all "check" methods."""
self.doc = XMLDocument()
def tearDown(self):
"""This method is executed after all "check" methods."""
self.doc.doc.unlink()
def xmlNewFile(self):
"""Private method to return a xml document."""
return \
u'<root><first/><market><cucumber/><fruits color="red"/></market></root>'
def xmlNodeFromString(self, string):
"""Private method to return a xml node from string"""
return self.doc.parseString(string).root()
def checkXMLDocumentInstantiation(self):
"""Check whether the Case class could be instantiated."""
xmldoc = None
tag = None
xmldoc = XMLDocument(tag=tag)
assert xmldoc, 'Could not instantiate XMLDocument'
def checkXmlAddChild(self):
"""Check whether a node child could be added."""
node = self.doc.xmlAddChild("table", name="test")
node.xmlAddChild("field", "label", name="info", type="text")
truc = node.toString()
doc = '<table name="test">'\
'<field label="" name="info" type="text"/>'\
'</table>'
assert doc == truc, 'Could not use the xmlAddChild method'
def checkNodeList(self):
"""Check whether a node could be found if it does exist."""
xmldoc = self.doc.parseString(self.xmlNewFile())
node = '<fruits color="red"/>'
nodeList = xmldoc._nodeList('fruits')
truc = nodeList[0].toxml()
assert node == truc, 'Could not use the _nodeList method'
nodeList = xmldoc._nodeList('fruits', 'color')
truc = nodeList[0].toxml()
assert node == truc, 'Could not use the _nodeList method'
nodeList = xmldoc._nodeList('fruits', color="red")
truc = nodeList[0].toxml()
assert node == truc, 'Could not use the _nodeList method'
def checkChildNodeList(self):
"""Check whether a child node could be found if it does exist."""
xmldoc = self.doc.parseString(self.xmlNewFile())
n = self.doc._inst(xmldoc.doc.firstChild.childNodes[1])
node = '<fruits color="red"/>'
nodeList = n._childNodeList('fruits')
truc = nodeList[0].toxml()
assert node == truc, 'Could not use the _childNodeList method'
nodeList = n._childNodeList('fruits', 'color')
truc = nodeList[0].toxml()
assert node == truc, 'Could not use the _childNodeList method'
nodeList = n._childNodeList('fruits', color="red")
truc = nodeList[0].toxml()
assert node == truc, 'Could not use the _childNodeList method'
nodeList = xmldoc._childNodeList('fruits', color="red")
self.failUnless(nodeList==[], 'Could not use the _childNodeList method')
def checkXmlInitNodeList(self):
"""Check whether a node child list could be get."""
nList1 = self.doc.xmlInitNodeList("table", name="test")
nList2 = nList1[0].xmlInitNodeList("field", "label", name="info", type="text")
truc = nList1[0].toString()
doc = '<table name="test">'\
'<field label="" name="info" type="text"/>'\
'</table>'
assert doc == truc, 'Could not use the xmlInitNodeList method'
xmldoc = self.doc.parseString(self.xmlNewFile())
node = '<fruits color="red"/>'
nodeList = xmldoc.xmlInitNodeList('fruits')
truc = nodeList[0].toString()
assert node == truc, 'Could not use the xmlInitNodeList method'
nodeList = xmldoc.xmlInitNodeList('fruits', 'color')
truc = nodeList[0].toString()
assert node == truc, 'Could not use the xmlInitNodeList method'
nodeList = xmldoc.xmlInitNodeList('fruits', color="red")
truc = nodeList[0].toString()
assert node == truc, 'Could not use the xmlinitNodeList method'
def checkXmlInitNode(self):
"""Check whether a node child could be get."""
n1 = self.doc.xmlInitNode("table", name="test")
n2 = n1.xmlInitNode("field", "label", name="info", type="text")
truc = n1.toString()
doc = '<table name="test">'\
'<field label="" name="info" type="text"/>'\
'</table>'
assert doc == truc, 'Could not use the xmlInitNodeList method'
xmldoc = self.doc.parseString(self.xmlNewFile())
node = '<fruits color="red"/>'
truc = xmldoc.xmlInitNode('fruits').toString()
assert node == truc, 'Could not use the xmlInitNode method'
truc = xmldoc.xmlInitNode('fruits', 'color').toString()
assert node == truc, 'Could not use the xmlInitNode method'
truc = xmldoc.xmlInitNode('fruits', color="red").toString()
assert node == truc, 'Could not use the xmlInitNode method'
def checkXmlInitChildNodeList(self):
"""Check whether a child node list could be found if it does exist."""
xmldoc = self.doc.parseString(self.xmlNewFile())
thermo = self.doc._inst(xmldoc.doc.firstChild.childNodes[1])
truc = '<market><cucumber/><fruits color="red"/></market>'
assert thermo.toString() == truc, 'Could not use the firstChild.childNodes method'
node = '<fruits color="red"/>'
nodeList = thermo.xmlInitChildNodeList('fruits')
truc = nodeList[0].toString()
assert node == truc, 'Could not use the xmlInitChildNodeList method'
nodeList = thermo.xmlInitChildNodeList('fruits', 'color')
truc = nodeList[0].toString()
assert node == truc, 'Could not use the xmlInitChildNodeList method'
nodeList = thermo.xmlInitChildNodeList('fruits', color="red")
truc = nodeList[0].toString()
assert node == truc, 'Could not use the xmlInitChildNodeList method'
def checkXmlInitChildNode(self):
"""Check whether a node child could be get."""
n1 = self.doc.xmlInitChildNode("table", name="test")
n2 = n1.xmlInitChildNode("field", "label", name="info", type="text")
truc = n1.toString()
doc = '<table name="test">'\
'<field label="" name="info" type="text"/>'\
'</table>'
assert doc == truc, 'Could not use the xmlInitNodeList method'
xmldoc = self.doc.parseString(self.xmlNewFile())
thermo = self.doc._inst(xmldoc.doc.firstChild.childNodes[1])
node = '<fruits color="red"/>'
truc = thermo.xmlInitChildNode('fruits').toString()
assert node == truc, 'Could not use the xmlInitChildNode method'
truc = thermo.xmlInitChildNode('fruits', 'color').toString()
assert node == truc, 'Could not use the xmlInitChildNode method'
truc = thermo.xmlInitChildNode('fruits', color="red").toString()
assert node == truc, 'Could not use the xmlInitChildNode method'
def checkXmlGetNodeList(self):
"""Check whether a node list could be found if it does exist."""
xmldoc = self.doc.parseString(self.xmlNewFile())
node = '<fruits color="red"/>'
nodeList = xmldoc.xmlGetNodeList('fruits')
truc = nodeList[0].toString()
assert node == truc, 'Could not use the xmlGetNodeList method'
nodeList = xmldoc.xmlGetNodeList('fruits', 'color')
truc = nodeList[0].toString()
assert node == truc, 'Could not use the xmlGetNodeList method'
nodeList = xmldoc.xmlGetNodeList('fruits', color="red")
truc = nodeList[0].toString()
assert node == truc, 'Could not use the xmlGetNodeList method'
nodeList = xmldoc.xmlGetNodeList('fruits', color="red")
self.failIf(nodeList==[], 'Could not use the xmlGetNodeList method')
def checkXmlGetChildNodeList(self):
"""Check whether a child node list could be found if it does exist."""
xmldoc = self.doc.parseString(self.xmlNewFile())
thermo = self.doc._inst(xmldoc.doc.firstChild.childNodes[1])
node = '<fruits color="red"/>'
nodeList = thermo.xmlGetChildNodeList('fruits')
truc = nodeList[0].toString()
assert node == truc, 'Could not use the xmlGetChildNodeList method'
nodeList = thermo.xmlGetChildNodeList('fruits', 'color')
truc = nodeList[0].toString()
assert node == truc, 'Could not use the xmlGetChildNodeList method'
nodeList = thermo.xmlGetChildNodeList('fruits', color="red")
truc = nodeList[0].toString()
assert node == truc, 'Could not use the xmlGetChildNodeList method'
nodeList = xmldoc.xmlGetChildNodeList('fruits', color="red")
self.failUnless(nodeList==[], 'Could not use the xmlGetChildNodeList method')
def checkXmlGetNode(self):
"""Check whether a child node could be found if it does exist."""
xmldoc = self.doc.parseString(self.xmlNewFile())
node = '<fruits color="red"/>'
truc = xmldoc.xmlGetNode('fruits').toString()
assert node == truc, 'Could not use the xmlGetNode method'
truc = xmldoc.xmlGetNode('fruits', 'color').toString()
assert node == truc, 'Could not use the xmlGetNode method'
truc = xmldoc.xmlGetNode('fruits', color="red").toString()
assert node == truc, 'Could not use the xmlGetNode method'
empty = xmldoc.xmlGetNode('fruits', color="red")
assert empty, 'Could not use the xmlGetNode method'
def checkXmlGetChildNode(self):
"""Check whether a child node could be found if it does exist."""
xmldoc = self.doc.parseString(self.xmlNewFile())
n = self.doc._inst(xmldoc.doc.firstChild.childNodes[1])
node = '<fruits color="red"/>'
truc = n.xmlGetChildNode('fruits').toString()
assert node == truc, 'Could not use the xmlGetChildNode method'
truc = n.xmlGetChildNode('fruits', 'color').toString()
assert node == truc, 'Could not use the xmlGetChildNode method'
truc = n.xmlGetChildNode('fruits', color="red").toString()
assert node == truc, 'Could not use the xmlGetChildNode method'
empty = xmldoc.xmlGetChildNode('fruits', color="red")
self.failUnless(empty==None, 'Could not use the xmlGetChildNode method')
def checkXMLDocumentUnicodeParseString(self):
"""Check whether a XMLDocument with unicode string could be created."""
d = XMLDocument()
d.parseString(u'<fran\xe7ais> a=attach\xe9</fran\xe7ais>')
t = u'<?xml version="1.0" encoding="utf-8"?>' \
u'<fran\xe7ais> a=attach\xe9</fran\xe7ais>'
if sys.version[0] == '2':
t = t.encode("utf-8")
assert d.toString() == t, 'Could not use the parseString method with utf-8 encoding'
t = u'<?xml version="1.0" encoding="utf-8"?>\n' \
u'<fran\xe7ais> a=attach\xe9</fran\xe7ais>\n'
if sys.version[0] == '2':
t = t.encode("utf-8")
assert d.toPrettyString() == t, 'Could not use the parseString method with utf-8 encoding'
t = self.xmlNodeFromString(u'<fran\xe7ais> a=attach\xe9</fran\xe7ais>')
assert d.root() == t, 'Could not use the parseString method with utf-8 encoding'
def checkXmlNodeFromString(self):
""""Check whether two XML nodes could be compared."""
n1 = self.xmlNodeFromString(u'<fruits taste="ok" color="red"><a>toto</a><c a="2é"/></fruits>')
n2 = XMLDocument().parseString(u'<fruits color="red" taste="ok"><c a="2é"/><a>toto</a></fruits>').root()
assert n1 == n2, 'These two nodes are not identical'
n3 = self.xmlNodeFromString(u'<fruits><b/><a>123.0</a></fruits>')
n4 = XMLDocument().parseString(u'<fruits><a>123</a><b/></fruits>').root()
assert n3 == n4, 'These two nodes are not identical'
d1 = '<fruits><apple from="W" name="P"/><apple from="P"/></fruits>'
d2 = '<fruits><apple from="P"/><apple from="W" name="P"/></fruits>'
n5 = self.xmlNodeFromString(d1)
n6 = XMLDocument().parseString(d2).root()
assert n5 == n6, 'This two node are not identical'
d1 = '<velocity_pressure>'\
'<variable label="U" name="velocity_U"/>'\
'<variable label="V" name="velocity_V"/>'\
'<variable label="W" name="velocity_W"/>'\
'<variable label="P" name="pressure"/>'\
'</velocity_pressure>'
d2 = '<velocity_pressure>'\
'<variable label="P" name="pressure"/>'\
'<variable label="U" name="velocity_U"/>'\
'<variable label="V" name="velocity_V"/>'\
'<variable label="W" name="velocity_W"/>'\
'</velocity_pressure>'
n5 = self.xmlNodeFromString(d1)
n6 = XMLDocument().parseString(d2).root()
assert n5 == n6, 'This two node are not identical'
d1 = '<turbulence model="Rij-epsilon">'\
'<property label="turb. vi" name="turbulent_viscosity"/>'\
'<variable label="R11" name="component_R11"/>'\
'</turbulence>'
d2 = '<turbulence model="Rij-epsilon">'\
'<variable label="R11" name="component_R11"/>'\
'<property label="turb. vi" name="turbulent_viscosity"/>'\
'</turbulence>'
n5 = self.xmlNodeFromString(d1)
n6 = XMLDocument().parseString(d2).root()
assert n5 == n6, 'This two node are not identical'
def checkCaseInstantiation(self):
"""Check whether the Case class could be instantiated."""
case = None
case = Case()
assert case, 'Could not instantiate Case'
def checkCaseParseString(self):
"""Check whether a Case could be created."""
rootNode = '<' + '_GUI study="" case="" version="2.0"/>'
case = Case()
assert case.root() == self.xmlNodeFromString(rootNode), \
'Could not use the parseString method'
def checkXmlSaveDocument(self):
"""Check whether a Case could be save on the file system"""
case = Case()
case.parseString(u'<fruits color="red" taste="ok"><c a="2é">to</c></fruits>')
case['xmlfile'] = os.path.dirname(os.getcwd()) + "/ToTo"
if os.path.isfile(case['xmlfile']):
os.remove(case['xmlfile'])
case.xmlSaveDocument()
if not os.path.isfile(case['xmlfile']):
assert False, \
'Could not save the file ' + case['xmlfile']
d= case.parse(case['xmlfile'])
os.remove(case['xmlfile'])
d.xmlCleanAllBlank(d.root())
assert case.root() == d.root(), \
'Could not use the xmlSaveDocument method'
## def checkFailUnless(self):
## """Test"""
## self.failUnless(1==1, "One should be one.")
##
##
## def checkFailIf(self):
## """Test"""
## self.failIf(1==2,"I don't one to be one, I want it to be two.")
def suite():
"""unittest function"""
testSuite = unittest.makeSuite(XMLengineTestCase, "check")
return testSuite
def runTest():
"""unittest function"""
print("XMLengineTestCase to be completed...")
runner = unittest.TextTestRunner()
runner.run(suite())
#-------------------------------------------------------------------------------
# End of XMLengine
#-------------------------------------------------------------------------------
|