public void testChildrenArraysInvariants() throws Exception {
Directory indexDir = newDirectory();
TaxonomyWriter tw = new LuceneTaxonomyWriter(indexDir);
fillTaxonomy(tw);
tw.close();
TaxonomyReader tr = new LuceneTaxonomyReader(indexDir);
ChildrenArrays ca = tr.getChildrenArrays();
int[] youngestChildArray = ca.getYoungestChildArray();
assertEquals(tr.getSize(), youngestChildArray.length);
int[] olderSiblingArray = ca.getOlderSiblingArray();
assertEquals(tr.getSize(), olderSiblingArray.length);
// test that the "youngest child" of every category is indeed a child:
for (int i=0; i<tr.getSize(); i++) {
int youngestChild = youngestChildArray[i];
if (youngestChild != TaxonomyReader.INVALID_ORDINAL) {
assertEquals(i, tr.getParent(youngestChild));
}
}
// test that the "older sibling" of every category is indeed older (lower)
// (it can also be INVALID_ORDINAL, which is lower than any ordinal)
for (int i=0; i<tr.getSize(); i++) {
assertTrue("olderSiblingArray["+i+"] should be <"+i, olderSiblingArray[i] < i);
}
// test that the "older sibling" of every category is indeed a sibling
// (they share the same parent)
for (int i=0; i<tr.getSize(); i++) {
int sibling = olderSiblingArray[i];
if (sibling == TaxonomyReader.INVALID_ORDINAL) {
continue;
}
assertEquals(tr.getParent(i), tr.getParent(sibling));
}
// And now for slightly more complex (and less "invariant-like"...)
// tests:
// test that the "youngest child" is indeed the youngest (so we don't
// miss the first children in the chain)
for (int i=0; i<tr.getSize(); i++) {
// Find the really youngest child:
int j;
for (j=tr.getSize()-1; j>i; j--) {
if (tr.getParent(j)==i) {
break; // found youngest child
}
}
if (j==i) { // no child found
j=TaxonomyReader.INVALID_ORDINAL;
}
assertEquals(j, youngestChildArray[i]);
}
// test that the "older sibling" is indeed the least oldest one - and
// not a too old one or -1 (so we didn't miss some children in the
// middle or the end of the chain).
for (int i=0; i<tr.getSize(); i++) {
// Find the youngest older sibling:
int j;
for (j=i-1; j>=0; j--) {
if (tr.getParent(j)==tr.getParent(i)) {
break; // found youngest older sibling
}
}
if (j<0) { // no sibling found
j=TaxonomyReader.INVALID_ORDINAL;
}
assertEquals(j, olderSiblingArray[i]);
}
tr.close();
indexDir.close();
}