/usr/lib/python2.7/dist-packages/tables/tests/test_tree.py is in python-tables 3.2.2-2.
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 | # -*- coding: utf-8 -*-
from __future__ import print_function
import os
import sys
import time
import tempfile
import warnings
import tables
from tables import Group, Leaf, Table, Array
from tables import StringCol, IntCol, Int16Col, FloatCol, Float32Col
from tables.tests import common
from tables.tests.common import unittest
from tables.tests.common import PyTablesTestCase as TestCase
# Test Record class
class Record(tables.IsDescription):
var1 = StringCol(itemsize=4) # 4-character String
var2 = IntCol() # integer
var3 = Int16Col() # short integer
var4 = FloatCol() # double (double-precision)
var5 = Float32Col() # float (single-precision)
class TreeTestCase(common.TempFileMixin, TestCase):
open_mode = "w"
title = "This is the table title"
expectedrows = 10
appendrows = 5
def setUp(self):
super(TreeTestCase, self).setUp()
# Create an instance of HDF5 Table
self.populateFile()
self.h5file.close()
def populateFile(self):
group = self.h5file.root
maxshort = 1 << 15
# maxint = 2147483647 # (2 ** 31 - 1)
for j in range(3):
# Create a table
table = self.h5file.create_table(group, 'table'+str(j), Record,
title=self.title,
filters=None,
expectedrows=self.expectedrows)
# Get the record object associated with the new table
d = table.row
# Fill the table
for i in xrange(self.expectedrows):
d['var1'] = '%04d' % (self.expectedrows - i)
d['var2'] = i
d['var3'] = i % maxshort
d['var4'] = float(i)
d['var5'] = float(i)
d.append() # This injects the Record values
# Flush the buffer for this table
table.flush()
# Create a couple of arrays in each group
var1List = [x['var1'] for x in table.iterrows()]
var4List = [x['var4'] for x in table.iterrows()]
self.h5file.create_array(group, 'var1', var1List, "1")
self.h5file.create_array(group, 'var4', var4List, "4")
# Create a new group (descendant of group)
group2 = self.h5file.create_group(group, 'group'+str(j))
# Iterate over this new group (group2)
group = group2
def test00_getNode(self):
"""Checking the File.get_node() with string node names"""
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test00_getNode..." % self.__class__.__name__)
self.h5file = tables.open_file(self.h5fname, "r")
nodelist = ['/', '/table0', '/group0/var1', '/group0/group1/var4']
nodenames = []
for node in nodelist:
object = self.h5file.get_node(node)
nodenames.append(object._v_pathname)
self.assertEqual(nodenames, nodelist)
if common.verbose:
print("get_node(pathname) test passed")
nodegroups = [
'/', '/group0', '/group0/group1', '/group0/group1/group2']
nodenames = ['var1', 'var4']
nodepaths = []
for group in nodegroups:
for name in nodenames:
try:
object = self.h5file.get_node(group, name)
except LookupError:
pass
else:
nodepaths.append(object._v_pathname)
self.assertEqual(nodepaths,
['/var1', '/var4',
'/group0/var1', '/group0/var4',
'/group0/group1/var1', '/group0/group1/var4'])
if common.verbose:
print("get_node(groupname, name) test passed")
nodelist = ['/', '/group0', '/group0/group1', '/group0/group1/group2',
'/table0']
nodenames = []
groupobjects = []
# warnings.filterwarnings("error", category=UserWarning)
for node in nodelist:
try:
object = self.h5file.get_node(node, classname='Group')
except LookupError:
if common.verbose:
(type, value, traceback) = sys.exc_info()
print("\nGreat!, the next LookupError was catched!")
print(value)
else:
nodenames.append(object._v_pathname)
groupobjects.append(object)
self.assertEqual(nodenames,
['/', '/group0', '/group0/group1',
'/group0/group1/group2'])
if common.verbose:
print("get_node(groupname, classname='Group') test passed")
# Reset the warning
# warnings.filterwarnings("default", category=UserWarning)
nodenames = ['var1', 'var4']
nodearrays = []
for group in groupobjects:
for name in nodenames:
try:
object = self.h5file.get_node(group, name, 'Array')
except:
pass
else:
nodearrays.append(object._v_pathname)
self.assertEqual(nodearrays,
['/var1', '/var4',
'/group0/var1', '/group0/var4',
'/group0/group1/var1', '/group0/group1/var4'])
if common.verbose:
print("get_node(groupobject, name, classname='Array') test passed")
def test01_getNodeClass(self):
"""Checking the File.get_node() with instances"""
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test01_getNodeClass..." %
self.__class__.__name__)
self.h5file = tables.open_file(self.h5fname, "r")
# This tree ways of get_node usage should return a table instance
table = self.h5file.get_node("/group0/table1")
self.assertTrue(isinstance(table, Table))
table = self.h5file.get_node("/group0", "table1")
self.assertTrue(isinstance(table, Table))
table = self.h5file.get_node(self.h5file.root.group0, "table1")
self.assertTrue(isinstance(table, Table))
# This should return an array instance
arr = self.h5file.get_node("/group0/var1")
self.assertTrue(isinstance(arr, Array))
self.assertTrue(isinstance(arr, Leaf))
# And this a Group
group = self.h5file.get_node("/group0", "group1", "Group")
self.assertTrue(isinstance(group, Group))
def test02_listNodes(self):
"""Checking the File.list_nodes() method"""
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test02_listNodes..." % self.__class__.__name__)
# Made the warnings to raise an error
# warnings.filterwarnings("error", category=UserWarning)
self.h5file = tables.open_file(self.h5fname, "r")
self.assertRaises(TypeError,
self.h5file.list_nodes, '/', 'NoSuchClass')
nodelist = ['/', '/group0', '/group0/table1', '/group0/group1/group2',
'/var1']
nodenames = []
objects = []
for node in nodelist:
try:
objectlist = self.h5file.list_nodes(node)
except:
pass
else:
objects.extend(objectlist)
for object in objectlist:
nodenames.append(object._v_pathname)
self.assertEqual(nodenames,
['/group0', '/table0', '/var1', '/var4',
'/group0/group1', '/group0/table1',
'/group0/var1', '/group0/var4'])
if common.verbose:
print("list_nodes(pathname) test passed")
nodenames = []
for node in objects:
try:
objectlist = self.h5file.list_nodes(node)
except:
pass
else:
for object in objectlist:
nodenames.append(object._v_pathname)
self.assertEqual(nodenames,
['/group0/group1', '/group0/table1',
'/group0/var1', '/group0/var4',
'/group0/group1/group2', '/group0/group1/table2',
'/group0/group1/var1', '/group0/group1/var4'])
if common.verbose:
print("list_nodes(groupobject) test passed")
nodenames = []
for node in objects:
try:
objectlist = self.h5file.list_nodes(node, 'Leaf')
except TypeError:
if common.verbose:
(type, value, traceback) = sys.exc_info()
print("\nGreat!, the next TypeError was catched!")
print(value)
else:
for object in objectlist:
nodenames.append(object._v_pathname)
self.assertEqual(nodenames,
['/group0/table1',
'/group0/var1', '/group0/var4',
'/group0/group1/table2',
'/group0/group1/var1', '/group0/group1/var4'])
if common.verbose:
print("list_nodes(groupobject, classname = 'Leaf') test passed")
nodenames = []
for node in objects:
try:
objectlist = self.h5file.list_nodes(node, 'Table')
except TypeError:
if common.verbose:
(type, value, traceback) = sys.exc_info()
print("\nGreat!, the next TypeError was catched!")
print(value)
else:
for object in objectlist:
nodenames.append(object._v_pathname)
self.assertEqual(nodenames,
['/group0/table1', '/group0/group1/table2'])
if common.verbose:
print("list_nodes(groupobject, classname = 'Table') test passed")
# Reset the warning
# warnings.filterwarnings("default", category=UserWarning)
def test02b_iterNodes(self):
"""Checking the File.iter_nodes() method"""
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test02b_iterNodes..." % self.__class__.__name__)
self.h5file = tables.open_file(self.h5fname, "r")
self.assertRaises(TypeError,
self.h5file.list_nodes, '/', 'NoSuchClass')
nodelist = ['/', '/group0', '/group0/table1', '/group0/group1/group2',
'/var1']
nodenames = []
objects = []
for node in nodelist:
try:
objectlist = [o for o in self.h5file.iter_nodes(node)]
except:
pass
else:
objects.extend(objectlist)
for object in objectlist:
nodenames.append(object._v_pathname)
self.assertEqual(nodenames,
['/group0', '/table0', '/var1', '/var4',
'/group0/group1', '/group0/table1',
'/group0/var1', '/group0/var4'])
if common.verbose:
print("iter_nodes(pathname) test passed")
nodenames = []
for node in objects:
try:
objectlist = [o for o in self.h5file.iter_nodes(node)]
except:
pass
else:
for object in objectlist:
nodenames.append(object._v_pathname)
self.assertEqual(nodenames,
['/group0/group1', '/group0/table1',
'/group0/var1', '/group0/var4',
'/group0/group1/group2', '/group0/group1/table2',
'/group0/group1/var1', '/group0/group1/var4'])
if common.verbose:
print("iter_nodes(groupobject) test passed")
nodenames = []
for node in objects:
try:
objectlist = [o for o in self.h5file.iter_nodes(node, 'Leaf')]
except TypeError:
if common.verbose:
(type, value, traceback) = sys.exc_info()
print("\nGreat!, the next TypeError was catched!")
print(value)
else:
for object in objectlist:
nodenames.append(object._v_pathname)
self.assertEqual(nodenames,
['/group0/table1',
'/group0/var1', '/group0/var4',
'/group0/group1/table2',
'/group0/group1/var1', '/group0/group1/var4'])
if common.verbose:
print("iter_nodes(groupobject, classname = 'Leaf') test passed")
nodenames = []
for node in objects:
try:
objectlist = [o for o in self.h5file.iter_nodes(node, 'Table')]
except TypeError:
if common.verbose:
(type, value, traceback) = sys.exc_info()
print("\nGreat!, the next TypeError was catched!")
print(value)
else:
for object in objectlist:
nodenames.append(object._v_pathname)
self.assertEqual(nodenames,
['/group0/table1', '/group0/group1/table2'])
if common.verbose:
print("iter_nodes(groupobject, classname = 'Table') test passed")
# Reset the warning
# warnings.filterwarnings("default", category=UserWarning)
def test03_TraverseTree(self):
"""Checking the File.walk_groups() method"""
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test03_TraverseTree..." %
self.__class__.__name__)
self.h5file = tables.open_file(self.h5fname, "r")
groups = []
tables_ = []
arrays = []
for group in self.h5file.walk_groups():
groups.append(group._v_pathname)
for table in self.h5file.list_nodes(group, 'Table'):
tables_.append(table._v_pathname)
for arr in self.h5file.list_nodes(group, 'Array'):
arrays.append(arr._v_pathname)
self.assertEqual(groups,
["/", "/group0", "/group0/group1",
"/group0/group1/group2"])
self.assertEqual(
tables_,
["/table0", "/group0/table1", "/group0/group1/table2"])
self.assertEqual(arrays,
['/var1', '/var4',
'/group0/var1', '/group0/var4',
'/group0/group1/var1', '/group0/group1/var4'])
if common.verbose:
print("walk_groups() test passed")
groups = []
tables_ = []
arrays = []
for group in self.h5file.walk_groups("/group0/group1"):
groups.append(group._v_pathname)
for table in self.h5file.list_nodes(group, 'Table'):
tables_.append(table._v_pathname)
for arr in self.h5file.list_nodes(group, 'Array'):
arrays.append(arr._v_pathname)
self.assertEqual(groups,
["/group0/group1", "/group0/group1/group2"])
self.assertEqual(tables_, ["/group0/group1/table2"])
self.assertEqual(arrays, [
'/group0/group1/var1', '/group0/group1/var4'])
if common.verbose:
print("walk_groups(pathname) test passed")
def test04_walkNodes(self):
"""Checking File.walk_nodes"""
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test04_walkNodes..." % self.__class__.__name__)
self.h5file = tables.open_file(self.h5fname, "r")
self.assertRaises(TypeError,
self.h5file.walk_nodes('/', 'NoSuchClass').next)
groups = []
tables1 = []
tables2 = []
arrays = []
for group in self.h5file.walk_nodes(classname="Group"):
groups.append(group._v_pathname)
for table in group._f_iter_nodes(classname='Table'):
tables1.append(table._v_pathname)
# Test the recursivity
for table in self.h5file.root._f_walknodes('Table'):
tables2.append(table._v_pathname)
for arr in self.h5file.walk_nodes(classname='Array'):
arrays.append(arr._v_pathname)
self.assertEqual(groups,
["/", "/group0", "/group0/group1",
"/group0/group1/group2"])
self.assertEqual(tables1,
["/table0", "/group0/table1",
"/group0/group1/table2"])
self.assertEqual(tables2,
["/table0", "/group0/table1",
"/group0/group1/table2"])
self.assertEqual(arrays,
['/var1', '/var4',
'/group0/var1', '/group0/var4',
'/group0/group1/var1', '/group0/group1/var4'])
if common.verbose:
print("File.__iter__() and Group.__iter__ test passed")
groups = []
tables_ = []
arrays = []
for group in self.h5file.walk_nodes("/group0/group1",
classname="Group"):
groups.append(group._v_pathname)
for table in group._f_walknodes('Table'):
tables_.append(table._v_pathname)
for arr in self.h5file.walk_nodes(group, 'Array'):
arrays.append(arr._v_pathname)
self.assertEqual(groups,
["/group0/group1", "/group0/group1/group2"])
self.assertEqual(tables_, ["/group0/group1/table2"])
self.assertEqual(arrays, [
'/group0/group1/var1', '/group0/group1/var4'])
if common.verbose:
print("walk_nodes(pathname, classname) test passed")
class DeepTreeTestCase(common.TempFileMixin, TestCase):
"""Checks for deep hierarchy levels in PyTables trees."""
def setUp(self):
super(DeepTreeTestCase, self).setUp()
# Here we put a more conservative limit to deal with more platforms
# With maxdepth = 64 this test would take less than 40 MB
# of main memory to run, which is quite reasonable nowadays.
# With maxdepth = 1024 this test will take around 300 MB.
if common.heavy:
self.maxdepth = 256 # Takes around 60 MB of memory!
else:
self.maxdepth = 64 # This should be safe for most machines
if common.verbose:
print("Maximum depth tested :", self.maxdepth)
# Open a new empty HDF5 file
group = self.h5file.root
if common.verbose:
print("Depth writing progress: ", end=' ')
# Iterate until maxdepth
for depth in range(self.maxdepth):
# Save it on the HDF5 file
if common.verbose:
print("%3d," % (depth), end=' ')
# Create a couple of arrays here
self.h5file.create_array(
group, 'array', [1, 1], "depth: %d" % depth)
self.h5file.create_array(
group, 'array2', [1, 1], "depth: %d" % depth)
# And also a group
self.h5file.create_group(group, 'group2_' + str(depth))
# Finally, iterate over a new group
group = self.h5file.create_group(group, 'group' + str(depth))
# Close the file
self.h5file.close()
def _check_tree(self, filename):
# Open the previous HDF5 file in read-only mode
with tables.open_file(filename, mode="r") as h5file:
group = h5file.root
if common.verbose:
print("\nDepth reading progress: ", end=' ')
# Get the metadata on the previosly saved arrays
for depth in range(self.maxdepth):
if common.verbose:
print("%3d," % (depth), end=' ')
# Check the contents
self.assertEqual(group.array[:], [1, 1])
self.assertTrue("array2" in group)
self.assertTrue("group2_"+str(depth) in group)
# Iterate over the next group
group = h5file.get_node(group, 'group' + str(depth))
if common.verbose:
print() # This flush the stdout buffer
def test00_deepTree(self):
"""Creation of a large depth object tree."""
self._check_tree(self.h5fname)
def test01a_copyDeepTree(self):
"""Copy of a large depth object tree."""
self.h5file = tables.open_file(self.h5fname, mode="r")
h5fname2 = tempfile.mktemp(".h5")
try:
with tables.open_file(h5fname2, mode="w") as h5file2:
if common.verbose:
print("\nCopying deep tree...")
self.h5file.copy_node(self.h5file.root, h5file2.root,
recursive=True)
self.h5file.close()
self._check_tree(h5fname2)
finally:
if os.path.exists(h5fname2):
os.remove(h5fname2)
def test01b_copyDeepTree(self):
"""Copy of a large depth object tree with small node cache."""
self.h5file = tables.open_file(self.h5fname, mode="r",
node_cache_slots=10)
h5fname2 = tempfile.mktemp(".h5")
try:
with tables.open_file(h5fname2, mode="w",
node_cache_slots=10) as h5file2:
if common.verbose:
print("\nCopying deep tree...")
self.h5file.copy_node(self.h5file.root, h5file2.root,
recursive=True)
self.h5file.close()
self._check_tree(h5fname2)
finally:
if os.path.exists(h5fname2):
os.remove(h5fname2)
def test01c_copyDeepTree(self):
"""Copy of a large depth object tree with no node cache."""
self.h5file = tables.open_file(self.h5fname, mode="r",
node_cache_slots=0)
h5fname2 = tempfile.mktemp(".h5")
try:
with tables.open_file(h5fname2, mode="w",
node_cache_slots=0) as h5file2:
if common.verbose:
print("\nCopying deep tree...")
self.h5file.copy_node(self.h5file.root, h5file2.root,
recursive=True)
self.h5file.close()
self._check_tree(h5fname2)
finally:
if os.path.exists(h5fname2):
os.remove(h5fname2)
@unittest.skipUnless(common.heavy, 'only in heavy mode')
def test01d_copyDeepTree(self):
"""Copy of a large depth object tree with static node cache."""
self.h5file = tables.open_file(self.h5fname, mode="r",
node_cache_slots=-256)
h5fname2 = tempfile.mktemp(".h5")
try:
with tables.open_file(h5fname2, mode="w",
node_cache_slots=-256) as h5file2:
if common.verbose:
print("\nCopying deep tree...")
self.h5file.copy_node(self.h5file.root, h5file2.root,
recursive=True)
self.h5file.close()
self._check_tree(h5fname2)
finally:
if os.path.exists(h5fname2):
os.remove(h5fname2)
class WideTreeTestCase(common.TempFileMixin, TestCase):
"""Checks for maximum number of children for a Group."""
def test00_Leafs(self):
"""Checking creation of large number of leafs (1024) per group.
Variable 'maxchildren' controls this check. PyTables support up
to 4096 children per group, but this would take too much memory
(up to 64 MB) for testing purposes (may be we can add a test for
big platforms). A 1024 children run takes up to 30 MB. A 512
children test takes around 25 MB.
"""
if common.heavy:
maxchildren = 4096
else:
maxchildren = 256
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test00_wideTree..." %
self.__class__.__name__)
print("Maximum number of children tested :", maxchildren)
a = [1, 1]
if common.verbose:
print("Children writing progress: ", end=' ')
for child in range(maxchildren):
if common.verbose:
print("%3d," % (child), end=' ')
self.h5file.create_array(self.h5file.root, 'array' + str(child),
a, "child: %d" % child)
if common.verbose:
print()
t1 = time.time()
a = [1, 1]
# Open the previous HDF5 file in read-only mode
self._reopen()
if common.verbose:
print("\nTime spent opening a file with %d arrays: %s s" %
(maxchildren, time.time()-t1))
print("\nChildren reading progress: ", end=' ')
# Get the metadata on the previosly saved arrays
for child in range(maxchildren):
if common.verbose:
print("%3d," % (child), end=' ')
# Create an array for later comparison
# Get the actual array
array_ = getattr(self.h5file.root, 'array' + str(child))
b = array_.read()
# Arrays a and b must be equal
self.assertEqual(a, b)
if common.verbose:
print() # This flush the stdout buffer
def test01_wideTree(self):
"""Checking creation of large number of groups (1024) per group.
Variable 'maxchildren' controls this check. PyTables support up
to 4096 children per group, but this would take too much memory
(up to 64 MB) for testing purposes (may be we can add a test for
big platforms). A 1024 children run takes up to 30 MB. A 512
children test takes around 25 MB.
"""
if common.heavy:
# for big platforms!
maxchildren = 4096
else:
# for standard platforms
maxchildren = 256
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test00_wideTree..." %
self.__class__.__name__)
print("Maximum number of children tested :", maxchildren)
if common.verbose:
print("Children writing progress: ", end=' ')
for child in range(maxchildren):
if common.verbose:
print("%3d," % (child), end=' ')
self.h5file.create_group(self.h5file.root, 'group' + str(child),
"child: %d" % child)
if common.verbose:
print()
t1 = time.time()
# Open the previous HDF5 file in read-only mode
self._reopen()
if common.verbose:
print("\nTime spent opening a file with %d groups: %s s" %
(maxchildren, time.time()-t1))
print("\nChildren reading progress: ", end=' ')
# Get the metadata on the previosly saved arrays
for child in range(maxchildren):
if common.verbose:
print("%3d," % (child), end=' ')
# Get the actual group
group = getattr(self.h5file.root, 'group' + str(child))
# Arrays a and b must be equal
self.assertEqual(group._v_title, "child: %d" % child)
if common.verbose:
print() # This flush the stdout buffer
class HiddenTreeTestCase(common.TempFileMixin, TestCase):
"""Check for hidden groups, leaves and hierarchies."""
def setUp(self):
super(HiddenTreeTestCase, self).setUp()
self.visible = [] # list of visible object paths
self.hidden = [] # list of hidden object paths
# Create some visible nodes: a, g, g/a1, g/a2, g/g, g/g/a.
h5f = self.h5file
h5f.create_array('/', 'a', [0])
g = h5f.create_group('/', 'g')
h5f.create_array(g, 'a1', [0])
h5f.create_array(g, 'a2', [0])
g_g = h5f.create_group(g, 'g')
h5f.create_array(g_g, 'a', [0])
self.visible.extend(['/a', '/g', '/g/a1', '/g/a2', '/g/g', '/g/g/a'])
# Create some hidden nodes: _p_a, _p_g, _p_g/a, _p_g/_p_a, g/_p_a.
h5f.create_array('/', '_p_a', [0])
hg = h5f.create_group('/', '_p_g')
h5f.create_array(hg, 'a', [0])
h5f.create_array(hg, '_p_a', [0])
h5f.create_array(g, '_p_a', [0])
self.hidden.extend(
['/_p_a', '/_p_g', '/_p_g/a', '/_p_g/_p_a', '/g/_p_a'])
# The test behind commented out because the .objects dictionary
# has been removed (as well as .leaves and .groups)
def _test00_objects(self):
"""Absence of hidden nodes in `File.objects`."""
objects = self.h5file.objects
warnings.filterwarnings('ignore', category=DeprecationWarning)
for vpath in self.visible:
self.assertTrue(
vpath in objects,
"Missing visible node ``%s`` from ``File.objects``." % vpath)
for hpath in self.hidden:
self.assertTrue(
hpath not in objects,
"Found hidden node ``%s`` in ``File.objects``." % hpath)
warnings.filterwarnings('default', category=DeprecationWarning)
# The test behind commented out because the .objects dictionary
# has been removed (as well as .leaves and .groups)
def _test00b_objects(self):
"""Object dictionaries conformance with ``walk_nodes()``."""
def dictCheck(dictName, classname):
file_ = self.h5file
objects = getattr(file_, dictName)
walkPaths = [node._v_pathname
for node in file_.walk_nodes('/', classname)]
dictPaths = [path for path in objects]
walkPaths.sort()
dictPaths.sort()
self.assertEqual(
walkPaths, dictPaths,
"nodes in ``%s`` do not match those from ``walk_nodes()``"
% dictName)
self.assertEqual(
len(walkPaths), len(objects),
"length of ``%s`` differs from that of ``walk_nodes()``"
% dictName)
warnings.filterwarnings('ignore', category=DeprecationWarning)
dictCheck('objects', None)
dictCheck('groups', 'Group')
dictCheck('leaves', 'Leaf')
warnings.filterwarnings('default', category=DeprecationWarning)
def test01_getNode(self):
"""Node availability via `File.get_node()`."""
h5f = self.h5file
for vpath in self.visible:
h5f.get_node(vpath)
for hpath in self.hidden:
h5f.get_node(hpath)
def test02_walkGroups(self):
"""Hidden group absence in `File.walk_groups()`."""
hidden = self.hidden
for group in self.h5file.walk_groups('/'):
pathname = group._v_pathname
self.assertTrue(pathname not in hidden,
"Walked across hidden group ``%s``." % pathname)
def test03_walkNodes(self):
"""Hidden node absence in `File.walk_nodes()`."""
hidden = self.hidden
for node in self.h5file.walk_nodes('/'):
pathname = node._v_pathname
self.assertTrue(pathname not in hidden,
"Walked across hidden node ``%s``." % pathname)
def test04_listNodesVisible(self):
"""Listing visible nodes under a visible group (list_nodes)."""
hidden = self.hidden
for node in self.h5file.list_nodes('/g'):
pathname = node._v_pathname
self.assertTrue(pathname not in hidden,
"Listed hidden node ``%s``." % pathname)
def test04b_listNodesVisible(self):
"""Listing visible nodes under a visible group (iter_nodes)."""
hidden = self.hidden
for node in self.h5file.iter_nodes('/g'):
pathname = node._v_pathname
self.assertTrue(pathname not in hidden,
"Listed hidden node ``%s``." % pathname)
def test05_listNodesHidden(self):
"""Listing visible nodes under a hidden group (list_nodes)."""
hidden = self.hidden
node_to_find = '/_p_g/a'
found_node = False
for node in self.h5file.list_nodes('/_p_g'):
pathname = node._v_pathname
if pathname == node_to_find:
found_node = True
self.assertTrue(pathname in hidden,
"Listed hidden node ``%s``." % pathname)
self.assertTrue(found_node,
"Hidden node ``%s`` was not listed." % node_to_find)
def test05b_iterNodesHidden(self):
"""Listing visible nodes under a hidden group (iter_nodes)."""
hidden = self.hidden
node_to_find = '/_p_g/a'
found_node = False
for node in self.h5file.iter_nodes('/_p_g'):
pathname = node._v_pathname
if pathname == node_to_find:
found_node = True
self.assertTrue(pathname in hidden,
"Listed hidden node ``%s``." % pathname)
self.assertTrue(found_node,
"Hidden node ``%s`` was not listed." % node_to_find)
# The test behind commented out because the .objects dictionary
# has been removed (as well as .leaves and .groups)
def _test06_reopen(self):
"""Reopening a file with hidden nodes."""
self.h5file.close()
self.h5file = tables.open_file(self.h5fname)
self.test00_objects()
def test07_move(self):
"""Moving a node between hidden and visible groups."""
is_visible_node = self.h5file.is_visible_node
self.assertFalse(is_visible_node('/_p_g/a'))
self.h5file.move_node('/_p_g/a', '/g', 'a')
self.assertTrue(is_visible_node('/g/a'))
self.h5file.move_node('/g/a', '/_p_g', 'a')
self.assertFalse(is_visible_node('/_p_g/a'))
def test08_remove(self):
"""Removing a visible group with hidden children."""
self.assertTrue('/g/_p_a' in self.h5file)
self.h5file.root.g._f_remove(recursive=True)
self.assertFalse('/g/_p_a' in self.h5file)
class CreateParentsTestCase(common.TempFileMixin, TestCase):
"""Test the ``createparents`` flag.
These are mainly for the user interface. More thorough tests on the
workings of the flag can be found in the ``test_do_undo.py`` module.
"""
filters = tables.Filters(complevel=4) # simply non-default
def setUp(self):
super(CreateParentsTestCase, self).setUp()
self.h5file.create_array('/', 'array', [1])
self.h5file.create_group('/', 'group', filters=self.filters)
def test00_parentType(self):
"""Using the right type of parent node argument."""
h5file, root = self.h5file, self.h5file.root
self.assertRaises(TypeError, h5file.create_array,
root.group, 'arr', [1], createparents=True)
self.assertRaises(TypeError, h5file.copy_node,
'/array', root.group, createparents=True)
self.assertRaises(TypeError, h5file.move_node,
'/array', root.group, createparents=True)
self.assertRaises(TypeError, h5file.copy_children,
'/group', root, createparents=True)
def test01_inside(self):
"""Placing a node inside a nonexistent child of itself."""
self.assertRaises(tables.NodeError, self.h5file.move_node,
'/group', '/group/foo/bar',
createparents=True)
self.assertFalse('/group/foo' in self.h5file)
self.assertRaises(tables.NodeError, self.h5file.copy_node,
'/group', '/group/foo/bar',
recursive=True, createparents=True)
self.assertFalse('/group/foo' in self.h5fname)
def test02_filters(self):
"""Propagating the filters of created parent groups."""
self.h5file.create_group('/group/foo/bar', 'baz', createparents=True)
self.assertTrue('/group/foo/bar/baz' in self.h5file)
for group in self.h5file.walk_groups('/group'):
self.assertEqual(self.filters, group._v_filters)
def suite():
theSuite = unittest.TestSuite()
# This counter is useful when detecting memory leaks
niter = 1
for i in range(niter):
theSuite.addTest(unittest.makeSuite(TreeTestCase))
theSuite.addTest(unittest.makeSuite(DeepTreeTestCase))
theSuite.addTest(unittest.makeSuite(WideTreeTestCase))
theSuite.addTest(unittest.makeSuite(HiddenTreeTestCase))
theSuite.addTest(unittest.makeSuite(CreateParentsTestCase))
return theSuite
if __name__ == '__main__':
common.parse_argv(sys.argv)
common.print_versions()
unittest.main(defaultTest='suite')
|