extend JavaTest to test the size prefixed binary as well

This commit is contained in:
Robert Schmidtke 2017-10-02 17:34:36 +02:00
parent 2939516fdf
commit 68be4420dd
1 changed files with 37 additions and 17 deletions

View File

@ -29,23 +29,28 @@ class JavaTest {
// First, let's test reading a FlatBuffer generated by C++ code:
// This file was generated from monsterdata_test.json
byte[] data = null;
File file = new File("monsterdata_test.mon");
RandomAccessFile f = null;
try {
f = new RandomAccessFile(file, "r");
data = new byte[(int)f.length()];
f.readFully(data);
f.close();
} catch(java.io.IOException e) {
System.out.println("FlatBuffers test: couldn't read file");
return;
String[] filenames = new String[] { "monsterdata_test.mon", "monsterdata_test.mops" };
byte[][] data = { null, null };
for (int i = 0; i < filenames.length; ++i) {
File file = new File(filenames[i]);
RandomAccessFile f = null;
try {
f = new RandomAccessFile(file, "r");
data[i] = new byte[(int)f.length()];
f.readFully(data[i]);
f.close();
} catch(java.io.IOException e) {
System.out.println("FlatBuffers test: couldn't read file " + filenames[i]);
return;
}
}
// Now test it:
ByteBuffer bb = ByteBuffer.wrap(data);
TestBuffer(bb);
ByteBuffer bb = ByteBuffer.wrap(data[0]);
TestBuffer(bb, false);
bb = ByteBuffer.wrap(data[1]);
TestBuffer(bb, true);
// Second, let's create a FlatBuffer from scratch in Java, and test it also.
// We use an initial size of 1 to exercise the reallocation algorithm,
@ -79,10 +84,25 @@ class JavaTest {
TestEq(Any.name(Any.Monster), "Monster");
}
static void TestBuffer(ByteBuffer bb) {
TestEq(Monster.MonsterBufferHasIdentifier(bb), true);
static void TestBuffer(ByteBuffer bb, boolean sizePrefix) {
if (sizePrefix) {
// the first 4 bytes hold the length of the remaining buffer
TestEq(Monster.getSizePrefix(bb), bb.remaining() - 4);
Monster monster = Monster.getRootAsMonster(bb);
// advance buffer by these 4 bytes to check the identifier
ByteBuffer _bb = bb.slice();
_bb.position(4);
TestEq(Monster.MonsterBufferHasIdentifier(_bb), true);
} else {
TestEq(Monster.MonsterBufferHasIdentifier(bb), true);
}
Monster monster;
if (sizePrefix) {
monster = Monster.getSizePrefixedRootAsMonster(bb);
} else {
monster = Monster.getRootAsMonster(bb);
}
TestEq(monster.hp(), (short)80);
TestEq(monster.mana(), (short)150); // default
@ -133,7 +153,7 @@ class JavaTest {
// this method checks additional fields not present in the binary buffer read from file
// these new tests are performed on top of the regular tests
static void TestExtendedBuffer(ByteBuffer bb) {
TestBuffer(bb);
TestBuffer(bb, false);
Monster monster = Monster.getRootAsMonster(bb);