提交 353303a7 编写于 作者: Y Yueh-Hsuan Chiang

Merge pull request #380 from fyrz/RocksJava-Junit-Framework

[RocksJava] Test framework support
......@@ -32,9 +32,9 @@ NATIVE_JAVA_CLASSES = org.rocksdb.AbstractComparator\
org.rocksdb.StringAppendOperator\
org.rocksdb.WriteBatch\
org.rocksdb.WriteBatch.Handler\
org.rocksdb.WriteBatchInternal\
org.rocksdb.WriteBatchTest\
org.rocksdb.WriteOptions\
org.rocksdb.test.WriteBatchInternal\
org.rocksdb.test.WriteBatchTest\
org.rocksdb.WriteOptions\
ROCKSDB_MAJOR = $(shell egrep "ROCKSDB_MAJOR.[0-9]" ../include/rocksdb/version.h | cut -d ' ' -f 3)
ROCKSDB_MINOR = $(shell egrep "ROCKSDB_MINOR.[0-9]" ../include/rocksdb/version.h | cut -d ' ' -f 3)
......@@ -43,21 +43,57 @@ ROCKSDB_PATCH = $(shell egrep "ROCKSDB_PATCH.[0-9]" ../include/rocksdb/version.h
NATIVE_INCLUDE = ./include
ARCH := $(shell getconf LONG_BIT)
ROCKSDB_JAR = rocksdbjni-$(ROCKSDB_MAJOR).$(ROCKSDB_MINOR).$(ROCKSDB_PATCH)-linux$(ARCH).jar
ifeq ($(PLATFORM), OS_MACOSX)
ROCKSDB_JAR = rocksdbjni-$(ROCKSDB_MAJOR).$(ROCKSDB_MINOR).$(ROCKSDB_PATCH)-osx.jar
endif
JAVA_TESTS = org.rocksdb.test.BackupableDBTest\
org.rocksdb.test.BlockBasedTableConfigTest\
org.rocksdb.test.ColumnFamilyOptionsTest\
org.rocksdb.test.ColumnFamilyTest\
org.rocksdb.test.ComparatorOptionsTest\
org.rocksdb.test.ComparatorTest\
org.rocksdb.test.DBOptionsTest\
org.rocksdb.test.DirectComparatorTest\
org.rocksdb.test.FilterTest\
org.rocksdb.test.FlushTest\
org.rocksdb.test.KeyMayExistTest\
org.rocksdb.test.MemTableTest\
org.rocksdb.test.MergeTest\
org.rocksdb.test.MixedOptionsTest\
org.rocksdb.test.OptionsTest\
org.rocksdb.test.PlainTableConfigTest\
org.rocksdb.test.ReadOnlyTest\
org.rocksdb.test.ReadOptionsTest\
org.rocksdb.test.RocksDBTest\
org.rocksdb.test.RocksEnvTest\
org.rocksdb.test.RocksIteratorTest\
org.rocksdb.test.SnapshotTest\
org.rocksdb.test.StatisticsCollectorTest\
org.rocksdb.test.WriteBatchHandlerTest\
org.rocksdb.test.WriteBatchTest\
org.rocksdb.test.WriteOptionsTest\
JAVA_TEST_LIBDIR = ./test-libs/
JAVA_JUNIT_JAR = $(JAVA_TEST_LIBDIR)junit-4.12-beta-2.jar
JAVA_HAMCR_JAR = $(JAVA_TEST_LIBDIR)hamcrest-core-1.3.jar
JAVA_MOCKITO_JAR = $(JAVA_TEST_LIBDIR)mockito-all-1.9.5.jar
JAVA_CGLIB_JAR = $(JAVA_TEST_LIBDIR)cglib-2.2.2.jar
JAVA_ASSERTJ_JAR = $(JAVA_TEST_LIBDIR)assertj-core-1.7.0.jar
JAVA_TESTCLASSPATH = $(ROCKSDB_JAR):$(JAVA_JUNIT_JAR):$(JAVA_HAMCR_JAR):$(JAVA_MOCKITO_JAR):$(JAVA_CGLIB_JAR):$(JAVA_ASSERTJ_JAR):.:./*
clean:
-find . -name "*.class" -exec rm {} \;
-find . -name "hs*.log" -exec rm {} \;
rm -rf javadoc/*
rm -rf test-libs/
javadocs:
mkdir -p javadoc; javadoc -d javadoc -sourcepath . -subpackages org
mkdir -p javadoc; javadoc -d javadoc -sourcepath . -subpackages org -exclude org.rocksdb.test
java: javadocs
java: javadocs resolve_test_deps
javac org/rocksdb/util/*.java org/rocksdb/*.java
javac -cp $(JAVA_TESTCLASSPATH) org/rocksdb/test/*.java
@cp ../HISTORY.md ./HISTORY-CPP.md
@rm -f ./HISTORY-CPP.md
javah -d $(NATIVE_INCLUDE) -jni $(NATIVE_JAVA_CLASSES)
......@@ -76,33 +112,16 @@ column_family_sample: java
java -ea -Djava.library.path=.:../ -cp ".:./*" -Xcheck:jni RocksDBColumnFamilySample /tmp/rocksdbjni
@rm -rf /tmp/rocksdbjni
test: java
@rm -rf /tmp/rocksdbjni_*
javac org/rocksdb/test/*.java
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.WriteBatchTest
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.BackupableDBTest
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.BlockBasedTableConfigTest
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.DBOptionsTest
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.ColumnFamilyTest
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.ColumnFamilyOptionsTest
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.FilterTest
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.FlushTest
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.KeyMayExistTest
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.MemTableTest
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.MergeTest
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.MixedOptionsTest
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.OptionsTest
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.PlainTableConfigTest
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.ReadOnlyTest
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.ReadOptionsTest
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.RocksIteratorTest
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.SnapshotTest
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.StatisticsCollectorTest
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.ComparatorOptionsTest
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.ComparatorTest
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.DirectComparatorTest
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.WriteBatchHandlerTest
@rm -rf /tmp/rocksdbjni_*
resolve_test_deps:
mkdir -p "$(JAVA_TEST_LIBDIR)"
test -s "$(JAVA_JUNIT_JAR)" || curl -k -L -o $(JAVA_JUNIT_JAR) http://search.maven.org/remotecontent?filepath=junit/junit/4.12-beta-2/junit-4.12-beta-2.jar
test -s "$(JAVA_HAMCR_JAR)" || curl -k -L -o $(JAVA_HAMCR_JAR) http://search.maven.org/remotecontent?filepath=org/hamcrest/hamcrest-core/1.3/hamcrest-core-1.3.jar
test -s "$(JAVA_MOCKITO_JAR)" || curl -k -L -o "$(JAVA_MOCKITO_JAR)" http://search.maven.org/remotecontent?filepath=org/mockito/mockito-all/1.9.5/mockito-all-1.9.5.jar
test -s "$(JAVA_CGLIB_JAR)" || curl -k -L -o "$(JAVA_CGLIB_JAR)" http://search.maven.org/remotecontent?filepath=cglib/cglib/2.2.2/cglib-2.2.2.jar
test -s "$(JAVA_ASSERTJ_JAR)" || curl -k -L -o "$(JAVA_ASSERTJ_JAR)" http://central.maven.org/maven2/org/assertj/assertj-core/1.7.0/assertj-core-1.7.0.jar
test: java resolve_test_deps
java -ea -Djava.library.path=.:../ -cp "$(JAVA_TESTCLASSPATH)" org.rocksdb.test.RocksJunitRunner $(JAVA_TESTS)
db_bench: java
javac org/rocksdb/benchmark/*.java
......@@ -30,9 +30,11 @@ public class ColumnFamilyHandle extends RocksObject {
* before freeing the native handle.</p>
*/
@Override protected void disposeInternal() {
assert(isInitialized());
if (rocksDB_.isInitialized()) {
disposeInternal(nativeHandle_);
synchronized (rocksDB_) {
assert (isInitialized());
if (rocksDB_.isInitialized()) {
disposeInternal(nativeHandle_);
}
}
}
......
......@@ -1010,7 +1010,6 @@ public class Options extends RocksObject
long cfOptHandle);
private native void disposeInternal(long handle);
private native void setEnv(long optHandle, long envHandle);
private native long getEnvHandle(long handle);
private native void prepareForBulkLoad(long handle);
// DB native handles
......
......@@ -155,7 +155,6 @@ public class ReadOptions extends RocksObject {
@Override protected void disposeInternal() {
assert(isInitialized());
disposeInternal(nativeHandle_);
}
private native void disposeInternal(long handle);
......
......@@ -103,6 +103,7 @@ public class RocksDB extends RocksObject {
// This allows to use the rocksjni default Options instead of
// the c++ one.
Options options = new Options();
options.setCreateIfMissing(true);
return open(options, path);
}
......@@ -363,8 +364,10 @@ public class RocksDB extends RocksObject {
}
@Override protected void disposeInternal() {
assert(isInitialized());
disposeInternal(nativeHandle_);
synchronized (this) {
assert (isInitialized());
disposeInternal(nativeHandle_);
}
}
/**
......@@ -1150,6 +1153,8 @@ public class RocksDB extends RocksObject {
throws RocksDBException, IllegalArgumentException {
// throws RocksDBException if something goes wrong
dropColumnFamily(nativeHandle_, columnFamilyHandle.nativeHandle_);
// After the drop the native handle is not valid anymore
columnFamilyHandle.nativeHandle_ = 0;
}
/**
......
......@@ -18,6 +18,7 @@ public class RocksEnv extends RocksObject {
static {
default_env_ = new RocksEnv(getDefaultEnvInternal());
}
private static native long getDefaultEnvInternal();
......@@ -101,7 +102,7 @@ public class RocksEnv extends RocksObject {
* {@link RocksObject} must implement to release their associated C++
* resource.
*/
protected void disposeInternal() {
@Override protected void disposeInternal() {
disposeInternal(nativeHandle_);
}
private native void disposeInternal(long handle);
......
......@@ -143,9 +143,11 @@ public class RocksIterator extends RocksObject {
* before freeing the native handle.</p>
*/
@Override protected void disposeInternal() {
assert(isInitialized());
if (rocksDB_.isInitialized()) {
disposeInternal(nativeHandle_);
synchronized (rocksDB_) {
assert (isInitialized());
if (rocksDB_.isInitialized()) {
disposeInternal(nativeHandle_);
}
}
}
......
......@@ -221,13 +221,3 @@ public class WriteBatch extends RocksObject {
private native void disposeInternal(long handle);
}
}
/**
* Package-private class which provides java api to access
* c++ WriteBatchInternal.
*/
class WriteBatchInternal {
static native void setSequence(WriteBatch batch, long sn);
static native long sequence(WriteBatch batch);
static native void append(WriteBatch b1, WriteBatch b2);
}
// Copyright (c) 2014, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
package org.rocksdb;
import java.util.*;
import java.io.UnsupportedEncodingException;
/**
* This class mimics the db/write_batch_test.cc in the c++ rocksdb library.
*/
public class WriteBatchTest {
static {
RocksDB.loadLibrary();
}
public static void main(String args[]) {
System.out.println("Testing WriteBatchTest.Empty ===");
Empty();
System.out.println("Testing WriteBatchTest.Multiple ===");
Multiple();
System.out.println("Testing WriteBatchTest.Append ===");
Append();
System.out.println("Testing WriteBatchTest.Blob ===");
Blob();
// The following tests have not yet ported.
// Continue();
// PutGatherSlices();
System.out.println("Passed all WriteBatchTest!");
}
static void Empty() {
WriteBatch batch = new WriteBatch();
assert(batch.count() == 0);
}
static void Multiple() {
try {
WriteBatch batch = new WriteBatch();
batch.put("foo".getBytes("US-ASCII"), "bar".getBytes("US-ASCII"));
batch.remove("box".getBytes("US-ASCII"));
batch.put("baz".getBytes("US-ASCII"), "boo".getBytes("US-ASCII"));
WriteBatchInternal.setSequence(batch, 100);
assert(100 == WriteBatchInternal.sequence(batch));
assert(3 == batch.count());
assert(("Put(baz, boo)@102" +
"Delete(box)@101" +
"Put(foo, bar)@100")
.equals(new String(getContents(batch), "US-ASCII")));
} catch (UnsupportedEncodingException e) {
System.err.println(e);
assert(false);
}
}
static void Append() {
WriteBatch b1 = new WriteBatch();
WriteBatch b2 = new WriteBatch();
WriteBatchInternal.setSequence(b1, 200);
WriteBatchInternal.setSequence(b2, 300);
WriteBatchInternal.append(b1, b2);
assert(getContents(b1).length == 0);
assert(b1.count() == 0);
try {
b2.put("a".getBytes("US-ASCII"), "va".getBytes("US-ASCII"));
WriteBatchInternal.append(b1, b2);
assert("Put(a, va)@200".equals(new String(getContents(b1), "US-ASCII")));
assert(1 == b1.count());
b2.clear();
b2.put("b".getBytes("US-ASCII"), "vb".getBytes("US-ASCII"));
WriteBatchInternal.append(b1, b2);
assert(("Put(a, va)@200" +
"Put(b, vb)@201")
.equals(new String(getContents(b1), "US-ASCII")));
assert(2 == b1.count());
b2.remove("foo".getBytes("US-ASCII"));
WriteBatchInternal.append(b1, b2);
assert(("Put(a, va)@200" +
"Put(b, vb)@202" +
"Put(b, vb)@201" +
"Delete(foo)@203")
.equals(new String(getContents(b1), "US-ASCII")));
assert(4 == b1.count());
} catch (UnsupportedEncodingException e) {
System.err.println(e);
assert(false);
}
}
static void Blob() {
WriteBatch batch = new WriteBatch();
try {
batch.put("k1".getBytes("US-ASCII"), "v1".getBytes("US-ASCII"));
batch.put("k2".getBytes("US-ASCII"), "v2".getBytes("US-ASCII"));
batch.put("k3".getBytes("US-ASCII"), "v3".getBytes("US-ASCII"));
batch.putLogData("blob1".getBytes("US-ASCII"));
batch.remove("k2".getBytes("US-ASCII"));
batch.putLogData("blob2".getBytes("US-ASCII"));
batch.merge("foo".getBytes("US-ASCII"), "bar".getBytes("US-ASCII"));
assert(5 == batch.count());
assert(("Merge(foo, bar)@4" +
"Put(k1, v1)@0" +
"Delete(k2)@3" +
"Put(k2, v2)@1" +
"Put(k3, v3)@2")
.equals(new String(getContents(batch), "US-ASCII")));
} catch (UnsupportedEncodingException e) {
System.err.println(e);
assert(false);
}
}
static native byte[] getContents(WriteBatch batch);
}
......@@ -12,6 +12,7 @@ import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Random;
import static org.assertj.core.api.Assertions.assertThat;
import static org.rocksdb.test.Types.byteToInt;
import static org.rocksdb.test.Types.intToByte;
......@@ -75,13 +76,13 @@ public abstract class AbstractComparatorTest {
int count = 0;
for (it.seekToFirst(); it.isValid(); it.next()) {
final int thisKey = byteToInt(it.key());
assert(thisKey > lastKey);
assertThat(thisKey).isGreaterThan(lastKey);
lastKey = thisKey;
count++;
}
db.close();
assert(count == ITERATIONS);
assertThat(count).isEqualTo(ITERATIONS);
} catch (final RocksDBException e) {
System.err.format("[ERROR]: %s%n", e);
......
......@@ -5,121 +5,161 @@
package org.rocksdb.test;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.rocksdb.*;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class BackupableDBTest {
static final String db_path = "/tmp/rocksdbjni_backupable_db_test";
static final String backup_path = "/tmp/rocksdbjni_backupable_db_backup_test";
static {
RocksDB.loadLibrary();
}
public static void main(String[] args) {
Options opt = new Options();
opt.setCreateIfMissing(true);
@ClassRule
public static final RocksMemoryResource rocksMemoryResource =
new RocksMemoryResource();
@Rule
public TemporaryFolder dbFolder = new TemporaryFolder();
BackupableDBOptions bopt = new BackupableDBOptions(backup_path, false,
true, false, true, 0, 0);
@Rule
public TemporaryFolder backupFolder = new TemporaryFolder();
@Test
public void backupableDb() throws RocksDBException {
Options opt = null;
BackupableDBOptions bopt = null;
BackupableDB bdb = null;
List<BackupInfo> backupInfos;
List<BackupInfo> restoreInfos;
RestoreOptions ropt = null;
RestoreBackupableDB rdb = null;
try {
bdb = BackupableDB.open(opt, bopt, db_path);
opt = new Options();
opt.setCreateIfMissing(true);
bopt = new BackupableDBOptions(
backupFolder.getRoot().getAbsolutePath(), false,
true, false, true, 0, 0);
assertThat(bopt.backupDir()).isEqualTo(
backupFolder.getRoot().getAbsolutePath());
List<BackupInfo> backupInfos;
List<BackupInfo> restoreInfos;
bdb = BackupableDB.open(opt, bopt,
dbFolder.getRoot().getAbsolutePath());
bdb.put("abc".getBytes(), "def".getBytes());
bdb.put("ghi".getBytes(), "jkl".getBytes());
backupInfos = bdb.getBackupInfos();
assert(backupInfos.size() == 0);
assertThat(backupInfos.size()).
isEqualTo(0);
bdb.createNewBackup(true);
backupInfos = bdb.getBackupInfos();
assert(backupInfos.size() == 1);
assertThat(backupInfos.size()).
isEqualTo(1);
// Retrieving backup infos twice shall not
// lead to different results
List<BackupInfo> tmpBackupInfo = bdb.getBackupInfos();
assert(tmpBackupInfo.get(0).backupId() ==
backupInfos.get(0).backupId());
assert(tmpBackupInfo.get(0).timestamp() ==
backupInfos.get(0).timestamp());
assert(tmpBackupInfo.get(0).size() ==
backupInfos.get(0).size());
assert(tmpBackupInfo.get(0).numberFiles() ==
backupInfos.get(0).numberFiles());
assertThat(tmpBackupInfo.get(0).backupId()).
isEqualTo(backupInfos.get(0).backupId());
assertThat(tmpBackupInfo.get(0).timestamp()).
isEqualTo(backupInfos.get(0).timestamp());
assertThat(tmpBackupInfo.get(0).size()).
isEqualTo(backupInfos.get(0).size());
assertThat(tmpBackupInfo.get(0).numberFiles()).
isEqualTo(backupInfos.get(0).numberFiles());
// delete record after backup
bdb.remove("abc".getBytes());
byte[] value = bdb.get("abc".getBytes());
assert(value == null);
assertThat(value).isNull();
bdb.close();
// restore from backup
RestoreOptions ropt = new RestoreOptions(false);
RestoreBackupableDB rdb = new RestoreBackupableDB(bopt);
ropt = new RestoreOptions(false);
rdb = new RestoreBackupableDB(bopt);
// getting backup infos from restorable db should
// lead to the same infos as from backupable db
restoreInfos = rdb.getBackupInfos();
assert(restoreInfos.size() == backupInfos.size());
assert(restoreInfos.get(0).backupId() ==
backupInfos.get(0).backupId());
assert(restoreInfos.get(0).timestamp() ==
backupInfos.get(0).timestamp());
assert(restoreInfos.get(0).size() ==
backupInfos.get(0).size());
assert(restoreInfos.get(0).numberFiles() ==
backupInfos.get(0).numberFiles());
rdb.restoreDBFromLatestBackup(db_path, db_path,
assertThat(restoreInfos.size()).
isEqualTo(backupInfos.size());
assertThat(restoreInfos.get(0).backupId()).
isEqualTo(backupInfos.get(0).backupId());
assertThat(restoreInfos.get(0).timestamp()).
isEqualTo(backupInfos.get(0).timestamp());
assertThat(restoreInfos.get(0).size()).
isEqualTo(backupInfos.get(0).size());
assertThat(restoreInfos.get(0).numberFiles()).
isEqualTo(backupInfos.get(0).numberFiles());
rdb.restoreDBFromLatestBackup(
dbFolder.getRoot().getAbsolutePath(),
dbFolder.getRoot().getAbsolutePath(),
ropt);
// do nothing because there is only one backup
rdb.purgeOldBackups(1);
restoreInfos = rdb.getBackupInfos();
assert(restoreInfos.size() == 1);
assertThat(restoreInfos.size()).
isEqualTo(1);
rdb.dispose();
ropt.dispose();
// verify that backed up data contains deleted record
bdb = BackupableDB.open(opt, bopt, db_path);
bdb = BackupableDB.open(opt, bopt,
dbFolder.getRoot().getAbsolutePath());
value = bdb.get("abc".getBytes());
assert(new String(value).equals("def"));
assertThat(new String(value)).
isEqualTo("def");
bdb.createNewBackup(false);
// after new backup there must be two backup infos
backupInfos = bdb.getBackupInfos();
assert(backupInfos.size() == 2);
assertThat(backupInfos.size()).
isEqualTo(2);
// deleting the backup must be possible using the
// id provided by backup infos
bdb.deleteBackup(backupInfos.get(1).backupId());
// after deletion there should only be one info
backupInfos = bdb.getBackupInfos();
assert(backupInfos.size() == 1);
assertThat(backupInfos.size()).
isEqualTo(1);
bdb.createNewBackup(false);
bdb.createNewBackup(false);
bdb.createNewBackup(false);
backupInfos = bdb.getBackupInfos();
assert(backupInfos.size() == 4);
assertThat(backupInfos.size()).
isEqualTo(4);
// purge everything and keep two
bdb.purgeOldBackups(2);
// backup infos need to be two
backupInfos = bdb.getBackupInfos();
assert(backupInfos.size() == 2);
assert(backupInfos.get(0).backupId() == 4);
assert(backupInfos.get(1).backupId() == 5);
System.out.println("Backup and restore test passed");
} catch (RocksDBException e) {
System.err.format("[ERROR]: %s%n", e);
e.printStackTrace();
assertThat(backupInfos.size()).
isEqualTo(2);
assertThat(backupInfos.get(0).backupId()).
isEqualTo(4);
assertThat(backupInfos.get(1).backupId()).
isEqualTo(5);
} finally {
opt.dispose();
bopt.dispose();
if (opt != null) {
opt.dispose();
}
if (bopt != null) {
bopt.dispose();
}
if (bdb != null) {
bdb.close();
}
if (ropt != null) {
ropt.dispose();
}
if (rdb != null) {
rdb.dispose();
}
}
}
}
......@@ -5,43 +5,158 @@
package org.rocksdb.test;
import org.rocksdb.BlockBasedTableConfig;
import org.rocksdb.ChecksumType;
import org.rocksdb.IndexType;
import org.junit.ClassRule;
import org.junit.Test;
import org.rocksdb.*;
import static org.assertj.core.api.Assertions.assertThat;
public class BlockBasedTableConfigTest {
public static void main(String[] args) {
BlockBasedTableConfig blockBasedTableConfig =
new BlockBasedTableConfig();
@ClassRule
public static final RocksMemoryResource rocksMemoryResource =
new RocksMemoryResource();
@Test
public void noBlockCache() {
BlockBasedTableConfig blockBasedTableConfig = new BlockBasedTableConfig();
blockBasedTableConfig.setNoBlockCache(true);
assert(blockBasedTableConfig.noBlockCache());
blockBasedTableConfig.setBlockCacheSize(8*1024);
assert(blockBasedTableConfig.blockCacheSize() == (8*1024));
assertThat(blockBasedTableConfig.noBlockCache()).isTrue();
}
@Test
public void blockCacheSize() {
BlockBasedTableConfig blockBasedTableConfig = new BlockBasedTableConfig();
blockBasedTableConfig.setBlockCacheSize(8 * 1024);
assertThat(blockBasedTableConfig.blockCacheSize()).
isEqualTo(8 * 1024);
}
@Test
public void blockSizeDeviation() {
BlockBasedTableConfig blockBasedTableConfig = new BlockBasedTableConfig();
blockBasedTableConfig.setBlockSizeDeviation(12);
assert(blockBasedTableConfig.blockSizeDeviation() == 12);
assertThat(blockBasedTableConfig.blockSizeDeviation()).
isEqualTo(12);
}
@Test
public void blockRestartInterval() {
BlockBasedTableConfig blockBasedTableConfig = new BlockBasedTableConfig();
blockBasedTableConfig.setBlockRestartInterval(15);
assert(blockBasedTableConfig.blockRestartInterval() == 15);
assertThat(blockBasedTableConfig.blockRestartInterval()).
isEqualTo(15);
}
@Test
public void wholeKeyFiltering() {
BlockBasedTableConfig blockBasedTableConfig = new BlockBasedTableConfig();
blockBasedTableConfig.setWholeKeyFiltering(false);
assert(!blockBasedTableConfig.wholeKeyFiltering());
assertThat(blockBasedTableConfig.wholeKeyFiltering()).
isFalse();
}
@Test
public void cacheIndexAndFilterBlocks() {
BlockBasedTableConfig blockBasedTableConfig = new BlockBasedTableConfig();
blockBasedTableConfig.setCacheIndexAndFilterBlocks(true);
assert(blockBasedTableConfig.cacheIndexAndFilterBlocks());
assertThat(blockBasedTableConfig.cacheIndexAndFilterBlocks()).
isTrue();
}
@Test
public void hashIndexAllowCollision() {
BlockBasedTableConfig blockBasedTableConfig = new BlockBasedTableConfig();
blockBasedTableConfig.setHashIndexAllowCollision(false);
assert(!blockBasedTableConfig.hashIndexAllowCollision());
assertThat(blockBasedTableConfig.hashIndexAllowCollision()).
isFalse();
}
@Test
public void blockCacheCompressedSize() {
BlockBasedTableConfig blockBasedTableConfig = new BlockBasedTableConfig();
blockBasedTableConfig.setBlockCacheCompressedSize(40);
assert(blockBasedTableConfig.blockCacheCompressedSize() == 40);
assertThat(blockBasedTableConfig.blockCacheCompressedSize()).
isEqualTo(40);
}
@Test
public void checksumType() {
BlockBasedTableConfig blockBasedTableConfig = new BlockBasedTableConfig();
blockBasedTableConfig.setChecksumType(ChecksumType.kNoChecksum);
blockBasedTableConfig.setChecksumType(ChecksumType.kxxHash);
assert(blockBasedTableConfig.checksumType().equals(
assertThat(blockBasedTableConfig.checksumType().equals(
ChecksumType.kxxHash));
}
@Test
public void indexType() {
BlockBasedTableConfig blockBasedTableConfig = new BlockBasedTableConfig();
assertThat(IndexType.values().length).isEqualTo(2);
blockBasedTableConfig.setIndexType(IndexType.kHashSearch);
assert(blockBasedTableConfig.indexType().equals(
assertThat(blockBasedTableConfig.indexType().equals(
IndexType.kHashSearch));
assertThat(IndexType.valueOf("kBinarySearch")).isNotNull();
blockBasedTableConfig.setIndexType(IndexType.valueOf("kBinarySearch"));
assertThat(blockBasedTableConfig.indexType().equals(
IndexType.kBinarySearch));
}
@Test
public void blockCacheCompressedNumShardBits() {
BlockBasedTableConfig blockBasedTableConfig = new BlockBasedTableConfig();
blockBasedTableConfig.setBlockCacheCompressedNumShardBits(4);
assert(blockBasedTableConfig.blockCacheCompressedNumShardBits()
== 4);
assertThat(blockBasedTableConfig.blockCacheCompressedNumShardBits()).
isEqualTo(4);
}
@Test
public void cacheNumShardBits() {
BlockBasedTableConfig blockBasedTableConfig = new BlockBasedTableConfig();
blockBasedTableConfig.setCacheNumShardBits(5);
assert(blockBasedTableConfig.cacheNumShardBits() == 5);
System.out.println("BlockBasedTableConfig test passed");
assertThat(blockBasedTableConfig.cacheNumShardBits()).
isEqualTo(5);
}
@Test
public void blockSize() {
BlockBasedTableConfig blockBasedTableConfig = new BlockBasedTableConfig();
blockBasedTableConfig.setBlockSize(10);
assertThat(blockBasedTableConfig.blockSize()).isEqualTo(10);
}
@Test
public void blockBasedTableWithFilter() {
Options options = null;
try {
options = new Options();
options.setTableFormatConfig(
new BlockBasedTableConfig().setFilter(
new BloomFilter(10)));
assertThat(options.tableFactoryName()).
isEqualTo("BlockBasedTable");
} finally {
if (options != null) {
options.dispose();
}
}
}
@Test
public void blockBasedTableWithoutFilter() {
Options options = null;
try {
options = new Options();
options.setTableFormatConfig(
new BlockBasedTableConfig().setFilter(null));
assertThat(options.tableFactoryName()).
isEqualTo("BlockBasedTable");
} finally {
if (options != null) {
options.dispose();
}
}
}
}
......@@ -5,225 +5,584 @@
package org.rocksdb.test;
import org.junit.ClassRule;
import org.junit.Test;
import org.rocksdb.*;
import java.util.Random;
import static org.assertj.core.api.Assertions.assertThat;
public class ColumnFamilyOptionsTest {
static {
RocksDB.loadLibrary();
}
public static void testCFOptions(ColumnFamilyOptionsInterface opt) {
Random rand = PlatformRandomHelper.
getPlatformSpecificRandomFactory();
{ // WriteBufferSize test
try {
long longValue = rand.nextLong();
opt.setWriteBufferSize(longValue);
assert(opt.writeBufferSize() == longValue);
} catch (RocksDBException e) {
assert(false);
@ClassRule
public static final RocksMemoryResource rocksMemoryResource =
new RocksMemoryResource();
public static final Random rand = PlatformRandomHelper.
getPlatformSpecificRandomFactory();
@Test
public void writeBufferSize() throws RocksDBException {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
long longValue = rand.nextLong();
opt.setWriteBufferSize(longValue);
assertThat(opt.writeBufferSize()).isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // MaxWriteBufferNumber test
@Test
public void maxWriteBufferNumber() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
int intValue = rand.nextInt();
opt.setMaxWriteBufferNumber(intValue);
assert(opt.maxWriteBufferNumber() == intValue);
assertThat(opt.maxWriteBufferNumber()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // MinWriteBufferNumberToMerge test
@Test
public void minWriteBufferNumberToMerge() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
int intValue = rand.nextInt();
opt.setMinWriteBufferNumberToMerge(intValue);
assert(opt.minWriteBufferNumberToMerge() == intValue);
assertThat(opt.minWriteBufferNumberToMerge()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // NumLevels test
@Test
public void numLevels() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
int intValue = rand.nextInt();
opt.setNumLevels(intValue);
assert(opt.numLevels() == intValue);
assertThat(opt.numLevels()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // LevelFileNumCompactionTrigger test
@Test
public void levelZeroFileNumCompactionTrigger() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
int intValue = rand.nextInt();
opt.setLevelZeroFileNumCompactionTrigger(intValue);
assert(opt.levelZeroFileNumCompactionTrigger() == intValue);
assertThat(opt.levelZeroFileNumCompactionTrigger()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // LevelSlowdownWritesTrigger test
@Test
public void levelZeroSlowdownWritesTrigger() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
int intValue = rand.nextInt();
opt.setLevelZeroSlowdownWritesTrigger(intValue);
assert(opt.levelZeroSlowdownWritesTrigger() == intValue);
assertThat(opt.levelZeroSlowdownWritesTrigger()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // LevelStopWritesTrigger test
@Test
public void levelZeroStopWritesTrigger() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
int intValue = rand.nextInt();
opt.setLevelZeroStopWritesTrigger(intValue);
assert(opt.levelZeroStopWritesTrigger() == intValue);
assertThat(opt.levelZeroStopWritesTrigger()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // MaxMemCompactionLevel test
@Test
public void maxMemCompactionLevel() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
int intValue = rand.nextInt();
opt.setMaxMemCompactionLevel(intValue);
assert(opt.maxMemCompactionLevel() == intValue);
assertThat(opt.maxMemCompactionLevel()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // TargetFileSizeBase test
@Test
public void targetFileSizeBase() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
long longValue = rand.nextLong();
opt.setTargetFileSizeBase(longValue);
assert(opt.targetFileSizeBase() == longValue);
assertThat(opt.targetFileSizeBase()).isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // TargetFileSizeMultiplier test
@Test
public void targetFileSizeMultiplier() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
int intValue = rand.nextInt();
opt.setTargetFileSizeMultiplier(intValue);
assert(opt.targetFileSizeMultiplier() == intValue);
assertThat(opt.targetFileSizeMultiplier()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // MaxBytesForLevelBase test
@Test
public void maxBytesForLevelBase() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
long longValue = rand.nextLong();
opt.setMaxBytesForLevelBase(longValue);
assert(opt.maxBytesForLevelBase() == longValue);
assertThat(opt.maxBytesForLevelBase()).isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // MaxBytesForLevelMultiplier test
@Test
public void maxBytesForLevelMultiplier() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
int intValue = rand.nextInt();
opt.setMaxBytesForLevelMultiplier(intValue);
assert(opt.maxBytesForLevelMultiplier() == intValue);
assertThat(opt.maxBytesForLevelMultiplier()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // ExpandedCompactionFactor test
@Test
public void expandedCompactionFactor() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
int intValue = rand.nextInt();
opt.setExpandedCompactionFactor(intValue);
assert(opt.expandedCompactionFactor() == intValue);
assertThat(opt.expandedCompactionFactor()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // SourceCompactionFactor test
@Test
public void sourceCompactionFactor() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
int intValue = rand.nextInt();
opt.setSourceCompactionFactor(intValue);
assert(opt.sourceCompactionFactor() == intValue);
assertThat(opt.sourceCompactionFactor()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // MaxGrandparentOverlapFactor test
@Test
public void maxGrandparentOverlapFactor() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
int intValue = rand.nextInt();
opt.setMaxGrandparentOverlapFactor(intValue);
assert(opt.maxGrandparentOverlapFactor() == intValue);
assertThat(opt.maxGrandparentOverlapFactor()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // SoftRateLimit test
@Test
public void softRateLimit() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
double doubleValue = rand.nextDouble();
opt.setSoftRateLimit(doubleValue);
assert(opt.softRateLimit() == doubleValue);
assertThat(opt.softRateLimit()).isEqualTo(doubleValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // HardRateLimit test
@Test
public void hardRateLimit() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
double doubleValue = rand.nextDouble();
opt.setHardRateLimit(doubleValue);
assert(opt.hardRateLimit() == doubleValue);
assertThat(opt.hardRateLimit()).isEqualTo(doubleValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // RateLimitDelayMaxMilliseconds test
@Test
public void rateLimitDelayMaxMilliseconds() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
int intValue = rand.nextInt();
opt.setRateLimitDelayMaxMilliseconds(intValue);
assert(opt.rateLimitDelayMaxMilliseconds() == intValue);
assertThat(opt.rateLimitDelayMaxMilliseconds()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // ArenaBlockSize test
try {
long longValue = rand.nextLong();
opt.setArenaBlockSize(longValue);
assert(opt.arenaBlockSize() == longValue);
} catch (RocksDBException e) {
assert(false);
@Test
public void arenaBlockSize() throws RocksDBException {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
long longValue = rand.nextLong();
opt.setArenaBlockSize(longValue);
assertThat(opt.arenaBlockSize()).isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // DisableAutoCompactions test
@Test
public void disableAutoCompactions() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
boolean boolValue = rand.nextBoolean();
opt.setDisableAutoCompactions(boolValue);
assert(opt.disableAutoCompactions() == boolValue);
assertThat(opt.disableAutoCompactions()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // PurgeRedundantKvsWhileFlush test
@Test
public void purgeRedundantKvsWhileFlush() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
boolean boolValue = rand.nextBoolean();
opt.setPurgeRedundantKvsWhileFlush(boolValue);
assert(opt.purgeRedundantKvsWhileFlush() == boolValue);
assertThat(opt.purgeRedundantKvsWhileFlush()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // VerifyChecksumsInCompaction test
@Test
public void verifyChecksumsInCompaction() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
boolean boolValue = rand.nextBoolean();
opt.setVerifyChecksumsInCompaction(boolValue);
assert(opt.verifyChecksumsInCompaction() == boolValue);
assertThat(opt.verifyChecksumsInCompaction()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // FilterDeletes test
@Test
public void filterDeletes() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
boolean boolValue = rand.nextBoolean();
opt.setFilterDeletes(boolValue);
assert(opt.filterDeletes() == boolValue);
assertThat(opt.filterDeletes()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // MaxSequentialSkipInIterations test
@Test
public void maxSequentialSkipInIterations() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
long longValue = rand.nextLong();
opt.setMaxSequentialSkipInIterations(longValue);
assert(opt.maxSequentialSkipInIterations() == longValue);
assertThat(opt.maxSequentialSkipInIterations()).isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // InplaceUpdateSupport test
@Test
public void inplaceUpdateSupport() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
boolean boolValue = rand.nextBoolean();
opt.setInplaceUpdateSupport(boolValue);
assert(opt.inplaceUpdateSupport() == boolValue);
assertThat(opt.inplaceUpdateSupport()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // InplaceUpdateNumLocks test
try {
long longValue = rand.nextLong();
opt.setInplaceUpdateNumLocks(longValue);
assert(opt.inplaceUpdateNumLocks() == longValue);
} catch (RocksDBException e) {
assert(false);
@Test
public void inplaceUpdateNumLocks() throws RocksDBException {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
long longValue = rand.nextLong();
opt.setInplaceUpdateNumLocks(longValue);
assertThat(opt.inplaceUpdateNumLocks()).isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // MemtablePrefixBloomBits test
@Test
public void memtablePrefixBloomBits() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
int intValue = rand.nextInt();
opt.setMemtablePrefixBloomBits(intValue);
assert(opt.memtablePrefixBloomBits() == intValue);
assertThat(opt.memtablePrefixBloomBits()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // MemtablePrefixBloomProbes test
@Test
public void memtablePrefixBloomProbes() {
ColumnFamilyOptions opt = null;
try {
int intValue = rand.nextInt();
opt = new ColumnFamilyOptions();
opt.setMemtablePrefixBloomProbes(intValue);
assert(opt.memtablePrefixBloomProbes() == intValue);
assertThat(opt.memtablePrefixBloomProbes()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // BloomLocality test
@Test
public void bloomLocality() {
ColumnFamilyOptions opt = null;
try {
int intValue = rand.nextInt();
opt = new ColumnFamilyOptions();
opt.setBloomLocality(intValue);
assert(opt.bloomLocality() == intValue);
assertThat(opt.bloomLocality()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // MaxSuccessiveMerges test
try {
long longValue = rand.nextLong();
opt.setMaxSuccessiveMerges(longValue);
assert(opt.maxSuccessiveMerges() == longValue);
} catch (RocksDBException e){
assert(false);
@Test
public void maxSuccessiveMerges() throws RocksDBException {
ColumnFamilyOptions opt = null;
try {
long longValue = rand.nextLong();
opt = new ColumnFamilyOptions();
opt.setMaxSuccessiveMerges(longValue);
assertThat(opt.maxSuccessiveMerges()).isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // MinPartialMergeOperands test
@Test
public void minPartialMergeOperands() {
ColumnFamilyOptions opt = null;
try {
int intValue = rand.nextInt();
opt = new ColumnFamilyOptions();
opt.setMinPartialMergeOperands(intValue);
assert(opt.minPartialMergeOperands() == intValue);
assertThat(opt.minPartialMergeOperands()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
@Test
public void memTable() throws RocksDBException {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
opt.setMemTableConfig(new HashLinkedListMemTableConfig());
assertThat(opt.memTableFactoryName()).
isEqualTo("HashLinkedListRepFactory");
} finally {
if (opt != null) {
opt.dispose();
}
}
}
@Test
public void comparator() throws RocksDBException {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
opt.setComparator(BuiltinComparator.BYTEWISE_COMPARATOR);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
@Test
public void linkageOfPrepMethods() {
ColumnFamilyOptions options = null;
try {
options = new ColumnFamilyOptions();
options.optimizeUniversalStyleCompaction();
options.optimizeUniversalStyleCompaction(4000);
options.optimizeLevelStyleCompaction();
options.optimizeLevelStyleCompaction(3000);
options.optimizeForPointLookup(10);
} finally {
if (options != null) {
options.dispose();
}
}
}
@Test
public void shouldSetTestPrefixExtractor() {
ColumnFamilyOptions options = null;
try {
options = new ColumnFamilyOptions();
options.useFixedLengthPrefixExtractor(100);
options.useFixedLengthPrefixExtractor(10);
} finally {
if (options != null) {
options.dispose();
}
}
}
public static void main(String[] args) {
ColumnFamilyOptions opt = new ColumnFamilyOptions();
testCFOptions(opt);
opt.dispose();
System.out.println("Passed DBOptionsTest");
@Test
public void compressionTypes() {
ColumnFamilyOptions ColumnFamilyOptions = null;
try {
ColumnFamilyOptions = new ColumnFamilyOptions();
for (CompressionType compressionType :
CompressionType.values()) {
ColumnFamilyOptions.setCompressionType(compressionType);
assertThat(ColumnFamilyOptions.compressionType()).
isEqualTo(compressionType);
assertThat(CompressionType.valueOf("NO_COMPRESSION")).
isEqualTo(CompressionType.NO_COMPRESSION);
}
} finally {
if (ColumnFamilyOptions != null) {
ColumnFamilyOptions.dispose();
}
}
}
@Test
public void compactionStyles() {
ColumnFamilyOptions ColumnFamilyOptions = null;
try {
ColumnFamilyOptions = new ColumnFamilyOptions();
for (CompactionStyle compactionStyle :
CompactionStyle.values()) {
ColumnFamilyOptions.setCompactionStyle(compactionStyle);
assertThat(ColumnFamilyOptions.compactionStyle()).
isEqualTo(compactionStyle);
assertThat(CompactionStyle.valueOf("FIFO")).
isEqualTo(CompactionStyle.FIFO);
}
} finally {
if (ColumnFamilyOptions != null) {
ColumnFamilyOptions.dispose();
}
}
}
}
......@@ -5,30 +5,32 @@
package org.rocksdb.test;
import org.junit.ClassRule;
import org.junit.Test;
import org.rocksdb.ComparatorOptions;
import org.rocksdb.RocksDB;
import java.util.Random;
import static org.assertj.core.api.Assertions.assertThat;
public class ComparatorOptionsTest {
static {
RocksDB.loadLibrary();
}
@ClassRule
public static final RocksMemoryResource rocksMemoryResource =
new RocksMemoryResource();
public static void main(String[] args) {
@Test
public void comparatorOptions() {
final ComparatorOptions copt = new ComparatorOptions();
Random rand = new Random();
assertThat(copt).isNotNull();
{ // UseAdaptiveMutex test
copt.setUseAdaptiveMutex(true);
assert(copt.useAdaptiveMutex() == true);
assertThat(copt.useAdaptiveMutex()).isTrue();
copt.setUseAdaptiveMutex(false);
assert(copt.useAdaptiveMutex() == false);
assertThat(copt.useAdaptiveMutex()).isFalse();
}
copt.dispose();
System.out.println("Passed ComparatorOptionsTest");
}
}
......@@ -5,19 +5,28 @@
package org.rocksdb.test;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.rocksdb.*;
import java.io.IOException;
import java.nio.file.FileSystems;
import static org.assertj.core.api.Assertions.assertThat;
public class ComparatorTest {
private static final String db_path = "/tmp/comparator_db";
static {
RocksDB.loadLibrary();
}
@ClassRule
public static final RocksMemoryResource rocksMemoryResource =
new RocksMemoryResource();
@Rule
public TemporaryFolder dbFolder = new TemporaryFolder();
public static void main(String[] args) throws IOException {
@Test
public void javaComparator() throws IOException {
final AbstractComparatorTest comparatorTest = new AbstractComparatorTest() {
@Override
......@@ -38,8 +47,153 @@ public class ComparatorTest {
};
// test the round-tripability of keys written and read with the Comparator
comparatorTest.testRoundtrip(FileSystems.getDefault().getPath(db_path));
comparatorTest.testRoundtrip(FileSystems.getDefault().getPath(
dbFolder.getRoot().getAbsolutePath()));
}
@Test
public void builtinForwardComparator()
throws RocksDBException {
Options options = null;
RocksDB rocksDB = null;
RocksIterator rocksIterator = null;
try {
options = new Options();
options.setCreateIfMissing(true);
options.setComparator(BuiltinComparator.BYTEWISE_COMPARATOR);
rocksDB = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath());
rocksDB.put("abc1".getBytes(), "abc1".getBytes());
rocksDB.put("abc2".getBytes(), "abc2".getBytes());
rocksDB.put("abc3".getBytes(), "abc3".getBytes());
rocksIterator = rocksDB.newIterator();
// Iterate over keys using a iterator
rocksIterator.seekToFirst();
assertThat(rocksIterator.isValid()).isTrue();
assertThat(rocksIterator.key()).isEqualTo(
"abc1".getBytes());
assertThat(rocksIterator.value()).isEqualTo(
"abc1".getBytes());
rocksIterator.next();
assertThat(rocksIterator.isValid()).isTrue();
assertThat(rocksIterator.key()).isEqualTo(
"abc2".getBytes());
assertThat(rocksIterator.value()).isEqualTo(
"abc2".getBytes());
rocksIterator.next();
assertThat(rocksIterator.isValid()).isTrue();
assertThat(rocksIterator.key()).isEqualTo(
"abc3".getBytes());
assertThat(rocksIterator.value()).isEqualTo(
"abc3".getBytes());
rocksIterator.next();
assertThat(rocksIterator.isValid()).isFalse();
// Get last one
rocksIterator.seekToLast();
assertThat(rocksIterator.isValid()).isTrue();
assertThat(rocksIterator.key()).isEqualTo(
"abc3".getBytes());
assertThat(rocksIterator.value()).isEqualTo(
"abc3".getBytes());
// Seek for abc
rocksIterator.seek("abc".getBytes());
assertThat(rocksIterator.isValid()).isTrue();
assertThat(rocksIterator.key()).isEqualTo(
"abc1".getBytes());
assertThat(rocksIterator.value()).isEqualTo(
"abc1".getBytes());
} finally {
if (rocksIterator != null) {
rocksIterator.dispose();
}
if (rocksDB != null) {
rocksDB.close();
}
if (options != null) {
options.dispose();
}
}
}
@Test
public void builtinReverseComparator()
throws RocksDBException {
Options options = null;
RocksDB rocksDB = null;
RocksIterator rocksIterator = null;
try {
options = new Options();
options.setCreateIfMissing(true);
options.setComparator(
BuiltinComparator.REVERSE_BYTEWISE_COMPARATOR);
rocksDB = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath());
rocksDB.put("abc1".getBytes(), "abc1".getBytes());
rocksDB.put("abc2".getBytes(), "abc2".getBytes());
rocksDB.put("abc3".getBytes(), "abc3".getBytes());
rocksIterator = rocksDB.newIterator();
// Iterate over keys using a iterator
rocksIterator.seekToFirst();
assertThat(rocksIterator.isValid()).isTrue();
assertThat(rocksIterator.key()).isEqualTo(
"abc3".getBytes());
assertThat(rocksIterator.value()).isEqualTo(
"abc3".getBytes());
rocksIterator.next();
assertThat(rocksIterator.isValid()).isTrue();
assertThat(rocksIterator.key()).isEqualTo(
"abc2".getBytes());
assertThat(rocksIterator.value()).isEqualTo(
"abc2".getBytes());
rocksIterator.next();
assertThat(rocksIterator.isValid()).isTrue();
assertThat(rocksIterator.key()).isEqualTo(
"abc1".getBytes());
assertThat(rocksIterator.value()).isEqualTo(
"abc1".getBytes());
rocksIterator.next();
assertThat(rocksIterator.isValid()).isFalse();
// Get last one
rocksIterator.seekToLast();
assertThat(rocksIterator.isValid()).isTrue();
assertThat(rocksIterator.key()).isEqualTo(
"abc1".getBytes());
assertThat(rocksIterator.value()).isEqualTo(
"abc1".getBytes());
// Will be invalid because abc is after abc1
rocksIterator.seek("abc".getBytes());
assertThat(rocksIterator.isValid()).isFalse();
// Will be abc3 because the next one after abc999
// is abc3
rocksIterator.seek("abc999".getBytes());
assertThat(rocksIterator.key()).isEqualTo(
"abc3".getBytes());
assertThat(rocksIterator.value()).isEqualTo(
"abc3".getBytes());
} finally {
if (rocksIterator != null) {
rocksIterator.dispose();
}
if (rocksDB != null) {
rocksDB.close();
}
if (options != null) {
options.dispose();
}
}
}
System.out.println("Passed ComparatorTest");
@Test
public void builtinComparatorEnum(){
assertThat(BuiltinComparator.BYTEWISE_COMPARATOR.ordinal())
.isEqualTo(0);
assertThat(
BuiltinComparator.REVERSE_BYTEWISE_COMPARATOR.ordinal())
.isEqualTo(1);
}
}
......@@ -5,224 +5,533 @@
package org.rocksdb.test;
import org.rocksdb.DBOptions;
import org.rocksdb.DBOptionsInterface;
import org.rocksdb.RocksDB;
import org.rocksdb.RocksDBException;
import org.junit.ClassRule;
import org.junit.Test;
import org.rocksdb.*;
import java.util.Random;
import static org.assertj.core.api.Assertions.assertThat;
public class DBOptionsTest {
static {
RocksDB.loadLibrary();
}
public static void testDBOptions(DBOptionsInterface opt) {
Random rand = PlatformRandomHelper.
getPlatformSpecificRandomFactory();
{ // CreateIfMissing test
@ClassRule
public static final RocksMemoryResource rocksMemoryResource =
new RocksMemoryResource();
public static final Random rand = PlatformRandomHelper.
getPlatformSpecificRandomFactory();
@Test
public void createIfMissing() {
DBOptions opt = null;
try {
opt = new DBOptions();
boolean boolValue = rand.nextBoolean();
opt.setCreateIfMissing(boolValue);
assert(opt.createIfMissing() == boolValue);
assertThat(opt.createIfMissing()).
isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // CreateMissingColumnFamilies test
@Test
public void createMissingColumnFamilies() {
DBOptions opt = null;
try {
opt = new DBOptions();
boolean boolValue = rand.nextBoolean();
opt.setCreateMissingColumnFamilies(boolValue);
assert(opt.createMissingColumnFamilies() == boolValue);
assertThat(opt.createMissingColumnFamilies()).
isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // ErrorIfExists test
@Test
public void errorIfExists() {
DBOptions opt = null;
try {
opt = new DBOptions();
boolean boolValue = rand.nextBoolean();
opt.setErrorIfExists(boolValue);
assert(opt.errorIfExists() == boolValue);
assertThat(opt.errorIfExists()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // ParanoidChecks test
@Test
public void paranoidChecks() {
DBOptions opt = null;
try {
opt = new DBOptions();
boolean boolValue = rand.nextBoolean();
opt.setParanoidChecks(boolValue);
assert(opt.paranoidChecks() == boolValue);
assertThat(opt.paranoidChecks()).
isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{
// MaxTotalWalSize test
@Test
public void maxTotalWalSize() {
DBOptions opt = null;
try {
opt = new DBOptions();
long longValue = rand.nextLong();
opt.setMaxTotalWalSize(longValue);
assert(opt.maxTotalWalSize() == longValue);
assertThat(opt.maxTotalWalSize()).
isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // MaxOpenFiles test
@Test
public void maxOpenFiles() {
DBOptions opt = null;
try {
opt = new DBOptions();
int intValue = rand.nextInt();
opt.setMaxOpenFiles(intValue);
assert(opt.maxOpenFiles() == intValue);
assertThat(opt.maxOpenFiles()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // DisableDataSync test
@Test
public void disableDataSync() {
DBOptions opt = null;
try {
opt = new DBOptions();
boolean boolValue = rand.nextBoolean();
opt.setDisableDataSync(boolValue);
assert(opt.disableDataSync() == boolValue);
assertThat(opt.disableDataSync()).
isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // UseFsync test
@Test
public void useFsync() {
DBOptions opt = null;
try {
opt = new DBOptions();
boolean boolValue = rand.nextBoolean();
opt.setUseFsync(boolValue);
assert(opt.useFsync() == boolValue);
assertThat(opt.useFsync()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // DbLogDir test
@Test
public void dbLogDir() {
DBOptions opt = null;
try {
opt = new DBOptions();
String str = "path/to/DbLogDir";
opt.setDbLogDir(str);
assert(opt.dbLogDir().equals(str));
assertThat(opt.dbLogDir()).isEqualTo(str);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // WalDir test
@Test
public void walDir() {
DBOptions opt = null;
try {
opt = new DBOptions();
String str = "path/to/WalDir";
opt.setWalDir(str);
assert(opt.walDir().equals(str));
assertThat(opt.walDir()).isEqualTo(str);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // DeleteObsoleteFilesPeriodMicros test
@Test
public void deleteObsoleteFilesPeriodMicros() {
DBOptions opt = null;
try {
opt = new DBOptions();
long longValue = rand.nextLong();
opt.setDeleteObsoleteFilesPeriodMicros(longValue);
assert(opt.deleteObsoleteFilesPeriodMicros() == longValue);
assertThat(opt.deleteObsoleteFilesPeriodMicros()).
isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // MaxBackgroundCompactions test
@Test
public void maxBackgroundCompactions() {
DBOptions opt = null;
try {
opt = new DBOptions();
int intValue = rand.nextInt();
opt.setMaxBackgroundCompactions(intValue);
assert(opt.maxBackgroundCompactions() == intValue);
assertThat(opt.maxBackgroundCompactions()).
isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // MaxBackgroundFlushes test
@Test
public void maxBackgroundFlushes() {
DBOptions opt = null;
try {
opt = new DBOptions();
int intValue = rand.nextInt();
opt.setMaxBackgroundFlushes(intValue);
assert(opt.maxBackgroundFlushes() == intValue);
assertThat(opt.maxBackgroundFlushes()).
isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // MaxLogFileSize test
try {
long longValue = rand.nextLong();
opt.setMaxLogFileSize(longValue);
assert(opt.maxLogFileSize() == longValue);
} catch (RocksDBException e) {
System.out.println(e.getMessage());
assert(false);
@Test
public void maxLogFileSize() throws RocksDBException {
DBOptions opt = null;
try {
opt = new DBOptions();
long longValue = rand.nextLong();
opt.setMaxLogFileSize(longValue);
assertThat(opt.maxLogFileSize()).isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // LogFileTimeToRoll test
try {
long longValue = rand.nextLong();
opt.setLogFileTimeToRoll(longValue);
assert(opt.logFileTimeToRoll() == longValue);
} catch (RocksDBException e) {
assert(false);
@Test
public void logFileTimeToRoll() throws RocksDBException {
DBOptions opt = null;
try {
opt = new DBOptions();
long longValue = rand.nextLong();
opt.setLogFileTimeToRoll(longValue);
assertThat(opt.logFileTimeToRoll()).
isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // KeepLogFileNum test
try {
long longValue = rand.nextLong();
opt.setKeepLogFileNum(longValue);
assert(opt.keepLogFileNum() == longValue);
} catch (RocksDBException e) {
assert(false);
@Test
public void keepLogFileNum() throws RocksDBException {
DBOptions opt = null;
try {
opt = new DBOptions();
long longValue = rand.nextLong();
opt.setKeepLogFileNum(longValue);
assertThat(opt.keepLogFileNum()).isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // MaxManifestFileSize test
@Test
public void maxManifestFileSize() {
DBOptions opt = null;
try {
opt = new DBOptions();
long longValue = rand.nextLong();
opt.setMaxManifestFileSize(longValue);
assert(opt.maxManifestFileSize() == longValue);
assertThat(opt.maxManifestFileSize()).
isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // TableCacheNumshardbits test
@Test
public void tableCacheNumshardbits() {
DBOptions opt = null;
try {
opt = new DBOptions();
int intValue = rand.nextInt();
opt.setTableCacheNumshardbits(intValue);
assert(opt.tableCacheNumshardbits() == intValue);
assertThat(opt.tableCacheNumshardbits()).
isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // TableCacheRemoveScanCountLimit test
@Test
public void tableCacheRemoveScanCountLimit() {
DBOptions opt = null;
try {
opt = new DBOptions();
int intValue = rand.nextInt();
opt.setTableCacheRemoveScanCountLimit(intValue);
assert(opt.tableCacheRemoveScanCountLimit() == intValue);
assertThat(opt.tableCacheRemoveScanCountLimit()).
isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
@Test
public void walSizeLimitMB() {
DBOptions opt = null;
try {
opt = new DBOptions();
long longValue = rand.nextLong();
opt.setWalSizeLimitMB(longValue);
assertThat(opt.walSizeLimitMB()).isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // WalTtlSeconds test
@Test
public void walTtlSeconds() {
DBOptions opt = null;
try {
opt = new DBOptions();
long longValue = rand.nextLong();
opt.setWalTtlSeconds(longValue);
assert(opt.walTtlSeconds() == longValue);
assertThat(opt.walTtlSeconds()).isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // ManifestPreallocationSize test
try {
long longValue = rand.nextLong();
opt.setManifestPreallocationSize(longValue);
assert(opt.manifestPreallocationSize() == longValue);
} catch (RocksDBException e) {
assert(false);
@Test
public void manifestPreallocationSize() throws RocksDBException {
DBOptions opt = null;
try {
opt = new DBOptions();
long longValue = rand.nextLong();
opt.setManifestPreallocationSize(longValue);
assertThat(opt.manifestPreallocationSize()).
isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // AllowOsBuffer test
@Test
public void allowOsBuffer() {
DBOptions opt = null;
try {
opt = new DBOptions();
boolean boolValue = rand.nextBoolean();
opt.setAllowOsBuffer(boolValue);
assert(opt.allowOsBuffer() == boolValue);
assertThat(opt.allowOsBuffer()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // AllowMmapReads test
@Test
public void allowMmapReads() {
DBOptions opt = null;
try {
opt = new DBOptions();
boolean boolValue = rand.nextBoolean();
opt.setAllowMmapReads(boolValue);
assert(opt.allowMmapReads() == boolValue);
assertThat(opt.allowMmapReads()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // AllowMmapWrites test
@Test
public void allowMmapWrites() {
DBOptions opt = null;
try {
opt = new DBOptions();
boolean boolValue = rand.nextBoolean();
opt.setAllowMmapWrites(boolValue);
assert(opt.allowMmapWrites() == boolValue);
assertThat(opt.allowMmapWrites()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // IsFdCloseOnExec test
@Test
public void isFdCloseOnExec() {
DBOptions opt = null;
try {
opt = new DBOptions();
boolean boolValue = rand.nextBoolean();
opt.setIsFdCloseOnExec(boolValue);
assert(opt.isFdCloseOnExec() == boolValue);
assertThat(opt.isFdCloseOnExec()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // SkipLogErrorOnRecovery test
@Test
public void skipLogErrorOnRecovery() {
DBOptions opt = null;
try {
opt = new DBOptions();
boolean boolValue = rand.nextBoolean();
opt.setSkipLogErrorOnRecovery(boolValue);
assert(opt.skipLogErrorOnRecovery() == boolValue);
assertThat(opt.skipLogErrorOnRecovery()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // StatsDumpPeriodSec test
@Test
public void statsDumpPeriodSec() {
DBOptions opt = null;
try {
opt = new DBOptions();
int intValue = rand.nextInt();
opt.setStatsDumpPeriodSec(intValue);
assert(opt.statsDumpPeriodSec() == intValue);
assertThat(opt.statsDumpPeriodSec()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // AdviseRandomOnOpen test
@Test
public void adviseRandomOnOpen() {
DBOptions opt = null;
try {
opt = new DBOptions();
boolean boolValue = rand.nextBoolean();
opt.setAdviseRandomOnOpen(boolValue);
assert(opt.adviseRandomOnOpen() == boolValue);
assertThat(opt.adviseRandomOnOpen()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // UseAdaptiveMutex test
@Test
public void useAdaptiveMutex() {
DBOptions opt = null;
try {
opt = new DBOptions();
boolean boolValue = rand.nextBoolean();
opt.setUseAdaptiveMutex(boolValue);
assert(opt.useAdaptiveMutex() == boolValue);
assertThat(opt.useAdaptiveMutex()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // BytesPerSync test
@Test
public void bytesPerSync() {
DBOptions opt = null;
try {
opt = new DBOptions();
long longValue = rand.nextLong();
opt.setBytesPerSync(longValue);
assert(opt.bytesPerSync() == longValue);
assertThat(opt.bytesPerSync()).isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
public static void main(String[] args) {
DBOptions opt = new DBOptions();
testDBOptions(opt);
opt.dispose();
System.out.println("Passed DBOptionsTest");
@Test
public void rateLimiterConfig() {
DBOptions options = null;
DBOptions anotherOptions = null;
try {
options = new DBOptions();
RateLimiterConfig rateLimiterConfig =
new GenericRateLimiterConfig(1000, 0, 1);
options.setRateLimiterConfig(rateLimiterConfig);
// Test with parameter initialization
anotherOptions = new DBOptions();
anotherOptions.setRateLimiterConfig(
new GenericRateLimiterConfig(1000));
} finally {
if (options != null) {
options.dispose();
}
if (anotherOptions != null) {
anotherOptions.dispose();
}
}
}
@Test
public void statistics() {
DBOptions options = new DBOptions();
Statistics statistics = options.createStatistics().
statisticsPtr();
assertThat(statistics).isNotNull();
DBOptions anotherOptions = new DBOptions();
statistics = anotherOptions.statisticsPtr();
assertThat(statistics).isNotNull();
}
}
......@@ -5,19 +5,25 @@
package org.rocksdb.test;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.rocksdb.*;
import java.io.IOException;
import java.nio.file.FileSystems;
public class DirectComparatorTest {
private static final String db_path = "/tmp/direct_comparator_db";
@ClassRule
public static final RocksMemoryResource rocksMemoryResource =
new RocksMemoryResource();
static {
RocksDB.loadLibrary();
}
@Rule
public TemporaryFolder dbFolder = new TemporaryFolder();
public static void main(String[] args) throws IOException {
@Test
public void directComparator() throws IOException {
final AbstractComparatorTest comparatorTest = new AbstractComparatorTest() {
@Override
......@@ -41,8 +47,7 @@ public class DirectComparatorTest {
};
// test the round-tripability of keys written and read with the DirectComparator
comparatorTest.testRoundtrip(FileSystems.getDefault().getPath(db_path));
System.out.println("Passed DirectComparatorTest");
comparatorTest.testRoundtrip(FileSystems.getDefault().getPath(
dbFolder.getRoot().getAbsolutePath()));
}
}
// Copyright (c) 2014, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
package org.rocksdb.test;
import org.junit.Test;
import org.rocksdb.util.Environment;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import static org.assertj.core.api.Assertions.assertThat;
public class EnvironmentTest {
// Init static context
private static Environment environment =
new Environment();
@Test
public void mac32() {
setEnvironmentClassFields("mac", "32");
assertThat(Environment.isWindows()).isFalse();
assertThat(Environment.getJniLibraryExtension()).
isEqualTo(".jnilib");
assertThat(Environment.getJniLibraryName("rocksdb")).
isEqualTo("librocksdbjni-osx.jnilib");
assertThat(Environment.getSharedLibraryName("rocksdb")).
isEqualTo("librocksdbjni.dylib");
}
@Test
public void mac64() {
setEnvironmentClassFields("mac", "64");
assertThat(Environment.isWindows()).isFalse();
assertThat(Environment.getJniLibraryExtension()).
isEqualTo(".jnilib");
assertThat(Environment.getJniLibraryName("rocksdb")).
isEqualTo("librocksdbjni-osx.jnilib");
assertThat(Environment.getSharedLibraryName("rocksdb")).
isEqualTo("librocksdbjni.dylib");
}
@Test
public void nix32() {
// Linux
setEnvironmentClassFields("Linux", "32");
assertThat(Environment.isWindows()).isFalse();
assertThat(Environment.getJniLibraryExtension()).
isEqualTo(".so");
assertThat(Environment.getJniLibraryName("rocksdb")).
isEqualTo("librocksdbjni-linux32.so");
assertThat(Environment.getSharedLibraryName("rocksdb")).
isEqualTo("librocksdbjni.so");
// UNIX
setEnvironmentClassFields("Unix", "32");
assertThat(Environment.isWindows()).isFalse();
assertThat(Environment.getJniLibraryExtension()).
isEqualTo(".so");
assertThat(Environment.getJniLibraryName("rocksdb")).
isEqualTo("librocksdbjni-linux32.so");
assertThat(Environment.getSharedLibraryName("rocksdb")).
isEqualTo("librocksdbjni.so");
// AIX
setEnvironmentClassFields("aix", "32");
assertThat(Environment.isWindows()).isFalse();
assertThat(Environment.getJniLibraryExtension()).
isEqualTo(".so");
assertThat(Environment.getJniLibraryName("rocksdb")).
isEqualTo("librocksdbjni-linux32.so");
assertThat(Environment.getSharedLibraryName("rocksdb")).
isEqualTo("librocksdbjni.so");
}
@Test
public void nix64() {
setEnvironmentClassFields("Linux", "x64");
assertThat(Environment.isWindows()).isFalse();
assertThat(Environment.getJniLibraryExtension()).
isEqualTo(".so");
assertThat(Environment.getJniLibraryName("rocksdb")).
isEqualTo("librocksdbjni-linux64.so");
assertThat(Environment.getSharedLibraryName("rocksdb")).
isEqualTo("librocksdbjni.so");
// UNIX
setEnvironmentClassFields("Unix", "x64");
assertThat(Environment.isWindows()).isFalse();
assertThat(Environment.getJniLibraryExtension()).
isEqualTo(".so");
assertThat(Environment.getJniLibraryName("rocksdb")).
isEqualTo("librocksdbjni-linux64.so");
assertThat(Environment.getSharedLibraryName("rocksdb")).
isEqualTo("librocksdbjni.so");
// AIX
setEnvironmentClassFields("aix", "x64");
assertThat(Environment.isWindows()).isFalse();
assertThat(Environment.getJniLibraryExtension()).
isEqualTo(".so");
assertThat(Environment.getJniLibraryName("rocksdb")).
isEqualTo("librocksdbjni-linux64.so");
assertThat(Environment.getSharedLibraryName("rocksdb")).
isEqualTo("librocksdbjni.so");
}
@Test
public void detectWindows(){
setEnvironmentClassFields("win", "x64");
assertThat(Environment.isWindows()).isTrue();
}
@Test(expected = UnsupportedOperationException.class)
public void failWinJniLibraryName(){
setEnvironmentClassFields("win", "x64");
Environment.getJniLibraryName("rocksdb");
}
@Test(expected = UnsupportedOperationException.class)
public void failWinSharedLibrary(){
setEnvironmentClassFields("win", "x64");
Environment.getSharedLibraryName("rocksdb");
}
private void setEnvironmentClassFields(String osName,
String osArch) {
setEnvironmentClassField("OS", osName);
setEnvironmentClassField("ARCH", osArch);
}
private void setEnvironmentClassField(String fieldName, String value) {
final Field field;
try {
field = Environment.class.getDeclaredField(fieldName);
field.setAccessible(true);
final Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, value);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
......@@ -5,38 +5,44 @@
package org.rocksdb.test;
import org.junit.ClassRule;
import org.junit.Test;
import org.rocksdb.*;
public class FilterTest {
static {
RocksDB.loadLibrary();
}
public static void main(String[] args) {
Options options = new Options();
// test table config
BlockBasedTableConfig blockConfig = new BlockBasedTableConfig();
options.setTableFormatConfig(new BlockBasedTableConfig().
setFilter(new BloomFilter()));
options.dispose();
System.gc();
System.runFinalization();
// new Bloom filter
options = new Options();
blockConfig = new BlockBasedTableConfig();
blockConfig.setFilter(new BloomFilter());
options.setTableFormatConfig(blockConfig);
BloomFilter bloomFilter = new BloomFilter(10);
blockConfig.setFilter(bloomFilter);
options.setTableFormatConfig(blockConfig);
System.gc();
System.runFinalization();
blockConfig.setFilter(new BloomFilter(10, false));
options.setTableFormatConfig(blockConfig);
options.dispose();
options = null;
blockConfig = null;
System.gc();
System.runFinalization();
System.out.println("Filter test passed");
@ClassRule
public static final RocksMemoryResource rocksMemoryResource =
new RocksMemoryResource();
@Test
public void filter() {
Options options = null;
try {
options = new Options();
// test table config
options.setTableFormatConfig(new BlockBasedTableConfig().
setFilter(new BloomFilter()));
options.dispose();
System.gc();
System.runFinalization();
// new Bloom filter
options = new Options();
BlockBasedTableConfig blockConfig = new BlockBasedTableConfig();
blockConfig.setFilter(new BloomFilter());
options.setTableFormatConfig(blockConfig);
BloomFilter bloomFilter = new BloomFilter(10);
blockConfig.setFilter(bloomFilter);
options.setTableFormatConfig(blockConfig);
System.gc();
System.runFinalization();
blockConfig.setFilter(new BloomFilter(10, false));
options.setTableFormatConfig(blockConfig);
} finally {
if (options != null) {
options.dispose();
}
}
}
}
// Copyright (c) 2014, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
package org.rocksdb.test;
import org.rocksdb.*;
public class FlushTest {
static final String db_path = "/tmp/rocksdbjni_flush_test";
static {
RocksDB.loadLibrary();
}
public static void main(String[] args) {
RocksDB db = null;
Options options = new Options();
WriteOptions wOpt = new WriteOptions();
FlushOptions flushOptions = new FlushOptions();
try {
// Setup options
options.setCreateIfMissing(true);
options.setMaxWriteBufferNumber(10);
options.setMinWriteBufferNumberToMerge(10);
flushOptions.setWaitForFlush(true);
wOpt.setDisableWAL(true);
db = RocksDB.open(options, db_path);
db.put(wOpt, "key1".getBytes(), "value1".getBytes());
db.put(wOpt, "key2".getBytes(), "value2".getBytes());
db.put(wOpt, "key3".getBytes(), "value3".getBytes());
db.put(wOpt, "key4".getBytes(), "value4".getBytes());
assert(db.getProperty("rocksdb.num-entries-active-mem-table").equals("4"));
db.flush(flushOptions);
assert(db.getProperty("rocksdb.num-entries-active-mem-table").equals("0"));
} catch (RocksDBException e) {
assert(false);
}
db.close();
options.dispose();
wOpt.dispose();
flushOptions.dispose();
}
}
// Copyright (c) 2014, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
package org.rocksdb.test;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.rocksdb.*;
import static org.assertj.core.api.Assertions.assertThat;
public class FlushTest {
@ClassRule
public static final RocksMemoryResource rocksMemoryResource =
new RocksMemoryResource();
@Rule
public TemporaryFolder dbFolder = new TemporaryFolder();
@Test
public void flush() throws RocksDBException {
RocksDB db = null;
Options options = null;
WriteOptions wOpt = null;
FlushOptions flushOptions = null;
try {
options = new Options();
// Setup options
options.setCreateIfMissing(true);
options.setMaxWriteBufferNumber(10);
options.setMinWriteBufferNumberToMerge(10);
wOpt = new WriteOptions();
flushOptions = new FlushOptions();
flushOptions.setWaitForFlush(true);
wOpt.setDisableWAL(true);
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath());
db.put(wOpt, "key1".getBytes(), "value1".getBytes());
db.put(wOpt, "key2".getBytes(), "value2".getBytes());
db.put(wOpt, "key3".getBytes(), "value3".getBytes());
db.put(wOpt, "key4".getBytes(), "value4".getBytes());
assertThat(db.getProperty("rocksdb.num-entries-active-mem-table")).isEqualTo("4");
db.flush(flushOptions);
assertThat(db.getProperty("rocksdb.num-entries-active-mem-table")).
isEqualTo("0");
} finally {
if (flushOptions != null) {
flushOptions.dispose();
}
if (db != null) {
db.close();
}
if (options != null) {
options.dispose();
}
if (wOpt != null) {
wOpt.dispose();
}
}
}
}
......@@ -4,73 +4,89 @@
// of patent rights can be found in the PATENTS file in the same directory.
package org.rocksdb.test;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.rocksdb.*;
import java.util.ArrayList;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class KeyMayExistTest {
static final String DB_PATH = "/tmp/rocksdbjni_keymayexit_test";
static {
RocksDB.loadLibrary();
}
public static void main(String[] args){
RocksDB db;
DBOptions options = new DBOptions();
options.setCreateIfMissing(true)
.setCreateMissingColumnFamilies(true);
@ClassRule
public static final RocksMemoryResource rocksMemoryResource =
new RocksMemoryResource();
@Rule
public TemporaryFolder dbFolder = new TemporaryFolder();
@Test
public void keyMayExist() throws RocksDBException {
RocksDB db = null;
DBOptions options = null;
try {
options = new DBOptions();
options.setCreateIfMissing(true)
.setCreateMissingColumnFamilies(true);
// open database using cf names
List<ColumnFamilyDescriptor> cfNames =
new ArrayList<ColumnFamilyDescriptor>();
List<ColumnFamilyDescriptor> cfDescriptors =
new ArrayList<>();
List<ColumnFamilyHandle> columnFamilyHandleList =
new ArrayList<ColumnFamilyHandle>();
cfNames.add(new ColumnFamilyDescriptor("default"));
cfNames.add(new ColumnFamilyDescriptor("new_cf"));
db = RocksDB.open(options, DB_PATH, cfNames, columnFamilyHandleList);
assert(columnFamilyHandleList.size()==2);
new ArrayList<>();
cfDescriptors.add(new ColumnFamilyDescriptor("default"));
cfDescriptors.add(new ColumnFamilyDescriptor("new_cf"));
db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath(),
cfDescriptors, columnFamilyHandleList);
assertThat(columnFamilyHandleList.size()).
isEqualTo(2);
db.put("key".getBytes(), "value".getBytes());
// Test without column family
StringBuffer retValue = new StringBuffer();
if (db.keyMayExist("key".getBytes(), retValue)) {
assert(retValue.toString().equals("value"));
} else {
assert(false);
}
boolean exists = db.keyMayExist("key".getBytes(), retValue);
assertThat(exists).isTrue();
assertThat(retValue.toString()).
isEqualTo("value");
// Test without column family but with readOptions
retValue = new StringBuffer();
if (db.keyMayExist(new ReadOptions(), "key".getBytes(),
retValue)) {
assert(retValue.toString().equals("value"));
} else {
assert(false);
}
exists = db.keyMayExist(new ReadOptions(), "key".getBytes(),
retValue);
assertThat(exists).isTrue();
assertThat(retValue.toString()).
isEqualTo("value");
// Test with column family
retValue = new StringBuffer();
if (db.keyMayExist(columnFamilyHandleList.get(0), "key".getBytes(),
retValue)) {
assert(retValue.toString().equals("value"));
} else {
assert(false);
}
exists = db.keyMayExist(columnFamilyHandleList.get(0), "key".getBytes(),
retValue);
assertThat(exists).isTrue();
assertThat(retValue.toString()).
isEqualTo("value");
// Test with column family and readOptions
retValue = new StringBuffer();
if (db.keyMayExist(new ReadOptions(),
exists = db.keyMayExist(new ReadOptions(),
columnFamilyHandleList.get(0), "key".getBytes(),
retValue)) {
assert(retValue.toString().equals("value"));
} else {
assert(false);
}
retValue);
assertThat(exists).isTrue();
assertThat(retValue.toString()).
isEqualTo("value");
// KeyMayExist in CF1 must return false
assert(db.keyMayExist(columnFamilyHandleList.get(1), "key".getBytes(),
retValue) == false);
System.out.println("Passed KeyMayExistTest");
}catch (RocksDBException e){
e.printStackTrace();
assert(false);
assertThat(db.keyMayExist(columnFamilyHandleList.get(1),
"key".getBytes(), retValue)).isFalse();
} finally {
if (db != null) {
db.close();
}
if (options != null) {
options.dispose();
}
}
}
}
......@@ -5,103 +5,134 @@
package org.rocksdb.test;
import org.junit.ClassRule;
import org.junit.Test;
import org.rocksdb.*;
import static org.assertj.core.api.Assertions.assertThat;
public class MemTableTest {
static {
RocksDB.loadLibrary();
}
public static void main(String[] args) {
Options options = new Options();
// Test HashSkipListMemTableConfig
HashSkipListMemTableConfig memTableConfig =
new HashSkipListMemTableConfig();
assert(memTableConfig.bucketCount() == 1000000);
memTableConfig.setBucketCount(2000000);
assert(memTableConfig.bucketCount() == 2000000);
assert(memTableConfig.height() == 4);
memTableConfig.setHeight(5);
assert(memTableConfig.height() == 5);
assert(memTableConfig.branchingFactor() == 4);
memTableConfig.setBranchingFactor(6);
assert(memTableConfig.branchingFactor() == 6);
@ClassRule
public static final RocksMemoryResource rocksMemoryResource =
new RocksMemoryResource();
@Test
public void hashSkipListMemTable() throws RocksDBException {
Options options = null;
try {
options = new Options();
// Test HashSkipListMemTableConfig
HashSkipListMemTableConfig memTableConfig =
new HashSkipListMemTableConfig();
assertThat(memTableConfig.bucketCount()).
isEqualTo(1000000);
memTableConfig.setBucketCount(2000000);
assertThat(memTableConfig.bucketCount()).
isEqualTo(2000000);
assertThat(memTableConfig.height()).
isEqualTo(4);
memTableConfig.setHeight(5);
assertThat(memTableConfig.height()).
isEqualTo(5);
assertThat(memTableConfig.branchingFactor()).
isEqualTo(4);
memTableConfig.setBranchingFactor(6);
assertThat(memTableConfig.branchingFactor()).
isEqualTo(6);
options.setMemTableConfig(memTableConfig);
} catch (RocksDBException e) {
assert(false);
} finally {
if (options != null) {
options.dispose();
}
}
memTableConfig = null;
options.dispose();
System.gc();
System.runFinalization();
// Test SkipList
options = new Options();
SkipListMemTableConfig skipMemTableConfig =
new SkipListMemTableConfig();
assert(skipMemTableConfig.lookahead() == 0);
skipMemTableConfig.setLookahead(20);
assert(skipMemTableConfig.lookahead() == 20);
}
@Test
public void skipListMemTable() throws RocksDBException {
Options options = null;
try {
options = new Options();
SkipListMemTableConfig skipMemTableConfig =
new SkipListMemTableConfig();
assertThat(skipMemTableConfig.lookahead()).
isEqualTo(0);
skipMemTableConfig.setLookahead(20);
assertThat(skipMemTableConfig.lookahead()).
isEqualTo(20);
options.setMemTableConfig(skipMemTableConfig);
} catch (RocksDBException e) {
assert(false);
options.dispose();
} finally {
if (options != null) {
options.dispose();
}
}
skipMemTableConfig = null;
options.dispose();
System.gc();
System.runFinalization();
// Test HashLinkedListMemTableConfig
options = new Options();
HashLinkedListMemTableConfig hashLinkedListMemTableConfig =
new HashLinkedListMemTableConfig();
assert(hashLinkedListMemTableConfig.bucketCount() == 50000);
hashLinkedListMemTableConfig.setBucketCount(100000);
assert(hashLinkedListMemTableConfig.bucketCount() == 100000);
assert(hashLinkedListMemTableConfig.hugePageTlbSize() == 0);
hashLinkedListMemTableConfig.setHugePageTlbSize(1);
assert(hashLinkedListMemTableConfig.hugePageTlbSize() == 1);
assert(hashLinkedListMemTableConfig.
bucketEntriesLoggingThreshold() == 4096);
hashLinkedListMemTableConfig.
setBucketEntriesLoggingThreshold(200);
assert(hashLinkedListMemTableConfig.
bucketEntriesLoggingThreshold() == 200);
assert(hashLinkedListMemTableConfig.
ifLogBucketDistWhenFlush() == true);
hashLinkedListMemTableConfig.
setIfLogBucketDistWhenFlush(false);
assert(hashLinkedListMemTableConfig.
ifLogBucketDistWhenFlush() == false);
assert(hashLinkedListMemTableConfig.
thresholdUseSkiplist() == 256);
hashLinkedListMemTableConfig.setThresholdUseSkiplist(29);
assert(hashLinkedListMemTableConfig.
thresholdUseSkiplist() == 29);
}
@Test
public void hashLinkedListMemTable() throws RocksDBException {
Options options = null;
try {
options = new Options();
HashLinkedListMemTableConfig hashLinkedListMemTableConfig =
new HashLinkedListMemTableConfig();
assertThat(hashLinkedListMemTableConfig.bucketCount()).
isEqualTo(50000);
hashLinkedListMemTableConfig.setBucketCount(100000);
assertThat(hashLinkedListMemTableConfig.bucketCount()).
isEqualTo(100000);
assertThat(hashLinkedListMemTableConfig.hugePageTlbSize()).
isEqualTo(0);
hashLinkedListMemTableConfig.setHugePageTlbSize(1);
assertThat(hashLinkedListMemTableConfig.hugePageTlbSize()).
isEqualTo(1);
assertThat(hashLinkedListMemTableConfig.
bucketEntriesLoggingThreshold()).
isEqualTo(4096);
hashLinkedListMemTableConfig.
setBucketEntriesLoggingThreshold(200);
assertThat(hashLinkedListMemTableConfig.
bucketEntriesLoggingThreshold()).
isEqualTo(200);
assertThat(hashLinkedListMemTableConfig.
ifLogBucketDistWhenFlush()).isTrue();
hashLinkedListMemTableConfig.
setIfLogBucketDistWhenFlush(false);
assertThat(hashLinkedListMemTableConfig.
ifLogBucketDistWhenFlush()).isFalse();
assertThat(hashLinkedListMemTableConfig.
thresholdUseSkiplist()).
isEqualTo(256);
hashLinkedListMemTableConfig.setThresholdUseSkiplist(29);
assertThat(hashLinkedListMemTableConfig.
thresholdUseSkiplist()).
isEqualTo(29);
options.setMemTableConfig(hashLinkedListMemTableConfig);
} catch (RocksDBException e) {
assert(false);
} finally {
if (options != null) {
options.dispose();
}
}
hashLinkedListMemTableConfig = null;
options.dispose();
System.gc();
System.runFinalization();
// test VectorMemTableConfig
options = new Options();
VectorMemTableConfig vectorMemTableConfig =
new VectorMemTableConfig();
assert(vectorMemTableConfig.reservedSize() == 0);
vectorMemTableConfig.setReservedSize(123);
assert(vectorMemTableConfig.reservedSize() == 123);
}
@Test
public void vectorMemTable() throws RocksDBException {
Options options = null;
try {
options = new Options();
VectorMemTableConfig vectorMemTableConfig =
new VectorMemTableConfig();
assertThat(vectorMemTableConfig.reservedSize()).
isEqualTo(0);
vectorMemTableConfig.setReservedSize(123);
assertThat(vectorMemTableConfig.reservedSize()).
isEqualTo(123);
options.setMemTableConfig(vectorMemTableConfig);
} catch (RocksDBException e) {
assert(false);
options.dispose();
} finally {
if (options != null) {
options.dispose();
}
}
vectorMemTableConfig = null;
options.dispose();
System.gc();
System.runFinalization();
System.out.println("Mem-table test passed");
}
}
......@@ -7,192 +7,249 @@ package org.rocksdb.test;
import java.util.List;
import java.util.ArrayList;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.rocksdb.*;
import static org.assertj.core.api.Assertions.assertThat;
public class MergeTest {
static final String db_path_string = "/tmp/rocksdbjni_mergestring_db";
static final String db_cf_path_string = "/tmp/rocksdbjni_mergecfstring_db";
static final String db_path_operator = "/tmp/rocksdbjni_mergeoperator_db";
static {
RocksDB.loadLibrary();
}
@ClassRule
public static final RocksMemoryResource rocksMemoryResource =
new RocksMemoryResource();
public static void testStringOption()
@Rule
public TemporaryFolder dbFolder = new TemporaryFolder();
@Test
public void stringOption()
throws InterruptedException, RocksDBException {
Options opt = new Options();
opt.setCreateIfMissing(true);
opt.setMergeOperatorName("stringappend");
RocksDB db = RocksDB.open(opt, db_path_string);
// writing aa under key
db.put("key".getBytes(), "aa".getBytes());
// merge bb under key
db.merge("key".getBytes(), "bb".getBytes());
byte[] value = db.get("key".getBytes());
String strValue = new String(value);
db.close();
opt.dispose();
assert(strValue.equals("aa,bb"));
RocksDB db = null;
Options opt = null;
try {
String db_path_string =
dbFolder.getRoot().getAbsolutePath();
opt = new Options();
opt.setCreateIfMissing(true);
opt.setMergeOperatorName("stringappend");
db = RocksDB.open(opt, db_path_string);
// writing aa under key
db.put("key".getBytes(), "aa".getBytes());
// merge bb under key
db.merge("key".getBytes(), "bb".getBytes());
byte[] value = db.get("key".getBytes());
String strValue = new String(value);
assertThat(strValue).isEqualTo("aa,bb");
} finally {
if (db != null) {
db.close();
}
if (opt != null) {
opt.dispose();
}
}
}
public static void testCFStringOption()
@Test
public void cFStringOption()
throws InterruptedException, RocksDBException {
DBOptions opt = new DBOptions();
opt.setCreateIfMissing(true);
opt.setCreateMissingColumnFamilies(true);
List<ColumnFamilyDescriptor> cfDescr =
new ArrayList<ColumnFamilyDescriptor>();
RocksDB db = null;
DBOptions opt = null;
List<ColumnFamilyHandle> columnFamilyHandleList =
new ArrayList<ColumnFamilyHandle>();
cfDescr.add(new ColumnFamilyDescriptor("default",
new ColumnFamilyOptions().setMergeOperatorName(
"stringappend")));
cfDescr.add(new ColumnFamilyDescriptor("default",
new ColumnFamilyOptions().setMergeOperatorName(
"stringappend")));
RocksDB db = RocksDB.open(opt, db_cf_path_string,
cfDescr, columnFamilyHandleList);
// writing aa under key
db.put(columnFamilyHandleList.get(1),
"cfkey".getBytes(), "aa".getBytes());
// merge bb under key
db.merge(columnFamilyHandleList.get(1),
"cfkey".getBytes(), "bb".getBytes());
byte[] value = db.get(columnFamilyHandleList.get(1), "cfkey".getBytes());
String strValue = new String(value);
for (ColumnFamilyHandle handle : columnFamilyHandleList) {
handle.dispose();
new ArrayList<>();
try {
String db_path_string =
dbFolder.getRoot().getAbsolutePath();
opt = new DBOptions();
opt.setCreateIfMissing(true);
opt.setCreateMissingColumnFamilies(true);
List<ColumnFamilyDescriptor> cfDescriptors =
new ArrayList<>();
cfDescriptors.add(new ColumnFamilyDescriptor("default",
new ColumnFamilyOptions().setMergeOperatorName(
"stringappend")));
cfDescriptors.add(new ColumnFamilyDescriptor("default",
new ColumnFamilyOptions().setMergeOperatorName(
"stringappend")));
db = RocksDB.open(opt, db_path_string,
cfDescriptors, columnFamilyHandleList);
// writing aa under key
db.put(columnFamilyHandleList.get(1),
"cfkey".getBytes(), "aa".getBytes());
// merge bb under key
db.merge(columnFamilyHandleList.get(1),
"cfkey".getBytes(), "bb".getBytes());
byte[] value = db.get(columnFamilyHandleList.get(1), "cfkey".getBytes());
String strValue = new String(value);
assertThat(strValue).isEqualTo("aa,bb");
} finally {
for (ColumnFamilyHandle handle : columnFamilyHandleList) {
handle.dispose();
}
if (db != null) {
db.close();
}
if (opt != null) {
opt.dispose();
}
}
db.close();
opt.dispose();
assert(strValue.equals("aa,bb"));
}
public static void testOperatorOption()
@Test
public void operatorOption()
throws InterruptedException, RocksDBException {
Options opt = new Options();
opt.setCreateIfMissing(true);
StringAppendOperator stringAppendOperator = new StringAppendOperator();
opt.setMergeOperator(stringAppendOperator);
RocksDB db = RocksDB.open(opt, db_path_string);
// Writing aa under key
db.put("key".getBytes(), "aa".getBytes());
// Writing bb under key
db.merge("key".getBytes(), "bb".getBytes());
byte[] value = db.get("key".getBytes());
String strValue = new String(value);
db.close();
opt.dispose();
assert(strValue.equals("aa,bb"));
RocksDB db = null;
Options opt = null;
try {
String db_path_string =
dbFolder.getRoot().getAbsolutePath();
opt = new Options();
opt.setCreateIfMissing(true);
StringAppendOperator stringAppendOperator = new StringAppendOperator();
opt.setMergeOperator(stringAppendOperator);
db = RocksDB.open(opt, db_path_string);
// Writing aa under key
db.put("key".getBytes(), "aa".getBytes());
// Writing bb under key
db.merge("key".getBytes(), "bb".getBytes());
byte[] value = db.get("key".getBytes());
String strValue = new String(value);
assertThat(strValue).isEqualTo("aa,bb");
} finally {
if (db != null) {
db.close();
}
if (opt != null) {
opt.dispose();
}
}
}
public static void testCFOperatorOption()
@Test
public void cFOperatorOption()
throws InterruptedException, RocksDBException {
DBOptions opt = new DBOptions();
opt.setCreateIfMissing(true);
opt.setCreateMissingColumnFamilies(true);
StringAppendOperator stringAppendOperator = new StringAppendOperator();
List<ColumnFamilyDescriptor> cfDescr =
new ArrayList<ColumnFamilyDescriptor>();
List<ColumnFamilyHandle> columnFamilyHandleList =
new ArrayList<ColumnFamilyHandle>();
cfDescr.add(new ColumnFamilyDescriptor("default",
new ColumnFamilyOptions().setMergeOperator(
stringAppendOperator)));
cfDescr.add(new ColumnFamilyDescriptor("new_cf",
new ColumnFamilyOptions().setMergeOperator(
stringAppendOperator)));
RocksDB db = RocksDB.open(opt, db_path_operator,
cfDescr, columnFamilyHandleList);
// writing aa under key
db.put(columnFamilyHandleList.get(1),
"cfkey".getBytes(), "aa".getBytes());
// merge bb under key
db.merge(columnFamilyHandleList.get(1),
"cfkey".getBytes(), "bb".getBytes());
byte[] value = db.get(columnFamilyHandleList.get(1), "cfkey".getBytes());
String strValue = new String(value);
// Test also with createColumnFamily
ColumnFamilyHandle columnFamilyHandle = db.createColumnFamily(
new ColumnFamilyDescriptor("new_cf2",
new ColumnFamilyOptions().setMergeOperator(
new StringAppendOperator())));
// writing xx under cfkey2
db.put(columnFamilyHandle, "cfkey2".getBytes(), "xx".getBytes());
// merge yy under cfkey2
db.merge(columnFamilyHandle, "cfkey2".getBytes(), "yy".getBytes());
value = db.get(columnFamilyHandle, "cfkey2".getBytes());
String strValueTmpCf = new String(value);
db.close();
opt.dispose();
assert(strValue.equals("aa,bb"));
assert(strValueTmpCf.equals("xx,yy"));
RocksDB db = null;
DBOptions opt = null;
ColumnFamilyHandle columnFamilyHandle = null;
try {
String db_path_string =
dbFolder.getRoot().getAbsolutePath();
opt = new DBOptions();
opt.setCreateIfMissing(true);
opt.setCreateMissingColumnFamilies(true);
StringAppendOperator stringAppendOperator = new StringAppendOperator();
List<ColumnFamilyDescriptor> cfDescriptors =
new ArrayList<>();
List<ColumnFamilyHandle> columnFamilyHandleList =
new ArrayList<>();
cfDescriptors.add(new ColumnFamilyDescriptor("default",
new ColumnFamilyOptions().setMergeOperator(
stringAppendOperator)));
cfDescriptors.add(new ColumnFamilyDescriptor("new_cf",
new ColumnFamilyOptions().setMergeOperator(
stringAppendOperator)));
db = RocksDB.open(opt, db_path_string,
cfDescriptors, columnFamilyHandleList);
// writing aa under key
db.put(columnFamilyHandleList.get(1),
"cfkey".getBytes(), "aa".getBytes());
// merge bb under key
db.merge(columnFamilyHandleList.get(1),
"cfkey".getBytes(), "bb".getBytes());
byte[] value = db.get(columnFamilyHandleList.get(1), "cfkey".getBytes());
String strValue = new String(value);
// Test also with createColumnFamily
columnFamilyHandle = db.createColumnFamily(
new ColumnFamilyDescriptor("new_cf2",
new ColumnFamilyOptions().setMergeOperator(stringAppendOperator)));
// writing xx under cfkey2
db.put(columnFamilyHandle, "cfkey2".getBytes(), "xx".getBytes());
// merge yy under cfkey2
db.merge(columnFamilyHandle, new WriteOptions(), "cfkey2".getBytes(), "yy".getBytes());
value = db.get(columnFamilyHandle, "cfkey2".getBytes());
String strValueTmpCf = new String(value);
columnFamilyHandle.dispose();
assertThat(strValue).isEqualTo("aa,bb");
assertThat(strValueTmpCf).isEqualTo("xx,yy");
} finally {
if (columnFamilyHandle != null) {
columnFamilyHandle.dispose();
}
if (db != null) {
db.close();
}
if (opt != null) {
opt.dispose();
}
}
}
public static void testOperatorGcBehaviour()
@Test
public void operatorGcBehaviour()
throws RocksDBException {
Options opt = new Options();
opt.setCreateIfMissing(true);
StringAppendOperator stringAppendOperator = new StringAppendOperator();
opt.setMergeOperator(stringAppendOperator);
RocksDB db = RocksDB.open(opt, db_path_string);
db.close();
opt.dispose();
System.gc();
System.runFinalization();
// test reuse
opt = new Options();
opt.setMergeOperator(stringAppendOperator);
db = RocksDB.open(opt, db_path_string);
db.close();
opt.dispose();
System.gc();
System.runFinalization();
// test param init
opt = new Options();
opt.setMergeOperator(new StringAppendOperator());
db = RocksDB.open(opt, db_path_string);
db.close();
opt.dispose();
System.gc();
System.runFinalization();
// test replace one with another merge operator instance
opt = new Options();
opt.setMergeOperator(stringAppendOperator);
StringAppendOperator newStringAppendOperator = new StringAppendOperator();
opt.setMergeOperator(newStringAppendOperator);
db = RocksDB.open(opt, db_path_string);
db.close();
opt.dispose();
stringAppendOperator = null;
newStringAppendOperator = null;
System.gc();
System.runFinalization();
}
public static void main(String[] args)
throws InterruptedException, RocksDBException {
testStringOption();
testCFStringOption();
testOperatorOption();
testCFOperatorOption();
testOperatorGcBehaviour();
System.out.println("Passed MergeTest.");
Options opt = null;
RocksDB db = null;
try {
String db_path_string =
dbFolder.getRoot().getAbsolutePath();
opt = new Options();
opt.setCreateIfMissing(true);
StringAppendOperator stringAppendOperator = new StringAppendOperator();
opt.setMergeOperator(stringAppendOperator);
db = RocksDB.open(opt, db_path_string);
db.close();
opt.dispose();
System.gc();
System.runFinalization();
// test reuse
opt = new Options();
opt.setMergeOperator(stringAppendOperator);
db = RocksDB.open(opt, db_path_string);
db.close();
opt.dispose();
System.gc();
System.runFinalization();
// test param init
opt = new Options();
opt.setMergeOperator(new StringAppendOperator());
db = RocksDB.open(opt, db_path_string);
db.close();
opt.dispose();
System.gc();
System.runFinalization();
// test replace one with another merge operator instance
opt = new Options();
opt.setMergeOperator(stringAppendOperator);
StringAppendOperator newStringAppendOperator = new StringAppendOperator();
opt.setMergeOperator(newStringAppendOperator);
db = RocksDB.open(opt, db_path_string);
db.close();
opt.dispose();
} finally {
if (db != null) {
db.close();
}
if (opt != null) {
opt.dispose();
}
}
}
}
......@@ -5,26 +5,33 @@
package org.rocksdb.test;
import org.junit.ClassRule;
import org.junit.Test;
import org.rocksdb.*;
import static org.assertj.core.api.Assertions.assertThat;
public class MixedOptionsTest {
static {
RocksDB.loadLibrary();
}
public static void main(String[] args) {
@ClassRule
public static final RocksMemoryResource rocksMemoryResource =
new RocksMemoryResource();
@Test
public void mixedOptionsTest(){
// Set a table factory and check the names
ColumnFamilyOptions cfOptions = new ColumnFamilyOptions();
cfOptions.setTableFormatConfig(new BlockBasedTableConfig().
setFilter(new BloomFilter()));
assert(cfOptions.tableFactoryName().equals(
"BlockBasedTable"));
assertThat(cfOptions.tableFactoryName()).isEqualTo(
"BlockBasedTable");
cfOptions.setTableFormatConfig(new PlainTableConfig());
assert(cfOptions.tableFactoryName().equals("PlainTable"));
assertThat(cfOptions.tableFactoryName()).isEqualTo("PlainTable");
// Initialize a dbOptions object from cf options and
// db options
DBOptions dbOptions = new DBOptions();
Options options = new Options(dbOptions, cfOptions);
assert(options.tableFactoryName().equals("PlainTable"));
assertThat(options.tableFactoryName()).isEqualTo("PlainTable");
// Free instances
options.dispose();
options = null;
......
......@@ -5,30 +5,94 @@
package org.rocksdb.test;
import org.junit.ClassRule;
import org.junit.Test;
import org.rocksdb.EncodingType;
import org.rocksdb.Options;
import org.rocksdb.PlainTableConfig;
import static org.assertj.core.api.Assertions.assertThat;
public class PlainTableConfigTest {
public static void main(String[] args) {
@ClassRule
public static final RocksMemoryResource rocksMemoryResource =
new RocksMemoryResource();
@Test
public void keySize() {
PlainTableConfig plainTableConfig = new PlainTableConfig();
plainTableConfig.setKeySize(5);
assert(plainTableConfig.keySize() == 5);
assertThat(plainTableConfig.keySize()).
isEqualTo(5);
}
@Test
public void bloomBitsPerKey() {
PlainTableConfig plainTableConfig = new PlainTableConfig();
plainTableConfig.setBloomBitsPerKey(11);
assert(plainTableConfig.bloomBitsPerKey() == 11);
assertThat(plainTableConfig.bloomBitsPerKey()).
isEqualTo(11);
}
@Test
public void hashTableRatio() {
PlainTableConfig plainTableConfig = new PlainTableConfig();
plainTableConfig.setHashTableRatio(0.95);
assert(plainTableConfig.hashTableRatio() == 0.95);
assertThat(plainTableConfig.hashTableRatio()).
isEqualTo(0.95);
}
@Test
public void indexSparseness() {
PlainTableConfig plainTableConfig = new PlainTableConfig();
plainTableConfig.setIndexSparseness(18);
assert(plainTableConfig.indexSparseness() == 18);
assertThat(plainTableConfig.indexSparseness()).
isEqualTo(18);
}
@Test
public void hugePageTlbSize() {
PlainTableConfig plainTableConfig = new PlainTableConfig();
plainTableConfig.setHugePageTlbSize(1);
assert(plainTableConfig.hugePageTlbSize() == 1);
assertThat(plainTableConfig.hugePageTlbSize()).
isEqualTo(1);
}
@Test
public void encodingType() {
PlainTableConfig plainTableConfig = new PlainTableConfig();
plainTableConfig.setEncodingType(EncodingType.kPrefix);
assert(plainTableConfig.encodingType().equals(
EncodingType.kPrefix));
assertThat(plainTableConfig.encodingType()).isEqualTo(
EncodingType.kPrefix);
}
@Test
public void fullScanMode() {
PlainTableConfig plainTableConfig = new PlainTableConfig();
plainTableConfig.setFullScanMode(true);
assert(plainTableConfig.fullScanMode());
assertThat(plainTableConfig.fullScanMode()).isTrue(); }
@Test
public void storeIndexInFile() {
PlainTableConfig plainTableConfig = new PlainTableConfig();
plainTableConfig.setStoreIndexInFile(true);
assert(plainTableConfig.storeIndexInFile());
System.out.println("PlainTableConfig test passed");
assertThat(plainTableConfig.storeIndexInFile()).
isTrue();
}
@Test
public void plainTableConfig() {
Options opt = null;
try {
opt = new Options();
PlainTableConfig plainTableConfig = new PlainTableConfig();
opt.setTableFormatConfig(plainTableConfig);
assertThat(opt.tableFactoryName()).isEqualTo("PlainTable");
} finally {
if (opt != null) {
opt.dispose();
}
}
}
}
......@@ -18,11 +18,11 @@ public class PlatformRandomHelper {
* @return boolean value indicating if operating system is 64 Bit.
*/
public static boolean isOs64Bit(){
boolean is64Bit = false;
boolean is64Bit;
if (System.getProperty("os.name").contains("Windows")) {
is64Bit = (System.getenv("ProgramFiles(x86)") != null);
} else {
is64Bit = (System.getProperty("os.arch").indexOf("64") != -1);
is64Bit = (System.getProperty("os.arch").contains("64"));
}
return is64Bit;
}
......
......@@ -4,41 +4,59 @@
// of patent rights can be found in the PATENTS file in the same directory.
package org.rocksdb.test;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.rocksdb.*;
import java.util.ArrayList;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class ReadOnlyTest {
static final String DB_PATH = "/tmp/rocksdbjni_readonly_test";
static {
RocksDB.loadLibrary();
}
public static void main(String[] args){
RocksDB db = null, db2 = null, db3 = null;
@ClassRule
public static final RocksMemoryResource rocksMemoryResource =
new RocksMemoryResource();
@Rule
public TemporaryFolder dbFolder = new TemporaryFolder();
@Test
public void readOnlyOpen() throws RocksDBException {
RocksDB db = null;
RocksDB db2 = null;
RocksDB db3 = null;
Options options = null;
List<ColumnFamilyHandle> columnFamilyHandleList =
new ArrayList<ColumnFamilyHandle>();
List<ColumnFamilyHandle> db2ColumnFamilyHandleList =
new ArrayList<ColumnFamilyHandle>();
List<ColumnFamilyHandle> db3ColumnFamilyHandleList =
new ArrayList<ColumnFamilyHandle>();
Options options = new Options();
options.setCreateIfMissing(true);
new ArrayList<>();
List<ColumnFamilyHandle> readOnlyColumnFamilyHandleList =
new ArrayList<>();
List<ColumnFamilyHandle> readOnlyColumnFamilyHandleList2 =
new ArrayList<>();
try {
db = RocksDB.open(options, DB_PATH);
options = new Options();
options.setCreateIfMissing(true);
db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath());
db.put("key".getBytes(), "value".getBytes());
db2 = RocksDB.openReadOnly(DB_PATH);
assert("value".equals(new String(db2.get("key".getBytes()))));
db2 = RocksDB.openReadOnly(
dbFolder.getRoot().getAbsolutePath());
assertThat("value").
isEqualTo(new String(db2.get("key".getBytes())));
db.close();
db2.close();
List<ColumnFamilyDescriptor> cfDescriptors = new ArrayList<>();
cfDescriptors.add(
new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY,
new ColumnFamilyOptions()));
List<ColumnFamilyDescriptor> cfNames =
new ArrayList<ColumnFamilyDescriptor>();
cfNames.add(new ColumnFamilyDescriptor("default"));
db = RocksDB.open(DB_PATH, cfNames, columnFamilyHandleList);
db = RocksDB.open(
dbFolder.getRoot().getAbsolutePath(), cfDescriptors, columnFamilyHandleList);
columnFamilyHandleList.add(db.createColumnFamily(
new ColumnFamilyDescriptor("new_cf", new ColumnFamilyOptions())));
columnFamilyHandleList.add(db.createColumnFamily(
......@@ -46,85 +64,270 @@ public class ReadOnlyTest {
db.put(columnFamilyHandleList.get(2), "key2".getBytes(),
"value2".getBytes());
db2 = RocksDB.openReadOnly(DB_PATH, cfNames, db2ColumnFamilyHandleList);
assert(db2.get("key2".getBytes())==null);
assert(db2.get(columnFamilyHandleList.get(0), "key2".getBytes())==null);
List<ColumnFamilyDescriptor> cfNewName =
new ArrayList<ColumnFamilyDescriptor>();
cfNewName.add(new ColumnFamilyDescriptor("default"));
cfNewName.add(new ColumnFamilyDescriptor("new_cf2"));
db3 = RocksDB.openReadOnly(DB_PATH, cfNewName, db3ColumnFamilyHandleList);
assert(new String(db3.get(db3ColumnFamilyHandleList.get(1),
"key2".getBytes())).equals("value2"));
}catch (RocksDBException e){
e.printStackTrace();
assert(false);
db2 = RocksDB.openReadOnly(
dbFolder.getRoot().getAbsolutePath(), cfDescriptors,
readOnlyColumnFamilyHandleList);
assertThat(db2.get("key2".getBytes())).isNull();
assertThat(db2.get(readOnlyColumnFamilyHandleList.get(0), "key2".getBytes())).
isNull();
cfDescriptors.clear();
cfDescriptors.add(
new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY,
new ColumnFamilyOptions()));
cfDescriptors.add(
new ColumnFamilyDescriptor("new_cf2", new ColumnFamilyOptions()));
db3 = RocksDB.openReadOnly(
dbFolder.getRoot().getAbsolutePath(), cfDescriptors, readOnlyColumnFamilyHandleList2);
assertThat(new String(db3.get(readOnlyColumnFamilyHandleList2.get(1),
"key2".getBytes()))).isEqualTo("value2");
} finally {
if (db != null) {
db.close();
}
if (db2 != null) {
db2.close();
}
if (db3 != null) {
db3.close();
}
if (options != null) {
options.dispose();
}
}
// test that put fails in readonly mode
}
@Test(expected = RocksDBException.class)
public void failToWriteInReadOnly() throws RocksDBException {
RocksDB db = null;
RocksDB rDb = null;
Options options = null;
try {
db2.put("key".getBytes(), "value".getBytes());
assert(false);
} catch (RocksDBException e) {
assert(true);
List<ColumnFamilyDescriptor> cfDescriptors = new ArrayList<>();
cfDescriptors.add(
new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY,
new ColumnFamilyOptions()));
List<ColumnFamilyHandle> readOnlyColumnFamilyHandleList =
new ArrayList<>();
options = new Options();
options.setCreateIfMissing(true);
db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath());
db.close();
rDb = RocksDB.openReadOnly(
dbFolder.getRoot().getAbsolutePath(), cfDescriptors,
readOnlyColumnFamilyHandleList);
// test that put fails in readonly mode
rDb.put("key".getBytes(), "value".getBytes());
} finally {
if (db != null) {
db.close();
}
if (rDb != null) {
rDb.close();
}
if (options != null) {
options.dispose();
}
}
}
@Test(expected = RocksDBException.class)
public void failToCFWriteInReadOnly() throws RocksDBException {
RocksDB db = null;
RocksDB rDb = null;
Options options = null;
try {
db3.put(db3ColumnFamilyHandleList.get(1),
List<ColumnFamilyDescriptor> cfDescriptors = new ArrayList<>();
cfDescriptors.add(
new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY,
new ColumnFamilyOptions()));
List<ColumnFamilyHandle> readOnlyColumnFamilyHandleList =
new ArrayList<>();
options = new Options();
options.setCreateIfMissing(true);
db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath());
db.close();
rDb = RocksDB.openReadOnly(
dbFolder.getRoot().getAbsolutePath(), cfDescriptors,
readOnlyColumnFamilyHandleList);
rDb.put(readOnlyColumnFamilyHandleList.get(0),
"key".getBytes(), "value".getBytes());
assert(false);
} catch (RocksDBException e) {
assert(true);
} finally {
if (db != null) {
db.close();
}
if (rDb != null) {
rDb.close();
}
if (options != null) {
options.dispose();
}
}
// test that remove fails in readonly mode
}
@Test(expected = RocksDBException.class)
public void failToRemoveInReadOnly() throws RocksDBException {
RocksDB db = null;
RocksDB rDb = null;
Options options = null;
try {
db2.remove("key".getBytes());
assert(false);
} catch (RocksDBException e) {
assert(true);
List<ColumnFamilyDescriptor> cfDescriptors = new ArrayList<>();
cfDescriptors.add(
new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY,
new ColumnFamilyOptions()));
List<ColumnFamilyHandle> readOnlyColumnFamilyHandleList =
new ArrayList<>();
options = new Options();
options.setCreateIfMissing(true);
db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath());
db.close();
rDb = RocksDB.openReadOnly(
dbFolder.getRoot().getAbsolutePath(), cfDescriptors,
readOnlyColumnFamilyHandleList);
rDb.remove("key".getBytes());
} finally {
if (db != null) {
db.close();
}
if (rDb != null) {
rDb.close();
}
if (options != null) {
options.dispose();
}
}
}
@Test(expected = RocksDBException.class)
public void failToCFRemoveInReadOnly() throws RocksDBException {
RocksDB db = null;
RocksDB rDb = null;
Options options = null;
try {
db3.remove(db3ColumnFamilyHandleList.get(1),
List<ColumnFamilyDescriptor> cfDescriptors = new ArrayList<>();
cfDescriptors.add(
new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY,
new ColumnFamilyOptions()));
List<ColumnFamilyHandle> readOnlyColumnFamilyHandleList =
new ArrayList<>();
options = new Options();
options.setCreateIfMissing(true);
db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath());
db.close();
rDb = RocksDB.openReadOnly(
dbFolder.getRoot().getAbsolutePath(), cfDescriptors,
readOnlyColumnFamilyHandleList);
rDb.remove(readOnlyColumnFamilyHandleList.get(0),
"key".getBytes());
assert(false);
} catch (RocksDBException e) {
assert(true);
} finally {
if (db != null) {
db.close();
}
if (rDb != null) {
rDb.close();
}
if (options != null) {
options.dispose();
}
}
// test that write fails in readonly mode
WriteBatch wb = new WriteBatch();
wb.put("key".getBytes(), "value".getBytes());
}
@Test(expected = RocksDBException.class)
public void failToWriteBatchReadOnly() throws RocksDBException {
RocksDB db = null;
RocksDB rDb = null;
Options options = null;
try {
db2.write(new WriteOptions(), wb);
assert(false);
} catch (RocksDBException e) {
assert(true);
List<ColumnFamilyDescriptor> cfDescriptors = new ArrayList<>();
cfDescriptors.add(
new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY,
new ColumnFamilyOptions()));
List<ColumnFamilyHandle> readOnlyColumnFamilyHandleList =
new ArrayList<>();
options = new Options();
options.setCreateIfMissing(true);
db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath());
db.close();
rDb = RocksDB.openReadOnly(
dbFolder.getRoot().getAbsolutePath(), cfDescriptors,
readOnlyColumnFamilyHandleList);
WriteBatch wb = new WriteBatch();
wb.put("key".getBytes(), "value".getBytes());
rDb.write(new WriteOptions(), wb);
} finally {
if (db != null) {
db.close();
}
if (rDb != null) {
rDb.close();
}
if (options != null) {
options.dispose();
}
}
wb.dispose();
wb = new WriteBatch();
wb.put(db3ColumnFamilyHandleList.get(1),
"key".getBytes(), "value".getBytes());
}
@Test(expected = RocksDBException.class)
public void failToCFWriteBatchReadOnly() throws RocksDBException {
RocksDB db = null;
RocksDB rDb = null;
Options options = null;
WriteBatch wb = null;
try {
db3.write(new WriteOptions(), wb);
assert(false);
} catch (RocksDBException e) {
assert(true);
}
wb.dispose();
// cleanup c++ pointers
for (ColumnFamilyHandle columnFamilyHandle :
columnFamilyHandleList) {
columnFamilyHandle.dispose();
}
db.close();
for (ColumnFamilyHandle columnFamilyHandle :
db2ColumnFamilyHandleList) {
columnFamilyHandle.dispose();
}
db2.close();
for (ColumnFamilyHandle columnFamilyHandle :
db3ColumnFamilyHandleList) {
columnFamilyHandle.dispose();
List<ColumnFamilyDescriptor> cfDescriptors = new ArrayList<>();
cfDescriptors.add(
new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY,
new ColumnFamilyOptions()));
List<ColumnFamilyHandle> readOnlyColumnFamilyHandleList =
new ArrayList<>();
options = new Options();
options.setCreateIfMissing(true);
db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath());
db.close();
rDb = RocksDB.openReadOnly(
dbFolder.getRoot().getAbsolutePath(), cfDescriptors,
readOnlyColumnFamilyHandleList);
wb = new WriteBatch();
wb.put(readOnlyColumnFamilyHandleList.get(0),
"key".getBytes(), "value".getBytes());
rDb.write(new WriteOptions(), wb);
} finally {
if (db != null) {
db.close();
}
if (rDb != null) {
rDb.close();
}
if (options != null) {
options.dispose();
}
if (wb != null) {
wb.dispose();
}
}
db3.close();
System.out.println("Passed ReadOnlyTest");
}
}
......@@ -6,35 +6,147 @@
package org.rocksdb.test;
import java.util.Random;
import org.rocksdb.RocksDB;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.rocksdb.ReadOptions;
import static org.assertj.core.api.Assertions.assertThat;
public class ReadOptionsTest {
static {
RocksDB.loadLibrary();
}
public static void main(String[] args) {
ReadOptions opt = new ReadOptions();
Random rand = new Random();
{ // VerifyChecksums test
@ClassRule
public static final RocksMemoryResource rocksMemoryResource =
new RocksMemoryResource();
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void verifyChecksum(){
ReadOptions opt = null;
try {
opt = new ReadOptions();
Random rand = new Random();
boolean boolValue = rand.nextBoolean();
opt.setVerifyChecksums(boolValue);
assert(opt.verifyChecksums() == boolValue);
assertThat(opt.verifyChecksums()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // FillCache test
@Test
public void fillCache(){
ReadOptions opt = null;
try {
opt = new ReadOptions();
Random rand = new Random();
boolean boolValue = rand.nextBoolean();
opt.setFillCache(boolValue);
assert(opt.fillCache() == boolValue);
assertThat(opt.fillCache()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
{ // Tailing test
@Test
public void tailing(){
ReadOptions opt = null;
try {
opt = new ReadOptions();
Random rand = new Random();
boolean boolValue = rand.nextBoolean();
opt.setTailing(boolValue);
assert(opt.tailing() == boolValue);
assertThat(opt.tailing()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
@Test
public void snapshot(){
ReadOptions opt = null;
try {
opt = new ReadOptions();
opt.setSnapshot(null);
assertThat(opt.snapshot()).isNull();
} finally {
if (opt != null) {
opt.dispose();
}
}
}
@Test
public void failSetVerifyChecksumUninitialized(){
ReadOptions readOptions = setupUninitializedReadOptions(
exception);
readOptions.setVerifyChecksums(true);
}
@Test
public void failVerifyChecksumUninitialized(){
ReadOptions readOptions = setupUninitializedReadOptions(
exception);
readOptions.verifyChecksums();
}
@Test
public void failSetFillCacheUninitialized(){
ReadOptions readOptions = setupUninitializedReadOptions(
exception);
readOptions.setFillCache(true);
}
@Test
public void failFillCacheUninitialized(){
ReadOptions readOptions = setupUninitializedReadOptions(
exception);
readOptions.fillCache();
}
@Test
public void failSetTailingUninitialized(){
ReadOptions readOptions = setupUninitializedReadOptions(
exception);
readOptions.setTailing(true);
}
@Test
public void failTailingUninitialized(){
ReadOptions readOptions = setupUninitializedReadOptions(
exception);
readOptions.tailing();
}
@Test
public void failSetSnapshotUninitialized(){
ReadOptions readOptions = setupUninitializedReadOptions(
exception);
readOptions.setSnapshot(null);
}
@Test
public void failSnapshotUninitialized(){
ReadOptions readOptions = setupUninitializedReadOptions(
exception);
readOptions.snapshot();
}
opt.dispose();
System.out.println("Passed ReadOptionsTest");
private ReadOptions setupUninitializedReadOptions(
ExpectedException exception) {
ReadOptions readOptions = new ReadOptions();
readOptions.dispose();
exception.expect(AssertionError.class);
return readOptions;
}
}
此差异已折叠。
// Copyright (c) 2014, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
package org.rocksdb.test;
import org.junit.ClassRule;
import org.junit.Test;
import org.rocksdb.RocksEnv;
import static org.assertj.core.api.Assertions.assertThat;
public class RocksEnvTest {
@ClassRule
public static final RocksMemoryResource rocksMemoryResource =
new RocksMemoryResource();
@Test
public void rocksEnv(){
RocksEnv rocksEnv = RocksEnv.getDefault();
rocksEnv.setBackgroundThreads(5);
// default rocksenv will always return zero for flush pool
// no matter what was set via setBackgroundThreads
assertThat(rocksEnv.getThreadPoolQueueLen(RocksEnv.FLUSH_POOL)).
isEqualTo(0);
rocksEnv.setBackgroundThreads(5, RocksEnv.FLUSH_POOL);
// default rocksenv will always return zero for flush pool
// no matter what was set via setBackgroundThreads
assertThat(rocksEnv.getThreadPoolQueueLen(RocksEnv.FLUSH_POOL)).
isEqualTo(0);
rocksEnv.setBackgroundThreads(5, RocksEnv.COMPACTION_POOL);
// default rocksenv will always return zero for compaction pool
// no matter what was set via setBackgroundThreads
assertThat(rocksEnv.getThreadPoolQueueLen(RocksEnv.COMPACTION_POOL)).
isEqualTo(0);
}
}
// Copyright (c) 2014, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
package org.rocksdb.test;
import org.junit.internal.JUnitSystem;
import org.junit.internal.RealSystem;
import org.junit.internal.TextListener;
import org.junit.runner.Description;
import org.junit.runner.JUnitCore;
import java.util.ArrayList;
import java.util.List;
/**
* Custom Junit Runner to print also Test classes
* and executed methods to command prompt.
*/
public class RocksJunitRunner {
/**
* Listener which overrides default functionality
* to print class and method to system out.
*/
static class RocksJunitListener extends TextListener {
/**
* RocksJunitListener constructor
*
* @param system JUnitSystem
*/
public RocksJunitListener(JUnitSystem system) {
super(system);
}
@Override
public void testStarted(Description description) {
System.out.format("Run: %s testing now -> %s \n",
description.getClassName(),
description.getMethodName());
}
}
/**
* Main method to execute tests
*
* @param args Test classes as String names
*/
public static void main(String[] args){
JUnitCore runner = new JUnitCore();
final JUnitSystem system = new RealSystem();
runner.addListener(new RocksJunitListener(system));
try {
List<Class<?>> classes = new ArrayList<>();
for (String arg : args) {
classes.add(Class.forName(arg));
}
runner.run(classes.toArray(new Class[1]));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
......@@ -124,7 +124,7 @@ void Java_org_rocksdb_BackupableDBOptions_newBackupableDBOptions(
* Signature: (J)Ljava/lang/String;
*/
jstring Java_org_rocksdb_BackupableDBOptions_backupDir(
JNIEnv* env, jobject jopt, jlong jhandle, jstring jpath) {
JNIEnv* env, jobject jopt, jlong jhandle) {
auto bopt = reinterpret_cast<rocksdb::BackupableDBOptions*>(jhandle);
return env->NewStringUTF(bopt->backup_dir.c_str());
}
......
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册