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
|
#!/usr/bin/env python
#
# Copyright (c), 2016-2020, SISSA (International School for Advanced Studies).
# All rights reserved.
# This file is distributed under the terms of the MIT License.
# See the file 'LICENSE' in the root directory of the present
# distribution, or http://opensource.org/licenses/MIT.
#
# @author Davide Brunato <brunato@sissa.it>
#
"""Tests concerning XML resources"""
import io
import unittest
import os
import contextlib
import copy
import pathlib
import platform
import warnings
from io import StringIO, BytesIO
from urllib.request import urlopen, build_opener, FileHandler
from urllib.response import addinfourl
from urllib.parse import urlsplit, uses_relative
from pathlib import Path, PurePath, PureWindowsPath
from xml.etree import ElementTree
try:
import lxml.etree as lxml_etree
except ImportError:
lxml_etree = None
from xmlschema import fetch_namespaces, fetch_resource, fetch_schema, \
fetch_schema_locations, XMLResource, XMLResourceError, XMLSchema
from xmlschema.names import XSD_NAMESPACE
from xmlschema.utils.etree import is_etree_element, is_lxml_element
from xmlschema.testing import SKIP_REMOTE_TESTS, XMLSchemaTestCase, run_xmlschema_tests
from xmlschema.utils.urls import normalize_url
from xmlschema.exceptions import XMLSchemaTypeError, XMLSchemaValueError, \
XMLResourceForbidden, XMLResourceBlocked, XMLResourceOSError
from xmlschema.resources import XMLResourceManager, iterfind_parser
from xmlschema.resources.sax import defuse_xml
DRIVE_REGEX = '(/[a-zA-Z]:|/)' if platform.system() == 'Windows' else ''
XML_WITH_NAMESPACES = '<pfa:root xmlns:pfa="http://xmlschema.test/nsa">\n' \
' <pfb:elem xmlns:pfb="http://xmlschema.test/nsb"/>\n' \
'</pfa:root>'
@contextlib.contextmanager
def working_dir(path):
current = Path().absolute()
try:
os.chdir(path)
yield
finally:
os.chdir(current)
def is_windows_path(path):
"""Checks if the path argument is a Windows platform path."""
return '\\' in path or ':' in path or '|' in path
def add_leading_slash(path):
return '/' + path if path and path[0] not in ('/', '\\') else path
def filter_windows_path(path):
if path.startswith('/\\'):
return path[1:]
elif path and path[0] not in ('/', '\\'):
return '/' + path
else:
return path
class TestResources(XMLSchemaTestCase):
cases_dir = pathlib.Path(__file__).absolute().parent.joinpath('test_cases')
@classmethod
def setUpClass(cls):
cls.vh_dir = cls.casepath('examples/vehicles')
cls.vh_xsd_file = cls.casepath('examples/vehicles/vehicles.xsd')
cls.vh_xml_file = cls.casepath('examples/vehicles/vehicles.xml')
cls.col_dir = cls.casepath('examples/collection')
cls.col_xsd_file = cls.casepath('examples/collection/collection.xsd')
cls.col_xml_file = cls.casepath('examples/collection/collection.xml')
def check_url(self, url, expected):
url_parts = urlsplit(url)
if urlsplit(expected).scheme not in uses_relative:
expected = add_leading_slash(expected)
expected_parts = urlsplit(expected, scheme='file')
self.assertEqual(url_parts.scheme, expected_parts.scheme,
"%r: Schemes differ." % url)
self.assertEqual(url_parts.netloc, expected_parts.netloc,
"%r: Netloc parts differ." % url)
self.assertEqual(url_parts.query, expected_parts.query,
"%r: Query parts differ." % url)
self.assertEqual(url_parts.fragment, expected_parts.fragment,
"%r: Fragment parts differ." % url)
if is_windows_path(url_parts.path) or is_windows_path(expected_parts.path):
path = PureWindowsPath(filter_windows_path(url_parts.path))
expected_path = PureWindowsPath(filter_windows_path(expected_parts.path))
else:
path = PurePath(url_parts.path)
expected_path = PurePath(expected_parts.path)
self.assertEqual(path, expected_path, "%r: Paths differ." % url)
def test_fetch_resource_function(self):
with self.assertRaises(ValueError) as ctx:
fetch_resource('')
self.assertIn('argument must contain a not empty string', str(ctx.exception))
wrong_path = self.casepath('resources/dummy_file.txt')
self.assertRaises(OSError, fetch_resource, wrong_path)
wrong_path = self.casepath('/home/dummy_file.txt')
self.assertRaises(OSError, fetch_resource, wrong_path)
filepath = self.casepath('resources/dummy file.txt')
self.assertTrue(fetch_resource(filepath).endswith('dummy%20file.txt'))
filepath = Path(self.casepath('resources/dummy file.txt')).relative_to(os.getcwd())
self.assertTrue(fetch_resource(str(filepath), '/home').endswith('dummy%20file.txt'))
filepath = self.casepath('resources/dummy file.xml')
self.assertTrue(fetch_resource(filepath).endswith('dummy%20file.xml'))
with urlopen(fetch_resource(filepath)) as res:
self.assertEqual(res.read(), b'<root>DUMMY CONTENT</root>')
with working_dir(pathlib.Path(__file__).parent):
filepath = 'test_cases/resources/dummy file.xml'
result = fetch_resource(filepath)
self.assertTrue(result.startswith('file://'))
self.assertTrue(result.endswith('dummy%20file.xml'))
base_url = "file:///wrong/base/url"
result = fetch_resource(filepath, base_url)
self.assertTrue(result.startswith('file://'))
self.assertTrue(result.endswith('dummy%20file.xml'))
def test_fetch_namespaces_function(self):
self.assertFalse(fetch_namespaces(self.casepath('resources/malformed.xml')))
def test_fetch_schema_locations_function(self):
schema_url, locations = fetch_schema_locations(self.col_xml_file)
self.check_url(schema_url, self.col_xsd_file)
self.assertEqual(locations[0][0], 'http://example.com/ns/collection')
self.check_url(locations[0][1], self.col_xsd_file)
with self.assertRaises(ValueError) as ctx:
fetch_schema_locations(self.col_xml_file, allow='none')
self.assertIn('not found a schema for', str(ctx.exception))
with self.assertRaises(ValueError) as ctx:
fetch_schema_locations('<empty/>')
self.assertEqual(
"provided arguments don't contain any schema location hint",
str(ctx.exception)
)
schema_url, locations_ = fetch_schema_locations('<empty/>', locations)
self.check_url(schema_url, self.col_xsd_file)
self.assertListEqual(locations, locations_)
locations = [('', self.casepath('resources/dummy file.xml'))]
with self.assertRaises(ValueError) as ctx:
fetch_schema_locations('<empty/>', locations)
self.assertIn('not found a schema for', str(ctx.exception))
with working_dir(pathlib.Path(__file__).parent):
locations = [('http://example.com/ns/collection',
'test_cases/examples/collection/collection.xsd')]
schema_url, locations_ = fetch_schema_locations('<empty/>', locations)
self.check_url(schema_url, self.col_xsd_file)
self.assertNotEqual(locations, locations_)
base_url = "file:///wrong/base/url"
with self.assertRaises(ValueError) as ctx:
fetch_schema_locations('<empty/>', locations, base_url)
self.assertIn('not found a schema for', str(ctx.exception))
def test_fetch_schema_function(self):
self.check_url(fetch_schema(self.vh_xml_file), self.vh_xsd_file)
# Tests on XMLResource instances
def test_xml_resource_representation(self):
resource = XMLResource(self.vh_xml_file)
self.assertTrue(str(resource).startswith(
"XMLResource(root=<Element '{http://example.com/vehicles}vehicles'"
))
def test_xml_resource_from_url(self):
resource = XMLResource(self.vh_xml_file, lazy=True)
self.assertEqual(resource.source, self.vh_xml_file)
self.assertEqual(resource.root.tag, '{http://example.com/vehicles}vehicles')
self.check_url(resource.url, self.vh_xml_file)
self.assertTrue(resource.filepath.endswith('vehicles.xml'))
self.assertIsNone(resource.text)
with self.assertRaises(XMLResourceError) as ctx:
resource.load()
self.assertIn('can\'t load a lazy XML resource', str(ctx.exception))
self.assertIsNone(resource.text)
resource = XMLResource(self.vh_xml_file, lazy=False)
self.assertEqual(resource.source, self.vh_xml_file)
self.assertEqual(resource.root.tag, '{http://example.com/vehicles}vehicles')
self.check_url(resource.url, self.vh_xml_file)
self.assertIsNone(resource.text)
resource.load()
self.assertTrue(resource.text.startswith('<?xml'))
resource = XMLResource(self.vh_xml_file, lazy=False)
resource.url = resource.url[:-12] + 'unknown.xml'
with self.assertRaises(XMLResourceOSError):
resource.load()
def test_xml_resource_from_url_in_bytes(self):
resource = XMLResource(self.vh_xml_file.encode('utf-8'), lazy=False)
self.assertEqual(resource.source, self.vh_xml_file.encode('utf-8'))
self.assertEqual(resource.root.tag, '{http://example.com/vehicles}vehicles')
self.check_url(resource.url, self.vh_xml_file)
self.assertIsNone(resource.text)
resource.load()
self.assertTrue(resource.text.startswith('<?xml'))
def test_xml_resource_from_path(self):
path = Path(self.vh_xml_file)
resource = XMLResource(path, lazy=True)
self.assertIs(resource.source, path)
self.assertEqual(resource.root.tag, '{http://example.com/vehicles}vehicles')
self.check_url(resource.url, path.as_uri())
self.assertTrue(resource.filepath.endswith('vehicles.xml'))
self.assertIsNone(resource.text)
with self.assertRaises(XMLResourceError) as ctx:
resource.load()
self.assertIn('can\'t load a lazy XML resource', str(ctx.exception))
self.assertIsNone(resource.text)
resource = XMLResource(path, lazy=False)
self.assertEqual(resource.source, path)
self.assertEqual(resource.root.tag, '{http://example.com/vehicles}vehicles')
self.check_url(resource.url, path.as_uri())
self.assertIsNone(resource.text)
resource.load()
self.assertTrue(resource.text.startswith('<?xml'))
resource = XMLResource(path, lazy=False)
resource.url = resource.url[:-12] + 'unknown.xml'
with self.assertRaises(XMLResourceOSError):
resource.load()
def test_xml_resource_from_element_tree(self):
vh_etree = ElementTree.parse(self.vh_xml_file)
vh_root = vh_etree.getroot()
resource = XMLResource(vh_etree)
self.assertEqual(resource.source, vh_etree)
self.assertEqual(resource.root.tag, '{http://example.com/vehicles}vehicles')
self.assertIsNone(resource.url)
self.assertIsNone(resource.filepath)
self.assertIsNone(resource.text)
resource.load()
self.assertIsNone(resource.text)
resource = XMLResource(vh_root)
self.assertEqual(resource.source, vh_root)
self.assertEqual(resource.root.tag, '{http://example.com/vehicles}vehicles')
self.assertIsNone(resource.url)
self.assertIsNone(resource.filepath)
self.assertIsNone(resource.text)
resource.load()
self.assertIsNone(resource.text)
@unittest.skipIf(lxml_etree is None, "Skip: lxml is not available.")
def test_xml_resource_from_lxml(self):
vh_etree = lxml_etree.parse(self.vh_xml_file)
vh_root = vh_etree.getroot()
resource = XMLResource(vh_etree)
self.assertEqual(resource.source, vh_etree)
self.assertEqual(resource.root.tag, '{http://example.com/vehicles}vehicles')
self.assertIsNone(resource.url)
self.assertIsNone(resource.filepath)
self.assertIsNone(resource.text)
resource.load()
self.assertIsNone(resource.text)
resource = XMLResource(vh_root)
self.assertEqual(resource.source, vh_root)
self.assertEqual(resource.root.tag, '{http://example.com/vehicles}vehicles')
self.assertIsNone(resource.url)
self.assertIsNone(resource.filepath)
self.assertIsNone(resource.text)
resource.load()
self.assertIsNone(resource.text)
xml_text = resource.get_text()
self.assertIn('<vh:vehicles ', xml_text)
self.assertIn('<!-- Comment -->', xml_text)
self.assertIn('</vh:vehicles>', xml_text)
def test_xml_resource_from_resource(self):
xml_file = urlopen(f'file://{add_leading_slash(self.vh_xml_file)}')
try:
resource = XMLResource(xml_file, lazy=False)
self.assertEqual(resource.source, xml_file)
self.assertEqual(resource.root.tag, '{http://example.com/vehicles}vehicles')
self.assertIsNone(resource.url)
self.assertIsNone(resource.text)
resource.load()
self.assertTrue(resource.text.startswith('<?xml'))
self.assertFalse(xml_file.closed)
finally:
xml_file.close()
with open(self.vh_xml_file) as fp:
resource = XMLResource(fp)
self.assertIsNone(resource.text)
with self.assertRaises(XMLResourceOSError):
resource.load()
def test_xml_resource_from_file(self):
with open(self.vh_xsd_file) as schema_file:
resource = XMLResource(schema_file, lazy=False)
self.assertEqual(resource.source, schema_file)
self.assertEqual(resource.root.tag, '{http://www.w3.org/2001/XMLSchema}schema')
self.assertIsNone(resource.url)
self.assertIsNone(resource.text)
resource.load()
self.assertTrue(resource.text.startswith('<xs:schema'))
self.assertFalse(schema_file.closed)
for _ in resource.iter():
pass
self.assertFalse(schema_file.closed)
for _ in resource.iter_depth():
pass
self.assertFalse(schema_file.closed)
with open(self.vh_xsd_file) as schema_file:
resource = XMLResource(schema_file, lazy=True)
self.assertEqual(resource.source, schema_file)
self.assertEqual(resource.root.tag, '{http://www.w3.org/2001/XMLSchema}schema')
self.assertIsNone(resource.url)
self.assertIsNone(resource.text)
with self.assertRaises(XMLResourceError) as ctx:
resource.load()
self.assertEqual("can't load a lazy XML resource", str(ctx.exception))
self.assertFalse(schema_file.closed)
for _ in resource.iter():
pass
self.assertFalse(schema_file.closed)
for _ in resource.iter_depth():
pass
self.assertFalse(schema_file.closed)
def test_xml_resource_from_string(self):
with open(self.vh_xsd_file) as schema_file:
schema_text = schema_file.read()
resource = XMLResource(schema_text, lazy=False)
self.assertEqual(resource.source, schema_text)
self.assertEqual(resource.root.tag, '{http://www.w3.org/2001/XMLSchema}schema')
self.assertIsNone(resource.url)
self.assertTrue(resource.text.startswith('<xs:schema'))
invalid_xml = '<tns0:root>missing namespace declaration</tns0:root>'
with self.assertRaises(ElementTree.ParseError) as ctx:
XMLResource(invalid_xml)
self.assertEqual(
str(ctx.exception), 'invalid XML syntax: unbound prefix: line 1, column 0'
)
def test_xml_resource_from_string_io(self):
with open(self.vh_xsd_file) as schema_file:
schema_text = schema_file.read()
schema_file = StringIO(schema_text)
resource = XMLResource(schema_file)
self.assertEqual(resource.source, schema_file)
self.assertEqual(resource.root.tag, '{http://www.w3.org/2001/XMLSchema}schema')
self.assertIsNone(resource.url)
self.assertTrue(resource.text.startswith('<xs:schema'))
schema_file = StringIO(schema_text)
resource = XMLResource(schema_file, lazy=False)
self.assertEqual(resource.source, schema_file)
self.assertEqual(resource.root.tag, '{http://www.w3.org/2001/XMLSchema}schema')
self.assertIsNone(resource.url)
self.assertTrue(resource.text.startswith('<xs:schema'))
def test_xml_resource_from_bytes(self):
source = '<?xml version="1.0" encoding="iso-8859-1"?>\n<a>ç</a>'
resource = XMLResource(source.encode('iso-8859-1'))
self.assertIsNone(resource.text)
resource.load()
self.assertEqual(resource.text, source)
def test_xml_resource_from_bytes_io(self):
source = '<?xml version="1.0" encoding="iso-8859-1"?>\n<a>ç</a>'
resource = XMLResource(BytesIO(source.encode('iso-8859-1')))
self.assertIsNone(resource.text)
resource.load()
self.assertEqual(resource.text, source)
def test_xml_resource_from_malformed_source(self):
# related to issue #224
malformed_xml_file = self.casepath('resources/malformed.xml')
with self.assertRaises(ElementTree.ParseError):
XMLResource(malformed_xml_file)
with self.assertRaises(ElementTree.ParseError):
XMLResource(malformed_xml_file, defuse='always')
# the incremental parser does not found the incomplete root before the end
resource = XMLResource(malformed_xml_file, lazy=True)
self.assertEqual(resource.root.tag, 'malformed_xml_file')
resource = XMLResource('<malformed_xml_file>>', lazy=True)
self.assertEqual(resource.root.tag, 'malformed_xml_file')
with self.assertRaises(ElementTree.ParseError):
XMLResource('<malformed_xml_file<>', lazy=True)
def test_xml_resource_from_wrong_arguments(self):
self.assertRaises(TypeError, XMLResource, [b'<UNSUPPORTED_DATA_TYPE/>'])
with self.assertRaises(TypeError) as ctx:
XMLResource('<root/>', base_url=[b'/home'])
self.assertIn(' ', str(ctx.exception))
def test_xml_resource_namespace(self):
resource = XMLResource(self.vh_xml_file)
self.assertEqual(resource.namespace, 'http://example.com/vehicles')
resource = XMLResource(self.vh_xsd_file)
self.assertEqual(resource.namespace, 'http://www.w3.org/2001/XMLSchema')
resource = XMLResource(self.col_xml_file)
self.assertEqual(resource.namespace, 'http://example.com/ns/collection')
self.assertEqual(XMLResource('<A/>').namespace, '')
def test_xml_resource_access(self):
resource = XMLResource(self.vh_xml_file)
base_url = resource.base_url
XMLResource(self.vh_xml_file, allow='local')
XMLResource(
self.vh_xml_file, base_url=os.path.dirname(self.vh_xml_file), allow='sandbox'
)
with self.assertRaises(XMLResourceBlocked) as ctx:
XMLResource(self.vh_xml_file, allow='remote')
self.assertTrue(str(ctx.exception).startswith("block access to local resource"))
with self.assertRaises(XMLResourceOSError):
XMLResource("https://xmlschema.test/vehicles.xsd", allow='remote')
with self.assertRaises(XMLResourceBlocked) as ctx:
XMLResource("https://xmlschema.test/vehicles.xsd", allow='local')
self.assertEqual(str(ctx.exception),
"block access to remote resource https://xmlschema.test/vehicles.xsd")
with self.assertRaises(XMLSchemaValueError) as ctx:
XMLResource("https://xmlschema.test/vehicles.xsd", allow='sandbox')
self.assertEqual(str(ctx.exception),
"block access to files out of sandbox requires 'base_url' to be set")
with self.assertRaises(XMLSchemaValueError) as ctx:
XMLResource("/tmp/vehicles.xsd", allow='sandbox')
self.assertEqual(
str(ctx.exception),
"block access to files out of sandbox requires 'base_url' to be set",
)
source = "/tmp/vehicles.xsd"
with self.assertRaises(XMLResourceBlocked) as ctx:
XMLResource(source, base_url=base_url, allow='sandbox')
self.assertEqual(
str(ctx.exception),
f"block access to out of sandbox file {normalize_url(source)}",
)
with self.assertRaises(XMLSchemaTypeError) as ctx:
XMLResource("https://xmlschema.test/vehicles.xsd", allow=None)
self.assertEqual(str(ctx.exception),
"invalid type <class 'NoneType'> for argument 'allow'")
with self.assertRaises(XMLSchemaValueError) as ctx:
XMLResource("https://xmlschema.test/vehicles.xsd", allow='any')
self.assertIn("invalid value 'any' for argument 'allow'", str(ctx.exception))
with self.assertRaises(XMLResourceBlocked) as ctx:
XMLResource(self.vh_xml_file, allow='none')
self.assertTrue(str(ctx.exception).startswith('block access to resource'))
self.assertTrue(str(ctx.exception).endswith('vehicles.xml'))
with open(self.vh_xml_file) as fp:
resource = XMLResource(fp, allow='none')
self.assertIsInstance(resource, XMLResource)
self.assertIsNone(resource.url)
with open(self.vh_xml_file) as fp:
resource = XMLResource(fp.read(), allow='none')
self.assertIsInstance(resource, XMLResource)
self.assertIsNone(resource.url)
with open(self.vh_xml_file) as fp:
resource = XMLResource(StringIO(fp.read()), allow='none')
self.assertIsInstance(resource, XMLResource)
self.assertIsNone(resource.url)
def test_xml_resource_defuse(self):
resource = XMLResource(self.vh_xml_file, defuse='never', lazy=True)
self.assertEqual(resource.defuse, 'never')
self.assertRaises(ValueError, XMLResource, self.vh_xml_file, defuse='all')
self.assertRaises(TypeError, XMLResource, self.vh_xml_file, defuse=None)
self.assertIsInstance(resource.root, ElementTree.Element)
resource = XMLResource(self.vh_xml_file, defuse='always', lazy=True)
self.assertIsInstance(resource.root, ElementTree.Element)
xml_file = self.casepath('resources/with_entity.xml')
self.assertIsInstance(XMLResource(xml_file, lazy=True), XMLResource)
with self.assertRaises(XMLResourceForbidden):
XMLResource(xml_file, defuse='always', lazy=True)
xml_file = self.casepath('resources/unused_external_entity.xml')
self.assertIsInstance(XMLResource(xml_file, lazy=True), XMLResource)
with self.assertRaises(XMLResourceForbidden):
XMLResource(xml_file, defuse='always', lazy=True)
def test_xml_resource_defuse_other_source_types(self):
xml_file = self.casepath('resources/external_entity.xml')
self.assertIsInstance(XMLResource(xml_file, lazy=True), XMLResource)
with self.assertRaises(XMLResourceForbidden):
XMLResource(xml_file, defuse='always', lazy=True)
with self.assertRaises(XMLResourceForbidden):
XMLResource(xml_file, defuse='always', lazy=False)
with self.assertRaises(XMLResourceForbidden):
XMLResource(xml_file, defuse='always', lazy=True)
with self.assertRaises(XMLResourceForbidden):
with open(xml_file) as fp:
XMLResource(fp, defuse='always', lazy=False)
with self.assertRaises(XMLResourceForbidden):
with open(xml_file) as fp:
XMLResource(fp.read(), defuse='always', lazy=False)
with self.assertRaises(XMLResourceForbidden):
with open(xml_file) as fp:
XMLResource(StringIO(fp.read()), defuse='always', lazy=False)
def test_xml_resource_defuse_bypass_example(self):
unsafe_xml_file = self.casepath('resources/external_entity.xml')
safe_xml_file = self.casepath('resources/dummy file.xml')
with self.assertRaises(XMLResourceForbidden):
with open(unsafe_xml_file) as fp:
defuse_xml(fp)
url = normalize_url(safe_xml_file)
with open(unsafe_xml_file) as fp:
fp.url = url
with self.assertRaises(XMLResourceForbidden):
defuse_xml(fp)
# If XMLResource use fp.url attribute for defusing not-seekable
# resources the defuse checks would pass silently
with urlopen(fp.url) as fp2:
self.assertTrue(fp2.seekable())
self.assertIs(defuse_xml(fp2), fp2)
def test_xml_resource_defuse_nonlocal(self):
xml_file = self.casepath('resources/external_entity.xml')
resource = XMLResource(xml_file, defuse='nonlocal', lazy=True)
self.assertIsInstance(resource, XMLResource)
with self.assertRaises(XMLResourceForbidden):
with open(xml_file) as fp:
XMLResource(fp, defuse='nonlocal', lazy=True)
with self.assertRaises(XMLResourceForbidden):
with open(xml_file) as fp:
XMLResource(fp.read(), defuse='nonlocal', lazy=True)
with self.assertRaises(XMLResourceForbidden):
with open(xml_file) as fp:
XMLResource(StringIO(fp.read()), defuse='nonlocal', lazy=True)
def test_xml_resource_timeout(self):
resource = XMLResource(self.vh_xml_file, timeout=30)
self.assertEqual(resource.timeout, 30)
self.assertRaises(TypeError, XMLResource, self.vh_xml_file, timeout='100')
self.assertRaises(ValueError, XMLResource, self.vh_xml_file, timeout=0)
def test_xml_resource_laziness(self):
resource = XMLResource(self.vh_xml_file, lazy=True)
self.assertTrue(resource.is_lazy())
resource = XMLResource(self.vh_xml_file, lazy=False)
self.assertFalse(resource.is_lazy())
resource = XMLResource(self.vh_xml_file, lazy=1)
self.assertTrue(resource.is_lazy())
resource = XMLResource(self.vh_xml_file, lazy=2)
self.assertTrue(resource.is_lazy())
resource = XMLResource(self.vh_xml_file, lazy=0)
self.assertFalse(resource.is_lazy())
with self.assertRaises(ValueError):
XMLResource(self.vh_xml_file, lazy=-1)
with self.assertRaises(TypeError):
XMLResource(self.vh_xml_file, lazy='1')
def test_xml_resource_base_url(self):
resource = XMLResource(self.vh_xml_file)
base_url = resource.base_url
self.assertEqual(base_url, XMLResource(self.vh_xml_file, '/other').base_url)
with open(self.vh_xml_file) as fp:
self.assertIsNone(XMLResource(fp.read()).base_url)
with open(self.vh_xml_file) as fp:
resource = XMLResource(fp.read(), base_url='/foo')
self.assertEqual(resource.base_url, '/foo')
base_url = Path(self.vh_xml_file).parent
resource = XMLResource('vehicles.xml', base_url)
self.assertEqual(resource.base_url, base_url.as_uri())
resource = XMLResource('vehicles.xml', str(base_url))
self.assertEqual(resource.base_url, base_url.as_uri())
resource = XMLResource('vehicles.xml', str(base_url).encode())
self.assertEqual(resource.base_url, base_url.as_uri())
self.assertEqual(resource.base_url, base_url.as_uri())
with self.assertRaises(TypeError):
XMLResource(self.vh_xml_file, base_url=False)
with self.assertRaises(ValueError):
XMLResource(self.vh_xml_file, base_url='<root/>')
with self.assertRaises(ValueError):
XMLResource(self.vh_xml_file, base_url=b'<root/>')
def test_xml_resource_is_local(self):
resource = XMLResource(self.vh_xml_file)
self.assertTrue(resource.is_local())
def test_xml_resource_is_remote(self):
resource = XMLResource(self.vh_xml_file)
self.assertFalse(resource.is_remote())
def test_xml_resource_is_loaded(self):
resource = XMLResource(self.vh_xml_file, lazy=False)
self.assertFalse(resource.is_loaded())
resource.load()
self.assertTrue(resource.is_loaded())
def test_xml_resource__lazy_iterparse(self):
resource = XMLResource(self.vh_xml_file, lazy=True)
self.assertEqual(resource.defuse, 'remote')
for _, elem in resource._lazy_iterparse(self.col_xml_file):
self.assertTrue(is_etree_element(elem))
for _, elem in resource._lazy_iterparse(self.col_xml_file):
self.assertTrue(is_etree_element(elem))
self.assertDictEqual(
resource.get_nsmap(elem),
{'col': 'http://example.com/ns/collection',
'xsi': 'http://www.w3.org/2001/XMLSchema-instance'}
)
resource._defuse = 'always'
for _, elem in resource._lazy_iterparse(self.col_xml_file):
self.assertTrue(is_etree_element(elem))
def test_xml_resource__parse(self):
resource = XMLResource(self.vh_xml_file, lazy=False)
self.assertEqual(resource.defuse, 'remote')
with open(self.col_xml_file) as fp:
resource._parse(fp)
self.assertTrue(is_etree_element(resource.root))
resource._defuse = 'always'
with open(self.col_xml_file) as fp:
resource._parse(fp)
self.assertTrue(is_etree_element(resource.root))
with urlopen(resource.url) as fp:
resource._parse(fp)
self.assertTrue(is_etree_element(resource.root))
def test_xml_resource_tostring(self):
resource = XMLResource(self.vh_xml_file)
self.assertTrue(resource.tostring().startswith('<vh:vehicles'))
resource = XMLResource(self.vh_xml_file, lazy=True)
with self.assertRaises(XMLResourceError) as ctx:
resource.tostring()
self.assertEqual("can\'t serialize a lazy XML resource", str(ctx.exception))
resource = XMLResource(XML_WITH_NAMESPACES)
result = resource.tostring()
self.assertNotEqual(result, XML_WITH_NAMESPACES)
# With xml.etree.ElementTree namespace declarations are serialized
# with a loss of information (all collapsed into the root element).
self.assertEqual(result, '<pfa:root xmlns:pfa="http://xmlschema.test/nsa" '
'xmlns:pfb="http://xmlschema.test/nsb">\n'
' <pfb:elem />\n</pfa:root>')
if lxml_etree is not None:
root = lxml_etree.XML(XML_WITH_NAMESPACES)
resource = XMLResource(root)
# With lxml.etree there is no information loss.
self.assertEqual(resource.tostring(), XML_WITH_NAMESPACES)
def test_xml_resource_open(self):
resource = XMLResource(self.vh_xml_file)
xml_file = resource.open()
self.assertIsNot(xml_file, resource.source)
data = xml_file.read().decode('utf-8')
self.assertTrue(data.startswith('<?xml '))
xml_file.close()
resource.url = 'file:not-a-file'
with self.assertRaises(XMLResourceOSError):
resource.open()
resource = XMLResource('<A/>')
self.assertIsInstance(resource.open(), io.StringIO)
resource = XMLResource(b'<A/>')
self.assertIsInstance(resource.open(), io.BytesIO)
resource = XMLResource(source=open(self.vh_xml_file))
xml_file = resource.open()
self.assertIs(xml_file, resource.source)
xml_file.close()
def test_xml_resource_seek(self):
resource = XMLResource(self.vh_xml_file)
self.assertIsNone(resource.seek(0))
self.assertIsNone(resource.seek(1))
xml_file = open(self.vh_xml_file)
resource = XMLResource(source=xml_file)
self.assertEqual(resource.seek(0), 0)
self.assertEqual(resource.seek(1), 1)
xml_file.close()
def test_xml_resource_manager(self):
resource = XMLResource(self.vh_xml_file)
with XMLResourceManager(resource) as ctx:
self.assertTrue(callable(ctx.fp.read))
self.assertFalse(ctx.fp.closed)
self.assertTrue(ctx.fp.closed)
resource = XMLResource(open(self.vh_xml_file))
with XMLResourceManager(resource) as ctx:
self.assertTrue(callable(ctx.fp.read))
self.assertFalse(ctx.fp.closed)
self.assertFalse(ctx.fp.closed)
resource.close()
def test_xml_resource_close(self):
resource = XMLResource(self.vh_xml_file)
resource.close()
with resource.open() as xml_file:
self.assertTrue(callable(xml_file.read))
with open(self.vh_xml_file) as xml_file:
resource = XMLResource(source=xml_file)
resource.close()
with self.assertRaises(XMLResourceOSError):
resource.open()
with open(self.vh_xml_file) as xml_file:
resource = XMLResource(xml_file)
with self.assertRaises(XMLResourceOSError):
resource.load() # I/O operation on closed file
def test_xml_resource_iter(self):
resource = XMLResource(XMLSchema.meta_schema.source.url)
self.assertFalse(resource.is_lazy())
lazy_resource = XMLResource(XMLSchema.meta_schema.source.url, lazy=True)
self.assertTrue(lazy_resource.is_lazy())
tags = [x.tag for x in resource.iter()]
self.assertEqual(len(tags), 1390)
self.assertEqual(tags[0], '{%s}schema' % XSD_NAMESPACE)
lazy_tags = [x.tag for x in lazy_resource.iter()]
self.assertEqual(len(lazy_tags), 1390)
self.assertEqual(lazy_tags[0], '{%s}schema' % XSD_NAMESPACE)
self.assertNotEqual(tags, lazy_tags)
tags = [x.tag for x in resource.iter('{%s}complexType' % XSD_NAMESPACE)]
self.assertEqual(len(tags), 56)
self.assertEqual(tags[0], '{%s}complexType' % XSD_NAMESPACE)
self.assertListEqual(
tags, [x.tag for x in lazy_resource.iter('{%s}complexType' % XSD_NAMESPACE)]
)
def test_xml_resource_iter_depth(self):
resource = XMLResource(XMLSchema.meta_schema.source.url)
self.assertFalse(resource.is_lazy())
lazy_resource = XMLResource(XMLSchema.meta_schema.source.url, lazy=True)
self.assertTrue(lazy_resource.is_lazy())
# Note: Elements change using a lazy resource so compare only tags
tags = [x.tag for x in resource.iter_depth()]
self.assertEqual(len(tags), 1)
self.assertEqual(tags[0], '{%s}schema' % XSD_NAMESPACE)
lazy_tags = [x.tag for x in lazy_resource.iter_depth()]
self.assertEqual(len(lazy_tags), 156)
self.assertEqual(lazy_tags[0], '{%s}annotation' % XSD_NAMESPACE)
self.assertEqual(lazy_tags[-1], '{%s}element' % XSD_NAMESPACE)
lazy_tags = [x.tag for x in lazy_resource.iter_depth(mode=3)]
self.assertListEqual(tags, lazy_tags)
lazy_tags = [x.tag for x in lazy_resource.iter_depth(mode=1)]
self.assertEqual(len(lazy_tags), 156)
lazy_tags = [x.tag for x in lazy_resource.iter_depth(mode=4)]
self.assertEqual(len(lazy_tags), 157)
self.assertEqual(tags[0], lazy_tags[-1])
lazy_tags = [x.tag for x in lazy_resource.iter_depth(mode=5)]
self.assertEqual(len(lazy_tags), 158)
self.assertEqual(tags[0], lazy_tags[0])
self.assertEqual(tags[0], lazy_tags[-1])
with self.assertRaises(ValueError) as ctx:
_ = [x.tag for x in lazy_resource.iter_depth(mode=6)]
self.assertEqual("invalid argument mode=6", str(ctx.exception))
source = StringIO('<a xmlns:tns0="http://example.com/ns0"><b1>'
' <c1 xmlns:tns1="http://example.com/ns1"/>'
' <c2 xmlns:tns2="http://example.com/ns2" x="2"/>'
'</b1><b2><c3><d1/></c3></b2></a>')
resource = XMLResource(source, lazy=3)
ancestors = []
self.assertIs(next(resource.iter_depth(ancestors=ancestors)), resource.root[1][0][0])
nsmap = resource.get_nsmap(resource.root[1][0][0])
self.assertDictEqual(nsmap, {'tns0': 'http://example.com/ns0'})
self.assertListEqual(ancestors, [resource.root, resource.root[1], resource.root[1][0]])
def test_xml_resource_iterfind(self):
namespaces = {'xs': XSD_NAMESPACE}
resource = XMLResource(XMLSchema.meta_schema.source.url)
self.assertFalse(resource.is_lazy())
lazy_resource = XMLResource(XMLSchema.meta_schema.source.url, lazy=True)
self.assertTrue(lazy_resource.is_lazy())
tags = [x.tag for x in resource.iterfind(path='.')]
self.assertEqual(len(tags), 1)
self.assertEqual(tags[0], '{%s}schema' % XSD_NAMESPACE)
with self.assertRaises(XMLSchemaValueError) as ctx:
_ = [x.tag for x in lazy_resource.iterfind(path='.')]
self.assertEqual("can't use path '.' on a lazy resource", str(ctx.exception))
tags = [x.tag for x in resource.iterfind(path='*')]
self.assertEqual(len(tags), 156)
self.assertEqual(tags[0], '{%s}annotation' % XSD_NAMESPACE)
lazy_tags = [x.tag for x in lazy_resource.iterfind(path='*')]
self.assertListEqual(tags, lazy_tags)
tags = [x.tag for x in resource.iterfind('xs:complexType', namespaces)]
self.assertEqual(len(tags), 35)
self.assertTrue(all(t == '{%s}complexType' % XSD_NAMESPACE for t in tags))
lazy_tags = [x.tag for x in lazy_resource.iterfind('xs:complexType', namespaces)]
self.assertListEqual(tags, lazy_tags)
tags = [x.tag for x in resource.iterfind('. /. / xs:complexType', namespaces)]
self.assertEqual(len(tags), 35)
self.assertTrue(all(t == '{%s}complexType' % XSD_NAMESPACE for t in tags))
lazy_tags = [
x.tag for x in lazy_resource.iterfind('. /. / xs:complexType', namespaces)
]
self.assertListEqual(tags, lazy_tags)
def test_xml_resource_find(self):
root = ElementTree.XML('<a><b1><c1/><c2 x="2"/></b1><b2/></a>')
resource = XMLResource(root)
self.assertIs(resource.find('*/c2'), root[0][1])
self.assertIsNone(resource.find('*/c3'))
resource = XMLResource('<a><b1>'
' <c1 xmlns:tns1="http://example.com/ns1"/>'
' <c2 xmlns:tns2="http://example.com/ns2" x="2"/>'
'</b1><b2/></a>')
self.assertIs(resource.find('*/c2'), resource.root[0][1])
nsmap = resource.get_nsmap(resource.root[0][1])
self.assertDictEqual(nsmap, {'tns2': 'http://example.com/ns2'})
ancestors = []
self.assertIs(resource.find('*/c2', ancestors=ancestors),
resource.root[0][1])
nsmap = resource.get_nsmap(resource.root[0][1])
self.assertDictEqual(nsmap, {'tns2': 'http://example.com/ns2'})
self.assertListEqual(ancestors, [resource.root, resource.root[0]])
ancestors = []
self.assertIs(resource.find('.', ancestors=ancestors), resource.root)
self.assertDictEqual(resource.get_nsmap(resource.root), {})
self.assertListEqual(ancestors, [])
ancestors = []
self.assertIsNone(resource.find('b3', ancestors=ancestors))
self.assertListEqual(ancestors, [])
def test_xml_resource_lazy_find(self):
source = StringIO('<a><b1><c1/><c2 x="2"/></b1><b2/></a>')
resource = XMLResource(source, lazy=True)
self.assertIs(resource.find('*/c2'), resource.root[0][1])
source = StringIO('<a xmlns:tns0="http://example.com/ns0"><b1>'
' <c1 xmlns:tns1="http://example.com/ns1"/>'
' <c2 xmlns:tns2="http://example.com/ns2" x="2"/>'
'</b1><b2><c3><d1/></c3></b2></a>')
resource = XMLResource(source, lazy=True)
ancestors = []
self.assertIs(resource.find('*/c2', ancestors=ancestors),
resource.root[0][1])
nsmap = resource.get_nsmap(resource.root[0][1])
self.assertDictEqual(nsmap, {'tns0': 'http://example.com/ns0',
'tns2': 'http://example.com/ns2'})
self.assertListEqual(ancestors, [resource.root, resource.root[0]])
ancestors = []
self.assertIs(resource.find('*/c3', ancestors=ancestors),
resource.root[1][0])
nsmap = resource.get_nsmap(resource.root[1][0])
self.assertDictEqual(nsmap, {'tns0': 'http://example.com/ns0'})
self.assertListEqual(ancestors, [resource.root, resource.root[1]])
ancestors = []
self.assertIs(resource.find('*/c3/d1', ancestors=ancestors),
resource.root[1][0][0])
nsmap = resource.get_nsmap(resource.root[1][0][0])
self.assertDictEqual(nsmap, {'tns0': 'http://example.com/ns0'})
self.assertListEqual(ancestors,
[resource.root, resource.root[1], resource.root[1][0]])
ancestors = []
self.assertIs(resource.find('*', ancestors=ancestors),
resource.root[0])
nsmap = resource.get_nsmap(resource.root[0])
self.assertDictEqual(nsmap, {'tns0': 'http://example.com/ns0'})
self.assertListEqual(ancestors, [resource.root])
ancestors = []
with self.assertRaises(XMLSchemaValueError) as ctx:
resource.find('/b1', ancestors=ancestors)
self.assertEqual("can't use path '/b1' on a lazy resource", str(ctx.exception))
source.seek(0)
resource = XMLResource(source, lazy=2)
ancestors = []
self.assertIs(resource.find('*/c2', ancestors=ancestors),
resource.root[0][1])
nsmap = resource.get_nsmap(resource.root[0][1])
self.assertDictEqual(nsmap, {'tns0': 'http://example.com/ns0',
'tns2': 'http://example.com/ns2'})
self.assertListEqual(ancestors, [resource.root, resource.root[0]])
def test_xml_resource_findall(self):
root = ElementTree.XML('<a><b1><c1/><c2/></b1><b2/></a>')
resource = XMLResource(root)
self.assertListEqual(resource.findall('*/*'), root[0][:])
self.assertListEqual(resource.findall('*/c3'), [])
def test_iterfind_parser(self):
source = StringIO('<a><b1 x="9"><c1/><c2 x="2"/></b1><b2/></a>')
parser = iterfind_parser('/a/b2')
resource = XMLResource(source, iterparse=parser)
tags = [e.tag for e in resource.iter()]
self.assertListEqual(tags, ['a', 'b1', 'b2'])
parser = iterfind_parser('/a/b2', ancestors=[])
resource = XMLResource(source, iterparse=parser)
tags = [e.tag for e in resource.iter()]
self.assertListEqual(tags, ['a', 'b2'])
parser = iterfind_parser('./b2')
resource = XMLResource(source, iterparse=parser)
tags = [e.tag for e in resource.iter()]
self.assertListEqual(tags, ['a', 'b1', 'b2'])
def test_xml_resource_nsmap_tracking(self):
xsd_file = self.casepath('examples/collection/collection4.xsd')
resource = XMLResource(xsd_file)
root = resource.root
for elem in resource.iter():
nsmap = resource.get_nsmap(elem)
if elem is root[2][0] or elem in root[2][0]:
self.assertEqual(dict(nsmap), {'xs': 'http://www.w3.org/2001/XMLSchema',
'': 'http://www.w3.org/2001/XMLSchema'})
else:
self.assertEqual(dict(nsmap), {'xs': 'http://www.w3.org/2001/XMLSchema',
'': 'http://example.com/ns/collection'})
resource._nsmaps.clear()
resource._nsmaps[resource.root] = {}
for elem in resource.iter():
nsmap = resource.get_nsmap(elem)
if elem is resource.root:
self.assertEqual(nsmap, {})
else:
self.assertIsNone(nsmap)
if lxml_etree is not None:
tree = lxml_etree.parse(xsd_file)
resource = XMLResource(tree)
root = resource.root
for elem in resource.iter():
if callable(elem.tag):
continue
nsmap = resource.get_nsmap(elem)
if elem is root[2][0] or elem in root[2][0]:
self.assertEqual(dict(nsmap), {'xs': 'http://www.w3.org/2001/XMLSchema',
'': 'http://www.w3.org/2001/XMLSchema'})
else:
self.assertEqual(dict(nsmap), {'xs': 'http://www.w3.org/2001/XMLSchema',
'': 'http://example.com/ns/collection'})
resource = XMLResource(xsd_file, lazy=True)
root = resource.root
for k, elem in enumerate(resource.iter()):
if not k:
self.assertIs(elem, resource.root)
self.assertIsNot(root, resource.root)
nsmap = resource.get_nsmap(elem)
try:
if elem is resource.root[2][0] or elem in resource.root[2][0]:
self.assertEqual(nsmap[''], 'http://www.w3.org/2001/XMLSchema')
else:
self.assertEqual(nsmap[''], 'http://example.com/ns/collection')
except IndexError:
self.assertEqual(nsmap[''], 'http://example.com/ns/collection')
def test_xml_resource_get_namespaces(self):
with open(self.vh_xml_file) as schema_file:
resource = XMLResource(schema_file)
self.assertIsNone(resource.url)
self.assertEqual(set(resource.get_namespaces().keys()), {'vh', 'xsi'})
self.assertFalse(schema_file.closed)
with open(self.vh_xsd_file) as schema_file:
resource = XMLResource(schema_file)
self.assertIsNone(resource.url)
self.assertEqual(set(resource.get_namespaces().keys()), {'xs', 'vh'})
self.assertFalse(schema_file.closed)
resource = XMLResource(self.col_xml_file)
self.assertEqual(resource.url, normalize_url(self.col_xml_file))
self.assertEqual(set(resource.get_namespaces().keys()), {'col', 'xsi'})
resource = XMLResource(self.col_xsd_file)
self.assertEqual(resource.url, normalize_url(self.col_xsd_file))
self.assertEqual(set(resource.get_namespaces().keys()), {'', 'xs'})
resource = XMLResource("""<?xml version="1.0" ?>
<root xmlns="tns1">
<tns:elem1 xmlns:tns="tns1" xmlns="unknown"/>
</root>""", lazy=False)
self.assertEqual(set(resource.get_namespaces(root_only=False).keys()),
{'', 'tns', 'default'})
resource = XMLResource("""<?xml version="1.0" ?>
<root xmlns:tns="tns1">
<tns:elem1 xmlns:tns="tns1" xmlns="unknown"/>
</root>""", lazy=False)
self.assertEqual(set(resource.get_namespaces(root_only=False).keys()), {'default', 'tns'})
self.assertEqual(resource.get_namespaces(root_only=True).keys(), {'tns'})
resource = XMLResource("""<?xml version="1.0" ?>
<root xmlns:tns="tns1">
<tns:elem1 xmlns:tns="tns3" xmlns="unknown"/>
</root>""", lazy=False)
self.assertEqual(set(resource.get_namespaces(root_only=False).keys()),
{'default', 'tns', 'tns0'})
resource = XMLResource('<root/>')
with self.assertRaises(ValueError) as ctx:
resource.get_namespaces(namespaces={'xml': "http://example.com/ne"})
self.assertIn("reserved prefix 'xml'", str(ctx.exception))
def test_xml_resource_get_locations(self):
resource = XMLResource(self.col_xml_file)
self.check_url(resource.url, normalize_url(self.col_xml_file))
locations = resource.get_locations([('ns', 'other.xsd')], root_only=False)
self.assertEqual(len(locations), 2)
self.check_url(locations[0][1], os.path.join(self.col_dir, 'other.xsd'))
self.check_url(locations[1][1], normalize_url(self.col_xsd_file))
source = StringIO('<a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'
' xsi:schemaLocation="http://example.com/ns1 /loc1"><b1>'
' <c1 xsi:schemaLocation="http://example.com/ns2 /loc2"/>'
' <c2 xmlns:tns2="http://example.com/ns2" x="2"/>'
'</b1></a>')
resource = XMLResource(source)
locations = resource.get_locations(root_only=False)
self.assertEqual(len(locations), 2)
self.assertEqual(locations[0][0], 'http://example.com/ns1')
self.assertRegex(locations[0][1], f'file://{DRIVE_REGEX}/loc1')
self.assertEqual(locations[1][0], 'http://example.com/ns2')
self.assertRegex(locations[1][1], f'file://{DRIVE_REGEX}/loc2')
locations = resource.get_locations(root_only=True)
self.assertEqual(len(locations), 1)
self.assertEqual(locations[0][0], 'http://example.com/ns1')
self.assertRegex(locations[0][1], f'file://{DRIVE_REGEX}/loc1')
@unittest.skipIf(SKIP_REMOTE_TESTS or platform.system() == 'Windows',
"Remote networks are not accessible or avoid SSL "
"verification error on Windows.")
def test_remote_resource_loading(self):
url = "https://raw.githubusercontent.com/brunato/xmlschema/master/" \
"tests/test_cases/examples/collection/collection.xsd"
with urlopen(url) as rh:
col_xsd_resource = XMLResource(rh)
self.assertIsNone(col_xsd_resource.url, url)
self.assertIsNone(col_xsd_resource.filepath)
self.assertEqual(col_xsd_resource.namespace, XSD_NAMESPACE)
self.assertIsNone(col_xsd_resource.seek(0))
with self.assertRaises(XMLResourceOSError) as ctx:
col_xsd_resource.load()
self.assertIn('has been closed', str(ctx.exception))
col_xsd_resource = XMLResource(url)
col_xsd_resource.load()
col_schema = XMLSchema(col_xsd_resource.get_text())
self.assertTrue(isinstance(col_schema, XMLSchema))
vh_schema = XMLSchema("https://raw.githubusercontent.com/brunato/xmlschema/master/"
"tests/test_cases/examples/vehicles/vehicles.xsd")
self.assertTrue(isinstance(vh_schema, XMLSchema))
self.assertTrue(vh_schema.source.is_remote())
def test_schema_defuse(self):
vh_schema = XMLSchema(self.vh_xsd_file, defuse='always')
self.assertIsInstance(vh_schema.root, ElementTree.Element)
for schema in vh_schema.maps.iter_schemas():
self.assertIsInstance(schema.root, ElementTree.Element)
def test_schema_resource_access(self):
vh_schema = XMLSchema(self.vh_xsd_file, allow='sandbox')
self.assertTrue(isinstance(vh_schema, XMLSchema))
xsd_source = """
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:vh="http://example.com/vehicles">
<xs:import namespace="http://example.com/vehicles" schemaLocation="{}"/>
</xs:schema>""".format(self.vh_xsd_file)
schema = XMLSchema(xsd_source, allow='all')
self.assertTrue(isinstance(schema, XMLSchema))
self.assertIn("http://example.com/vehicles", schema.maps.namespaces)
self.assertEqual(len(schema.maps.namespaces["http://example.com/vehicles"]), 4)
with warnings.catch_warnings(record=True) as ctx:
warnings.simplefilter("always")
XMLSchema(xsd_source, allow='remote')
self.assertEqual(len(ctx), 1, "Expected one import warning")
self.assertIn("block access to local resource", str(ctx[0].message))
schema = XMLSchema(xsd_source, allow='local')
self.assertTrue(isinstance(schema, XMLSchema))
self.assertIn("http://example.com/vehicles", schema.maps.namespaces)
self.assertEqual(len(schema.maps.namespaces["http://example.com/vehicles"]), 4)
with self.assertRaises(XMLSchemaValueError) as ctx:
XMLSchema(xsd_source, allow='sandbox')
self.assertIn("block access to files out of sandbox", str(ctx.exception))
schema = XMLSchema(
xsd_source, base_url=os.path.dirname(self.vh_xsd_file), allow='all'
)
self.assertTrue(isinstance(schema, XMLSchema))
self.assertIn("http://example.com/vehicles", schema.maps.namespaces)
self.assertEqual(len(schema.maps.namespaces["http://example.com/vehicles"]), 4)
with warnings.catch_warnings(record=True) as ctx:
warnings.simplefilter("always")
XMLSchema(xsd_source, base_url='/improbable', allow='sandbox')
self.assertEqual(len(ctx), 1, "Expected one import warning")
self.assertIn("block access to out of sandbox", str(ctx[0].message))
def test_fid_with_name_attr(self):
"""XMLResource gets correct data when passed a file like object
with a name attribute that isn't on disk.
These file descriptors appear when working with the contents from a
zip using the zipfile module and with Django files in some
instances.
"""
class FileProxy:
def __init__(self, fid, fake_name):
self._fid = fid
self.name = fake_name
def __getattr__(self, attr):
try:
return self.__dict__[attr]
except (KeyError, AttributeError):
return getattr(self.__dict__["_fid"], attr)
with open(self.vh_xml_file) as xml_file:
resource = XMLResource(FileProxy(xml_file, fake_name="not__on____disk.xml"))
self.assertIsNone(resource.url)
self.assertEqual(set(resource.get_namespaces().keys()), {'vh', 'xsi'})
self.assertFalse(xml_file.closed)
def test_parent_map(self):
root = ElementTree.XML('<a><b1><c1/><c2/></b1><b2/></a>')
resource = XMLResource(root)
self.assertIsNone(resource.parent_map[root])
self.assertIs(resource.parent_map[root[0]], root)
self.assertIs(resource.parent_map[root[1]], root)
self.assertIs(resource.parent_map[root[0][0]], root[0])
self.assertIs(resource.parent_map[root[0][1]], root[0])
resource = XMLResource(StringIO('<a><b1><c1/><c2/></b1><b2/></a>'), lazy=True)
with self.assertRaises(XMLResourceError) as ctx:
_ = resource.parent_map
self.assertEqual("can't create the parent map of a lazy XML resource",
str(ctx.exception))
def test_get_nsmap(self):
source = '<a xmlns="uri1"><b1 xmlns:x="uri2"><c1/><c2/></b1><b2 xmlns="uri3"/></a>'
alien_elem = ElementTree.XML('<a/>')
root = ElementTree.XML(source)
resource = XMLResource(root)
self.assertIsNone(resource.get_nsmap(root))
self.assertIsNone(resource.get_nsmap(root[1]))
self.assertIsNone(resource.get_nsmap(alien_elem))
if lxml_etree is not None:
root = lxml_etree.XML(source)
resource = XMLResource(root)
self.assertDictEqual(resource.get_nsmap(root), {'': 'uri1'})
self.assertDictEqual(resource.get_nsmap(root[0]), {'x': 'uri2', '': 'uri1'})
self.assertDictEqual(resource.get_nsmap(root[1]), {'': 'uri3'})
self.assertIsNone(resource.get_nsmap(alien_elem))
resource = XMLResource(source)
root = resource.root
self.assertDictEqual(resource.get_nsmap(root), {'': 'uri1'})
self.assertDictEqual(resource.get_nsmap(root[0]), {'': 'uri1', 'x': 'uri2'})
self.assertDictEqual(resource.get_nsmap(root[1]), {'': 'uri3'})
self.assertIsNone(resource.get_nsmap(alien_elem))
resource = XMLResource(StringIO(source), lazy=True)
root = resource.root
self.assertTrue(resource.is_lazy())
self.assertDictEqual(resource.get_nsmap(root), {'': 'uri1'})
self.assertIsNone(resource.get_nsmap(root[0]))
self.assertIsNone(resource.get_nsmap(root[1]))
self.assertIsNone(resource.get_nsmap(alien_elem))
def test_get_xmlns(self):
source = '<a xmlns="uri1"><b1 xmlns:x="uri2"><c1/><c2/></b1><b2 xmlns="uri3"/></a>'
alien_elem = ElementTree.XML('<a/>')
root = ElementTree.XML(source)
resource = XMLResource(root)
self.assertIsNone(resource.get_xmlns(root))
self.assertIsNone(resource.get_xmlns(root[1]))
self.assertIsNone(resource.get_xmlns(alien_elem))
if lxml_etree is not None:
root = lxml_etree.XML(source)
resource = XMLResource(root)
self.assertListEqual(resource.get_xmlns(root), [('', 'uri1')])
self.assertListEqual(resource.get_xmlns(root[0]), [('x', 'uri2')])
self.assertListEqual(resource.get_xmlns(root[1]), [('', 'uri3')])
self.assertIsNone(resource.get_xmlns(alien_elem))
resource = XMLResource(source)
root = resource.root
self.assertListEqual(resource.get_xmlns(root), [('', 'uri1')])
self.assertListEqual(resource.get_xmlns(root[0]), [('x', 'uri2')])
self.assertListEqual(resource.get_xmlns(root[1]), [('', 'uri3')])
self.assertIsNone(resource.get_xmlns(alien_elem))
resource = XMLResource(StringIO(source), lazy=True)
root = resource.root
self.assertTrue(resource.is_lazy())
self.assertListEqual(resource.get_xmlns(root), [('', 'uri1')])
self.assertIsNone(resource.get_xmlns(root[0]))
self.assertIsNone(resource.get_xmlns(root[1]))
self.assertIsNone(resource.get_xmlns(alien_elem))
def test_xml_subresource(self):
resource = XMLResource(self.vh_xml_file, lazy=True)
with self.assertRaises(XMLResourceError) as ctx:
resource.subresource(resource.root)
self.assertEqual("can't create a subresource from a lazy XML resource",
str(ctx.exception))
resource = XMLResource(self.vh_xml_file)
root = resource.root
subresource = resource.subresource(root[0])
self.assertIs(subresource.root, resource.root[0])
with self.assertRaises(XMLSchemaTypeError) as ctx:
resource.subresource(None)
self.assertEqual("argument must be an Element instance", str(ctx.exception))
if lxml_etree is not None:
resource = XMLResource(lxml_etree.parse(self.vh_xml_file).getroot())
root = resource.root
subresource = resource.subresource(root[0])
self.assertIs(subresource.root, resource.root[0])
xml_text = '<a><b1 xmlns:x="tns0"><c1 xmlns:y="tns1"/><c2/></b1><b2/></a>'
resource = XMLResource(xml_text)
root = resource.root
subresource = resource.subresource(root[0])
self.assertIs(subresource.root, resource.root[0])
def test_loading_from_unrelated_dirs__issue_237(self):
relative_path = str(pathlib.Path(__file__).parent.joinpath(
'test_cases/issues/issue_237/dir1/issue_237.xsd'
))
schema = XMLSchema(relative_path)
self.assertEqual(schema.maps.namespaces[''][1].name, 'issue_237a.xsd')
self.assertEqual(schema.maps.namespaces[''][2].name, 'issue_237b.xsd')
def test_uri_mapper(self):
urn = 'urn:example:xmlschema:vehicles.xsd'
uri_mapper = {urn: self.vh_xsd_file}
with self.assertRaises(XMLResourceOSError):
XMLResource(urn)
resource = XMLResource(urn, uri_mapper=uri_mapper)
self.assertEqual(resource.url[-30:], 'examples/vehicles/vehicles.xsd')
vh_schema = XMLSchema(self.vh_xsd_file, uri_mapper=uri_mapper)
self.assertTrue(vh_schema.is_valid(self.vh_xml_file))
def uri_mapper(uri):
return self.vh_xsd_file if uri == urn else uri
resource = XMLResource(urn, uri_mapper=uri_mapper)
self.assertEqual(resource.url[-30:], 'examples/vehicles/vehicles.xsd')
def test_opener_argument(self):
class NoSeekFile(addinfourl):
def seekable(self): return False
def seek(self, pos, whence=0): return pos
class MyFileHandler(FileHandler):
def file_open(self, req):
obj = super().file_open(req)
if not isinstance(obj, addinfourl):
return obj
obj.close()
return NoSeekFile(open(obj.fp.name, 'rb'), obj.headers, obj.url, obj.code)
opener = build_opener(MyFileHandler)
resource = XMLResource(self.vh_xml_file, opener=opener)
fp = resource.open()
try:
self.assertIsInstance(fp, NoSeekFile)
finally:
fp.close()
resource = XMLResource(self.vh_xml_file, opener=opener, defuse='always')
try:
fp = resource.open()
self.assertIsInstance(fp, NoSeekFile)
self.assertFalse(fp.seekable())
self.assertEqual(fp.tell(), 0) # File not used for defusing XML data
finally:
fp.close()
def test_iterparse_argument(self):
resource = XMLResource(self.vh_xml_file, iterparse=ElementTree.iterparse)
k = 0
for k, elem in enumerate(resource.root.iter(), start=1):
self.assertTrue(is_etree_element(elem))
self.assertFalse(is_lxml_element(elem))
self.assertIsInstance(elem, ElementTree.Element)
if k == 0:
self.assertIs(elem, resource.root)
self.assertEqual(k, 7)
def test_iterparse_argument_with_parser_instance(self):
def iterparse(fp, events):
builder = ElementTree.TreeBuilder(insert_comments=True)
parser = ElementTree.XMLParser(target=builder)
return ElementTree.iterparse(fp, events=events, parser=parser)
resource = XMLResource(self.vh_xml_file, iterparse=iterparse)
k = 0
for k, elem in enumerate(resource.root.iter(), start=1):
self.assertTrue(is_etree_element(elem))
self.assertFalse(is_lxml_element(elem))
self.assertIsInstance(elem, ElementTree.Element)
if k == 0:
self.assertIs(elem, resource.root)
elif k == 4:
self.assertTrue(callable(elem.tag)) # <!-- Comment -->
self.assertEqual(k, 8)
@unittest.skipIf(lxml_etree is None, "Skip: lxml is not available.")
def test_iterparse_argument_with_lxml(self):
resource = XMLResource(self.vh_xml_file, iterparse=lxml_etree.iterparse)
k = 0
for k, elem in enumerate(resource.root.iter(), start=1):
self.assertTrue(is_lxml_element(elem))
self.assertIsInstance(elem, lxml_etree._Element)
if k == 0:
self.assertIs(elem, resource.root)
elif k == 4:
self.assertTrue(callable(elem.tag)) # <!-- Comment -->
self.assertEqual(k, 8)
@unittest.skipIf(lxml_etree is None, "Skip: lxml is not available.")
def test_iterparse_argument_for_html(self):
def iterparse(fp, events):
# Ignore deprecation warning of 'strip_cdata' option of HTMLParser(),
# no way to provide a parser instance or other parameters.
with warnings.catch_warnings():
warnings.simplefilter('ignore')
return lxml_etree.iterparse(fp, events=events, html=True)
html_source = (b"<html><head><title>page title</title></head>"
b"<body><p>foo<p>bar</body></html>")
with self.assertRaises(XMLResourceError) as ctx:
XMLResource(html_source, iterparse=lxml_etree.iterparse)
self.assertIn("Opening and ending tag mismatch", str(ctx.exception))
resource = XMLResource(html_source, iterparse=iterparse)
self.assertTrue(is_lxml_element(resource.root))
self.assertEqual(resource.root.tag, 'html')
k = 0
for k, elem in enumerate(resource.root.iter(), start=1):
self.assertTrue(is_lxml_element(elem))
self.assertIsInstance(elem, lxml_etree._Element)
if k == 0:
self.assertIs(elem, resource.root)
self.assertEqual(k, 6)
def test_xml_resource_copy(self):
path = Path(self.vh_xml_file)
resource = XMLResource(path, lazy=True)
other = copy.copy(resource)
self.assertIsNot(other, resource)
self.assertIs(other.root, resource.root)
self.assertIsNot(other._nsmaps, resource._nsmaps)
self.assertIsNot(other._xmlns, resource._xmlns)
if __name__ == '__main__':
run_xmlschema_tests('XML resources')
|