~ubuntu-branches/ubuntu/quantal/pytables/quantal

« back to all changes in this revision

Viewing changes to test/test_nestedtypes.py

  • Committer: Bazaar Package Importer
  • Author(s): Sebastian Dröge
  • Date: 2005-11-27 20:25:34 UTC
  • mfrom: (1.1.1 upstream)
  • Revision ID: james.westby@ubuntu.com-20051127202534-l8jzyd8357krw40h
Tags: 1.1.1-1ubuntu1
* Sync with Debian:
  + Use python 2.4 as default

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
"""
 
2
Test module for nested types under PyTables
 
3
===========================================
 
4
 
 
5
:Author:   Ivan Vilata
 
6
:Author:   Francesc Altet
 
7
:Contact:  ivilata@carabos.com
 
8
:Created:  2005-05-18
 
9
:License:  BSD
 
10
:Revision: $Id: test_nestedtypes.py 1178 2005-09-09 15:17:42Z faltet $
 
11
"""
 
12
 
 
13
import unittest
 
14
 
 
15
import numarray
 
16
import numarray.records
 
17
 
 
18
from test_all import verbose
 
19
import tables as t
 
20
import tables.nestedrecords as nr
 
21
from tables.IsDescription import Description
 
22
from tables.IndexArray import minRowIndex
 
23
import util
 
24
 
 
25
 
 
26
 
 
27
# This is the structure of the table used for testing (DON'T PANIC!):
 
28
#
 
29
# +-+---------------------------------+-----+----------+-+-+
 
30
# |x|Info                             |color|info      |y|z|
 
31
# | +-----+--+----------------+----+--+     +----+-----+ | |
 
32
# | |value|y2|Info2           |name|z2|     |Name|Value| | |
 
33
# | |     |  +----+-----+--+--+    |  |     |    |     | | |
 
34
# | |     |  |name|value|y3|z3|    |  |     |    |     | | |
 
35
# +-+-----+--+----+-----+--+--+----+--+-----+----+-----+-+-+
 
36
#
 
37
# Please note that some fields are explicitly ordered while others are
 
38
# ordered alphabetically by name.
 
39
 
 
40
# The declaration of the nested table:
 
41
class Info(t.IsDescription):
 
42
    _v_pos = 3
 
43
    Name = t.StringCol(length=2)
 
44
    Value = t.Complex64Col()
 
45
 
 
46
class TestTDescr(t.IsDescription):
 
47
 
 
48
    """A description that has several nested columns."""
 
49
 
 
50
    x = t.Int32Col(0, shape=2, pos=0) #0
 
51
    y = t.FloatCol(1, shape=(2,2))
 
52
    z = t.UInt8Col(1)
 
53
    color = t.StringCol(2, " ", pos=2)
 
54
    info = Info()
 
55
    class Info(t.IsDescription): #1
 
56
        _v_pos = 1
 
57
        name = t.StringCol(length=2)
 
58
        value = t.Complex64Col(pos=0) #0
 
59
        y2 = t.FloatCol(1, pos=1) #1
 
60
        z2 = t.UInt8Col(1)
 
61
        class Info2(t.IsDescription):
 
62
            y3 = t.Time64Col(1, shape=2)
 
63
            z3 = t.EnumCol({'r':4, 'g':2, 'b':1}, 'r', shape=2)
 
64
            name = t.StringCol(length=2)
 
65
            value = t.Complex64Col(shape=2)
 
66
 
 
67
# The corresponding nested array description:
 
68
testADescr = [
 
69
    ('x', '(2,)Int32'),
 
70
    ('Info', [
 
71
        ('value', 'Complex64'),
 
72
        ('y2', 'Float64'),
 
73
        ('Info2', [
 
74
            ('name', 'a2'),
 
75
            ('value', '(2,)Complex64'),
 
76
            ('y3', '(2,)Float64'),
 
77
            ('z3', '(2,)UInt32')]),
 
78
        ('name', 'a2'),
 
79
        ('z2', 'UInt8')]),
 
80
    ('color', 'a2'),
 
81
    ('info', [
 
82
        ('Name', 'a2'),
 
83
        ('Value', 'Complex64')]),
 
84
    ('y', '(2,2)Float64'),
 
85
    ('z', 'UInt8')]
 
86
 
 
87
# The corresponding nested array description (brief version):
 
88
testBDescr = [
 
89
    ('x', '(2,)i4'),
 
90
    ('Info', [
 
91
        ('value', '1c16'),
 
92
        ('y2', '1f8'),
 
93
        ('Info2', [
 
94
            ('name', '1a2'),
 
95
            ('value', '(2,)c16'),
 
96
            ('y3', '(2,)f8'),
 
97
            ('z3', '(2,)u4')]),
 
98
        ('name', '1a2'),
 
99
        ('z2', '1u1')]),
 
100
    ('color', '1a2'),
 
101
    ('info', [
 
102
        ('Name', '1a2'),
 
103
        ('Value', '1c16')]),
 
104
    ('y', '(2, 2)f8'),
 
105
    ('z', '1u1')]
 
106
 
 
107
# A nested array for testing:
 
108
testABuffer = [
 
109
    # x     Info                                                color info        y                  z
 
110
    #       value y2 Info2                            name z2         Name Value
 
111
    #                name   value    y3       z3
 
112
    [(3,2), [6j, 6., ['nn', (6j,4j), (6.,4.), (1,2)], 'NN', 8], 'cc', ['NN', 6j], ((6.,4.),(6.,4.)), 8],
 
113
    [(4,3), [7j, 7., ['oo', (7j,5j), (7.,5.), (2,1)], 'OO', 9], 'dd', ['OO', 7j], ((7.,5.),(7.,5.)), 9],
 
114
    ]
 
115
testAData = nr.array(testABuffer, descr=testADescr)
 
116
# The name of the column to be searched:
 
117
testCondCol = 'Info/z2'
 
118
# The name of a nested column (it can not be searched):
 
119
testNestedCol = 'Info'
 
120
# The condition to be applied on the column (all but the last row match it):
 
121
testCondition = lambda col: 2 < col < 9
 
122
 
 
123
 
 
124
 
 
125
def areDescriptionsEqual(desc1, desc2):
 
126
    """
 
127
    Are both `desc1` and `desc2` equivalent descriptions?
 
128
 
 
129
    The arguments may be description objects (``IsDescription``,
 
130
    ``Description``) or dictionaries.
 
131
    """
 
132
 
 
133
    if isinstance(desc1, t.Col):
 
134
        # This is a rough comparison but it suffices here.
 
135
        return (desc1.stype == desc2.stype and desc2.type == desc2.type
 
136
                and desc1.shape == desc2.shape
 
137
                and desc1.itemsize == desc2.itemsize
 
138
                and desc1._v_pos == desc2._v_pos
 
139
                and desc1.indexed == desc2.indexed)
 
140
 
 
141
    if hasattr(desc1, '_v_colObjects'):  # quacks like a Description
 
142
        cols1 = desc1._v_colObjects
 
143
    elif hasattr(desc1, 'columns'):  # quacks like an IsDescription
 
144
        cols1 = desc1.columns
 
145
    else:  # hope it quacks like a dictionary
 
146
        cols1 = desc1
 
147
 
 
148
    if hasattr(desc2, '_v_colObjects'):  # quacks like a Description
 
149
        cols2 = desc2._v_colObjects
 
150
    elif hasattr(desc2, 'columns'):  # quacks like an IsDescription
 
151
        cols2 = desc2.columns
 
152
    else:  # hope it quacks like a dictionary
 
153
        cols2 = desc2
 
154
 
 
155
    if len(cols1) != len(cols2):
 
156
        return False
 
157
 
 
158
    for (colName, colobj1) in cols1.iteritems():
 
159
        colobj2 = cols2[colName]
 
160
        if colName in ('_v_indexprops', '_v_pos'):
 
161
            # The comparison may not be quite exhaustive!
 
162
            return colobj1 == colobj2
 
163
        if not areDescriptionsEqual(colobj1, colobj2):
 
164
            return False
 
165
 
 
166
    return True
 
167
 
 
168
 
 
169
 
 
170
class DescriptionTestCase(util.PyTablesTestCase):
 
171
 
 
172
    """Test creating nested column descriptions."""
 
173
 
 
174
    _TestTDescr = TestTDescr
 
175
    _testADescr = testADescr
 
176
    _testBDescr = testBDescr
 
177
    _testAData = testAData
 
178
 
 
179
    def test00_instance(self):
 
180
        """Creating an instance of a nested description."""
 
181
 
 
182
        self._verboseHeader()
 
183
        self.assert_(
 
184
            areDescriptionsEqual(self._TestTDescr, self._TestTDescr()),
 
185
            "Table description does not match the given one.")
 
186
 
 
187
    def test01_instance(self):
 
188
        """Checking attrs of an instance of a nested description."""
 
189
 
 
190
        self._verboseHeader()
 
191
        descr = Description(self._TestTDescr().columns)
 
192
        if verbose:
 
193
            print "Generated description:", descr._v_nestedDescr
 
194
            print "Should look like:", self._testBDescr
 
195
        self.assert_(self._testBDescr == descr._v_nestedDescr,
 
196
                     "Description._v_nestedDescr does not match.")
 
197
 
 
198
 
 
199
 
 
200
class CreateTestCase(util.TempFileMixin, util.PyTablesTestCase):
 
201
 
 
202
    """Test creating a nested table and opening it."""
 
203
 
 
204
    _TestTDescr = TestTDescr
 
205
    _testABuffer = testABuffer
 
206
    _testAData = testAData
 
207
 
 
208
 
 
209
    def _checkColumns(self, cols, desc):
 
210
        """
 
211
        Check that `cols` has all the accessors for `self._TestTDescr`.
 
212
        """
 
213
 
 
214
        # ``_desc`` is a leaf column and ``cols`` a ``Column``.
 
215
        if isinstance(desc, t.Col):
 
216
            return isinstance(cols, t.Column)
 
217
 
 
218
        # ``_desc`` is a description object and ``cols`` a ``Cols``.
 
219
        descColumns = desc._v_colObjects
 
220
        for colName in descColumns:
 
221
            if colName not in cols._v_colnames:
 
222
                return False
 
223
            if not self._checkColumns(cols._f_col(colName),
 
224
                                      descColumns[colName]):
 
225
                return False
 
226
 
 
227
        return True
 
228
 
 
229
 
 
230
    def _checkDescription(self, table):
 
231
        """
 
232
        Check that description of `table` matches `self._TestTDescr`.
 
233
        """
 
234
 
 
235
        # Compare descriptions.
 
236
        self.assert_(
 
237
            areDescriptionsEqual(self._TestTDescr, table.description),
 
238
            "Table description does not match the given one.")
 
239
        # Check access to columns.
 
240
        self._checkColumns(table.cols, table.description)
 
241
 
 
242
 
 
243
    def test00_create(self):
 
244
        """Creating a nested table."""
 
245
 
 
246
        self._verboseHeader()
 
247
        tbl = self.h5file.createTable(
 
248
            '/', 'test', self._TestTDescr, title=self._getMethodName())
 
249
        self._checkDescription(tbl)
 
250
 
 
251
 
 
252
    def test01_open(self):
 
253
        """Opening a nested table."""
 
254
 
 
255
        self._verboseHeader()
 
256
        self.h5file.createTable(
 
257
            '/', 'test', self._TestTDescr, title=self._getMethodName())
 
258
        self._reopen()
 
259
        self._checkDescription(self.h5file.root.test)
 
260
 
 
261
 
 
262
    def test02_NestedRecArrayCompat(self):
 
263
        """Creating a compatible ``NestedRecArray``."""
 
264
 
 
265
        self._verboseHeader()
 
266
        tbl = self.h5file.createTable(
 
267
            '/', 'test', self._TestTDescr, title=self._getMethodName())
 
268
 
 
269
        nrarr = nr.array(testABuffer,
 
270
                         names=tbl.description._v_nestedNames,
 
271
                         formats=tbl.description._v_nestedFormats)
 
272
        self.assert_(util.areArraysEqual(nrarr, self._testAData),
 
273
                     "Can not create a compatible record array.")
 
274
 
 
275
 
 
276
    def test03_NRA(self):
 
277
        """Creating a table from a NestedRecArray object."""
 
278
 
 
279
        self._verboseHeader()
 
280
        tbl = self.h5file.createTable(
 
281
            '/', 'test', self._testAData, title=self._getMethodName())
 
282
        tbl.flush()
 
283
 
 
284
        readAData = tbl.read()
 
285
        self.assert_(util.areArraysEqual(self._testAData, readAData),
 
286
                     "Written and read values differ.")
 
287
 
 
288
    def test04_NRA2(self):
 
289
        """Creating a table from a generated NestedRecArray object."""
 
290
 
 
291
        self._verboseHeader()
 
292
        tbl = self.h5file.createTable(
 
293
            '/', 'test', self._TestTDescr, title=self._getMethodName())
 
294
        tbl.append(self._testAData)
 
295
        readAData = tbl.read()
 
296
 
 
297
        tbl2 = self.h5file.createTable(
 
298
            '/', 'test2', readAData, title=self._getMethodName())
 
299
        readAData2 = tbl2.read()
 
300
 
 
301
        self.assert_(util.areArraysEqual(self._testAData, readAData2),
 
302
                     "Written and read values differ.")
 
303
 
 
304
 
 
305
class WriteTestCase(util.TempFileMixin, util.PyTablesTestCase):
 
306
 
 
307
    """Test writing data in a nested table."""
 
308
 
 
309
    _TestTDescr = TestTDescr
 
310
    _testAData = testAData
 
311
    _testCondCol = testCondCol
 
312
    _testNestedCol = testNestedCol
 
313
 
 
314
 
 
315
    def _testCondition(self, col):
 
316
        """Get a condition on `col` that matches all but the last row."""
 
317
        return testCondition(col)
 
318
 
 
319
 
 
320
    def _appendRow(self, row, index):
 
321
        """
 
322
        Append the `index`-th row in `self._testAData` to `row`.
 
323
 
 
324
        Values are set field-by-field (be it nested or not).
 
325
        """
 
326
 
 
327
        record = self._testAData[index]
 
328
        for fieldName in self._testAData._names:
 
329
            row[fieldName] = record.field(fieldName)
 
330
        row.append()
 
331
 
 
332
 
 
333
    def _appendRowRecursive(self, row, index):
 
334
        """
 
335
        Append the `index`-th row in `self._testAData` to `row`.
 
336
 
 
337
        Values are set atom-by-atom.
 
338
        """
 
339
 
 
340
        record = self._testAData[index]
 
341
        # Flatten the record if it is nested,
 
342
        # to iterate easily over atomic fields.
 
343
        # If the record is not nested, do nothing.
 
344
        if isinstance(record, nr.NestedRecord):
 
345
            record = record.asRecord()
 
346
 
 
347
        # Add as an ordinary flat record.
 
348
        for fieldName in self._testAData._names:
 
349
            row[fieldName] = record.field(fieldName)
 
350
        row.append()
 
351
 
 
352
 
 
353
    def test00_append(self):
 
354
        """Appending a set of rows."""
 
355
 
 
356
        self._verboseHeader()
 
357
        tbl = self.h5file.createTable(
 
358
            '/', 'test', self._TestTDescr, title=self._getMethodName())
 
359
        tbl.append(self._testAData)
 
360
        tbl.flush()
 
361
 
 
362
        if self.reopen:
 
363
            self._reopen()
 
364
            tbl = self.h5file.root.test
 
365
 
 
366
        readAData = tbl.read()
 
367
        self.assert_(util.areArraysEqual(self._testAData, readAData),
 
368
                     "Written and read values differ.")
 
369
 
 
370
 
 
371
    def test01_row(self):
 
372
        """Appending individual rows."""
 
373
 
 
374
        self._verboseHeader()
 
375
        tbl = self.h5file.createTable(
 
376
            '/', 'test', self._TestTDescr, title=self._getMethodName())
 
377
 
 
378
        row = tbl.row
 
379
        # Add the first row atom by atom.
 
380
        self._appendRowRecursive(row, 0)
 
381
        # Add the rest of the rows field by field.
 
382
        for i in range(1, len(self._testAData)):
 
383
            self._appendRow(row, i)
 
384
        tbl.flush()
 
385
 
 
386
        if self.reopen:
 
387
            self._reopen()
 
388
            tbl = self.h5file.root.test
 
389
 
 
390
        readAData = tbl.read()
 
391
        self.assert_(util.areArraysEqual(self._testAData, readAData),
 
392
                     "Written and read values differ.")
 
393
 
 
394
 
 
395
    def test02_where(self):
 
396
        """Searching nested data."""
 
397
 
 
398
        self._verboseHeader()
 
399
        tbl = self.h5file.createTable(
 
400
            '/', 'test', self._TestTDescr, title=self._getMethodName())
 
401
        tbl.append(self._testAData)
 
402
        tbl.flush()
 
403
 
 
404
        if self.reopen:
 
405
            self._reopen()
 
406
            tbl = self.h5file.root.test
 
407
 
 
408
        searchedCoords = tbl.getWhereList(
 
409
            self._testCondition(tbl.cols._f_col(self._testCondCol)))
 
410
 
 
411
        # All but the last row match the condition.
 
412
        searchedCoords.sort()
 
413
        self.assertEqual(searchedCoords, range(len(self._testAData) - 1),
 
414
                         "Search returned incorrect results.")
 
415
 
 
416
 
 
417
    def test03_colscond(self):
 
418
        """Searching on a column with nested columns."""
 
419
 
 
420
        self._verboseHeader()
 
421
        tbl = self.h5file.createTable(
 
422
            '/', 'test', self._TestTDescr, title=self._getMethodName())
 
423
        tbl.append(self._testAData)
 
424
        tbl.flush()
 
425
 
 
426
        if self.reopen:
 
427
            self._reopen()
 
428
            tbl = self.h5file.root.test
 
429
 
 
430
        self.assertRaises(
 
431
            TypeError, self._testCondition,
 
432
            tbl.cols._f_col(self._testNestedCol))
 
433
 
 
434
 
 
435
    def test04_modifyColumn(self):
 
436
        """Modifying one single nested column (modifyColumn)."""
 
437
 
 
438
        self._verboseHeader()
 
439
        tbl = self.h5file.createTable(
 
440
            '/', 'test', self._TestTDescr, title=self._getMethodName())
 
441
        tbl.append(self._testAData)
 
442
        tbl.flush()
 
443
 
 
444
        nColumn = self._testNestedCol
 
445
        # Get the nested column data and swap the first and last rows.
 
446
        raTable = self._testAData.copy()
 
447
        raColumn = raTable.field(nColumn)
 
448
        # The next will not work until NestedRecords supports copies
 
449
        (raColumn[0], raColumn[-1]) = (raColumn[-1], raColumn[0])
 
450
 
 
451
        # Write the resulting column and re-read the whole table.
 
452
        tbl.modifyColumn(colname=nColumn, column=raColumn)
 
453
        tbl.flush()
 
454
 
 
455
        if self.reopen:
 
456
            self._reopen()
 
457
            tbl = self.h5file.root.test
 
458
 
 
459
        raReadTable = tbl.read()
 
460
        if verbose:
 
461
            print "Table read:", raReadTable
 
462
            print "Should look like:", raTable
 
463
 
 
464
        # Compare it to the written one.
 
465
        self.assert_(util.areArraysEqual(raTable, raReadTable),
 
466
                     "Written and read values differ.")
 
467
 
 
468
    def test05a_modifyColumns(self):
 
469
        """Modifying one nested column (modifyColumns)."""
 
470
 
 
471
        self._verboseHeader()
 
472
        tbl = self.h5file.createTable(
 
473
            '/', 'test', self._TestTDescr, title=self._getMethodName())
 
474
        tbl.append(self._testAData)
 
475
        tbl.flush()
 
476
 
 
477
        nColumn = self._testNestedCol
 
478
        # Get the nested column data and swap the first and last rows.
 
479
        raTable = self._testAData.copy()
 
480
        raColumn = raTable.field(nColumn)
 
481
        (raColumn[0], raColumn[-1]) = (raColumn[-1].copy(), raColumn[0].copy())
 
482
 
 
483
        # Write the resulting column and re-read the whole table.
 
484
        tbl.modifyColumns(names=[nColumn], columns=raColumn)
 
485
        tbl.flush()
 
486
 
 
487
        if self.reopen:
 
488
            self._reopen()
 
489
            tbl = self.h5file.root.test
 
490
 
 
491
        raReadTable = tbl.read()
 
492
        if verbose:
 
493
            print "Table read:", raReadTable
 
494
            print "Should look like:", raTable
 
495
 
 
496
        # Compare it to the written one.
 
497
        self.assert_(util.areArraysEqual(raTable, raReadTable),
 
498
                     "Written and read values differ.")
 
499
 
 
500
    def test05b_modifyColumns(self):
 
501
        """Modifying two nested columns (modifyColumns)."""
 
502
 
 
503
        self._verboseHeader()
 
504
        tbl = self.h5file.createTable(
 
505
            '/', 'test', self._TestTDescr, title=self._getMethodName())
 
506
        tbl.append(self._testAData)
 
507
        tbl.flush()
 
508
 
 
509
        # Get the nested column data and swap the first and last rows.
 
510
        colnames = ['x', 'color']  # Get the first two columns
 
511
        raCols = nr.fromarrays([self._testAData.copy().field('x'),
 
512
                                self._testAData.copy().field('color')],
 
513
                               descr=[('x','(2,)i4'), ('color', '1a2')])
 
514
                               #descr=tbl.description._v_nestedDescr[0:2])
 
515
                               # or...
 
516
                               # names=tbl.description._v_nestedNames[0:2],
 
517
                               # formats=tbl.description._v_nestedFormats[0:2])
 
518
        (raCols[0], raCols[-1]) = (raCols[-1].copy(), raCols[0].copy())
 
519
 
 
520
        # Write the resulting columns
 
521
        tbl.modifyColumns(names=colnames, columns=raCols)
 
522
        tbl.flush()
 
523
 
 
524
        if self.reopen:
 
525
            self._reopen()
 
526
            tbl = self.h5file.root.test
 
527
 
 
528
        # Re-read the appropriate columns
 
529
        raCols2 = nr.fromarrays([tbl.cols._f_col('x')[:],
 
530
                                 tbl.cols._f_col('color')[:]],
 
531
                                descr=raCols.descr)
 
532
        if verbose:
 
533
            print "Table read:", raCols2
 
534
            print "Should look like:", raCols
 
535
 
 
536
        # Compare it to the written one.
 
537
        self.assert_(util.areArraysEqual(raCols, raCols2),
 
538
                     "Written and read values differ.")
 
539
 
 
540
    def test06_modifyRows(self):
 
541
        "Checking modifying several rows at once (using nestedrecarray)"
 
542
 
 
543
        self._verboseHeader()
 
544
        tbl = self.h5file.createTable(
 
545
            '/', 'test', self._TestTDescr, title=self._getMethodName())
 
546
        tbl.append(self._testAData)
 
547
        tbl.flush()
 
548
 
 
549
        # Get the nested record and swap the first and last rows.
 
550
        raTable = self._testAData.copy()
 
551
        (raTable[0], raTable[-1]) = (raTable[-1].copy(), raTable[0].copy())
 
552
 
 
553
        # Write the resulting nested record and re-read the whole table.
 
554
        tbl.modifyRows(start=0, stop=2, rows=raTable)
 
555
        tbl.flush()
 
556
 
 
557
        if self.reopen:
 
558
            self._reopen()
 
559
            tbl = self.h5file.root.test
 
560
 
 
561
        raReadTable = tbl.read()
 
562
        if verbose:
 
563
            print "Table read:", raReadTable
 
564
            print "Should look like:", raTable
 
565
 
 
566
        # Compare it to the written one.
 
567
        self.assert_(util.areArraysEqual(raTable, raReadTable),
 
568
                     "Written and read values differ.")
 
569
 
 
570
    def test07_index(self):
 
571
        """Checking indexes of nested columns"""
 
572
 
 
573
        self._verboseHeader()
 
574
        tbl = self.h5file.createTable(
 
575
            '/', 'test', self._TestTDescr, title=self._getMethodName(),
 
576
            expectedrows = minRowIndex*2)
 
577
        for i in range(minRowIndex):
 
578
            tbl.append(self._testAData)
 
579
        tbl.flush()
 
580
        coltoindex = tbl.cols._f_col(self._testCondCol)
 
581
        indexrows = coltoindex.createIndex(testmode=1)
 
582
 
 
583
        if self.reopen:
 
584
            self._reopen()
 
585
            tbl = self.h5file.root.test
 
586
            coltoindex = tbl.cols._f_col(self._testCondCol)
 
587
 
 
588
        if verbose:
 
589
            print "Number of written rows:", tbl.nrows
 
590
            print "Number of indexed rows:", coltoindex.index.nelements
 
591
 
 
592
        # Check indexing flags:
 
593
        self.assert_(tbl.indexed == True, "Table not indexed")
 
594
        self.assert_(coltoindex.index <> None, "Column not indexed")
 
595
        self.assert_(tbl.colindexed[self._testCondCol], "Column not indexed")
 
596
        # Do a look-up for values
 
597
        searchedCoords = tbl.getWhereList(
 
598
            self._testCondition(tbl.cols._f_col(self._testCondCol)))
 
599
 
 
600
        if verbose:
 
601
            print "Searched coords:", searchedCoords
 
602
 
 
603
        # All even rows match the condition.
 
604
        searchedCoords.sort()
 
605
        self.assertEqual(searchedCoords, range(0, minRowIndex*2, 2),
 
606
                         "Search returned incorrect results.")
 
607
 
 
608
 
 
609
class WriteNoReopen(WriteTestCase):
 
610
    reopen = 0
 
611
 
 
612
class WriteReopen(WriteTestCase):
 
613
    reopen = 1
 
614
 
 
615
 
 
616
class ReadTestCase(util.TempFileMixin, util.PyTablesTestCase):
 
617
    """Checking the Table.Cols accessor."""
 
618
 
 
619
    _TestTDescr = TestTDescr
 
620
    _testABuffer = testABuffer
 
621
    _testAData = testAData
 
622
    _testNestedCol = testNestedCol
 
623
 
 
624
 
 
625
    def test01_read(self):
 
626
        """Checking Table.read with subgroups with a range index with step."""
 
627
 
 
628
        self._verboseHeader()
 
629
        tbl = self.h5file.createTable(
 
630
            '/', 'test', self._TestTDescr, title=self._getMethodName())
 
631
        tbl.append(self._testAData)
 
632
 
 
633
        if self.reopen:
 
634
            self._reopen()
 
635
            tbl = self.h5file.root.test
 
636
 
 
637
        nrarr = nr.array(testABuffer,
 
638
                         names=tbl.description._v_nestedNames,
 
639
                         formats=tbl.description._v_nestedFormats)
 
640
        tblcols = tbl.read(start=0, step=2, field='Info')
 
641
        nrarrcols = nrarr.field('Info')[0::2]
 
642
        if verbose:
 
643
            print "Read cols:", tblcols
 
644
            print "Should look like:", nrarrcols
 
645
        self.assert_(util.areArraysEqual(nrarrcols, tblcols),
 
646
                     "Original array are retrieved doesn't match.")
 
647
 
 
648
    def test02_read(self):
 
649
        """Checking Table.read with a nested Column."""
 
650
 
 
651
        self._verboseHeader()
 
652
        tbl = self.h5file.createTable(
 
653
            '/', 'test', self._TestTDescr, title=self._getMethodName())
 
654
        tbl.append(self._testAData)
 
655
 
 
656
        if self.reopen:
 
657
            self._reopen()
 
658
            tbl = self.h5file.root.test
 
659
 
 
660
        self.assertRaises(NotImplementedError, tbl.read, field='Info/value')
 
661
 
 
662
class ReadNoReopen(ReadTestCase):
 
663
    reopen = 0
 
664
 
 
665
class ReadReopen(ReadTestCase):
 
666
    reopen = 1
 
667
 
 
668
 
 
669
class ColsTestCase(util.TempFileMixin, util.PyTablesTestCase):
 
670
    """Checking the Table.Cols accessor."""
 
671
 
 
672
    _TestTDescr = TestTDescr
 
673
    _testABuffer = testABuffer
 
674
    _testAData = testAData
 
675
    _testNestedCol = testNestedCol
 
676
 
 
677
 
 
678
    def test01a_f_col(self):
 
679
        """Checking cols._f_col() with a subgroup."""
 
680
 
 
681
        self._verboseHeader()
 
682
        tbl = self.h5file.createTable(
 
683
            '/', 'test', self._TestTDescr, title=self._getMethodName())
 
684
 
 
685
        if self.reopen:
 
686
            self._reopen()
 
687
            tbl = self.h5file.root.test
 
688
 
 
689
        tblcol = tbl.cols._f_col(self._testNestedCol)
 
690
        if verbose:
 
691
            print "Column group name:", tblcol._v_desc._v_pathname
 
692
        self.assert_(tblcol._v_desc._v_pathname == self._testNestedCol,
 
693
                     "Column group name doesn't match.")
 
694
 
 
695
    def test01b_f_col(self):
 
696
        """Checking cols._f_col() with a column."""
 
697
 
 
698
        self._verboseHeader()
 
699
        tbl = self.h5file.createTable(
 
700
            '/', 'test', self._TestTDescr, title=self._getMethodName())
 
701
 
 
702
        if self.reopen:
 
703
            self._reopen()
 
704
            tbl = self.h5file.root.test
 
705
 
 
706
        tblcol = tbl.cols._f_col(self._testNestedCol+"/name")
 
707
        if verbose:
 
708
            print "Column name:", tblcol.name
 
709
        self.assert_(tblcol.name == "name",
 
710
                     "Column name doesn't match.")
 
711
 
 
712
    def test01c_f_col(self):
 
713
        """Checking cols._f_col() with a nested subgroup."""
 
714
 
 
715
        self._verboseHeader()
 
716
        tbl = self.h5file.createTable(
 
717
            '/', 'test', self._TestTDescr, title=self._getMethodName())
 
718
 
 
719
        tblcol = tbl.cols._f_col(self._testNestedCol+"/Info2")
 
720
        if verbose:
 
721
            print "Column group name:", tblcol._v_desc._v_pathname
 
722
        self.assert_(tblcol._v_desc._v_pathname == self._testNestedCol+"/Info2",
 
723
                     "Column group name doesn't match.")
 
724
 
 
725
    def test02a__len__(self):
 
726
        """Checking cols.__len__() in root level."""
 
727
 
 
728
        self._verboseHeader()
 
729
        tbl = self.h5file.createTable(
 
730
            '/', 'test', self._TestTDescr, title=self._getMethodName())
 
731
 
 
732
        if self.reopen:
 
733
            self._reopen()
 
734
            tbl = self.h5file.root.test
 
735
 
 
736
        length = len(tbl.cols)
 
737
        if verbose:
 
738
            print "Column group length:", length
 
739
        self.assert_(length == 6,
 
740
                     "Column group length doesn't match.")
 
741
 
 
742
    def test02b__len__(self):
 
743
        """Checking cols.__len__() in subgroup level."""
 
744
 
 
745
        self._verboseHeader()
 
746
        tbl = self.h5file.createTable(
 
747
            '/', 'test', self._TestTDescr, title=self._getMethodName())
 
748
 
 
749
        if self.reopen:
 
750
            self._reopen()
 
751
            tbl = self.h5file.root.test
 
752
 
 
753
        length = len(tbl.cols.Info)
 
754
        if verbose:
 
755
            print "Column group length:", length
 
756
        self.assert_(length == 5,
 
757
                     "Column group length doesn't match.")
 
758
 
 
759
    def test03a__getitem__(self):
 
760
        """Checking cols.__getitem__() with a single index."""
 
761
 
 
762
        self._verboseHeader()
 
763
        tbl = self.h5file.createTable(
 
764
            '/', 'test', self._TestTDescr, title=self._getMethodName())
 
765
        tbl.append(self._testAData)
 
766
 
 
767
        if self.reopen:
 
768
            self._reopen()
 
769
            tbl = self.h5file.root.test
 
770
 
 
771
        nrarr = nr.array(testABuffer,
 
772
                         names=tbl.description._v_nestedNames,
 
773
                         formats=tbl.description._v_nestedFormats)
 
774
        tblcols = tbl.cols[1]
 
775
        nrarrcols = nrarr[1]
 
776
        if verbose:
 
777
            print "Read cols:", tblcols
 
778
            print "Should look like:", nrarrcols
 
779
        self.assert_(util.areArraysEqual(nrarrcols, tblcols),
 
780
                     "Original array are retrieved doesn't match.")
 
781
 
 
782
    def test03b__getitem__(self):
 
783
        """Checking cols.__getitem__() with a range index."""
 
784
 
 
785
        self._verboseHeader()
 
786
        tbl = self.h5file.createTable(
 
787
            '/', 'test', self._TestTDescr, title=self._getMethodName())
 
788
        tbl.append(self._testAData)
 
789
 
 
790
        if self.reopen:
 
791
            self._reopen()
 
792
            tbl = self.h5file.root.test
 
793
 
 
794
        nrarr = nr.array(testABuffer,
 
795
                         names=tbl.description._v_nestedNames,
 
796
                         formats=tbl.description._v_nestedFormats)
 
797
        tblcols = tbl.cols[0:2]
 
798
        nrarrcols = nrarr[0:2]
 
799
        if verbose:
 
800
            print "Read cols:", tblcols
 
801
            print "Should look like:", nrarrcols
 
802
        self.assert_(util.areArraysEqual(nrarrcols, tblcols),
 
803
                     "Original array are retrieved doesn't match.")
 
804
 
 
805
    def test03c__getitem__(self):
 
806
        """Checking cols.__getitem__() with a range index with step."""
 
807
 
 
808
        self._verboseHeader()
 
809
        tbl = self.h5file.createTable(
 
810
            '/', 'test', self._TestTDescr, title=self._getMethodName())
 
811
        tbl.append(self._testAData)
 
812
 
 
813
        if self.reopen:
 
814
            self._reopen()
 
815
            tbl = self.h5file.root.test
 
816
 
 
817
        nrarr = nr.array(testABuffer,
 
818
                         names=tbl.description._v_nestedNames,
 
819
                         formats=tbl.description._v_nestedFormats)
 
820
        tblcols = tbl.cols[0::2]
 
821
        nrarrcols = nrarr[0::2]
 
822
        if verbose:
 
823
            print "Read cols:", tblcols
 
824
            print "Should look like:", nrarrcols
 
825
        self.assert_(util.areArraysEqual(nrarrcols, tblcols),
 
826
                     "Original array are retrieved doesn't match.")
 
827
 
 
828
 
 
829
    def test04a__getitem__(self):
 
830
        """Checking cols.__getitem__() with subgroups with a single index."""
 
831
 
 
832
        self._verboseHeader()
 
833
        tbl = self.h5file.createTable(
 
834
            '/', 'test', self._TestTDescr, title=self._getMethodName())
 
835
        tbl.append(self._testAData)
 
836
 
 
837
        if self.reopen:
 
838
            self._reopen()
 
839
            tbl = self.h5file.root.test
 
840
 
 
841
        nrarr = nr.array(testABuffer,
 
842
                         names=tbl.description._v_nestedNames,
 
843
                         formats=tbl.description._v_nestedFormats)
 
844
        tblcols = tbl.cols._f_col('Info')[1]
 
845
        nrarrcols = nrarr.field('Info')[1]
 
846
        if verbose:
 
847
            print "Read cols:", tblcols
 
848
            print "Should look like:", nrarrcols
 
849
        self.assert_(util.areArraysEqual(nrarrcols, tblcols),
 
850
                     "Original array are retrieved doesn't match.")
 
851
 
 
852
    def test04b__getitem__(self):
 
853
        """Checking cols.__getitem__() with subgroups with a range index."""
 
854
 
 
855
        self._verboseHeader()
 
856
        tbl = self.h5file.createTable(
 
857
            '/', 'test', self._TestTDescr, title=self._getMethodName())
 
858
        tbl.append(self._testAData)
 
859
 
 
860
        if self.reopen:
 
861
            self._reopen()
 
862
            tbl = self.h5file.root.test
 
863
 
 
864
        nrarr = nr.array(testABuffer,
 
865
                         names=tbl.description._v_nestedNames,
 
866
                         formats=tbl.description._v_nestedFormats)
 
867
        tblcols = tbl.cols._f_col('Info')[0:2]
 
868
        nrarrcols = nrarr.field('Info')[0:2]
 
869
        if verbose:
 
870
            print "Read cols:", tblcols
 
871
            print "Should look like:", nrarrcols
 
872
        self.assert_(util.areArraysEqual(nrarrcols, tblcols),
 
873
                     "Original array are retrieved doesn't match.")
 
874
 
 
875
    def test04c__getitem__(self):
 
876
        """Checking cols.__getitem__() with subgroups with a range index with step."""
 
877
 
 
878
        self._verboseHeader()
 
879
        tbl = self.h5file.createTable(
 
880
            '/', 'test', self._TestTDescr, title=self._getMethodName())
 
881
        tbl.append(self._testAData)
 
882
 
 
883
        if self.reopen:
 
884
            self._reopen()
 
885
            tbl = self.h5file.root.test
 
886
 
 
887
        nrarr = nr.array(testABuffer,
 
888
                         names=tbl.description._v_nestedNames,
 
889
                         formats=tbl.description._v_nestedFormats)
 
890
        tblcols = tbl.cols._f_col('Info')[0::2]
 
891
        nrarrcols = nrarr.field('Info')[0::2]
 
892
        if verbose:
 
893
            print "Read cols:", tblcols
 
894
            print "Should look like:", nrarrcols
 
895
        self.assert_(util.areArraysEqual(nrarrcols, tblcols),
 
896
                     "Original array are retrieved doesn't match.")
 
897
 
 
898
    def test05a__getitem__(self):
 
899
        """Checking cols.__getitem__() with a column with a single index."""
 
900
 
 
901
        self._verboseHeader()
 
902
        tbl = self.h5file.createTable(
 
903
            '/', 'test', self._TestTDescr, title=self._getMethodName())
 
904
        tbl.append(self._testAData)
 
905
 
 
906
        if self.reopen:
 
907
            self._reopen()
 
908
            tbl = self.h5file.root.test
 
909
 
 
910
        nrarr = nr.array(testABuffer,
 
911
                         names=tbl.description._v_nestedNames,
 
912
                         formats=tbl.description._v_nestedFormats)
 
913
        tblcols = tbl.cols._f_col('Info/value')[1]
 
914
        nrarrcols = nrarr.field('Info/value')[1]
 
915
        if verbose:
 
916
            print "Read cols:", tblcols
 
917
            print "Should look like:", nrarrcols
 
918
        self.assert_(nrarrcols == tblcols,
 
919
                     "Original array are retrieved doesn't match.")
 
920
 
 
921
    def test05b__getitem__(self):
 
922
        """Checking cols.__getitem__() with a column with a range index."""
 
923
 
 
924
        self._verboseHeader()
 
925
        tbl = self.h5file.createTable(
 
926
            '/', 'test', self._TestTDescr, title=self._getMethodName())
 
927
        tbl.append(self._testAData)
 
928
 
 
929
        if self.reopen:
 
930
            self._reopen()
 
931
            tbl = self.h5file.root.test
 
932
 
 
933
        nrarr = nr.array(testABuffer,
 
934
                         names=tbl.description._v_nestedNames,
 
935
                         formats=tbl.description._v_nestedFormats)
 
936
        tblcols = tbl.cols._f_col('Info/value')[0:2]
 
937
        nrarrcols = nrarr.field('Info/value')[0:2]
 
938
        if verbose:
 
939
            print "Read cols:", tblcols
 
940
            print "Should look like:", nrarrcols
 
941
        self.assert_(util.areArraysEqual(nrarrcols, tblcols),
 
942
                     "Original array are retrieved doesn't match.")
 
943
 
 
944
    def test05c__getitem__(self):
 
945
        """Checking cols.__getitem__() with a column with a range index with step."""
 
946
 
 
947
        self._verboseHeader()
 
948
        tbl = self.h5file.createTable(
 
949
            '/', 'test', self._TestTDescr, title=self._getMethodName())
 
950
        tbl.append(self._testAData)
 
951
 
 
952
        if self.reopen:
 
953
            self._reopen()
 
954
            tbl = self.h5file.root.test
 
955
 
 
956
        nrarr = nr.array(testABuffer,
 
957
                         names=tbl.description._v_nestedNames,
 
958
                         formats=tbl.description._v_nestedFormats)
 
959
        tblcols = tbl.cols._f_col('Info/value')[0::2]
 
960
        nrarrcols = nrarr.field('Info/value')[0::2]
 
961
        if verbose:
 
962
            print "Read cols:", tblcols
 
963
            print "Should look like:", nrarrcols
 
964
        self.assert_(util.areArraysEqual(nrarrcols, tblcols),
 
965
                     "Original array are retrieved doesn't match.")
 
966
 
 
967
 
 
968
class ColsNoReopen(ColsTestCase):
 
969
    reopen = 0
 
970
 
 
971
class ColsReopen(ColsTestCase):
 
972
    reopen = 1
 
973
 
 
974
 
 
975
 
 
976
#----------------------------------------------------------------------
 
977
 
 
978
def suite():
 
979
    """Return a test suite consisting of all the test cases in the module."""
 
980
 
 
981
    theSuite = unittest.TestSuite()
 
982
    niter = 1
 
983
    #heavy = 1  # uncomment this only for testing purposes
 
984
 
 
985
    #theSuite.addTest(unittest.makeSuite(DescriptionTestCase))
 
986
    #theSuite.addTest(unittest.makeSuite(WriteReopen))
 
987
    for i in range(niter):
 
988
        theSuite.addTest(unittest.makeSuite(DescriptionTestCase))
 
989
        theSuite.addTest(unittest.makeSuite(CreateTestCase))
 
990
        theSuite.addTest(unittest.makeSuite(WriteNoReopen))
 
991
        theSuite.addTest(unittest.makeSuite(WriteReopen))
 
992
        theSuite.addTest(unittest.makeSuite(ColsNoReopen))
 
993
        theSuite.addTest(unittest.makeSuite(ColsReopen))
 
994
        theSuite.addTest(unittest.makeSuite(ReadNoReopen))
 
995
        theSuite.addTest(unittest.makeSuite(ReadReopen))
 
996
 
 
997
    return theSuite
 
998
 
 
999
 
 
1000
if __name__ == '__main__':
 
1001
    unittest.main( defaultTest='suite' )
 
1002
 
 
1003
 
 
1004
 
 
1005
## Local Variables:
 
1006
## mode: python
 
1007
## py-indent-offset: 4
 
1008
## tab-width: 4
 
1009
## fill-column: 72
 
1010
## End: