rocksdb: switch to gtest

Summary:
Our existing test notation is very similar to what is used in gtest. It makes it easy to adopt what is different.
In this diff I modify existing [[ https://code.google.com/p/googletest/wiki/Primer#Test_Fixtures:_Using_the_Same_Data_Configuration_for_Multiple_Te | test fixture ]] classes to inherit from `testing::Test`. Also for unit tests that use fixture class, `TEST` is replaced with `TEST_F` as required in gtest.

There are several custom `main` functions in our existing tests. To make this transition easier, I modify all `main` functions to fallow gtest notation. But eventually we can remove them and use implementation of `main` that gtest provides.

```lang=bash
% cat ~/transform
#!/bin/sh
files=$(git ls-files '*test\.cc')
for file in $files
do
  if grep -q "rocksdb::test::RunAllTests()" $file
  then
    if grep -Eq '^class \w+Test {' $file
    then
      perl -pi -e 's/^(class \w+Test) {/${1}: public testing::Test {/g' $file
      perl -pi -e 's/^(TEST)/${1}_F/g' $file
    fi
    perl -pi -e 's/(int main.*\{)/${1}::testing::InitGoogleTest(&argc, argv);/g' $file
    perl -pi -e 's/rocksdb::test::RunAllTests/RUN_ALL_TESTS/g' $file
  fi
done
% sh ~/transform
% make format
```

Second iteration of this diff contains only scripted changes.

Third iteration contains manual changes to fix last errors and make it compilable.

Test Plan:
Build and notice no errors.
```lang=bash
% USE_CLANG=1 make check -j55
```
Tests are still testing.

Reviewers: meyering, sdong, rven, igor

Reviewed By: igor

Subscribers: dhruba, leveldb

Differential Revision: https://reviews.facebook.net/D35157
main
Igor Sugak 10 years ago
parent 413e35273e
commit b4b69e4f77
  1. 42
      db/column_family_test.cc
  2. 7
      db/compact_files_test.cc
  3. 9
      db/compaction_job_test.cc
  4. 35
      db/compaction_picker_test.cc
  5. 19
      db/comparator_db_test.cc
  6. 29
      db/corruption_test.cc
  7. 19
      db/cuckoo_table_db_test.cc
  8. 31
      db/db_iter_test.cc
  9. 396
      db/db_test.cc
  10. 13
      db/dbformat_test.cc
  11. 15
      db/deletefile_test.cc
  12. 23
      db/fault_injection_test.cc
  13. 15
      db/file_indexer_test.cc
  14. 11
      db/filename_test.cc
  15. 11
      db/flush_job_test.cc
  16. 15
      db/listener_test.cc
  17. 104
      db/log_test.cc
  18. 15
      db/perf_context_test.cc
  19. 29
      db/plain_table_db_test.cc
  20. 9
      db/prefix_test.cc
  21. 21
      db/skiplist_test.cc
  22. 10
      db/table_properties_collector_test.cc
  23. 19
      db/version_builder_test.cc
  24. 11
      db/version_edit_test.cc
  25. 34
      db/version_set_test.cc
  26. 17
      db/wal_manager_test.cc
  27. 29
      db/write_batch_test.cc
  28. 9
      db/write_controller_test.cc
  29. 21
      table/block_based_filter_block_test.cc
  30. 9
      table/block_hash_index_test.cc
  31. 11
      table/block_test.cc
  32. 29
      table/cuckoo_table_builder_test.cc
  33. 19
      table/cuckoo_table_reader_test.cc
  34. 17
      table/full_filter_block_test.cc
  35. 19
      table/merger_test.cc
  36. 57
      table/table_test.cc
  37. 11
      tools/reduce_levels_test.cc
  38. 15
      util/arena_test.cc
  39. 22
      util/auto_roll_logger_test.cc
  40. 17
      util/autovector_test.cc
  41. 19
      util/bloom_test.cc
  42. 27
      util/cache_test.cc
  43. 3
      util/coding_test.cc
  44. 3
      util/crc32c_test.cc
  45. 14
      util/dynamic_bloom_test.cc
  46. 36
      util/env_test.cc
  47. 7
      util/event_logger_test.cc
  48. 7
      util/filelock_test.cc
  49. 12
      util/histogram_test.cc
  50. 10
      util/manual_compaction_test.cc
  51. 17
      util/memenv_test.cc
  52. 19
      util/mock_env_test.cc
  53. 21
      util/options_test.cc
  54. 10
      util/rate_limiter_test.cc
  55. 13
      util/slice_transform_test.cc
  56. 15
      util/sst_dump_test.cc
  57. 182
      util/testharness.h
  58. 12
      util/thread_list_test.cc
  59. 19
      util/thread_local_test.cc
  60. 31
      utilities/backupable/backupable_db_test.cc
  61. 11
      utilities/document/document_db_test.cc
  62. 29
      utilities/document/json_document_test.cc
  63. 9
      utilities/geodb/geodb_test.cc
  64. 28
      utilities/merge_operators/string_append/stringappend_test.cc
  65. 26
      utilities/redis/redis_lists_test.cc
  66. 17
      utilities/spatialdb/spatial_db_test.cc
  67. 35
      utilities/ttl/ttl_test.cc
  68. 19
      utilities/write_batch_with_index/write_batch_with_index_test.cc

@ -47,7 +47,7 @@ class EnvCounter : public EnvWrapper {
int num_new_writable_file_; int num_new_writable_file_;
}; };
class ColumnFamilyTest { class ColumnFamilyTest : public testing::Test {
public: public:
ColumnFamilyTest() : rnd_(139) { ColumnFamilyTest() : rnd_(139) {
env_ = new EnvCounter(Env::Default()); env_ = new EnvCounter(Env::Default());
@ -333,7 +333,7 @@ class DumbLogger : public Logger {
virtual size_t GetLogFileSize() const override { return 0; } virtual size_t GetLogFileSize() const override { return 0; }
}; };
TEST(ColumnFamilyTest, DontReuseColumnFamilyID) { TEST_F(ColumnFamilyTest, DontReuseColumnFamilyID) {
for (int iter = 0; iter < 3; ++iter) { for (int iter = 0; iter < 3; ++iter) {
Open(); Open();
CreateColumnFamilies({"one", "two", "three"}); CreateColumnFamilies({"one", "two", "three"});
@ -360,8 +360,7 @@ TEST(ColumnFamilyTest, DontReuseColumnFamilyID) {
} }
} }
TEST_F(ColumnFamilyTest, AddDrop) {
TEST(ColumnFamilyTest, AddDrop) {
Open(); Open();
CreateColumnFamilies({"one", "two", "three"}); CreateColumnFamilies({"one", "two", "three"});
ASSERT_EQ("NOT_FOUND", Get(1, "fodor")); ASSERT_EQ("NOT_FOUND", Get(1, "fodor"));
@ -387,7 +386,7 @@ TEST(ColumnFamilyTest, AddDrop) {
std::vector<std::string>({"default", "four", "three"})); std::vector<std::string>({"default", "four", "three"}));
} }
TEST(ColumnFamilyTest, DropTest) { TEST_F(ColumnFamilyTest, DropTest) {
// first iteration - dont reopen DB before dropping // first iteration - dont reopen DB before dropping
// second iteration - reopen DB before dropping // second iteration - reopen DB before dropping
for (int iter = 0; iter < 2; ++iter) { for (int iter = 0; iter < 2; ++iter) {
@ -411,7 +410,7 @@ TEST(ColumnFamilyTest, DropTest) {
} }
} }
TEST(ColumnFamilyTest, WriteBatchFailure) { TEST_F(ColumnFamilyTest, WriteBatchFailure) {
Open(); Open();
CreateColumnFamiliesAndReopen({"one", "two"}); CreateColumnFamiliesAndReopen({"one", "two"});
WriteBatch batch; WriteBatch batch;
@ -429,7 +428,7 @@ TEST(ColumnFamilyTest, WriteBatchFailure) {
Close(); Close();
} }
TEST(ColumnFamilyTest, ReadWrite) { TEST_F(ColumnFamilyTest, ReadWrite) {
Open(); Open();
CreateColumnFamiliesAndReopen({"one", "two"}); CreateColumnFamiliesAndReopen({"one", "two"});
ASSERT_OK(Put(0, "foo", "v1")); ASSERT_OK(Put(0, "foo", "v1"));
@ -453,7 +452,7 @@ TEST(ColumnFamilyTest, ReadWrite) {
Close(); Close();
} }
TEST(ColumnFamilyTest, IgnoreRecoveredLog) { TEST_F(ColumnFamilyTest, IgnoreRecoveredLog) {
std::string backup_logs = dbname_ + "/backup_logs"; std::string backup_logs = dbname_ + "/backup_logs";
// delete old files in backup_logs directory // delete old files in backup_logs directory
@ -528,7 +527,7 @@ TEST(ColumnFamilyTest, IgnoreRecoveredLog) {
} }
} }
TEST(ColumnFamilyTest, FlushTest) { TEST_F(ColumnFamilyTest, FlushTest) {
Open(); Open();
CreateColumnFamiliesAndReopen({"one", "two"}); CreateColumnFamiliesAndReopen({"one", "two"});
ASSERT_OK(Put(0, "foo", "v1")); ASSERT_OK(Put(0, "foo", "v1"));
@ -577,7 +576,7 @@ TEST(ColumnFamilyTest, FlushTest) {
} }
// Makes sure that obsolete log files get deleted // Makes sure that obsolete log files get deleted
TEST(ColumnFamilyTest, LogDeletionTest) { TEST_F(ColumnFamilyTest, LogDeletionTest) {
db_options_.max_total_wal_size = std::numeric_limits<uint64_t>::max(); db_options_.max_total_wal_size = std::numeric_limits<uint64_t>::max();
column_family_options_.write_buffer_size = 100000; // 100KB column_family_options_.write_buffer_size = 100000; // 100KB
Open(); Open();
@ -644,7 +643,7 @@ TEST(ColumnFamilyTest, LogDeletionTest) {
} }
// Makes sure that obsolete log files get deleted // Makes sure that obsolete log files get deleted
TEST(ColumnFamilyTest, DifferentWriteBufferSizes) { TEST_F(ColumnFamilyTest, DifferentWriteBufferSizes) {
// disable flushing stale column families // disable flushing stale column families
db_options_.max_total_wal_size = std::numeric_limits<uint64_t>::max(); db_options_.max_total_wal_size = std::numeric_limits<uint64_t>::max();
Open(); Open();
@ -738,7 +737,7 @@ TEST(ColumnFamilyTest, DifferentWriteBufferSizes) {
Close(); Close();
} }
TEST(ColumnFamilyTest, MemtableNotSupportSnapshot) { TEST_F(ColumnFamilyTest, MemtableNotSupportSnapshot) {
Open(); Open();
auto* s1 = dbfull()->GetSnapshot(); auto* s1 = dbfull()->GetSnapshot();
ASSERT_TRUE(s1 != nullptr); ASSERT_TRUE(s1 != nullptr);
@ -759,7 +758,7 @@ TEST(ColumnFamilyTest, MemtableNotSupportSnapshot) {
Close(); Close();
} }
TEST(ColumnFamilyTest, DifferentMergeOperators) { TEST_F(ColumnFamilyTest, DifferentMergeOperators) {
Open(); Open();
CreateColumnFamilies({"first", "second"}); CreateColumnFamilies({"first", "second"});
ColumnFamilyOptions default_cf, first, second; ColumnFamilyOptions default_cf, first, second;
@ -789,7 +788,7 @@ TEST(ColumnFamilyTest, DifferentMergeOperators) {
Close(); Close();
} }
TEST(ColumnFamilyTest, DifferentCompactionStyles) { TEST_F(ColumnFamilyTest, DifferentCompactionStyles) {
Open(); Open();
CreateColumnFamilies({"one", "two"}); CreateColumnFamilies({"one", "two"});
ColumnFamilyOptions default_cf, one, two; ColumnFamilyOptions default_cf, one, two;
@ -864,7 +863,7 @@ std::string IterStatus(Iterator* iter) {
} }
} // anonymous namespace } // anonymous namespace
TEST(ColumnFamilyTest, NewIteratorsTest) { TEST_F(ColumnFamilyTest, NewIteratorsTest) {
// iter == 0 -- no tailing // iter == 0 -- no tailing
// iter == 2 -- tailing // iter == 2 -- tailing
for (int iter = 0; iter < 2; ++iter) { for (int iter = 0; iter < 2; ++iter) {
@ -909,7 +908,7 @@ TEST(ColumnFamilyTest, NewIteratorsTest) {
} }
} }
TEST(ColumnFamilyTest, ReadOnlyDBTest) { TEST_F(ColumnFamilyTest, ReadOnlyDBTest) {
Open(); Open();
CreateColumnFamiliesAndReopen({"one", "two", "three", "four"}); CreateColumnFamiliesAndReopen({"one", "two", "three", "four"});
ASSERT_OK(Put(0, "a", "b")); ASSERT_OK(Put(0, "a", "b"));
@ -959,7 +958,7 @@ TEST(ColumnFamilyTest, ReadOnlyDBTest) {
ASSERT_TRUE(!s.ok()); ASSERT_TRUE(!s.ok());
} }
TEST(ColumnFamilyTest, DontRollEmptyLogs) { TEST_F(ColumnFamilyTest, DontRollEmptyLogs) {
Open(); Open();
CreateColumnFamiliesAndReopen({"one", "two", "three", "four"}); CreateColumnFamiliesAndReopen({"one", "two", "three", "four"});
@ -981,7 +980,7 @@ TEST(ColumnFamilyTest, DontRollEmptyLogs) {
Close(); Close();
} }
TEST(ColumnFamilyTest, FlushStaleColumnFamilies) { TEST_F(ColumnFamilyTest, FlushStaleColumnFamilies) {
Open(); Open();
CreateColumnFamilies({"one", "two"}); CreateColumnFamilies({"one", "two"});
ColumnFamilyOptions default_cf, one, two; ColumnFamilyOptions default_cf, one, two;
@ -1010,7 +1009,7 @@ TEST(ColumnFamilyTest, FlushStaleColumnFamilies) {
Close(); Close();
} }
TEST(ColumnFamilyTest, CreateMissingColumnFamilies) { TEST_F(ColumnFamilyTest, CreateMissingColumnFamilies) {
Status s = TryOpen({"one", "two"}); Status s = TryOpen({"one", "two"});
ASSERT_TRUE(!s.ok()); ASSERT_TRUE(!s.ok());
db_options_.create_missing_column_families = true; db_options_.create_missing_column_families = true;
@ -1019,7 +1018,7 @@ TEST(ColumnFamilyTest, CreateMissingColumnFamilies) {
Close(); Close();
} }
TEST(ColumnFamilyTest, SanitizeOptions) { TEST_F(ColumnFamilyTest, SanitizeOptions) {
DBOptions db_options; DBOptions db_options;
for (int i = 1; i <= 3; i++) { for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) { for (int j = 1; j <= 3; j++) {
@ -1044,5 +1043,6 @@ TEST(ColumnFamilyTest, SanitizeOptions) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { int main(int argc, char** argv) {
return rocksdb::test::RunAllTests(); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} }

@ -13,7 +13,7 @@
namespace rocksdb { namespace rocksdb {
class CompactFilesTest { class CompactFilesTest : public testing::Test {
public: public:
CompactFilesTest() { CompactFilesTest() {
env_ = Env::Default(); env_ = Env::Default();
@ -53,7 +53,7 @@ class FlushedFileCollector : public EventListener {
std::mutex mutex_; std::mutex mutex_;
}; };
TEST(CompactFilesTest, ObsoleteFiles) { TEST_F(CompactFilesTest, ObsoleteFiles) {
Options options; Options options;
// to trigger compaction more easily // to trigger compaction more easily
const int kWriteBufferSize = 10000; const int kWriteBufferSize = 10000;
@ -100,5 +100,6 @@ TEST(CompactFilesTest, ObsoleteFiles) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { int main(int argc, char** argv) {
return rocksdb::test::RunAllTests(); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} }

@ -20,7 +20,7 @@
namespace rocksdb { namespace rocksdb {
// TODO(icanadi) Make it simpler once we mock out VersionSet // TODO(icanadi) Make it simpler once we mock out VersionSet
class CompactionJobTest { class CompactionJobTest : public testing::Test {
public: public:
CompactionJobTest() CompactionJobTest()
: env_(Env::Default()), : env_(Env::Default()),
@ -134,7 +134,7 @@ class CompactionJobTest {
std::shared_ptr<mock::MockTableFactory> mock_table_factory_; std::shared_ptr<mock::MockTableFactory> mock_table_factory_;
}; };
TEST(CompactionJobTest, Simple) { TEST_F(CompactionJobTest, Simple) {
auto cfd = versions_->GetColumnFamilySet()->GetDefault(); auto cfd = versions_->GetColumnFamilySet()->GetDefault();
auto expected_results = CreateTwoFiles(); auto expected_results = CreateTwoFiles();
@ -179,4 +179,7 @@ TEST(CompactionJobTest, Simple) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { return rocksdb::test::RunAllTests(); } int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

@ -19,7 +19,7 @@ class CountingLogger : public Logger {
size_t log_count; size_t log_count;
}; };
class CompactionPickerTest { class CompactionPickerTest : public testing::Test {
public: public:
const Comparator* ucmp_; const Comparator* ucmp_;
InternalKeyComparator icmp_; InternalKeyComparator icmp_;
@ -93,7 +93,7 @@ class CompactionPickerTest {
} }
}; };
TEST(CompactionPickerTest, Empty) { TEST_F(CompactionPickerTest, Empty) {
NewVersionStorage(6, kCompactionStyleLevel); NewVersionStorage(6, kCompactionStyleLevel);
UpdateVersionStorageInfo(); UpdateVersionStorageInfo();
std::unique_ptr<Compaction> compaction(level_compaction_picker.PickCompaction( std::unique_ptr<Compaction> compaction(level_compaction_picker.PickCompaction(
@ -101,7 +101,7 @@ TEST(CompactionPickerTest, Empty) {
ASSERT_TRUE(compaction.get() == nullptr); ASSERT_TRUE(compaction.get() == nullptr);
} }
TEST(CompactionPickerTest, Single) { TEST_F(CompactionPickerTest, Single) {
NewVersionStorage(6, kCompactionStyleLevel); NewVersionStorage(6, kCompactionStyleLevel);
mutable_cf_options_.level0_file_num_compaction_trigger = 2; mutable_cf_options_.level0_file_num_compaction_trigger = 2;
Add(0, 1U, "p", "q"); Add(0, 1U, "p", "q");
@ -112,7 +112,7 @@ TEST(CompactionPickerTest, Single) {
ASSERT_TRUE(compaction.get() == nullptr); ASSERT_TRUE(compaction.get() == nullptr);
} }
TEST(CompactionPickerTest, Level0Trigger) { TEST_F(CompactionPickerTest, Level0Trigger) {
NewVersionStorage(6, kCompactionStyleLevel); NewVersionStorage(6, kCompactionStyleLevel);
mutable_cf_options_.level0_file_num_compaction_trigger = 2; mutable_cf_options_.level0_file_num_compaction_trigger = 2;
Add(0, 1U, "150", "200"); Add(0, 1U, "150", "200");
@ -128,7 +128,7 @@ TEST(CompactionPickerTest, Level0Trigger) {
ASSERT_EQ(2U, compaction->input(0, 1)->fd.GetNumber()); ASSERT_EQ(2U, compaction->input(0, 1)->fd.GetNumber());
} }
TEST(CompactionPickerTest, Level1Trigger) { TEST_F(CompactionPickerTest, Level1Trigger) {
NewVersionStorage(6, kCompactionStyleLevel); NewVersionStorage(6, kCompactionStyleLevel);
Add(1, 66U, "150", "200", 1000000000U); Add(1, 66U, "150", "200", 1000000000U);
UpdateVersionStorageInfo(); UpdateVersionStorageInfo();
@ -140,7 +140,7 @@ TEST(CompactionPickerTest, Level1Trigger) {
ASSERT_EQ(66U, compaction->input(0, 0)->fd.GetNumber()); ASSERT_EQ(66U, compaction->input(0, 0)->fd.GetNumber());
} }
TEST(CompactionPickerTest, Level1Trigger2) { TEST_F(CompactionPickerTest, Level1Trigger2) {
NewVersionStorage(6, kCompactionStyleLevel); NewVersionStorage(6, kCompactionStyleLevel);
Add(1, 66U, "150", "200", 1000000001U); Add(1, 66U, "150", "200", 1000000001U);
Add(1, 88U, "201", "300", 1000000000U); Add(1, 88U, "201", "300", 1000000000U);
@ -159,7 +159,7 @@ TEST(CompactionPickerTest, Level1Trigger2) {
ASSERT_EQ(7U, compaction->input(1, 1)->fd.GetNumber()); ASSERT_EQ(7U, compaction->input(1, 1)->fd.GetNumber());
} }
TEST(CompactionPickerTest, LevelMaxScore) { TEST_F(CompactionPickerTest, LevelMaxScore) {
NewVersionStorage(6, kCompactionStyleLevel); NewVersionStorage(6, kCompactionStyleLevel);
mutable_cf_options_.target_file_size_base = 10000000; mutable_cf_options_.target_file_size_base = 10000000;
mutable_cf_options_.target_file_size_multiplier = 10; mutable_cf_options_.target_file_size_multiplier = 10;
@ -185,7 +185,7 @@ TEST(CompactionPickerTest, LevelMaxScore) {
ASSERT_EQ(7U, compaction->input(0, 0)->fd.GetNumber()); ASSERT_EQ(7U, compaction->input(0, 0)->fd.GetNumber());
} }
TEST(CompactionPickerTest, NeedsCompactionLevel) { TEST_F(CompactionPickerTest, NeedsCompactionLevel) {
const int kLevels = 6; const int kLevels = 6;
const int kFileCount = 20; const int kFileCount = 20;
@ -210,7 +210,7 @@ TEST(CompactionPickerTest, NeedsCompactionLevel) {
} }
} }
TEST(CompactionPickerTest, Level0TriggerDynamic) { TEST_F(CompactionPickerTest, Level0TriggerDynamic) {
int num_levels = ioptions_.num_levels; int num_levels = ioptions_.num_levels;
ioptions_.level_compaction_dynamic_level_bytes = true; ioptions_.level_compaction_dynamic_level_bytes = true;
mutable_cf_options_.level0_file_num_compaction_trigger = 2; mutable_cf_options_.level0_file_num_compaction_trigger = 2;
@ -232,7 +232,7 @@ TEST(CompactionPickerTest, Level0TriggerDynamic) {
ASSERT_EQ(num_levels - 1, compaction->output_level()); ASSERT_EQ(num_levels - 1, compaction->output_level());
} }
TEST(CompactionPickerTest, Level0TriggerDynamic2) { TEST_F(CompactionPickerTest, Level0TriggerDynamic2) {
int num_levels = ioptions_.num_levels; int num_levels = ioptions_.num_levels;
ioptions_.level_compaction_dynamic_level_bytes = true; ioptions_.level_compaction_dynamic_level_bytes = true;
mutable_cf_options_.level0_file_num_compaction_trigger = 2; mutable_cf_options_.level0_file_num_compaction_trigger = 2;
@ -256,7 +256,7 @@ TEST(CompactionPickerTest, Level0TriggerDynamic2) {
ASSERT_EQ(num_levels - 2, compaction->output_level()); ASSERT_EQ(num_levels - 2, compaction->output_level());
} }
TEST(CompactionPickerTest, Level0TriggerDynamic3) { TEST_F(CompactionPickerTest, Level0TriggerDynamic3) {
int num_levels = ioptions_.num_levels; int num_levels = ioptions_.num_levels;
ioptions_.level_compaction_dynamic_level_bytes = true; ioptions_.level_compaction_dynamic_level_bytes = true;
mutable_cf_options_.level0_file_num_compaction_trigger = 2; mutable_cf_options_.level0_file_num_compaction_trigger = 2;
@ -281,7 +281,7 @@ TEST(CompactionPickerTest, Level0TriggerDynamic3) {
ASSERT_EQ(num_levels - 3, compaction->output_level()); ASSERT_EQ(num_levels - 3, compaction->output_level());
} }
TEST(CompactionPickerTest, Level0TriggerDynamic4) { TEST_F(CompactionPickerTest, Level0TriggerDynamic4) {
int num_levels = ioptions_.num_levels; int num_levels = ioptions_.num_levels;
ioptions_.level_compaction_dynamic_level_bytes = true; ioptions_.level_compaction_dynamic_level_bytes = true;
mutable_cf_options_.level0_file_num_compaction_trigger = 2; mutable_cf_options_.level0_file_num_compaction_trigger = 2;
@ -312,7 +312,7 @@ TEST(CompactionPickerTest, Level0TriggerDynamic4) {
ASSERT_EQ(num_levels - 3, compaction->output_level()); ASSERT_EQ(num_levels - 3, compaction->output_level());
} }
TEST(CompactionPickerTest, LevelTriggerDynamic4) { TEST_F(CompactionPickerTest, LevelTriggerDynamic4) {
int num_levels = ioptions_.num_levels; int num_levels = ioptions_.num_levels;
ioptions_.level_compaction_dynamic_level_bytes = true; ioptions_.level_compaction_dynamic_level_bytes = true;
mutable_cf_options_.level0_file_num_compaction_trigger = 2; mutable_cf_options_.level0_file_num_compaction_trigger = 2;
@ -341,7 +341,7 @@ TEST(CompactionPickerTest, LevelTriggerDynamic4) {
ASSERT_EQ(num_levels - 1, compaction->output_level()); ASSERT_EQ(num_levels - 1, compaction->output_level());
} }
TEST(CompactionPickerTest, NeedsCompactionUniversal) { TEST_F(CompactionPickerTest, NeedsCompactionUniversal) {
NewVersionStorage(1, kCompactionStyleUniversal); NewVersionStorage(1, kCompactionStyleUniversal);
UniversalCompactionPicker universal_compaction_picker( UniversalCompactionPicker universal_compaction_picker(
ioptions_, &icmp_); ioptions_, &icmp_);
@ -360,7 +360,7 @@ TEST(CompactionPickerTest, NeedsCompactionUniversal) {
} }
} }
TEST(CompactionPickerTest, NeedsCompactionFIFO) { TEST_F(CompactionPickerTest, NeedsCompactionFIFO) {
NewVersionStorage(1, kCompactionStyleFIFO); NewVersionStorage(1, kCompactionStyleFIFO);
const int kFileCount = const int kFileCount =
mutable_cf_options_.level0_file_num_compaction_trigger * 3; mutable_cf_options_.level0_file_num_compaction_trigger * 3;
@ -390,4 +390,7 @@ TEST(CompactionPickerTest, NeedsCompactionFIFO) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { return rocksdb::test::RunAllTests(); } int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

@ -248,7 +248,7 @@ class TwoStrComparator : public Comparator {
}; };
} // namespace } // namespace
class ComparatorDBTest { class ComparatorDBTest : public testing::Test {
private: private:
std::string dbname_; std::string dbname_;
Env* env_; Env* env_;
@ -301,7 +301,7 @@ class ComparatorDBTest {
} }
}; };
TEST(ComparatorDBTest, Bytewise) { TEST_F(ComparatorDBTest, Bytewise) {
for (int rand_seed = 301; rand_seed < 306; rand_seed++) { for (int rand_seed = 301; rand_seed < 306; rand_seed++) {
DestroyAndReopen(); DestroyAndReopen();
Random rnd(rand_seed); Random rnd(rand_seed);
@ -311,7 +311,7 @@ TEST(ComparatorDBTest, Bytewise) {
} }
} }
TEST(ComparatorDBTest, SimpleSuffixReverseComparator) { TEST_F(ComparatorDBTest, SimpleSuffixReverseComparator) {
SetOwnedComparator(new test::SimpleSuffixReverseComparator()); SetOwnedComparator(new test::SimpleSuffixReverseComparator());
for (int rnd_seed = 301; rnd_seed < 316; rnd_seed++) { for (int rnd_seed = 301; rnd_seed < 316; rnd_seed++) {
@ -337,7 +337,7 @@ TEST(ComparatorDBTest, SimpleSuffixReverseComparator) {
} }
} }
TEST(ComparatorDBTest, Uint64Comparator) { TEST_F(ComparatorDBTest, Uint64Comparator) {
SetOwnedComparator(test::Uint64Comparator()); SetOwnedComparator(test::Uint64Comparator());
for (int rnd_seed = 301; rnd_seed < 316; rnd_seed++) { for (int rnd_seed = 301; rnd_seed < 316; rnd_seed++) {
@ -361,7 +361,7 @@ TEST(ComparatorDBTest, Uint64Comparator) {
} }
} }
TEST(ComparatorDBTest, DoubleComparator) { TEST_F(ComparatorDBTest, DoubleComparator) {
SetOwnedComparator(new DoubleComparator()); SetOwnedComparator(new DoubleComparator());
for (int rnd_seed = 301; rnd_seed < 316; rnd_seed++) { for (int rnd_seed = 301; rnd_seed < 316; rnd_seed++) {
@ -386,7 +386,7 @@ TEST(ComparatorDBTest, DoubleComparator) {
} }
} }
TEST(ComparatorDBTest, HashComparator) { TEST_F(ComparatorDBTest, HashComparator) {
SetOwnedComparator(new HashComparator()); SetOwnedComparator(new HashComparator());
for (int rnd_seed = 301; rnd_seed < 316; rnd_seed++) { for (int rnd_seed = 301; rnd_seed < 316; rnd_seed++) {
@ -405,7 +405,7 @@ TEST(ComparatorDBTest, HashComparator) {
} }
} }
TEST(ComparatorDBTest, TwoStrComparator) { TEST_F(ComparatorDBTest, TwoStrComparator) {
SetOwnedComparator(new TwoStrComparator()); SetOwnedComparator(new TwoStrComparator());
for (int rnd_seed = 301; rnd_seed < 316; rnd_seed++) { for (int rnd_seed = 301; rnd_seed < 316; rnd_seed++) {
@ -433,4 +433,7 @@ TEST(ComparatorDBTest, TwoStrComparator) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { return rocksdb::test::RunAllTests(); } int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

@ -29,7 +29,7 @@ namespace rocksdb {
static const int kValueSize = 1000; static const int kValueSize = 1000;
class CorruptionTest { class CorruptionTest : public testing::Test {
public: public:
test::ErrorEnv env_; test::ErrorEnv env_;
std::string dbname_; std::string dbname_;
@ -226,7 +226,7 @@ class CorruptionTest {
} }
}; };
TEST(CorruptionTest, Recovery) { TEST_F(CorruptionTest, Recovery) {
Build(100); Build(100);
Check(100, 100); Check(100, 100);
Corrupt(kLogFile, 19, 1); // WriteBatch tag for first record Corrupt(kLogFile, 19, 1); // WriteBatch tag for first record
@ -239,13 +239,13 @@ TEST(CorruptionTest, Recovery) {
Check(36, 36); Check(36, 36);
} }
TEST(CorruptionTest, RecoverWriteError) { TEST_F(CorruptionTest, RecoverWriteError) {
env_.writable_file_error_ = true; env_.writable_file_error_ = true;
Status s = TryReopen(); Status s = TryReopen();
ASSERT_TRUE(!s.ok()); ASSERT_TRUE(!s.ok());
} }
TEST(CorruptionTest, NewFileErrorDuringWrite) { TEST_F(CorruptionTest, NewFileErrorDuringWrite) {
// Do enough writing to force minor compaction // Do enough writing to force minor compaction
env_.writable_file_error_ = true; env_.writable_file_error_ = true;
const int num = const int num =
@ -268,7 +268,7 @@ TEST(CorruptionTest, NewFileErrorDuringWrite) {
Reopen(); Reopen();
} }
TEST(CorruptionTest, TableFile) { TEST_F(CorruptionTest, TableFile) {
Build(100); Build(100);
DBImpl* dbi = reinterpret_cast<DBImpl*>(db_); DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
dbi->TEST_FlushMemTable(); dbi->TEST_FlushMemTable();
@ -279,7 +279,7 @@ TEST(CorruptionTest, TableFile) {
Check(99, 99); Check(99, 99);
} }
TEST(CorruptionTest, TableFileIndexData) { TEST_F(CorruptionTest, TableFileIndexData) {
Build(10000); // Enough to build multiple Tables Build(10000); // Enough to build multiple Tables
DBImpl* dbi = reinterpret_cast<DBImpl*>(db_); DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
dbi->TEST_FlushMemTable(); dbi->TEST_FlushMemTable();
@ -289,14 +289,14 @@ TEST(CorruptionTest, TableFileIndexData) {
Check(5000, 9999); Check(5000, 9999);
} }
TEST(CorruptionTest, MissingDescriptor) { TEST_F(CorruptionTest, MissingDescriptor) {
Build(1000); Build(1000);
RepairDB(); RepairDB();
Reopen(); Reopen();
Check(1000, 1000); Check(1000, 1000);
} }
TEST(CorruptionTest, SequenceNumberRecovery) { TEST_F(CorruptionTest, SequenceNumberRecovery) {
ASSERT_OK(db_->Put(WriteOptions(), "foo", "v1")); ASSERT_OK(db_->Put(WriteOptions(), "foo", "v1"));
ASSERT_OK(db_->Put(WriteOptions(), "foo", "v2")); ASSERT_OK(db_->Put(WriteOptions(), "foo", "v2"));
ASSERT_OK(db_->Put(WriteOptions(), "foo", "v3")); ASSERT_OK(db_->Put(WriteOptions(), "foo", "v3"));
@ -317,7 +317,7 @@ TEST(CorruptionTest, SequenceNumberRecovery) {
ASSERT_EQ("v6", v); ASSERT_EQ("v6", v);
} }
TEST(CorruptionTest, CorruptedDescriptor) { TEST_F(CorruptionTest, CorruptedDescriptor) {
ASSERT_OK(db_->Put(WriteOptions(), "foo", "hello")); ASSERT_OK(db_->Put(WriteOptions(), "foo", "hello"));
DBImpl* dbi = reinterpret_cast<DBImpl*>(db_); DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
dbi->TEST_FlushMemTable(); dbi->TEST_FlushMemTable();
@ -334,7 +334,7 @@ TEST(CorruptionTest, CorruptedDescriptor) {
ASSERT_EQ("hello", v); ASSERT_EQ("hello", v);
} }
TEST(CorruptionTest, CompactionInputError) { TEST_F(CorruptionTest, CompactionInputError) {
Options options; Options options;
options.max_background_flushes = 0; options.max_background_flushes = 0;
Reopen(&options); Reopen(&options);
@ -352,7 +352,7 @@ TEST(CorruptionTest, CompactionInputError) {
Check(10000, 10000); Check(10000, 10000);
} }
TEST(CorruptionTest, CompactionInputErrorParanoid) { TEST_F(CorruptionTest, CompactionInputErrorParanoid) {
Options options; Options options;
options.paranoid_checks = true; options.paranoid_checks = true;
options.write_buffer_size = 131072; options.write_buffer_size = 131072;
@ -395,7 +395,7 @@ TEST(CorruptionTest, CompactionInputErrorParanoid) {
ASSERT_TRUE(!s.ok()) << "write did not fail in corrupted paranoid db"; ASSERT_TRUE(!s.ok()) << "write did not fail in corrupted paranoid db";
} }
TEST(CorruptionTest, UnrelatedKeys) { TEST_F(CorruptionTest, UnrelatedKeys) {
Build(10); Build(10);
DBImpl* dbi = reinterpret_cast<DBImpl*>(db_); DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
dbi->TEST_FlushMemTable(); dbi->TEST_FlushMemTable();
@ -411,7 +411,7 @@ TEST(CorruptionTest, UnrelatedKeys) {
ASSERT_EQ(Value(1000, &tmp2).ToString(), v); ASSERT_EQ(Value(1000, &tmp2).ToString(), v);
} }
TEST(CorruptionTest, FileSystemStateCorrupted) { TEST_F(CorruptionTest, FileSystemStateCorrupted) {
for (int iter = 0; iter < 2; ++iter) { for (int iter = 0; iter < 2; ++iter) {
Options options; Options options;
options.paranoid_checks = true; options.paranoid_checks = true;
@ -447,5 +447,6 @@ TEST(CorruptionTest, FileSystemStateCorrupted) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { int main(int argc, char** argv) {
return rocksdb::test::RunAllTests(); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} }

@ -14,7 +14,7 @@
namespace rocksdb { namespace rocksdb {
class CuckooTableDBTest { class CuckooTableDBTest : public testing::Test {
private: private:
std::string dbname_; std::string dbname_;
Env* env_; Env* env_;
@ -106,7 +106,7 @@ class CuckooTableDBTest {
} }
}; };
TEST(CuckooTableDBTest, Flush) { TEST_F(CuckooTableDBTest, Flush) {
// Try with empty DB first. // Try with empty DB first.
ASSERT_TRUE(dbfull() != nullptr); ASSERT_TRUE(dbfull() != nullptr);
ASSERT_EQ("NOT_FOUND", Get("key2")); ASSERT_EQ("NOT_FOUND", Get("key2"));
@ -169,7 +169,7 @@ TEST(CuckooTableDBTest, Flush) {
ASSERT_EQ("NOT_FOUND", Get("key6")); ASSERT_EQ("NOT_FOUND", Get("key6"));
} }
TEST(CuckooTableDBTest, FlushWithDuplicateKeys) { TEST_F(CuckooTableDBTest, FlushWithDuplicateKeys) {
Options options = CurrentOptions(); Options options = CurrentOptions();
Reopen(&options); Reopen(&options);
ASSERT_OK(Put("key1", "v1")); ASSERT_OK(Put("key1", "v1"));
@ -200,7 +200,7 @@ static std::string Uint64Key(uint64_t i) {
} }
} // namespace. } // namespace.
TEST(CuckooTableDBTest, Uint64Comparator) { TEST_F(CuckooTableDBTest, Uint64Comparator) {
Options options = CurrentOptions(); Options options = CurrentOptions();
options.comparator = test::Uint64Comparator(); options.comparator = test::Uint64Comparator();
Reopen(&options); Reopen(&options);
@ -227,7 +227,7 @@ TEST(CuckooTableDBTest, Uint64Comparator) {
ASSERT_EQ("v4", Get(Uint64Key(4))); ASSERT_EQ("v4", Get(Uint64Key(4)));
} }
TEST(CuckooTableDBTest, CompactionIntoMultipleFiles) { TEST_F(CuckooTableDBTest, CompactionIntoMultipleFiles) {
// Create a big L0 file and check it compacts into multiple files in L1. // Create a big L0 file and check it compacts into multiple files in L1.
Options options = CurrentOptions(); Options options = CurrentOptions();
options.write_buffer_size = 270 << 10; options.write_buffer_size = 270 << 10;
@ -250,7 +250,7 @@ TEST(CuckooTableDBTest, CompactionIntoMultipleFiles) {
} }
} }
TEST(CuckooTableDBTest, SameKeyInsertedInTwoDifferentFilesAndCompacted) { TEST_F(CuckooTableDBTest, SameKeyInsertedInTwoDifferentFilesAndCompacted) {
// Insert same key twice so that they go to different SST files. Then wait for // Insert same key twice so that they go to different SST files. Then wait for
// compaction and check if the latest value is stored and old value removed. // compaction and check if the latest value is stored and old value removed.
Options options = CurrentOptions(); Options options = CurrentOptions();
@ -278,7 +278,7 @@ TEST(CuckooTableDBTest, SameKeyInsertedInTwoDifferentFilesAndCompacted) {
} }
} }
TEST(CuckooTableDBTest, AdaptiveTable) { TEST_F(CuckooTableDBTest, AdaptiveTable) {
Options options = CurrentOptions(); Options options = CurrentOptions();
// Write some keys using cuckoo table. // Write some keys using cuckoo table.
@ -315,4 +315,7 @@ TEST(CuckooTableDBTest, AdaptiveTable) {
} }
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { return rocksdb::test::RunAllTests(); } int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

@ -139,14 +139,14 @@ class TestIterator : public Iterator {
std::vector<std::pair<std::string, std::string>> data_; std::vector<std::pair<std::string, std::string>> data_;
}; };
class DBIteratorTest { class DBIteratorTest : public testing::Test {
public: public:
Env* env_; Env* env_;
DBIteratorTest() : env_(Env::Default()) {} DBIteratorTest() : env_(Env::Default()) {}
}; };
TEST(DBIteratorTest, DBIteratorPrevNext) { TEST_F(DBIteratorTest, DBIteratorPrevNext) {
Options options; Options options;
{ {
@ -289,7 +289,7 @@ TEST(DBIteratorTest, DBIteratorPrevNext) {
} }
} }
TEST(DBIteratorTest, DBIteratorEmpty) { TEST_F(DBIteratorTest, DBIteratorEmpty) {
Options options; Options options;
{ {
@ -317,7 +317,7 @@ TEST(DBIteratorTest, DBIteratorEmpty) {
} }
} }
TEST(DBIteratorTest, DBIteratorUseSkipCountSkips) { TEST_F(DBIteratorTest, DBIteratorUseSkipCountSkips) {
Options options; Options options;
options.statistics = rocksdb::CreateDBStatistics(); options.statistics = rocksdb::CreateDBStatistics();
options.merge_operator = MergeOperators::CreateFromStringId("stringappend"); options.merge_operator = MergeOperators::CreateFromStringId("stringappend");
@ -357,7 +357,7 @@ TEST(DBIteratorTest, DBIteratorUseSkipCountSkips) {
ASSERT_EQ(TestGetTickerCount(options, NUMBER_OF_RESEEKS_IN_ITERATION), 3u); ASSERT_EQ(TestGetTickerCount(options, NUMBER_OF_RESEEKS_IN_ITERATION), 3u);
} }
TEST(DBIteratorTest, DBIteratorUseSkip) { TEST_F(DBIteratorTest, DBIteratorUseSkip) {
Options options; Options options;
options.merge_operator = MergeOperators::CreateFromStringId("stringappend"); options.merge_operator = MergeOperators::CreateFromStringId("stringappend");
{ {
@ -586,7 +586,7 @@ TEST(DBIteratorTest, DBIteratorUseSkip) {
} }
} }
TEST(DBIteratorTest, DBIterator1) { TEST_F(DBIteratorTest, DBIterator1) {
Options options; Options options;
options.merge_operator = MergeOperators::CreateFromStringId("stringappend"); options.merge_operator = MergeOperators::CreateFromStringId("stringappend");
@ -610,7 +610,7 @@ TEST(DBIteratorTest, DBIterator1) {
ASSERT_EQ(db_iter->key().ToString(), "b"); ASSERT_EQ(db_iter->key().ToString(), "b");
} }
TEST(DBIteratorTest, DBIterator2) { TEST_F(DBIteratorTest, DBIterator2) {
Options options; Options options;
options.merge_operator = MergeOperators::CreateFromStringId("stringappend"); options.merge_operator = MergeOperators::CreateFromStringId("stringappend");
@ -633,7 +633,7 @@ TEST(DBIteratorTest, DBIterator2) {
ASSERT_TRUE(!db_iter->Valid()); ASSERT_TRUE(!db_iter->Valid());
} }
TEST(DBIteratorTest, DBIterator3) { TEST_F(DBIteratorTest, DBIterator3) {
Options options; Options options;
options.merge_operator = MergeOperators::CreateFromStringId("stringappend"); options.merge_operator = MergeOperators::CreateFromStringId("stringappend");
@ -655,7 +655,7 @@ TEST(DBIteratorTest, DBIterator3) {
db_iter->Next(); db_iter->Next();
ASSERT_TRUE(!db_iter->Valid()); ASSERT_TRUE(!db_iter->Valid());
} }
TEST(DBIteratorTest, DBIterator4) { TEST_F(DBIteratorTest, DBIterator4) {
Options options; Options options;
options.merge_operator = MergeOperators::CreateFromStringId("stringappend"); options.merge_operator = MergeOperators::CreateFromStringId("stringappend");
@ -682,7 +682,7 @@ TEST(DBIteratorTest, DBIterator4) {
ASSERT_TRUE(!db_iter->Valid()); ASSERT_TRUE(!db_iter->Valid());
} }
TEST(DBIteratorTest, DBIterator5) { TEST_F(DBIteratorTest, DBIterator5) {
Options options; Options options;
options.merge_operator = MergeOperators::CreateFromStringId("stringappend"); options.merge_operator = MergeOperators::CreateFromStringId("stringappend");
{ {
@ -840,7 +840,7 @@ TEST(DBIteratorTest, DBIterator5) {
} }
} }
TEST(DBIteratorTest, DBIterator6) { TEST_F(DBIteratorTest, DBIterator6) {
Options options; Options options;
options.merge_operator = MergeOperators::CreateFromStringId("stringappend"); options.merge_operator = MergeOperators::CreateFromStringId("stringappend");
{ {
@ -994,7 +994,7 @@ TEST(DBIteratorTest, DBIterator6) {
} }
} }
TEST(DBIteratorTest, DBIterator7) { TEST_F(DBIteratorTest, DBIterator7) {
Options options; Options options;
options.merge_operator = MergeOperators::CreateFromStringId("stringappend"); options.merge_operator = MergeOperators::CreateFromStringId("stringappend");
{ {
@ -1376,7 +1376,7 @@ TEST(DBIteratorTest, DBIterator7) {
ASSERT_TRUE(!db_iter->Valid()); ASSERT_TRUE(!db_iter->Valid());
} }
} }
TEST(DBIteratorTest, DBIterator8) { TEST_F(DBIteratorTest, DBIterator8) {
Options options; Options options;
options.merge_operator = MergeOperators::CreateFromStringId("stringappend"); options.merge_operator = MergeOperators::CreateFromStringId("stringappend");
@ -1402,4 +1402,7 @@ TEST(DBIteratorTest, DBIterator8) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { return rocksdb::test::RunAllTests(); } int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

File diff suppressed because it is too large Load Diff

@ -49,9 +49,9 @@ static void TestKey(const std::string& key,
ASSERT_TRUE(!ParseInternalKey(Slice("bar"), &decoded)); ASSERT_TRUE(!ParseInternalKey(Slice("bar"), &decoded));
} }
class FormatTest { }; class FormatTest : public testing::Test {};
TEST(FormatTest, InternalKey_EncodeDecode) { TEST_F(FormatTest, InternalKey_EncodeDecode) {
const char* keys[] = { "", "k", "hello", "longggggggggggggggggggggg" }; const char* keys[] = { "", "k", "hello", "longggggggggggggggggggggg" };
const uint64_t seq[] = { const uint64_t seq[] = {
1, 2, 3, 1, 2, 3,
@ -67,7 +67,7 @@ TEST(FormatTest, InternalKey_EncodeDecode) {
} }
} }
TEST(FormatTest, InternalKeyShortSeparator) { TEST_F(FormatTest, InternalKeyShortSeparator) {
// When user keys are same // When user keys are same
ASSERT_EQ(IKey("foo", 100, kTypeValue), ASSERT_EQ(IKey("foo", 100, kTypeValue),
Shorten(IKey("foo", 100, kTypeValue), Shorten(IKey("foo", 100, kTypeValue),
@ -103,14 +103,14 @@ TEST(FormatTest, InternalKeyShortSeparator) {
IKey("foo", 200, kTypeValue))); IKey("foo", 200, kTypeValue)));
} }
TEST(FormatTest, InternalKeyShortestSuccessor) { TEST_F(FormatTest, InternalKeyShortestSuccessor) {
ASSERT_EQ(IKey("g", kMaxSequenceNumber, kValueTypeForSeek), ASSERT_EQ(IKey("g", kMaxSequenceNumber, kValueTypeForSeek),
ShortSuccessor(IKey("foo", 100, kTypeValue))); ShortSuccessor(IKey("foo", 100, kTypeValue)));
ASSERT_EQ(IKey("\xff\xff", 100, kTypeValue), ASSERT_EQ(IKey("\xff\xff", 100, kTypeValue),
ShortSuccessor(IKey("\xff\xff", 100, kTypeValue))); ShortSuccessor(IKey("\xff\xff", 100, kTypeValue)));
} }
TEST(FormatTest, IterKeyOperation) { TEST_F(FormatTest, IterKeyOperation) {
IterKey k; IterKey k;
const char p[] = "abcdefghijklmnopqrstuvwxyz"; const char p[] = "abcdefghijklmnopqrstuvwxyz";
const char q[] = "0123456789"; const char q[] = "0123456789";
@ -152,5 +152,6 @@ TEST(FormatTest, IterKeyOperation) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { int main(int argc, char** argv) {
return rocksdb::test::RunAllTests(); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} }

@ -23,7 +23,7 @@
namespace rocksdb { namespace rocksdb {
class DeleteFileTest { class DeleteFileTest : public testing::Test {
public: public:
std::string dbname_; std::string dbname_;
Options options_; Options options_;
@ -146,7 +146,7 @@ class DeleteFileTest {
}; };
TEST(DeleteFileTest, AddKeysAndQueryLevels) { TEST_F(DeleteFileTest, AddKeysAndQueryLevels) {
CreateTwoLevels(); CreateTwoLevels();
std::vector<LiveFileMetaData> metadata; std::vector<LiveFileMetaData> metadata;
db_->GetLiveFilesMetaData(&metadata); db_->GetLiveFilesMetaData(&metadata);
@ -192,7 +192,7 @@ TEST(DeleteFileTest, AddKeysAndQueryLevels) {
CloseDB(); CloseDB();
} }
TEST(DeleteFileTest, PurgeObsoleteFilesTest) { TEST_F(DeleteFileTest, PurgeObsoleteFilesTest) {
CreateTwoLevels(); CreateTwoLevels();
// there should be only one (empty) log file because CreateTwoLevels() // there should be only one (empty) log file because CreateTwoLevels()
// flushes the memtables to disk // flushes the memtables to disk
@ -220,7 +220,7 @@ TEST(DeleteFileTest, PurgeObsoleteFilesTest) {
CloseDB(); CloseDB();
} }
TEST(DeleteFileTest, DeleteFileWithIterator) { TEST_F(DeleteFileTest, DeleteFileWithIterator) {
CreateTwoLevels(); CreateTwoLevels();
ReadOptions options; ReadOptions options;
Iterator* it = db_->NewIterator(options); Iterator* it = db_->NewIterator(options);
@ -251,7 +251,7 @@ TEST(DeleteFileTest, DeleteFileWithIterator) {
CloseDB(); CloseDB();
} }
TEST(DeleteFileTest, DeleteLogFiles) { TEST_F(DeleteFileTest, DeleteLogFiles) {
AddKeys(10, 0); AddKeys(10, 0);
VectorLogPtr logfiles; VectorLogPtr logfiles;
db_->GetSortedWalFiles(logfiles); db_->GetSortedWalFiles(logfiles);
@ -288,7 +288,7 @@ TEST(DeleteFileTest, DeleteLogFiles) {
CloseDB(); CloseDB();
} }
TEST(DeleteFileTest, DeleteNonDefaultColumnFamily) { TEST_F(DeleteFileTest, DeleteNonDefaultColumnFamily) {
CloseDB(); CloseDB();
DBOptions db_options; DBOptions db_options;
db_options.create_if_missing = true; db_options.create_if_missing = true;
@ -360,6 +360,7 @@ TEST(DeleteFileTest, DeleteNonDefaultColumnFamily) {
} //namespace rocksdb } //namespace rocksdb
int main(int argc, char** argv) { int main(int argc, char** argv) {
return rocksdb::test::RunAllTests(); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} }

@ -406,7 +406,7 @@ Status TestWritableFile::Sync() {
return Status::OK(); return Status::OK();
} }
class FaultInjectionTest { class FaultInjectionTest : public testing::Test {
protected: protected:
enum OptionConfig { enum OptionConfig {
kDefault, kDefault,
@ -447,11 +447,8 @@ class FaultInjectionTest {
base_env_(nullptr), base_env_(nullptr),
env_(NULL), env_(NULL),
db_(NULL) { db_(NULL) {
NewDB();
} }
~FaultInjectionTest() { EXPECT_OK(TearDown()); }
bool ChangeOptions() { bool ChangeOptions() {
option_config_++; option_config_++;
if (option_config_ >= kEnd) { if (option_config_ >= kEnd) {
@ -532,15 +529,9 @@ class FaultInjectionTest {
return s; return s;
} }
Status SetUp() { void SetUp() override { ASSERT_OK(NewDB()); }
Status s = TearDown();
if (s.ok()) {
s = NewDB();
}
return s;
}
Status TearDown() { void TearDown() override {
CloseDB(); CloseDB();
Status s = DestroyDB(dbname_, options_); Status s = DestroyDB(dbname_, options_);
@ -550,7 +541,7 @@ class FaultInjectionTest {
tiny_cache_.reset(); tiny_cache_.reset();
return s; ASSERT_OK(s);
} }
void Build(const WriteOptions& write_options, int start_idx, int num_vals) { void Build(const WriteOptions& write_options, int start_idx, int num_vals) {
@ -696,10 +687,9 @@ class FaultInjectionTest {
} }
}; };
TEST(FaultInjectionTest, FaultTest) { TEST_F(FaultInjectionTest, FaultTest) {
do { do {
Random rnd(301); Random rnd(301);
ASSERT_OK(SetUp());
for (size_t idx = 0; idx < kNumIterations; idx++) { for (size_t idx = 0; idx < kNumIterations; idx++) {
int num_pre_sync = rnd.Uniform(kMaxNumValues); int num_pre_sync = rnd.Uniform(kMaxNumValues);
@ -739,5 +729,6 @@ TEST(FaultInjectionTest, FaultTest) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { int main(int argc, char** argv) {
return rocksdb::test::RunAllTests(); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} }

@ -41,7 +41,7 @@ class IntComparator : public Comparator {
void FindShortSuccessor(std::string* key) const override {} void FindShortSuccessor(std::string* key) const override {}
}; };
class FileIndexerTest { class FileIndexerTest : public testing::Test {
public: public:
FileIndexerTest() FileIndexerTest()
: kNumLevels(4), files(new std::vector<FileMetaData*>[kNumLevels]) {} : kNumLevels(4), files(new std::vector<FileMetaData*>[kNumLevels]) {}
@ -90,7 +90,7 @@ class FileIndexerTest {
}; };
// Case 0: Empty // Case 0: Empty
TEST(FileIndexerTest, Empty) { TEST_F(FileIndexerTest, Empty) {
Arena arena; Arena arena;
indexer = new FileIndexer(&ucmp); indexer = new FileIndexer(&ucmp);
indexer->UpdateIndex(&arena, 0, files); indexer->UpdateIndex(&arena, 0, files);
@ -98,7 +98,7 @@ TEST(FileIndexerTest, Empty) {
} }
// Case 1: no overlap, files are on the left of next level files // Case 1: no overlap, files are on the left of next level files
TEST(FileIndexerTest, no_overlap_left) { TEST_F(FileIndexerTest, no_overlap_left) {
Arena arena; Arena arena;
indexer = new FileIndexer(&ucmp); indexer = new FileIndexer(&ucmp);
// level 1 // level 1
@ -138,7 +138,7 @@ TEST(FileIndexerTest, no_overlap_left) {
} }
// Case 2: no overlap, files are on the right of next level files // Case 2: no overlap, files are on the right of next level files
TEST(FileIndexerTest, no_overlap_right) { TEST_F(FileIndexerTest, no_overlap_right) {
Arena arena; Arena arena;
indexer = new FileIndexer(&ucmp); indexer = new FileIndexer(&ucmp);
// level 1 // level 1
@ -180,7 +180,7 @@ TEST(FileIndexerTest, no_overlap_right) {
} }
// Case 3: empty L2 // Case 3: empty L2
TEST(FileIndexerTest, empty_L2) { TEST_F(FileIndexerTest, empty_L2) {
Arena arena; Arena arena;
indexer = new FileIndexer(&ucmp); indexer = new FileIndexer(&ucmp);
for (uint32_t i = 1; i < kNumLevels; ++i) { for (uint32_t i = 1; i < kNumLevels; ++i) {
@ -220,7 +220,7 @@ TEST(FileIndexerTest, empty_L2) {
} }
// Case 4: mixed // Case 4: mixed
TEST(FileIndexerTest, mixed) { TEST_F(FileIndexerTest, mixed) {
Arena arena; Arena arena;
indexer = new FileIndexer(&ucmp); indexer = new FileIndexer(&ucmp);
// level 1 // level 1
@ -343,5 +343,6 @@ TEST(FileIndexerTest, mixed) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { int main(int argc, char** argv) {
return rocksdb::test::RunAllTests(); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} }

@ -16,9 +16,9 @@
namespace rocksdb { namespace rocksdb {
class FileNameTest { }; class FileNameTest : public testing::Test {};
TEST(FileNameTest, Parse) { TEST_F(FileNameTest, Parse) {
Slice db; Slice db;
FileType type; FileType type;
uint64_t number; uint64_t number;
@ -105,7 +105,7 @@ TEST(FileNameTest, Parse) {
}; };
} }
TEST(FileNameTest, InfoLogFileName) { TEST_F(FileNameTest, InfoLogFileName) {
std::string dbname = ("/data/rocksdb"); std::string dbname = ("/data/rocksdb");
std::string db_absolute_path; std::string db_absolute_path;
Env::Default()->GetAbsolutePath(dbname, &db_absolute_path); Env::Default()->GetAbsolutePath(dbname, &db_absolute_path);
@ -121,7 +121,7 @@ TEST(FileNameTest, InfoLogFileName) {
OldInfoLogFileName(dbname, 666u, db_absolute_path, "/data/rocksdb_log")); OldInfoLogFileName(dbname, 666u, db_absolute_path, "/data/rocksdb_log"));
} }
TEST(FileNameTest, Construction) { TEST_F(FileNameTest, Construction) {
uint64_t number; uint64_t number;
FileType type; FileType type;
std::string fname; std::string fname;
@ -175,5 +175,6 @@ TEST(FileNameTest, Construction) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { int main(int argc, char** argv) {
return rocksdb::test::RunAllTests(); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} }

@ -20,7 +20,7 @@ namespace rocksdb {
// TODO(icanadi) Mock out everything else: // TODO(icanadi) Mock out everything else:
// 1. VersionSet // 1. VersionSet
// 2. Memtable // 2. Memtable
class FlushJobTest { class FlushJobTest : public testing::Test {
public: public:
FlushJobTest() FlushJobTest()
: env_(Env::Default()), : env_(Env::Default()),
@ -80,7 +80,7 @@ class FlushJobTest {
std::shared_ptr<mock::MockTableFactory> mock_table_factory_; std::shared_ptr<mock::MockTableFactory> mock_table_factory_;
}; };
TEST(FlushJobTest, Empty) { TEST_F(FlushJobTest, Empty) {
JobContext job_context(0); JobContext job_context(0);
auto cfd = versions_->GetColumnFamilySet()->GetDefault(); auto cfd = versions_->GetColumnFamilySet()->GetDefault();
EventLogger event_logger(db_options_.info_log.get()); EventLogger event_logger(db_options_.info_log.get());
@ -93,7 +93,7 @@ TEST(FlushJobTest, Empty) {
job_context.Clean(); job_context.Clean();
} }
TEST(FlushJobTest, NonEmpty) { TEST_F(FlushJobTest, NonEmpty) {
JobContext job_context(0); JobContext job_context(0);
auto cfd = versions_->GetColumnFamilySet()->GetDefault(); auto cfd = versions_->GetColumnFamilySet()->GetDefault();
auto new_mem = cfd->ConstructNewMemtable(*cfd->GetLatestMutableCFOptions()); auto new_mem = cfd->ConstructNewMemtable(*cfd->GetLatestMutableCFOptions());
@ -123,4 +123,7 @@ TEST(FlushJobTest, NonEmpty) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { return rocksdb::test::RunAllTests(); } int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

@ -35,7 +35,7 @@
namespace rocksdb { namespace rocksdb {
class EventListenerTest { class EventListenerTest : public testing::Test {
public: public:
EventListenerTest() { EventListenerTest() {
dbname_ = test::TmpDir() + "/listener_test"; dbname_ = test::TmpDir() + "/listener_test";
@ -157,7 +157,7 @@ class TestCompactionListener : public EventListener {
std::vector<DB*> compacted_dbs_; std::vector<DB*> compacted_dbs_;
}; };
TEST(EventListenerTest, OnSingleDBCompactionTest) { TEST_F(EventListenerTest, OnSingleDBCompactionTest) {
const int kTestKeySize = 16; const int kTestKeySize = 16;
const int kTestValueSize = 984; const int kTestValueSize = 984;
const int kEntrySize = kTestKeySize + kTestValueSize; const int kEntrySize = kTestKeySize + kTestValueSize;
@ -226,7 +226,7 @@ class TestFlushListener : public EventListener {
int stop_count; int stop_count;
}; };
TEST(EventListenerTest, OnSingleDBFlushTest) { TEST_F(EventListenerTest, OnSingleDBFlushTest) {
Options options; Options options;
options.write_buffer_size = 100000; options.write_buffer_size = 100000;
TestFlushListener* listener = new TestFlushListener(); TestFlushListener* listener = new TestFlushListener();
@ -257,7 +257,7 @@ TEST(EventListenerTest, OnSingleDBFlushTest) {
} }
} }
TEST(EventListenerTest, MultiCF) { TEST_F(EventListenerTest, MultiCF) {
Options options; Options options;
options.write_buffer_size = 100000; options.write_buffer_size = 100000;
TestFlushListener* listener = new TestFlushListener(); TestFlushListener* listener = new TestFlushListener();
@ -287,7 +287,7 @@ TEST(EventListenerTest, MultiCF) {
} }
} }
TEST(EventListenerTest, MultiDBMultiListeners) { TEST_F(EventListenerTest, MultiDBMultiListeners) {
std::vector<TestFlushListener*> listeners; std::vector<TestFlushListener*> listeners;
const int kNumDBs = 5; const int kNumDBs = 5;
const int kNumListeners = 10; const int kNumListeners = 10;
@ -363,7 +363,7 @@ TEST(EventListenerTest, MultiDBMultiListeners) {
} }
} }
TEST(EventListenerTest, DisableBGCompaction) { TEST_F(EventListenerTest, DisableBGCompaction) {
Options options; Options options;
TestFlushListener* listener = new TestFlushListener(); TestFlushListener* listener = new TestFlushListener();
const int kSlowdownTrigger = 5; const int kSlowdownTrigger = 5;
@ -396,6 +396,7 @@ TEST(EventListenerTest, DisableBGCompaction) {
#endif // ROCKSDB_LITE #endif // ROCKSDB_LITE
int main(int argc, char** argv) { int main(int argc, char** argv) {
return rocksdb::test::RunAllTests(); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} }

@ -41,7 +41,7 @@ static std::string RandomSkewedString(int i, Random* rnd) {
return BigString(NumberString(i), rnd->Skewed(17)); return BigString(NumberString(i), rnd->Skewed(17));
} }
class LogTest { class LogTest : public testing::Test {
private: private:
class StringDest : public WritableFile { class StringDest : public WritableFile {
public: public:
@ -329,12 +329,9 @@ uint64_t LogTest::initial_offset_last_record_offsets_[] =
2 * (kHeaderSize + 10000) + 2 * (kHeaderSize + 10000) +
(2 * log::kBlockSize - 1000) + 3 * kHeaderSize}; (2 * log::kBlockSize - 1000) + 3 * kHeaderSize};
TEST_F(LogTest, Empty) { ASSERT_EQ("EOF", Read()); }
TEST(LogTest, Empty) { TEST_F(LogTest, ReadWrite) {
ASSERT_EQ("EOF", Read());
}
TEST(LogTest, ReadWrite) {
Write("foo"); Write("foo");
Write("bar"); Write("bar");
Write(""); Write("");
@ -347,7 +344,7 @@ TEST(LogTest, ReadWrite) {
ASSERT_EQ("EOF", Read()); // Make sure reads at eof work ASSERT_EQ("EOF", Read()); // Make sure reads at eof work
} }
TEST(LogTest, ManyBlocks) { TEST_F(LogTest, ManyBlocks) {
for (int i = 0; i < 100000; i++) { for (int i = 0; i < 100000; i++) {
Write(NumberString(i)); Write(NumberString(i));
} }
@ -357,7 +354,7 @@ TEST(LogTest, ManyBlocks) {
ASSERT_EQ("EOF", Read()); ASSERT_EQ("EOF", Read());
} }
TEST(LogTest, Fragmentation) { TEST_F(LogTest, Fragmentation) {
Write("small"); Write("small");
Write(BigString("medium", 50000)); Write(BigString("medium", 50000));
Write(BigString("large", 100000)); Write(BigString("large", 100000));
@ -367,7 +364,7 @@ TEST(LogTest, Fragmentation) {
ASSERT_EQ("EOF", Read()); ASSERT_EQ("EOF", Read());
} }
TEST(LogTest, MarginalTrailer) { TEST_F(LogTest, MarginalTrailer) {
// Make a trailer that is exactly the same length as an empty record. // Make a trailer that is exactly the same length as an empty record.
const int n = kBlockSize - 2*kHeaderSize; const int n = kBlockSize - 2*kHeaderSize;
Write(BigString("foo", n)); Write(BigString("foo", n));
@ -380,7 +377,7 @@ TEST(LogTest, MarginalTrailer) {
ASSERT_EQ("EOF", Read()); ASSERT_EQ("EOF", Read());
} }
TEST(LogTest, MarginalTrailer2) { TEST_F(LogTest, MarginalTrailer2) {
// Make a trailer that is exactly the same length as an empty record. // Make a trailer that is exactly the same length as an empty record.
const int n = kBlockSize - 2*kHeaderSize; const int n = kBlockSize - 2*kHeaderSize;
Write(BigString("foo", n)); Write(BigString("foo", n));
@ -393,7 +390,7 @@ TEST(LogTest, MarginalTrailer2) {
ASSERT_EQ("", ReportMessage()); ASSERT_EQ("", ReportMessage());
} }
TEST(LogTest, ShortTrailer) { TEST_F(LogTest, ShortTrailer) {
const int n = kBlockSize - 2*kHeaderSize + 4; const int n = kBlockSize - 2*kHeaderSize + 4;
Write(BigString("foo", n)); Write(BigString("foo", n));
ASSERT_EQ((unsigned int)(kBlockSize - kHeaderSize + 4), WrittenBytes()); ASSERT_EQ((unsigned int)(kBlockSize - kHeaderSize + 4), WrittenBytes());
@ -405,7 +402,7 @@ TEST(LogTest, ShortTrailer) {
ASSERT_EQ("EOF", Read()); ASSERT_EQ("EOF", Read());
} }
TEST(LogTest, AlignedEof) { TEST_F(LogTest, AlignedEof) {
const int n = kBlockSize - 2*kHeaderSize + 4; const int n = kBlockSize - 2*kHeaderSize + 4;
Write(BigString("foo", n)); Write(BigString("foo", n));
ASSERT_EQ((unsigned int)(kBlockSize - kHeaderSize + 4), WrittenBytes()); ASSERT_EQ((unsigned int)(kBlockSize - kHeaderSize + 4), WrittenBytes());
@ -413,7 +410,7 @@ TEST(LogTest, AlignedEof) {
ASSERT_EQ("EOF", Read()); ASSERT_EQ("EOF", Read());
} }
TEST(LogTest, RandomRead) { TEST_F(LogTest, RandomRead) {
const int N = 500; const int N = 500;
Random write_rnd(301); Random write_rnd(301);
for (int i = 0; i < N; i++) { for (int i = 0; i < N; i++) {
@ -428,7 +425,7 @@ TEST(LogTest, RandomRead) {
// Tests of all the error paths in log_reader.cc follow: // Tests of all the error paths in log_reader.cc follow:
TEST(LogTest, ReadError) { TEST_F(LogTest, ReadError) {
Write("foo"); Write("foo");
ForceError(); ForceError();
ASSERT_EQ("EOF", Read()); ASSERT_EQ("EOF", Read());
@ -436,7 +433,7 @@ TEST(LogTest, ReadError) {
ASSERT_EQ("OK", MatchError("read error")); ASSERT_EQ("OK", MatchError("read error"));
} }
TEST(LogTest, BadRecordType) { TEST_F(LogTest, BadRecordType) {
Write("foo"); Write("foo");
// Type is stored in header[6] // Type is stored in header[6]
IncrementByte(6, 100); IncrementByte(6, 100);
@ -446,7 +443,7 @@ TEST(LogTest, BadRecordType) {
ASSERT_EQ("OK", MatchError("unknown record type")); ASSERT_EQ("OK", MatchError("unknown record type"));
} }
TEST(LogTest, TruncatedTrailingRecordIsIgnored) { TEST_F(LogTest, TruncatedTrailingRecordIsIgnored) {
Write("foo"); Write("foo");
ShrinkSize(4); // Drop all payload as well as a header byte ShrinkSize(4); // Drop all payload as well as a header byte
ASSERT_EQ("EOF", Read()); ASSERT_EQ("EOF", Read());
@ -455,7 +452,7 @@ TEST(LogTest, TruncatedTrailingRecordIsIgnored) {
ASSERT_EQ("", ReportMessage()); ASSERT_EQ("", ReportMessage());
} }
TEST(LogTest, BadLength) { TEST_F(LogTest, BadLength) {
const int kPayloadSize = kBlockSize - kHeaderSize; const int kPayloadSize = kBlockSize - kHeaderSize;
Write(BigString("bar", kPayloadSize)); Write(BigString("bar", kPayloadSize));
Write("foo"); Write("foo");
@ -466,7 +463,7 @@ TEST(LogTest, BadLength) {
ASSERT_EQ("OK", MatchError("bad record length")); ASSERT_EQ("OK", MatchError("bad record length"));
} }
TEST(LogTest, BadLengthAtEndIsIgnored) { TEST_F(LogTest, BadLengthAtEndIsIgnored) {
Write("foo"); Write("foo");
ShrinkSize(1); ShrinkSize(1);
ASSERT_EQ("EOF", Read()); ASSERT_EQ("EOF", Read());
@ -474,7 +471,7 @@ TEST(LogTest, BadLengthAtEndIsIgnored) {
ASSERT_EQ("", ReportMessage()); ASSERT_EQ("", ReportMessage());
} }
TEST(LogTest, ChecksumMismatch) { TEST_F(LogTest, ChecksumMismatch) {
Write("foo"); Write("foo");
IncrementByte(0, 10); IncrementByte(0, 10);
ASSERT_EQ("EOF", Read()); ASSERT_EQ("EOF", Read());
@ -482,7 +479,7 @@ TEST(LogTest, ChecksumMismatch) {
ASSERT_EQ("OK", MatchError("checksum mismatch")); ASSERT_EQ("OK", MatchError("checksum mismatch"));
} }
TEST(LogTest, UnexpectedMiddleType) { TEST_F(LogTest, UnexpectedMiddleType) {
Write("foo"); Write("foo");
SetByte(6, kMiddleType); SetByte(6, kMiddleType);
FixChecksum(0, 3); FixChecksum(0, 3);
@ -491,7 +488,7 @@ TEST(LogTest, UnexpectedMiddleType) {
ASSERT_EQ("OK", MatchError("missing start")); ASSERT_EQ("OK", MatchError("missing start"));
} }
TEST(LogTest, UnexpectedLastType) { TEST_F(LogTest, UnexpectedLastType) {
Write("foo"); Write("foo");
SetByte(6, kLastType); SetByte(6, kLastType);
FixChecksum(0, 3); FixChecksum(0, 3);
@ -500,7 +497,7 @@ TEST(LogTest, UnexpectedLastType) {
ASSERT_EQ("OK", MatchError("missing start")); ASSERT_EQ("OK", MatchError("missing start"));
} }
TEST(LogTest, UnexpectedFullType) { TEST_F(LogTest, UnexpectedFullType) {
Write("foo"); Write("foo");
Write("bar"); Write("bar");
SetByte(6, kFirstType); SetByte(6, kFirstType);
@ -511,7 +508,7 @@ TEST(LogTest, UnexpectedFullType) {
ASSERT_EQ("OK", MatchError("partial record without end")); ASSERT_EQ("OK", MatchError("partial record without end"));
} }
TEST(LogTest, UnexpectedFirstType) { TEST_F(LogTest, UnexpectedFirstType) {
Write("foo"); Write("foo");
Write(BigString("bar", 100000)); Write(BigString("bar", 100000));
SetByte(6, kFirstType); SetByte(6, kFirstType);
@ -522,7 +519,7 @@ TEST(LogTest, UnexpectedFirstType) {
ASSERT_EQ("OK", MatchError("partial record without end")); ASSERT_EQ("OK", MatchError("partial record without end"));
} }
TEST(LogTest, MissingLastIsIgnored) { TEST_F(LogTest, MissingLastIsIgnored) {
Write(BigString("bar", kBlockSize)); Write(BigString("bar", kBlockSize));
// Remove the LAST block, including header. // Remove the LAST block, including header.
ShrinkSize(14); ShrinkSize(14);
@ -531,7 +528,7 @@ TEST(LogTest, MissingLastIsIgnored) {
ASSERT_EQ(0U, DroppedBytes()); ASSERT_EQ(0U, DroppedBytes());
} }
TEST(LogTest, PartialLastIsIgnored) { TEST_F(LogTest, PartialLastIsIgnored) {
Write(BigString("bar", kBlockSize)); Write(BigString("bar", kBlockSize));
// Cause a bad record length in the LAST block. // Cause a bad record length in the LAST block.
ShrinkSize(1); ShrinkSize(1);
@ -540,7 +537,7 @@ TEST(LogTest, PartialLastIsIgnored) {
ASSERT_EQ(0U, DroppedBytes()); ASSERT_EQ(0U, DroppedBytes());
} }
TEST(LogTest, ErrorJoinsRecords) { TEST_F(LogTest, ErrorJoinsRecords) {
// Consider two fragmented records: // Consider two fragmented records:
// first(R1) last(R1) first(R2) last(R2) // first(R1) last(R1) first(R2) last(R2)
// where the middle two fragments disappear. We do not want // where the middle two fragments disappear. We do not want
@ -563,61 +560,43 @@ TEST(LogTest, ErrorJoinsRecords) {
ASSERT_GE(dropped, 2 * kBlockSize); ASSERT_GE(dropped, 2 * kBlockSize);
} }
TEST(LogTest, ReadStart) { TEST_F(LogTest, ReadStart) { CheckInitialOffsetRecord(0, 0); }
CheckInitialOffsetRecord(0, 0);
}
TEST(LogTest, ReadSecondOneOff) { TEST_F(LogTest, ReadSecondOneOff) { CheckInitialOffsetRecord(1, 1); }
CheckInitialOffsetRecord(1, 1);
}
TEST(LogTest, ReadSecondTenThousand) { TEST_F(LogTest, ReadSecondTenThousand) { CheckInitialOffsetRecord(10000, 1); }
CheckInitialOffsetRecord(10000, 1);
}
TEST(LogTest, ReadSecondStart) { TEST_F(LogTest, ReadSecondStart) { CheckInitialOffsetRecord(10007, 1); }
CheckInitialOffsetRecord(10007, 1);
}
TEST(LogTest, ReadThirdOneOff) { TEST_F(LogTest, ReadThirdOneOff) { CheckInitialOffsetRecord(10008, 2); }
CheckInitialOffsetRecord(10008, 2);
}
TEST(LogTest, ReadThirdStart) { TEST_F(LogTest, ReadThirdStart) { CheckInitialOffsetRecord(20014, 2); }
CheckInitialOffsetRecord(20014, 2);
}
TEST(LogTest, ReadFourthOneOff) { TEST_F(LogTest, ReadFourthOneOff) { CheckInitialOffsetRecord(20015, 3); }
CheckInitialOffsetRecord(20015, 3);
}
TEST(LogTest, ReadFourthFirstBlockTrailer) { TEST_F(LogTest, ReadFourthFirstBlockTrailer) {
CheckInitialOffsetRecord(log::kBlockSize - 4, 3); CheckInitialOffsetRecord(log::kBlockSize - 4, 3);
} }
TEST(LogTest, ReadFourthMiddleBlock) { TEST_F(LogTest, ReadFourthMiddleBlock) {
CheckInitialOffsetRecord(log::kBlockSize + 1, 3); CheckInitialOffsetRecord(log::kBlockSize + 1, 3);
} }
TEST(LogTest, ReadFourthLastBlock) { TEST_F(LogTest, ReadFourthLastBlock) {
CheckInitialOffsetRecord(2 * log::kBlockSize + 1, 3); CheckInitialOffsetRecord(2 * log::kBlockSize + 1, 3);
} }
TEST(LogTest, ReadFourthStart) { TEST_F(LogTest, ReadFourthStart) {
CheckInitialOffsetRecord( CheckInitialOffsetRecord(
2 * (kHeaderSize + 1000) + (2 * log::kBlockSize - 1000) + 3 * kHeaderSize, 2 * (kHeaderSize + 1000) + (2 * log::kBlockSize - 1000) + 3 * kHeaderSize,
3); 3);
} }
TEST(LogTest, ReadEnd) { TEST_F(LogTest, ReadEnd) { CheckOffsetPastEndReturnsNoRecords(0); }
CheckOffsetPastEndReturnsNoRecords(0);
}
TEST(LogTest, ReadPastEnd) { TEST_F(LogTest, ReadPastEnd) { CheckOffsetPastEndReturnsNoRecords(5); }
CheckOffsetPastEndReturnsNoRecords(5);
}
TEST(LogTest, ClearEofSingleBlock) { TEST_F(LogTest, ClearEofSingleBlock) {
Write("foo"); Write("foo");
Write("bar"); Write("bar");
ForceEOF(3 + kHeaderSize + 2); ForceEOF(3 + kHeaderSize + 2);
@ -632,7 +611,7 @@ TEST(LogTest, ClearEofSingleBlock) {
ASSERT_TRUE(IsEOF()); ASSERT_TRUE(IsEOF());
} }
TEST(LogTest, ClearEofMultiBlock) { TEST_F(LogTest, ClearEofMultiBlock) {
size_t num_full_blocks = 5; size_t num_full_blocks = 5;
size_t n = (kBlockSize - kHeaderSize) * num_full_blocks + 25; size_t n = (kBlockSize - kHeaderSize) * num_full_blocks + 25;
Write(BigString("foo", n)); Write(BigString("foo", n));
@ -649,7 +628,7 @@ TEST(LogTest, ClearEofMultiBlock) {
ASSERT_TRUE(IsEOF()); ASSERT_TRUE(IsEOF());
} }
TEST(LogTest, ClearEofError) { TEST_F(LogTest, ClearEofError) {
// If an error occurs during Read() in UnmarkEOF(), the records contained // If an error occurs during Read() in UnmarkEOF(), the records contained
// in the buffer should be returned on subsequent calls of ReadRecord() // in the buffer should be returned on subsequent calls of ReadRecord()
// until no more full records are left, whereafter ReadRecord() should return // until no more full records are left, whereafter ReadRecord() should return
@ -667,7 +646,7 @@ TEST(LogTest, ClearEofError) {
ASSERT_EQ("EOF", Read()); ASSERT_EQ("EOF", Read());
} }
TEST(LogTest, ClearEofError2) { TEST_F(LogTest, ClearEofError2) {
Write("foo"); Write("foo");
Write("bar"); Write("bar");
UnmarkEOF(); UnmarkEOF();
@ -685,5 +664,6 @@ TEST(LogTest, ClearEofError2) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { int main(int argc, char** argv) {
return rocksdb::test::RunAllTests(); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} }

@ -59,9 +59,9 @@ std::shared_ptr<DB> OpenDb(bool read_only = false) {
return std::shared_ptr<DB>(db); return std::shared_ptr<DB>(db);
} }
class PerfContextTest { }; class PerfContextTest : public testing::Test {};
TEST(PerfContextTest, SeekIntoDeletion) { TEST_F(PerfContextTest, SeekIntoDeletion) {
DestroyDB(kDbName, Options()); DestroyDB(kDbName, Options());
auto db = OpenDb(); auto db = OpenDb();
WriteOptions write_options; WriteOptions write_options;
@ -144,7 +144,7 @@ TEST(PerfContextTest, SeekIntoDeletion) {
std::cout << "Seek uesr key comparison: \n" << hist_seek.ToString(); std::cout << "Seek uesr key comparison: \n" << hist_seek.ToString();
} }
TEST(PerfContextTest, StopWatchNanoOverhead) { TEST_F(PerfContextTest, StopWatchNanoOverhead) {
// profile the timer cost by itself! // profile the timer cost by itself!
const int kTotalIterations = 1000000; const int kTotalIterations = 1000000;
std::vector<uint64_t> timings(kTotalIterations); std::vector<uint64_t> timings(kTotalIterations);
@ -162,7 +162,7 @@ TEST(PerfContextTest, StopWatchNanoOverhead) {
std::cout << histogram.ToString(); std::cout << histogram.ToString();
} }
TEST(PerfContextTest, StopWatchOverhead) { TEST_F(PerfContextTest, StopWatchOverhead) {
// profile the timer cost by itself! // profile the timer cost by itself!
const int kTotalIterations = 1000000; const int kTotalIterations = 1000000;
uint64_t elapsed = 0; uint64_t elapsed = 0;
@ -425,7 +425,7 @@ void ProfileQueries(bool enabled_time = false) {
} }
} }
TEST(PerfContextTest, KeyComparisonCount) { TEST_F(PerfContextTest, KeyComparisonCount) {
SetPerfLevel(kEnableCount); SetPerfLevel(kEnableCount);
ProfileQueries(); ProfileQueries();
@ -448,7 +448,7 @@ TEST(PerfContextTest, KeyComparisonCount) {
// memtable. When there are two memtables, even the avg Seek Key comparison // memtable. When there are two memtables, even the avg Seek Key comparison
// starts to become linear to the input size. // starts to become linear to the input size.
TEST(PerfContextTest, SeekKeyComparison) { TEST_F(PerfContextTest, SeekKeyComparison) {
DestroyDB(kDbName, Options()); DestroyDB(kDbName, Options());
auto db = OpenDb(); auto db = OpenDb();
WriteOptions write_options; WriteOptions write_options;
@ -517,6 +517,7 @@ TEST(PerfContextTest, SeekKeyComparison) {
} }
int main(int argc, char** argv) { int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
for (int i = 1; i < argc; i++) { for (int i = 1; i < argc; i++) {
int n; int n;
@ -544,5 +545,5 @@ int main(int argc, char** argv) {
std::cout << kDbName << "\n"; std::cout << kDbName << "\n";
return rocksdb::test::RunAllTests(); return RUN_ALL_TESTS();
} }

@ -37,7 +37,7 @@ using std::unique_ptr;
namespace rocksdb { namespace rocksdb {
class PlainTableDBTest { class PlainTableDBTest : public testing::Test {
protected: protected:
private: private:
std::string dbname_; std::string dbname_;
@ -182,7 +182,7 @@ class PlainTableDBTest {
} }
}; };
TEST(PlainTableDBTest, Empty) { TEST_F(PlainTableDBTest, Empty) {
ASSERT_TRUE(dbfull() != nullptr); ASSERT_TRUE(dbfull() != nullptr);
ASSERT_EQ("NOT_FOUND", Get("0000000000000foo")); ASSERT_EQ("NOT_FOUND", Get("0000000000000foo"));
} }
@ -302,7 +302,7 @@ class TestPlainTableFactory : public PlainTableFactory {
bool* expect_bloom_not_match_; bool* expect_bloom_not_match_;
}; };
TEST(PlainTableDBTest, Flush) { TEST_F(PlainTableDBTest, Flush) {
for (size_t huge_page_tlb_size = 0; huge_page_tlb_size <= 2 * 1024 * 1024; for (size_t huge_page_tlb_size = 0; huge_page_tlb_size <= 2 * 1024 * 1024;
huge_page_tlb_size += 2 * 1024 * 1024) { huge_page_tlb_size += 2 * 1024 * 1024) {
for (EncodingType encoding_type : {kPlain, kPrefix}) { for (EncodingType encoding_type : {kPlain, kPrefix}) {
@ -389,7 +389,7 @@ TEST(PlainTableDBTest, Flush) {
} }
} }
TEST(PlainTableDBTest, Flush2) { TEST_F(PlainTableDBTest, Flush2) {
for (size_t huge_page_tlb_size = 0; huge_page_tlb_size <= 2 * 1024 * 1024; for (size_t huge_page_tlb_size = 0; huge_page_tlb_size <= 2 * 1024 * 1024;
huge_page_tlb_size += 2 * 1024 * 1024) { huge_page_tlb_size += 2 * 1024 * 1024) {
for (EncodingType encoding_type : {kPlain, kPrefix}) { for (EncodingType encoding_type : {kPlain, kPrefix}) {
@ -469,7 +469,7 @@ TEST(PlainTableDBTest, Flush2) {
} }
} }
TEST(PlainTableDBTest, Iterator) { TEST_F(PlainTableDBTest, Iterator) {
for (size_t huge_page_tlb_size = 0; huge_page_tlb_size <= 2 * 1024 * 1024; for (size_t huge_page_tlb_size = 0; huge_page_tlb_size <= 2 * 1024 * 1024;
huge_page_tlb_size += 2 * 1024 * 1024) { huge_page_tlb_size += 2 * 1024 * 1024) {
for (EncodingType encoding_type : {kPlain, kPrefix}) { for (EncodingType encoding_type : {kPlain, kPrefix}) {
@ -603,7 +603,7 @@ std::string MakeLongKey(size_t length, char c) {
} }
} // namespace } // namespace
TEST(PlainTableDBTest, IteratorLargeKeys) { TEST_F(PlainTableDBTest, IteratorLargeKeys) {
Options options = CurrentOptions(); Options options = CurrentOptions();
PlainTableOptions plain_table_options; PlainTableOptions plain_table_options;
@ -653,7 +653,7 @@ std::string MakeLongKeyWithPrefix(size_t length, char c) {
} }
} // namespace } // namespace
TEST(PlainTableDBTest, IteratorLargeKeysWithPrefix) { TEST_F(PlainTableDBTest, IteratorLargeKeysWithPrefix) {
Options options = CurrentOptions(); Options options = CurrentOptions();
PlainTableOptions plain_table_options; PlainTableOptions plain_table_options;
@ -695,7 +695,7 @@ TEST(PlainTableDBTest, IteratorLargeKeysWithPrefix) {
delete iter; delete iter;
} }
TEST(PlainTableDBTest, IteratorReverseSuffixComparator) { TEST_F(PlainTableDBTest, IteratorReverseSuffixComparator) {
Options options = CurrentOptions(); Options options = CurrentOptions();
options.create_if_missing = true; options.create_if_missing = true;
// Set only one bucket to force bucket conflict. // Set only one bucket to force bucket conflict.
@ -764,7 +764,7 @@ TEST(PlainTableDBTest, IteratorReverseSuffixComparator) {
delete iter; delete iter;
} }
TEST(PlainTableDBTest, HashBucketConflict) { TEST_F(PlainTableDBTest, HashBucketConflict) {
for (size_t huge_page_tlb_size = 0; huge_page_tlb_size <= 2 * 1024 * 1024; for (size_t huge_page_tlb_size = 0; huge_page_tlb_size <= 2 * 1024 * 1024;
huge_page_tlb_size += 2 * 1024 * 1024) { huge_page_tlb_size += 2 * 1024 * 1024) {
for (unsigned char i = 1; i <= 3; i++) { for (unsigned char i = 1; i <= 3; i++) {
@ -857,7 +857,7 @@ TEST(PlainTableDBTest, HashBucketConflict) {
} }
} }
TEST(PlainTableDBTest, HashBucketConflictReverseSuffixComparator) { TEST_F(PlainTableDBTest, HashBucketConflictReverseSuffixComparator) {
for (size_t huge_page_tlb_size = 0; huge_page_tlb_size <= 2 * 1024 * 1024; for (size_t huge_page_tlb_size = 0; huge_page_tlb_size <= 2 * 1024 * 1024;
huge_page_tlb_size += 2 * 1024 * 1024) { huge_page_tlb_size += 2 * 1024 * 1024) {
for (unsigned char i = 1; i <= 3; i++) { for (unsigned char i = 1; i <= 3; i++) {
@ -950,7 +950,7 @@ TEST(PlainTableDBTest, HashBucketConflictReverseSuffixComparator) {
} }
} }
TEST(PlainTableDBTest, NonExistingKeyToNonEmptyBucket) { TEST_F(PlainTableDBTest, NonExistingKeyToNonEmptyBucket) {
Options options = CurrentOptions(); Options options = CurrentOptions();
options.create_if_missing = true; options.create_if_missing = true;
// Set only one bucket to force bucket conflict. // Set only one bucket to force bucket conflict.
@ -1006,7 +1006,7 @@ static std::string RandomString(Random* rnd, int len) {
return r; return r;
} }
TEST(PlainTableDBTest, CompactionTrigger) { TEST_F(PlainTableDBTest, CompactionTrigger) {
Options options = CurrentOptions(); Options options = CurrentOptions();
options.write_buffer_size = 100 << 10; //100KB options.write_buffer_size = 100 << 10; //100KB
options.num_levels = 3; options.num_levels = 3;
@ -1040,7 +1040,7 @@ TEST(PlainTableDBTest, CompactionTrigger) {
ASSERT_EQ(NumTableFilesAtLevel(1), 1); ASSERT_EQ(NumTableFilesAtLevel(1), 1);
} }
TEST(PlainTableDBTest, AdaptiveTable) { TEST_F(PlainTableDBTest, AdaptiveTable) {
Options options = CurrentOptions(); Options options = CurrentOptions();
options.create_if_missing = true; options.create_if_missing = true;
@ -1086,5 +1086,6 @@ TEST(PlainTableDBTest, AdaptiveTable) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { int main(int argc, char** argv) {
return rocksdb::test::RunAllTests(); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} }

@ -144,7 +144,7 @@ std::string Get(DB* db, const ReadOptions& read_options, uint64_t prefix,
} }
} // namespace } // namespace
class PrefixTest { class PrefixTest : public testing::Test {
public: public:
std::shared_ptr<DB> OpenDb() { std::shared_ptr<DB> OpenDb() {
DB* db; DB* db;
@ -217,7 +217,7 @@ class PrefixTest {
Options options; Options options;
}; };
TEST(PrefixTest, TestResult) { TEST_F(PrefixTest, TestResult) {
for (int num_buckets = 1; num_buckets <= 2; num_buckets++) { for (int num_buckets = 1; num_buckets <= 2; num_buckets++) {
FirstOption(); FirstOption();
while (NextOptions(num_buckets)) { while (NextOptions(num_buckets)) {
@ -390,7 +390,7 @@ TEST(PrefixTest, TestResult) {
} }
} }
TEST(PrefixTest, DynamicPrefixIterator) { TEST_F(PrefixTest, DynamicPrefixIterator) {
while (NextOptions(FLAGS_bucket_count)) { while (NextOptions(FLAGS_bucket_count)) {
std::cout << "*** Mem table: " << options.memtable_factory->Name() std::cout << "*** Mem table: " << options.memtable_factory->Name()
<< std::endl; << std::endl;
@ -492,10 +492,11 @@ TEST(PrefixTest, DynamicPrefixIterator) {
} }
int main(int argc, char** argv) { int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
ParseCommandLineFlags(&argc, &argv, true); ParseCommandLineFlags(&argc, &argv, true);
std::cout << kDbName << "\n"; std::cout << kDbName << "\n";
return rocksdb::test::RunAllTests(); return RUN_ALL_TESTS();
} }
#endif // GFLAGS #endif // GFLAGS

@ -31,9 +31,9 @@ struct TestComparator {
} }
}; };
class SkipTest { }; class SkipTest : public testing::Test {};
TEST(SkipTest, Empty) { TEST_F(SkipTest, Empty) {
Arena arena; Arena arena;
TestComparator cmp; TestComparator cmp;
SkipList<Key, TestComparator> list(cmp, &arena); SkipList<Key, TestComparator> list(cmp, &arena);
@ -49,7 +49,7 @@ TEST(SkipTest, Empty) {
ASSERT_TRUE(!iter.Valid()); ASSERT_TRUE(!iter.Valid());
} }
TEST(SkipTest, InsertAndLookup) { TEST_F(SkipTest, InsertAndLookup) {
const int N = 2000; const int N = 2000;
const int R = 5000; const int R = 5000;
Random rnd(1000); Random rnd(1000);
@ -287,7 +287,7 @@ const uint32_t ConcurrentTest::K;
// Simple test that does single-threaded testing of the ConcurrentTest // Simple test that does single-threaded testing of the ConcurrentTest
// scaffolding. // scaffolding.
TEST(SkipTest, ConcurrentWithoutThreads) { TEST_F(SkipTest, ConcurrentWithoutThreads) {
ConcurrentTest test; ConcurrentTest test;
Random rnd(test::RandomSeed()); Random rnd(test::RandomSeed());
for (int i = 0; i < 10000; i++) { for (int i = 0; i < 10000; i++) {
@ -364,14 +364,15 @@ static void RunConcurrent(int run) {
} }
} }
TEST(SkipTest, Concurrent1) { RunConcurrent(1); } TEST_F(SkipTest, Concurrent1) { RunConcurrent(1); }
TEST(SkipTest, Concurrent2) { RunConcurrent(2); } TEST_F(SkipTest, Concurrent2) { RunConcurrent(2); }
TEST(SkipTest, Concurrent3) { RunConcurrent(3); } TEST_F(SkipTest, Concurrent3) { RunConcurrent(3); }
TEST(SkipTest, Concurrent4) { RunConcurrent(4); } TEST_F(SkipTest, Concurrent4) { RunConcurrent(4); }
TEST(SkipTest, Concurrent5) { RunConcurrent(5); } TEST_F(SkipTest, Concurrent5) { RunConcurrent(5); }
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { int main(int argc, char** argv) {
return rocksdb::test::RunAllTests(); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} }

@ -22,8 +22,7 @@
namespace rocksdb { namespace rocksdb {
class TablePropertiesTest { class TablePropertiesTest : public testing::Test {};
};
// TODO(kailiu) the following classes should be moved to some more general // TODO(kailiu) the following classes should be moved to some more general
// places, so that other tests can also make use of them. // places, so that other tests can also make use of them.
@ -195,7 +194,7 @@ void TestCustomizedTablePropertiesCollector(
} }
} // namespace } // namespace
TEST(TablePropertiesTest, CustomizedTablePropertiesCollector) { TEST_F(TablePropertiesTest, CustomizedTablePropertiesCollector) {
// Test properties collectors with internal keys or regular keys // Test properties collectors with internal keys or regular keys
// for block based table // for block based table
for (bool encode_as_internal : { true, false }) { for (bool encode_as_internal : { true, false }) {
@ -301,7 +300,7 @@ void TestInternalKeyPropertiesCollector(
} }
} // namespace } // namespace
TEST(TablePropertiesTest, InternalKeyPropertiesCollector) { TEST_F(TablePropertiesTest, InternalKeyPropertiesCollector) {
TestInternalKeyPropertiesCollector( TestInternalKeyPropertiesCollector(
kBlockBasedTableMagicNumber, kBlockBasedTableMagicNumber,
true /* sanitize */, true /* sanitize */,
@ -326,5 +325,6 @@ TEST(TablePropertiesTest, InternalKeyPropertiesCollector) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { int main(int argc, char** argv) {
return rocksdb::test::RunAllTests(); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} }

@ -12,7 +12,7 @@
namespace rocksdb { namespace rocksdb {
class VersionBuilderTest { class VersionBuilderTest : public testing::Test {
public: public:
const Comparator* ucmp_; const Comparator* ucmp_;
InternalKeyComparator icmp_; InternalKeyComparator icmp_;
@ -95,7 +95,7 @@ void UnrefFilesInVersion(VersionStorageInfo* new_vstorage) {
} }
} }
TEST(VersionBuilderTest, ApplyAndSaveTo) { TEST_F(VersionBuilderTest, ApplyAndSaveTo) {
Add(0, 1U, "150", "200", 100U); Add(0, 1U, "150", "200", 100U);
Add(1, 66U, "150", "200", 100U); Add(1, 66U, "150", "200", 100U);
@ -131,7 +131,7 @@ TEST(VersionBuilderTest, ApplyAndSaveTo) {
UnrefFilesInVersion(&new_vstorage); UnrefFilesInVersion(&new_vstorage);
} }
TEST(VersionBuilderTest, ApplyAndSaveToDynamic) { TEST_F(VersionBuilderTest, ApplyAndSaveToDynamic) {
ioptions_.level_compaction_dynamic_level_bytes = true; ioptions_.level_compaction_dynamic_level_bytes = true;
Add(0, 1U, "150", "200", 100U, 0, 200U, 200U, 0, 0, false, 200U, 200U); Add(0, 1U, "150", "200", 100U, 0, 200U, 200U, 0, 0, false, 200U, 200U);
@ -168,7 +168,7 @@ TEST(VersionBuilderTest, ApplyAndSaveToDynamic) {
UnrefFilesInVersion(&new_vstorage); UnrefFilesInVersion(&new_vstorage);
} }
TEST(VersionBuilderTest, ApplyAndSaveToDynamic2) { TEST_F(VersionBuilderTest, ApplyAndSaveToDynamic2) {
ioptions_.level_compaction_dynamic_level_bytes = true; ioptions_.level_compaction_dynamic_level_bytes = true;
Add(0, 1U, "150", "200", 100U, 0, 200U, 200U, 0, 0, false, 200U, 200U); Add(0, 1U, "150", "200", 100U, 0, 200U, 200U, 0, 0, false, 200U, 200U);
@ -207,7 +207,7 @@ TEST(VersionBuilderTest, ApplyAndSaveToDynamic2) {
UnrefFilesInVersion(&new_vstorage); UnrefFilesInVersion(&new_vstorage);
} }
TEST(VersionBuilderTest, ApplyMultipleAndSaveTo) { TEST_F(VersionBuilderTest, ApplyMultipleAndSaveTo) {
UpdateVersionStorageInfo(); UpdateVersionStorageInfo();
VersionEdit version_edit; VersionEdit version_edit;
@ -236,7 +236,7 @@ TEST(VersionBuilderTest, ApplyMultipleAndSaveTo) {
UnrefFilesInVersion(&new_vstorage); UnrefFilesInVersion(&new_vstorage);
} }
TEST(VersionBuilderTest, ApplyDeleteAndSaveTo) { TEST_F(VersionBuilderTest, ApplyDeleteAndSaveTo) {
UpdateVersionStorageInfo(); UpdateVersionStorageInfo();
EnvOptions env_options; EnvOptions env_options;
@ -273,7 +273,7 @@ TEST(VersionBuilderTest, ApplyDeleteAndSaveTo) {
UnrefFilesInVersion(&new_vstorage); UnrefFilesInVersion(&new_vstorage);
} }
TEST(VersionBuilderTest, EstimatedActiveKeys) { TEST_F(VersionBuilderTest, EstimatedActiveKeys) {
const uint32_t kTotalSamples = 20; const uint32_t kTotalSamples = 20;
const uint32_t kNumLevels = 5; const uint32_t kNumLevels = 5;
const uint32_t kFilesPerLevel = 8; const uint32_t kFilesPerLevel = 8;
@ -297,4 +297,7 @@ TEST(VersionBuilderTest, EstimatedActiveKeys) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { return rocksdb::test::RunAllTests(); } int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

@ -22,9 +22,9 @@ static void TestEncodeDecode(const VersionEdit& edit) {
ASSERT_EQ(encoded, encoded2); ASSERT_EQ(encoded, encoded2);
} }
class VersionEditTest { }; class VersionEditTest : public testing::Test {};
TEST(VersionEditTest, EncodeDecode) { TEST_F(VersionEditTest, EncodeDecode) {
static const uint64_t kBig = 1ull << 50; static const uint64_t kBig = 1ull << 50;
static const uint32_t kBig32Bit = 1ull << 30; static const uint32_t kBig32Bit = 1ull << 30;
@ -45,7 +45,7 @@ TEST(VersionEditTest, EncodeDecode) {
TestEncodeDecode(edit); TestEncodeDecode(edit);
} }
TEST(VersionEditTest, EncodeEmptyFile) { TEST_F(VersionEditTest, EncodeEmptyFile) {
VersionEdit edit; VersionEdit edit;
edit.AddFile(0, 0, 0, 0, edit.AddFile(0, 0, 0, 0,
InternalKey(), InternalKey(),
@ -55,7 +55,7 @@ TEST(VersionEditTest, EncodeEmptyFile) {
ASSERT_TRUE(!edit.EncodeTo(&buffer)); ASSERT_TRUE(!edit.EncodeTo(&buffer));
} }
TEST(VersionEditTest, ColumnFamilyTest) { TEST_F(VersionEditTest, ColumnFamilyTest) {
VersionEdit edit; VersionEdit edit;
edit.SetColumnFamily(2); edit.SetColumnFamily(2);
edit.AddColumnFamily("column_family"); edit.AddColumnFamily("column_family");
@ -71,5 +71,6 @@ TEST(VersionEditTest, ColumnFamilyTest) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { int main(int argc, char** argv) {
return rocksdb::test::RunAllTests(); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} }

@ -14,7 +14,7 @@
namespace rocksdb { namespace rocksdb {
class GenerateLevelFilesBriefTest { class GenerateLevelFilesBriefTest : public testing::Test {
public: public:
std::vector<FileMetaData*> files_; std::vector<FileMetaData*> files_;
LevelFilesBrief file_level_; LevelFilesBrief file_level_;
@ -49,21 +49,20 @@ class GenerateLevelFilesBriefTest {
} }
}; };
TEST(GenerateLevelFilesBriefTest, Empty) { TEST_F(GenerateLevelFilesBriefTest, Empty) {
DoGenerateLevelFilesBrief(&file_level_, files_, &arena_); DoGenerateLevelFilesBrief(&file_level_, files_, &arena_);
ASSERT_EQ(0u, file_level_.num_files); ASSERT_EQ(0u, file_level_.num_files);
ASSERT_EQ(0, Compare()); ASSERT_EQ(0, Compare());
} }
TEST(GenerateLevelFilesBriefTest, Single) { TEST_F(GenerateLevelFilesBriefTest, Single) {
Add("p", "q"); Add("p", "q");
DoGenerateLevelFilesBrief(&file_level_, files_, &arena_); DoGenerateLevelFilesBrief(&file_level_, files_, &arena_);
ASSERT_EQ(1u, file_level_.num_files); ASSERT_EQ(1u, file_level_.num_files);
ASSERT_EQ(0, Compare()); ASSERT_EQ(0, Compare());
} }
TEST_F(GenerateLevelFilesBriefTest, Multiple) {
TEST(GenerateLevelFilesBriefTest, Multiple) {
Add("150", "200"); Add("150", "200");
Add("200", "250"); Add("200", "250");
Add("300", "350"); Add("300", "350");
@ -89,7 +88,7 @@ Options GetOptionsWithNumLevels(int num_levels,
return opt; return opt;
} }
class VersionStorageInfoTest { class VersionStorageInfoTest : public testing::Test {
public: public:
const Comparator* ucmp_; const Comparator* ucmp_;
InternalKeyComparator icmp_; InternalKeyComparator icmp_;
@ -138,7 +137,7 @@ class VersionStorageInfoTest {
} }
}; };
TEST(VersionStorageInfoTest, MaxBytesForLevelStatic) { TEST_F(VersionStorageInfoTest, MaxBytesForLevelStatic) {
ioptions_.level_compaction_dynamic_level_bytes = false; ioptions_.level_compaction_dynamic_level_bytes = false;
mutable_cf_options_.max_bytes_for_level_base = 10; mutable_cf_options_.max_bytes_for_level_base = 10;
mutable_cf_options_.max_bytes_for_level_multiplier = 5; mutable_cf_options_.max_bytes_for_level_multiplier = 5;
@ -154,7 +153,7 @@ TEST(VersionStorageInfoTest, MaxBytesForLevelStatic) {
ASSERT_EQ(0, logger_->log_count); ASSERT_EQ(0, logger_->log_count);
} }
TEST(VersionStorageInfoTest, MaxBytesForLevelDynamic) { TEST_F(VersionStorageInfoTest, MaxBytesForLevelDynamic) {
ioptions_.level_compaction_dynamic_level_bytes = true; ioptions_.level_compaction_dynamic_level_bytes = true;
mutable_cf_options_.max_bytes_for_level_base = 1000; mutable_cf_options_.max_bytes_for_level_base = 1000;
mutable_cf_options_.max_bytes_for_level_multiplier = 5; mutable_cf_options_.max_bytes_for_level_multiplier = 5;
@ -196,7 +195,7 @@ TEST(VersionStorageInfoTest, MaxBytesForLevelDynamic) {
ASSERT_EQ(vstorage_.base_level(), 1); ASSERT_EQ(vstorage_.base_level(), 1);
} }
TEST(VersionStorageInfoTest, MaxBytesForLevelDynamicLotsOfData) { TEST_F(VersionStorageInfoTest, MaxBytesForLevelDynamicLotsOfData) {
ioptions_.level_compaction_dynamic_level_bytes = true; ioptions_.level_compaction_dynamic_level_bytes = true;
mutable_cf_options_.max_bytes_for_level_base = 100; mutable_cf_options_.max_bytes_for_level_base = 100;
mutable_cf_options_.max_bytes_for_level_multiplier = 2; mutable_cf_options_.max_bytes_for_level_multiplier = 2;
@ -216,7 +215,7 @@ TEST(VersionStorageInfoTest, MaxBytesForLevelDynamicLotsOfData) {
ASSERT_EQ(0, logger_->log_count); ASSERT_EQ(0, logger_->log_count);
} }
class FindLevelFileTest { class FindLevelFileTest : public testing::Test {
public: public:
LevelFilesBrief file_level_; LevelFilesBrief file_level_;
bool disjoint_sorted_files_; bool disjoint_sorted_files_;
@ -274,7 +273,7 @@ class FindLevelFileTest {
} }
}; };
TEST(FindLevelFileTest, LevelEmpty) { TEST_F(FindLevelFileTest, LevelEmpty) {
LevelFileInit(0); LevelFileInit(0);
ASSERT_EQ(0, Find("foo")); ASSERT_EQ(0, Find("foo"));
@ -284,7 +283,7 @@ TEST(FindLevelFileTest, LevelEmpty) {
ASSERT_TRUE(! Overlaps(nullptr, nullptr)); ASSERT_TRUE(! Overlaps(nullptr, nullptr));
} }
TEST(FindLevelFileTest, LevelSingle) { TEST_F(FindLevelFileTest, LevelSingle) {
LevelFileInit(1); LevelFileInit(1);
Add("p", "q"); Add("p", "q");
@ -316,7 +315,7 @@ TEST(FindLevelFileTest, LevelSingle) {
ASSERT_TRUE(Overlaps(nullptr, nullptr)); ASSERT_TRUE(Overlaps(nullptr, nullptr));
} }
TEST(FindLevelFileTest, LevelMultiple) { TEST_F(FindLevelFileTest, LevelMultiple) {
LevelFileInit(4); LevelFileInit(4);
Add("150", "200"); Add("150", "200");
@ -356,7 +355,7 @@ TEST(FindLevelFileTest, LevelMultiple) {
ASSERT_TRUE(Overlaps("450", "500")); ASSERT_TRUE(Overlaps("450", "500"));
} }
TEST(FindLevelFileTest, LevelMultipleNullBoundaries) { TEST_F(FindLevelFileTest, LevelMultipleNullBoundaries) {
LevelFileInit(4); LevelFileInit(4);
Add("150", "200"); Add("150", "200");
@ -378,7 +377,7 @@ TEST(FindLevelFileTest, LevelMultipleNullBoundaries) {
ASSERT_TRUE(Overlaps("450", nullptr)); ASSERT_TRUE(Overlaps("450", nullptr));
} }
TEST(FindLevelFileTest, LevelOverlapSequenceChecks) { TEST_F(FindLevelFileTest, LevelOverlapSequenceChecks) {
LevelFileInit(1); LevelFileInit(1);
Add("200", "200", 5000, 3000); Add("200", "200", 5000, 3000);
@ -389,7 +388,7 @@ TEST(FindLevelFileTest, LevelOverlapSequenceChecks) {
ASSERT_TRUE(Overlaps("200", "210")); ASSERT_TRUE(Overlaps("200", "210"));
} }
TEST(FindLevelFileTest, LevelOverlappingFiles) { TEST_F(FindLevelFileTest, LevelOverlappingFiles) {
LevelFileInit(2); LevelFileInit(2);
Add("150", "600"); Add("150", "600");
@ -412,5 +411,6 @@ TEST(FindLevelFileTest, LevelOverlappingFiles) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { int main(int argc, char** argv) {
return rocksdb::test::RunAllTests(); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} }

@ -23,7 +23,7 @@ namespace rocksdb {
// TODO(icanadi) mock out VersionSet // TODO(icanadi) mock out VersionSet
// TODO(icanadi) move other WalManager-specific tests from db_test here // TODO(icanadi) move other WalManager-specific tests from db_test here
class WalManagerTest { class WalManagerTest : public testing::Test {
public: public:
WalManagerTest() WalManagerTest()
: env_(Env::Default()), : env_(Env::Default()),
@ -104,7 +104,7 @@ class WalManagerTest {
uint64_t current_log_number_; uint64_t current_log_number_;
}; };
TEST(WalManagerTest, ReadFirstRecordCache) { TEST_F(WalManagerTest, ReadFirstRecordCache) {
Init(); Init();
std::string path = dbname_ + "/000001.log"; std::string path = dbname_ + "/000001.log";
unique_ptr<WritableFile> file; unique_ptr<WritableFile> file;
@ -192,7 +192,7 @@ int CountRecords(TransactionLogIterator* iter) {
} }
} // namespace } // namespace
TEST(WalManagerTest, WALArchivalSizeLimit) { TEST_F(WalManagerTest, WALArchivalSizeLimit) {
db_options_.WAL_ttl_seconds = 0; db_options_.WAL_ttl_seconds = 0;
db_options_.WAL_size_limit_MB = 1000; db_options_.WAL_size_limit_MB = 1000;
Init(); Init();
@ -230,7 +230,7 @@ TEST(WalManagerTest, WALArchivalSizeLimit) {
ASSERT_TRUE(log_files.empty()); ASSERT_TRUE(log_files.empty());
} }
TEST(WalManagerTest, WALArchivalTtl) { TEST_F(WalManagerTest, WALArchivalTtl) {
db_options_.WAL_ttl_seconds = 1000; db_options_.WAL_ttl_seconds = 1000;
Init(); Init();
@ -256,7 +256,7 @@ TEST(WalManagerTest, WALArchivalTtl) {
ASSERT_TRUE(log_files.empty()); ASSERT_TRUE(log_files.empty());
} }
TEST(WalManagerTest, TransactionLogIteratorMoveOverZeroFiles) { TEST_F(WalManagerTest, TransactionLogIteratorMoveOverZeroFiles) {
Init(); Init();
RollTheLog(false); RollTheLog(false);
Put("key1", std::string(1024, 'a')); Put("key1", std::string(1024, 'a'));
@ -270,7 +270,7 @@ TEST(WalManagerTest, TransactionLogIteratorMoveOverZeroFiles) {
ASSERT_EQ(2, CountRecords(iter.get())); ASSERT_EQ(2, CountRecords(iter.get()));
} }
TEST(WalManagerTest, TransactionLogIteratorJustEmptyFile) { TEST_F(WalManagerTest, TransactionLogIteratorJustEmptyFile) {
Init(); Init();
RollTheLog(false); RollTheLog(false);
auto iter = OpenTransactionLogIter(0); auto iter = OpenTransactionLogIter(0);
@ -280,4 +280,7 @@ TEST(WalManagerTest, TransactionLogIteratorJustEmptyFile) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { return rocksdb::test::RunAllTests(); } int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

@ -82,16 +82,16 @@ static std::string PrintContents(WriteBatch* b) {
return state; return state;
} }
class WriteBatchTest { }; class WriteBatchTest : public testing::Test {};
TEST(WriteBatchTest, Empty) { TEST_F(WriteBatchTest, Empty) {
WriteBatch batch; WriteBatch batch;
ASSERT_EQ("", PrintContents(&batch)); ASSERT_EQ("", PrintContents(&batch));
ASSERT_EQ(0, WriteBatchInternal::Count(&batch)); ASSERT_EQ(0, WriteBatchInternal::Count(&batch));
ASSERT_EQ(0, batch.Count()); ASSERT_EQ(0, batch.Count());
} }
TEST(WriteBatchTest, Multiple) { TEST_F(WriteBatchTest, Multiple) {
WriteBatch batch; WriteBatch batch;
batch.Put(Slice("foo"), Slice("bar")); batch.Put(Slice("foo"), Slice("bar"));
batch.Delete(Slice("box")); batch.Delete(Slice("box"));
@ -106,7 +106,7 @@ TEST(WriteBatchTest, Multiple) {
ASSERT_EQ(3, batch.Count()); ASSERT_EQ(3, batch.Count());
} }
TEST(WriteBatchTest, Corruption) { TEST_F(WriteBatchTest, Corruption) {
WriteBatch batch; WriteBatch batch;
batch.Put(Slice("foo"), Slice("bar")); batch.Put(Slice("foo"), Slice("bar"));
batch.Delete(Slice("box")); batch.Delete(Slice("box"));
@ -119,7 +119,7 @@ TEST(WriteBatchTest, Corruption) {
PrintContents(&batch)); PrintContents(&batch));
} }
TEST(WriteBatchTest, Append) { TEST_F(WriteBatchTest, Append) {
WriteBatch b1, b2; WriteBatch b1, b2;
WriteBatchInternal::SetSequence(&b1, 200); WriteBatchInternal::SetSequence(&b1, 200);
WriteBatchInternal::SetSequence(&b2, 300); WriteBatchInternal::SetSequence(&b2, 300);
@ -188,7 +188,7 @@ namespace {
}; };
} }
TEST(WriteBatchTest, MergeNotImplemented) { TEST_F(WriteBatchTest, MergeNotImplemented) {
WriteBatch batch; WriteBatch batch;
batch.Merge(Slice("foo"), Slice("bar")); batch.Merge(Slice("foo"), Slice("bar"));
ASSERT_EQ(1, batch.Count()); ASSERT_EQ(1, batch.Count());
@ -199,7 +199,7 @@ TEST(WriteBatchTest, MergeNotImplemented) {
ASSERT_OK(batch.Iterate(&handler)); ASSERT_OK(batch.Iterate(&handler));
} }
TEST(WriteBatchTest, PutNotImplemented) { TEST_F(WriteBatchTest, PutNotImplemented) {
WriteBatch batch; WriteBatch batch;
batch.Put(Slice("k1"), Slice("v1")); batch.Put(Slice("k1"), Slice("v1"));
ASSERT_EQ(1, batch.Count()); ASSERT_EQ(1, batch.Count());
@ -210,7 +210,7 @@ TEST(WriteBatchTest, PutNotImplemented) {
ASSERT_OK(batch.Iterate(&handler)); ASSERT_OK(batch.Iterate(&handler));
} }
TEST(WriteBatchTest, DeleteNotImplemented) { TEST_F(WriteBatchTest, DeleteNotImplemented) {
WriteBatch batch; WriteBatch batch;
batch.Delete(Slice("k2")); batch.Delete(Slice("k2"));
ASSERT_EQ(1, batch.Count()); ASSERT_EQ(1, batch.Count());
@ -221,7 +221,7 @@ TEST(WriteBatchTest, DeleteNotImplemented) {
ASSERT_OK(batch.Iterate(&handler)); ASSERT_OK(batch.Iterate(&handler));
} }
TEST(WriteBatchTest, Blob) { TEST_F(WriteBatchTest, Blob) {
WriteBatch batch; WriteBatch batch;
batch.Put(Slice("k1"), Slice("v1")); batch.Put(Slice("k1"), Slice("v1"));
batch.Put(Slice("k2"), Slice("v2")); batch.Put(Slice("k2"), Slice("v2"));
@ -251,7 +251,7 @@ TEST(WriteBatchTest, Blob) {
handler.seen); handler.seen);
} }
TEST(WriteBatchTest, Continue) { TEST_F(WriteBatchTest, Continue) {
WriteBatch batch; WriteBatch batch;
struct Handler : public TestHandler { struct Handler : public TestHandler {
@ -293,7 +293,7 @@ TEST(WriteBatchTest, Continue) {
handler.seen); handler.seen);
} }
TEST(WriteBatchTest, PutGatherSlices) { TEST_F(WriteBatchTest, PutGatherSlices) {
WriteBatch batch; WriteBatch batch;
batch.Put(Slice("foo"), Slice("bar")); batch.Put(Slice("foo"), Slice("bar"));
@ -336,7 +336,7 @@ class ColumnFamilyHandleImplDummy : public ColumnFamilyHandleImpl {
}; };
} // namespace anonymous } // namespace anonymous
TEST(WriteBatchTest, ColumnFamiliesBatchTest) { TEST_F(WriteBatchTest, ColumnFamiliesBatchTest) {
WriteBatch batch; WriteBatch batch;
ColumnFamilyHandleImplDummy zero(0), two(2), three(3), eight(8); ColumnFamilyHandleImplDummy zero(0), two(2), three(3), eight(8);
batch.Put(&zero, Slice("foo"), Slice("bar")); batch.Put(&zero, Slice("foo"), Slice("bar"));
@ -360,7 +360,7 @@ TEST(WriteBatchTest, ColumnFamiliesBatchTest) {
handler.seen); handler.seen);
} }
TEST(WriteBatchTest, ColumnFamiliesBatchWithIndexTest) { TEST_F(WriteBatchTest, ColumnFamiliesBatchWithIndexTest) {
WriteBatchWithIndex batch; WriteBatchWithIndex batch;
ColumnFamilyHandleImplDummy zero(0), two(2), three(3), eight(8); ColumnFamilyHandleImplDummy zero(0), two(2), three(3), eight(8);
batch.Put(&zero, Slice("foo"), Slice("bar")); batch.Put(&zero, Slice("foo"), Slice("bar"));
@ -445,5 +445,6 @@ TEST(WriteBatchTest, ColumnFamiliesBatchWithIndexTest) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { int main(int argc, char** argv) {
return rocksdb::test::RunAllTests(); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} }

@ -9,9 +9,9 @@
namespace rocksdb { namespace rocksdb {
class WriteControllerTest {}; class WriteControllerTest : public testing::Test {};
TEST(WriteControllerTest, SanityTest) { TEST_F(WriteControllerTest, SanityTest) {
WriteController controller; WriteController controller;
auto stop_token_1 = controller.GetStopToken(); auto stop_token_1 = controller.GetStopToken();
auto stop_token_2 = controller.GetStopToken(); auto stop_token_2 = controller.GetStopToken();
@ -37,4 +37,7 @@ TEST(WriteControllerTest, SanityTest) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { return rocksdb::test::RunAllTests(); } int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

@ -43,7 +43,7 @@ class TestHashFilter : public FilterPolicy {
} }
}; };
class FilterBlockTest { class FilterBlockTest : public testing::Test {
public: public:
TestHashFilter policy_; TestHashFilter policy_;
BlockBasedTableOptions table_options_; BlockBasedTableOptions table_options_;
@ -53,7 +53,7 @@ class FilterBlockTest {
} }
}; };
TEST(FilterBlockTest, EmptyBuilder) { TEST_F(FilterBlockTest, EmptyBuilder) {
BlockBasedFilterBlockBuilder builder(nullptr, table_options_); BlockBasedFilterBlockBuilder builder(nullptr, table_options_);
BlockContents block(builder.Finish(), false, kNoCompression); BlockContents block(builder.Finish(), false, kNoCompression);
ASSERT_EQ("\\x00\\x00\\x00\\x00\\x0b", EscapeString(block.data)); ASSERT_EQ("\\x00\\x00\\x00\\x00\\x0b", EscapeString(block.data));
@ -63,7 +63,7 @@ TEST(FilterBlockTest, EmptyBuilder) {
ASSERT_TRUE(reader.KeyMayMatch("foo", 100000)); ASSERT_TRUE(reader.KeyMayMatch("foo", 100000));
} }
TEST(FilterBlockTest, SingleChunk) { TEST_F(FilterBlockTest, SingleChunk) {
BlockBasedFilterBlockBuilder builder(nullptr, table_options_); BlockBasedFilterBlockBuilder builder(nullptr, table_options_);
builder.StartBlock(100); builder.StartBlock(100);
builder.Add("foo"); builder.Add("foo");
@ -85,7 +85,7 @@ TEST(FilterBlockTest, SingleChunk) {
ASSERT_TRUE(!reader.KeyMayMatch("other", 100)); ASSERT_TRUE(!reader.KeyMayMatch("other", 100));
} }
TEST(FilterBlockTest, MultiChunk) { TEST_F(FilterBlockTest, MultiChunk) {
BlockBasedFilterBlockBuilder builder(nullptr, table_options_); BlockBasedFilterBlockBuilder builder(nullptr, table_options_);
// First filter // First filter
@ -136,7 +136,7 @@ TEST(FilterBlockTest, MultiChunk) {
// Test for block based filter block // Test for block based filter block
// use new interface in FilterPolicy to create filter builder/reader // use new interface in FilterPolicy to create filter builder/reader
class BlockBasedFilterBlockTest { class BlockBasedFilterBlockTest : public testing::Test {
public: public:
BlockBasedTableOptions table_options_; BlockBasedTableOptions table_options_;
@ -147,7 +147,7 @@ class BlockBasedFilterBlockTest {
~BlockBasedFilterBlockTest() {} ~BlockBasedFilterBlockTest() {}
}; };
TEST(BlockBasedFilterBlockTest, BlockBasedEmptyBuilder) { TEST_F(BlockBasedFilterBlockTest, BlockBasedEmptyBuilder) {
FilterBlockBuilder* builder = new BlockBasedFilterBlockBuilder( FilterBlockBuilder* builder = new BlockBasedFilterBlockBuilder(
nullptr, table_options_); nullptr, table_options_);
BlockContents block(builder->Finish(), false, kNoCompression); BlockContents block(builder->Finish(), false, kNoCompression);
@ -161,7 +161,7 @@ TEST(BlockBasedFilterBlockTest, BlockBasedEmptyBuilder) {
delete reader; delete reader;
} }
TEST(BlockBasedFilterBlockTest, BlockBasedSingleChunk) { TEST_F(BlockBasedFilterBlockTest, BlockBasedSingleChunk) {
FilterBlockBuilder* builder = new BlockBasedFilterBlockBuilder( FilterBlockBuilder* builder = new BlockBasedFilterBlockBuilder(
nullptr, table_options_); nullptr, table_options_);
builder->StartBlock(100); builder->StartBlock(100);
@ -187,7 +187,7 @@ TEST(BlockBasedFilterBlockTest, BlockBasedSingleChunk) {
delete reader; delete reader;
} }
TEST(BlockBasedFilterBlockTest, BlockBasedMultiChunk) { TEST_F(BlockBasedFilterBlockTest, BlockBasedMultiChunk) {
FilterBlockBuilder* builder = new BlockBasedFilterBlockBuilder( FilterBlockBuilder* builder = new BlockBasedFilterBlockBuilder(
nullptr, table_options_); nullptr, table_options_);
@ -242,4 +242,7 @@ TEST(BlockBasedFilterBlockTest, BlockBasedMultiChunk) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { return rocksdb::test::RunAllTests(); } int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

@ -50,9 +50,9 @@ class MapIterator : public Iterator {
Data::const_iterator pos_; Data::const_iterator pos_;
}; };
class BlockTest {}; class BlockTest : public testing::Test {};
TEST(BlockTest, BasicTest) { TEST_F(BlockTest, BasicTest) {
const size_t keys_per_block = 4; const size_t keys_per_block = 4;
const size_t prefix_size = 2; const size_t prefix_size = 2;
std::vector<std::string> keys = {/* block 1 */ std::vector<std::string> keys = {/* block 1 */
@ -114,4 +114,7 @@ TEST(BlockTest, BasicTest) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { return rocksdb::test::RunAllTests(); } int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

@ -65,10 +65,10 @@ void GenerateRandomKVs(std::vector<std::string> *keys,
} }
} }
class BlockTest {}; class BlockTest : public testing::Test {};
// block test // block test
TEST(BlockTest, SimpleTest) { TEST_F(BlockTest, SimpleTest) {
Random rnd(301); Random rnd(301);
Options options = Options(); Options options = Options();
std::unique_ptr<InternalKeyComparator> ic; std::unique_ptr<InternalKeyComparator> ic;
@ -201,7 +201,7 @@ void CheckBlockContents(BlockContents contents, const int max_key,
} }
// In this test case, no two key share same prefix. // In this test case, no two key share same prefix.
TEST(BlockTest, SimpleIndexHash) { TEST_F(BlockTest, SimpleIndexHash) {
const int kMaxKey = 100000; const int kMaxKey = 100000;
std::vector<std::string> keys; std::vector<std::string> keys;
std::vector<std::string> values; std::vector<std::string> values;
@ -215,7 +215,7 @@ TEST(BlockTest, SimpleIndexHash) {
CheckBlockContents(std::move(contents), kMaxKey, keys, values); CheckBlockContents(std::move(contents), kMaxKey, keys, values);
} }
TEST(BlockTest, IndexHashWithSharedPrefix) { TEST_F(BlockTest, IndexHashWithSharedPrefix) {
const int kMaxKey = 100000; const int kMaxKey = 100000;
// for each prefix, there will be 5 keys starts with it. // for each prefix, there will be 5 keys starts with it.
const int kPrefixGroup = 5; const int kPrefixGroup = 5;
@ -237,5 +237,6 @@ TEST(BlockTest, IndexHashWithSharedPrefix) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char **argv) { int main(int argc, char **argv) {
return rocksdb::test::RunAllTests(); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} }

@ -25,7 +25,7 @@ uint64_t GetSliceHash(const Slice& s, uint32_t index,
} }
} // namespace } // namespace
class CuckooBuilderTest { class CuckooBuilderTest : public testing::Test {
public: public:
CuckooBuilderTest() { CuckooBuilderTest() {
env_ = Env::Default(); env_ = Env::Default();
@ -129,7 +129,7 @@ class CuckooBuilderTest {
const double kHashTableRatio = 0.9; const double kHashTableRatio = 0.9;
}; };
TEST(CuckooBuilderTest, SuccessWithEmptyFile) { TEST_F(CuckooBuilderTest, SuccessWithEmptyFile) {
unique_ptr<WritableFile> writable_file; unique_ptr<WritableFile> writable_file;
fname = test::TmpDir() + "/EmptyFile"; fname = test::TmpDir() + "/EmptyFile";
ASSERT_OK(env_->NewWritableFile(fname, &writable_file, env_options_)); ASSERT_OK(env_->NewWritableFile(fname, &writable_file, env_options_));
@ -142,7 +142,7 @@ TEST(CuckooBuilderTest, SuccessWithEmptyFile) {
CheckFileContents({}, {}, {}, "", 2, 2, false); CheckFileContents({}, {}, {}, "", 2, 2, false);
} }
TEST(CuckooBuilderTest, WriteSuccessNoCollisionFullKey) { TEST_F(CuckooBuilderTest, WriteSuccessNoCollisionFullKey) {
uint32_t num_hash_fun = 4; uint32_t num_hash_fun = 4;
std::vector<std::string> user_keys = {"key01", "key02", "key03", "key04"}; std::vector<std::string> user_keys = {"key01", "key02", "key03", "key04"};
std::vector<std::string> values = {"v01", "v02", "v03", "v04"}; std::vector<std::string> values = {"v01", "v02", "v03", "v04"};
@ -182,7 +182,7 @@ TEST(CuckooBuilderTest, WriteSuccessNoCollisionFullKey) {
expected_unused_bucket, expected_table_size, 2, false); expected_unused_bucket, expected_table_size, 2, false);
} }
TEST(CuckooBuilderTest, WriteSuccessWithCollisionFullKey) { TEST_F(CuckooBuilderTest, WriteSuccessWithCollisionFullKey) {
uint32_t num_hash_fun = 4; uint32_t num_hash_fun = 4;
std::vector<std::string> user_keys = {"key01", "key02", "key03", "key04"}; std::vector<std::string> user_keys = {"key01", "key02", "key03", "key04"};
std::vector<std::string> values = {"v01", "v02", "v03", "v04"}; std::vector<std::string> values = {"v01", "v02", "v03", "v04"};
@ -222,7 +222,7 @@ TEST(CuckooBuilderTest, WriteSuccessWithCollisionFullKey) {
expected_unused_bucket, expected_table_size, 4, false); expected_unused_bucket, expected_table_size, 4, false);
} }
TEST(CuckooBuilderTest, WriteSuccessWithCollisionAndCuckooBlock) { TEST_F(CuckooBuilderTest, WriteSuccessWithCollisionAndCuckooBlock) {
uint32_t num_hash_fun = 4; uint32_t num_hash_fun = 4;
std::vector<std::string> user_keys = {"key01", "key02", "key03", "key04"}; std::vector<std::string> user_keys = {"key01", "key02", "key03", "key04"};
std::vector<std::string> values = {"v01", "v02", "v03", "v04"}; std::vector<std::string> values = {"v01", "v02", "v03", "v04"};
@ -264,7 +264,7 @@ TEST(CuckooBuilderTest, WriteSuccessWithCollisionAndCuckooBlock) {
expected_unused_bucket, expected_table_size, 3, false, cuckoo_block_size); expected_unused_bucket, expected_table_size, 3, false, cuckoo_block_size);
} }
TEST(CuckooBuilderTest, WithCollisionPathFullKey) { TEST_F(CuckooBuilderTest, WithCollisionPathFullKey) {
// Have two hash functions. Insert elements with overlapping hashes. // Have two hash functions. Insert elements with overlapping hashes.
// Finally insert an element with hash value somewhere in the middle // Finally insert an element with hash value somewhere in the middle
// so that it displaces all the elements after that. // so that it displaces all the elements after that.
@ -309,7 +309,7 @@ TEST(CuckooBuilderTest, WithCollisionPathFullKey) {
expected_unused_bucket, expected_table_size, 2, false); expected_unused_bucket, expected_table_size, 2, false);
} }
TEST(CuckooBuilderTest, WithCollisionPathFullKeyAndCuckooBlock) { TEST_F(CuckooBuilderTest, WithCollisionPathFullKeyAndCuckooBlock) {
uint32_t num_hash_fun = 2; uint32_t num_hash_fun = 2;
std::vector<std::string> user_keys = {"key01", "key02", "key03", std::vector<std::string> user_keys = {"key01", "key02", "key03",
"key04", "key05"}; "key04", "key05"};
@ -351,7 +351,7 @@ TEST(CuckooBuilderTest, WithCollisionPathFullKeyAndCuckooBlock) {
expected_unused_bucket, expected_table_size, 2, false, 2); expected_unused_bucket, expected_table_size, 2, false, 2);
} }
TEST(CuckooBuilderTest, WriteSuccessNoCollisionUserKey) { TEST_F(CuckooBuilderTest, WriteSuccessNoCollisionUserKey) {
uint32_t num_hash_fun = 4; uint32_t num_hash_fun = 4;
std::vector<std::string> user_keys = {"key01", "key02", "key03", "key04"}; std::vector<std::string> user_keys = {"key01", "key02", "key03", "key04"};
std::vector<std::string> values = {"v01", "v02", "v03", "v04"}; std::vector<std::string> values = {"v01", "v02", "v03", "v04"};
@ -387,7 +387,7 @@ TEST(CuckooBuilderTest, WriteSuccessNoCollisionUserKey) {
expected_unused_bucket, expected_table_size, 2, true); expected_unused_bucket, expected_table_size, 2, true);
} }
TEST(CuckooBuilderTest, WriteSuccessWithCollisionUserKey) { TEST_F(CuckooBuilderTest, WriteSuccessWithCollisionUserKey) {
uint32_t num_hash_fun = 4; uint32_t num_hash_fun = 4;
std::vector<std::string> user_keys = {"key01", "key02", "key03", "key04"}; std::vector<std::string> user_keys = {"key01", "key02", "key03", "key04"};
std::vector<std::string> values = {"v01", "v02", "v03", "v04"}; std::vector<std::string> values = {"v01", "v02", "v03", "v04"};
@ -423,7 +423,7 @@ TEST(CuckooBuilderTest, WriteSuccessWithCollisionUserKey) {
expected_unused_bucket, expected_table_size, 4, true); expected_unused_bucket, expected_table_size, 4, true);
} }
TEST(CuckooBuilderTest, WithCollisionPathUserKey) { TEST_F(CuckooBuilderTest, WithCollisionPathUserKey) {
uint32_t num_hash_fun = 2; uint32_t num_hash_fun = 2;
std::vector<std::string> user_keys = {"key01", "key02", "key03", std::vector<std::string> user_keys = {"key01", "key02", "key03",
"key04", "key05"}; "key04", "key05"};
@ -461,7 +461,7 @@ TEST(CuckooBuilderTest, WithCollisionPathUserKey) {
expected_unused_bucket, expected_table_size, 2, true); expected_unused_bucket, expected_table_size, 2, true);
} }
TEST(CuckooBuilderTest, FailWhenCollisionPathTooLong) { TEST_F(CuckooBuilderTest, FailWhenCollisionPathTooLong) {
// Have two hash functions. Insert elements with overlapping hashes. // Have two hash functions. Insert elements with overlapping hashes.
// Finally try inserting an element with hash value somewhere in the middle // Finally try inserting an element with hash value somewhere in the middle
// and it should fail because the no. of elements to displace is too high. // and it should fail because the no. of elements to displace is too high.
@ -491,7 +491,7 @@ TEST(CuckooBuilderTest, FailWhenCollisionPathTooLong) {
ASSERT_OK(writable_file->Close()); ASSERT_OK(writable_file->Close());
} }
TEST(CuckooBuilderTest, FailWhenSameKeyInserted) { TEST_F(CuckooBuilderTest, FailWhenSameKeyInserted) {
hash_map = {{"repeatedkey", {0, 1, 2, 3}}}; hash_map = {{"repeatedkey", {0, 1, 2, 3}}};
uint32_t num_hash_fun = 4; uint32_t num_hash_fun = 4;
std::string user_key = "repeatedkey"; std::string user_key = "repeatedkey";
@ -515,4 +515,7 @@ TEST(CuckooBuilderTest, FailWhenSameKeyInserted) {
} }
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { return rocksdb::test::RunAllTests(); } int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

@ -64,8 +64,10 @@ uint64_t GetSliceHash(const Slice& s, uint32_t index,
} // namespace } // namespace
class CuckooReaderTest { class CuckooReaderTest : public testing::Test {
public: public:
using testing::Test::SetUp;
CuckooReaderTest() { CuckooReaderTest() {
options.allow_mmap_reads = true; options.allow_mmap_reads = true;
env = options.env; env = options.env;
@ -208,7 +210,7 @@ class CuckooReaderTest {
EnvOptions env_options; EnvOptions env_options;
}; };
TEST(CuckooReaderTest, WhenKeyExists) { TEST_F(CuckooReaderTest, WhenKeyExists) {
SetUp(kNumHashFunc); SetUp(kNumHashFunc);
fname = test::TmpDir() + "/CuckooReader_WhenKeyExists"; fname = test::TmpDir() + "/CuckooReader_WhenKeyExists";
for (uint64_t i = 0; i < num_items; i++) { for (uint64_t i = 0; i < num_items; i++) {
@ -235,7 +237,7 @@ TEST(CuckooReaderTest, WhenKeyExists) {
CreateCuckooFileAndCheckReader(); CreateCuckooFileAndCheckReader();
} }
TEST(CuckooReaderTest, WhenKeyExistsWithUint64Comparator) { TEST_F(CuckooReaderTest, WhenKeyExistsWithUint64Comparator) {
SetUp(kNumHashFunc); SetUp(kNumHashFunc);
fname = test::TmpDir() + "/CuckooReaderUint64_WhenKeyExists"; fname = test::TmpDir() + "/CuckooReaderUint64_WhenKeyExists";
for (uint64_t i = 0; i < num_items; i++) { for (uint64_t i = 0; i < num_items; i++) {
@ -263,7 +265,7 @@ TEST(CuckooReaderTest, WhenKeyExistsWithUint64Comparator) {
CreateCuckooFileAndCheckReader(test::Uint64Comparator()); CreateCuckooFileAndCheckReader(test::Uint64Comparator());
} }
TEST(CuckooReaderTest, CheckIterator) { TEST_F(CuckooReaderTest, CheckIterator) {
SetUp(2*kNumHashFunc); SetUp(2*kNumHashFunc);
fname = test::TmpDir() + "/CuckooReader_CheckIterator"; fname = test::TmpDir() + "/CuckooReader_CheckIterator";
for (uint64_t i = 0; i < num_items; i++) { for (uint64_t i = 0; i < num_items; i++) {
@ -282,7 +284,7 @@ TEST(CuckooReaderTest, CheckIterator) {
CheckIterator(); CheckIterator();
} }
TEST(CuckooReaderTest, CheckIteratorUint64) { TEST_F(CuckooReaderTest, CheckIteratorUint64) {
SetUp(2*kNumHashFunc); SetUp(2*kNumHashFunc);
fname = test::TmpDir() + "/CuckooReader_CheckIterator"; fname = test::TmpDir() + "/CuckooReader_CheckIterator";
for (uint64_t i = 0; i < num_items; i++) { for (uint64_t i = 0; i < num_items; i++) {
@ -302,7 +304,7 @@ TEST(CuckooReaderTest, CheckIteratorUint64) {
CheckIterator(test::Uint64Comparator()); CheckIterator(test::Uint64Comparator());
} }
TEST(CuckooReaderTest, WhenKeyNotFound) { TEST_F(CuckooReaderTest, WhenKeyNotFound) {
// Add keys with colliding hash values. // Add keys with colliding hash values.
SetUp(kNumHashFunc); SetUp(kNumHashFunc);
fname = test::TmpDir() + "/CuckooReader_WhenKeyNotFound"; fname = test::TmpDir() + "/CuckooReader_WhenKeyNotFound";
@ -503,7 +505,7 @@ void ReadKeys(uint64_t num, uint32_t batch_size) {
} }
} // namespace. } // namespace.
TEST(CuckooReaderTest, TestReadPerformance) { TEST_F(CuckooReaderTest, TestReadPerformance) {
if (!FLAGS_enable_perf) { if (!FLAGS_enable_perf) {
return; return;
} }
@ -534,8 +536,9 @@ TEST(CuckooReaderTest, TestReadPerformance) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
ParseCommandLineFlags(&argc, &argv, true); ParseCommandLineFlags(&argc, &argv, true);
return rocksdb::test::RunAllTests(); return RUN_ALL_TESTS();
} }
#endif // GFLAGS. #endif // GFLAGS.

@ -93,7 +93,7 @@ class TestHashFilter : public FilterPolicy {
} }
}; };
class PluginFullFilterBlockTest { class PluginFullFilterBlockTest : public testing::Test {
public: public:
BlockBasedTableOptions table_options_; BlockBasedTableOptions table_options_;
@ -102,7 +102,7 @@ class PluginFullFilterBlockTest {
} }
}; };
TEST(PluginFullFilterBlockTest, PluginEmptyBuilder) { TEST_F(PluginFullFilterBlockTest, PluginEmptyBuilder) {
FullFilterBlockBuilder builder( FullFilterBlockBuilder builder(
nullptr, true, table_options_.filter_policy->GetFilterBitsBuilder()); nullptr, true, table_options_.filter_policy->GetFilterBitsBuilder());
Slice block = builder.Finish(); Slice block = builder.Finish();
@ -115,7 +115,7 @@ TEST(PluginFullFilterBlockTest, PluginEmptyBuilder) {
ASSERT_TRUE(reader.KeyMayMatch("foo")); ASSERT_TRUE(reader.KeyMayMatch("foo"));
} }
TEST(PluginFullFilterBlockTest, PluginSingleChunk) { TEST_F(PluginFullFilterBlockTest, PluginSingleChunk) {
FullFilterBlockBuilder builder( FullFilterBlockBuilder builder(
nullptr, true, table_options_.filter_policy->GetFilterBitsBuilder()); nullptr, true, table_options_.filter_policy->GetFilterBitsBuilder());
builder.Add("foo"); builder.Add("foo");
@ -136,7 +136,7 @@ TEST(PluginFullFilterBlockTest, PluginSingleChunk) {
ASSERT_TRUE(!reader.KeyMayMatch("other")); ASSERT_TRUE(!reader.KeyMayMatch("other"));
} }
class FullFilterBlockTest { class FullFilterBlockTest : public testing::Test {
public: public:
BlockBasedTableOptions table_options_; BlockBasedTableOptions table_options_;
@ -147,7 +147,7 @@ class FullFilterBlockTest {
~FullFilterBlockTest() {} ~FullFilterBlockTest() {}
}; };
TEST(FullFilterBlockTest, EmptyBuilder) { TEST_F(FullFilterBlockTest, EmptyBuilder) {
FullFilterBlockBuilder builder( FullFilterBlockBuilder builder(
nullptr, true, table_options_.filter_policy->GetFilterBitsBuilder()); nullptr, true, table_options_.filter_policy->GetFilterBitsBuilder());
Slice block = builder.Finish(); Slice block = builder.Finish();
@ -160,7 +160,7 @@ TEST(FullFilterBlockTest, EmptyBuilder) {
ASSERT_TRUE(reader.KeyMayMatch("foo")); ASSERT_TRUE(reader.KeyMayMatch("foo"));
} }
TEST(FullFilterBlockTest, SingleChunk) { TEST_F(FullFilterBlockTest, SingleChunk) {
FullFilterBlockBuilder builder( FullFilterBlockBuilder builder(
nullptr, true, table_options_.filter_policy->GetFilterBitsBuilder()); nullptr, true, table_options_.filter_policy->GetFilterBitsBuilder());
builder.Add("foo"); builder.Add("foo");
@ -183,4 +183,7 @@ TEST(FullFilterBlockTest, SingleChunk) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { return rocksdb::test::RunAllTests(); } int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

@ -44,7 +44,7 @@ class VectorIterator : public Iterator {
size_t current_; size_t current_;
}; };
class MergerTest { class MergerTest : public testing::Test {
public: public:
MergerTest() MergerTest()
: rnd_(3), merging_iterator_(nullptr), single_iterator_(nullptr) {} : rnd_(3), merging_iterator_(nullptr), single_iterator_(nullptr) {}
@ -139,7 +139,7 @@ class MergerTest {
std::vector<std::string> all_keys_; std::vector<std::string> all_keys_;
}; };
TEST(MergerTest, SeekToRandomNextTest) { TEST_F(MergerTest, SeekToRandomNextTest) {
Generate(1000, 50, 50); Generate(1000, 50, 50);
for (int i = 0; i < 10; ++i) { for (int i = 0; i < 10; ++i) {
SeekToRandom(); SeekToRandom();
@ -148,7 +148,7 @@ TEST(MergerTest, SeekToRandomNextTest) {
} }
} }
TEST(MergerTest, SeekToRandomNextSmallStringsTest) { TEST_F(MergerTest, SeekToRandomNextSmallStringsTest) {
Generate(1000, 50, 2); Generate(1000, 50, 2);
for (int i = 0; i < 10; ++i) { for (int i = 0; i < 10; ++i) {
SeekToRandom(); SeekToRandom();
@ -157,7 +157,7 @@ TEST(MergerTest, SeekToRandomNextSmallStringsTest) {
} }
} }
TEST(MergerTest, SeekToRandomPrevTest) { TEST_F(MergerTest, SeekToRandomPrevTest) {
Generate(1000, 50, 50); Generate(1000, 50, 50);
for (int i = 0; i < 10; ++i) { for (int i = 0; i < 10; ++i) {
SeekToRandom(); SeekToRandom();
@ -166,7 +166,7 @@ TEST(MergerTest, SeekToRandomPrevTest) {
} }
} }
TEST(MergerTest, SeekToRandomRandomTest) { TEST_F(MergerTest, SeekToRandomRandomTest) {
Generate(200, 50, 50); Generate(200, 50, 50);
for (int i = 0; i < 3; ++i) { for (int i = 0; i < 3; ++i) {
SeekToRandom(); SeekToRandom();
@ -175,7 +175,7 @@ TEST(MergerTest, SeekToRandomRandomTest) {
} }
} }
TEST(MergerTest, SeekToFirstTest) { TEST_F(MergerTest, SeekToFirstTest) {
Generate(1000, 50, 50); Generate(1000, 50, 50);
for (int i = 0; i < 10; ++i) { for (int i = 0; i < 10; ++i) {
SeekToFirst(); SeekToFirst();
@ -184,7 +184,7 @@ TEST(MergerTest, SeekToFirstTest) {
} }
} }
TEST(MergerTest, SeekToLastTest) { TEST_F(MergerTest, SeekToLastTest) {
Generate(1000, 50, 50); Generate(1000, 50, 50);
for (int i = 0; i < 10; ++i) { for (int i = 0; i < 10; ++i) {
SeekToLast(); SeekToLast();
@ -195,4 +195,7 @@ TEST(MergerTest, SeekToLastTest) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { return rocksdb::test::RunAllTests(); } int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

@ -698,7 +698,7 @@ class FixedOrLessPrefixTransform : public SliceTransform {
} }
}; };
class HarnessTest { class HarnessTest : public testing::Test {
public: public:
HarnessTest() HarnessTest()
: ioptions_(options_), : ioptions_(options_),
@ -1006,7 +1006,7 @@ static bool Between(uint64_t val, uint64_t low, uint64_t high) {
} }
// Tests against all kinds of tables // Tests against all kinds of tables
class TableTest { class TableTest : public testing::Test {
public: public:
const InternalKeyComparator& GetPlainInternalComparator( const InternalKeyComparator& GetPlainInternalComparator(
const Comparator* comp) { const Comparator* comp) {
@ -1024,11 +1024,11 @@ class TableTest {
class GeneralTableTest : public TableTest {}; class GeneralTableTest : public TableTest {};
class BlockBasedTableTest : public TableTest {}; class BlockBasedTableTest : public TableTest {};
class PlainTableTest : public TableTest {}; class PlainTableTest : public TableTest {};
class TablePropertyTest {}; class TablePropertyTest : public testing::Test {};
// This test serves as the living tutorial for the prefix scan of user collected // This test serves as the living tutorial for the prefix scan of user collected
// properties. // properties.
TEST(TablePropertyTest, PrefixScanTest) { TEST_F(TablePropertyTest, PrefixScanTest) {
UserCollectedProperties props{{"num.111.1", "1"}, UserCollectedProperties props{{"num.111.1", "1"},
{"num.111.2", "2"}, {"num.111.2", "2"},
{"num.111.3", "3"}, {"num.111.3", "3"},
@ -1065,7 +1065,7 @@ TEST(TablePropertyTest, PrefixScanTest) {
// This test include all the basic checks except those for index size and block // This test include all the basic checks except those for index size and block
// size, which will be conducted in separated unit tests. // size, which will be conducted in separated unit tests.
TEST(BlockBasedTableTest, BasicBlockBasedTableProperties) { TEST_F(BlockBasedTableTest, BasicBlockBasedTableProperties) {
TableConstructor c(BytewiseComparator()); TableConstructor c(BytewiseComparator());
c.Add("a1", "val1"); c.Add("a1", "val1");
@ -1110,7 +1110,7 @@ TEST(BlockBasedTableTest, BasicBlockBasedTableProperties) {
ASSERT_EQ(content.size() + kBlockTrailerSize, props.data_size); ASSERT_EQ(content.size() + kBlockTrailerSize, props.data_size);
} }
TEST(BlockBasedTableTest, FilterPolicyNameProperties) { TEST_F(BlockBasedTableTest, FilterPolicyNameProperties) {
TableConstructor c(BytewiseComparator(), true); TableConstructor c(BytewiseComparator(), true);
c.Add("a1", "val1"); c.Add("a1", "val1");
std::vector<std::string> keys; std::vector<std::string> keys;
@ -1168,8 +1168,7 @@ void PrefetchRange(TableConstructor* c, Options* opt,
AssertKeysInCache(table_reader, keys_in_cache, keys_not_in_cache); AssertKeysInCache(table_reader, keys_in_cache, keys_not_in_cache);
} }
TEST_F(BlockBasedTableTest, PrefetchTest) {
TEST(BlockBasedTableTest, PrefetchTest) {
// The purpose of this test is to test the prefetching operation built into // The purpose of this test is to test the prefetching operation built into
// BlockBasedTable. // BlockBasedTable.
Options opt; Options opt;
@ -1251,8 +1250,7 @@ TEST(BlockBasedTableTest, PrefetchTest) {
Status::InvalidArgument(Slice("k06 "), Slice("k07"))); Status::InvalidArgument(Slice("k06 "), Slice("k07")));
} }
TEST_F(BlockBasedTableTest, TotalOrderSeekOnHashIndex) {
TEST(BlockBasedTableTest, TotalOrderSeekOnHashIndex) {
BlockBasedTableOptions table_options; BlockBasedTableOptions table_options;
for (int i = 0; i < 4; ++i) { for (int i = 0; i < 4; ++i) {
Options options; Options options;
@ -1349,7 +1347,7 @@ void AddInternalKey(TableConstructor* c, const std::string& prefix,
c->Add(k.Encode().ToString(), "v"); c->Add(k.Encode().ToString(), "v");
} }
TEST(TableTest, HashIndexTest) { TEST_F(TableTest, HashIndexTest) {
TableConstructor c(BytewiseComparator()); TableConstructor c(BytewiseComparator());
// keys with prefix length 3, make sure the key/value is big enough to fill // keys with prefix length 3, make sure the key/value is big enough to fill
@ -1462,7 +1460,7 @@ TEST(TableTest, HashIndexTest) {
// It's very hard to figure out the index block size of a block accurately. // It's very hard to figure out the index block size of a block accurately.
// To make sure we get the index size, we just make sure as key number // To make sure we get the index size, we just make sure as key number
// grows, the filter block size also grows. // grows, the filter block size also grows.
TEST(BlockBasedTableTest, IndexSizeStat) { TEST_F(BlockBasedTableTest, IndexSizeStat) {
uint64_t last_index_size = 0; uint64_t last_index_size = 0;
// we need to use random keys since the pure human readable texts // we need to use random keys since the pure human readable texts
@ -1500,7 +1498,7 @@ TEST(BlockBasedTableTest, IndexSizeStat) {
} }
} }
TEST(BlockBasedTableTest, NumBlockStat) { TEST_F(BlockBasedTableTest, NumBlockStat) {
Random rnd(test::RandomSeed()); Random rnd(test::RandomSeed());
TableConstructor c(BytewiseComparator()); TableConstructor c(BytewiseComparator());
Options options; Options options;
@ -1581,7 +1579,7 @@ class BlockCachePropertiesSnapshot {
// Make sure, by default, index/filter blocks were pre-loaded (meaning we won't // Make sure, by default, index/filter blocks were pre-loaded (meaning we won't
// use block cache to store them). // use block cache to store them).
TEST(BlockBasedTableTest, BlockCacheDisabledTest) { TEST_F(BlockBasedTableTest, BlockCacheDisabledTest) {
Options options; Options options;
options.create_if_missing = true; options.create_if_missing = true;
options.statistics = CreateDBStatistics(); options.statistics = CreateDBStatistics();
@ -1624,7 +1622,7 @@ TEST(BlockBasedTableTest, BlockCacheDisabledTest) {
// Due to the difficulities of the intersaction between statistics, this test // Due to the difficulities of the intersaction between statistics, this test
// only tests the case when "index block is put to block cache" // only tests the case when "index block is put to block cache"
TEST(BlockBasedTableTest, FilterBlockInBlockCache) { TEST_F(BlockBasedTableTest, FilterBlockInBlockCache) {
// -- Table construction // -- Table construction
Options options; Options options;
options.create_if_missing = true; options.create_if_missing = true;
@ -1756,7 +1754,7 @@ TEST(BlockBasedTableTest, FilterBlockInBlockCache) {
props.AssertFilterBlockStat(0, 0); props.AssertFilterBlockStat(0, 0);
} }
TEST(BlockBasedTableTest, BlockCacheLeak) { TEST_F(BlockBasedTableTest, BlockCacheLeak) {
// Check that when we reopen a table we don't lose access to blocks already // Check that when we reopen a table we don't lose access to blocks already
// in the cache. This test checks whether the Table actually makes use of the // in the cache. This test checks whether the Table actually makes use of the
// unique ID from the file. // unique ID from the file.
@ -1811,7 +1809,7 @@ TEST(BlockBasedTableTest, BlockCacheLeak) {
} }
} }
TEST(PlainTableTest, BasicPlainTableProperties) { TEST_F(PlainTableTest, BasicPlainTableProperties) {
PlainTableOptions plain_table_options; PlainTableOptions plain_table_options;
plain_table_options.user_key_len = 8; plain_table_options.user_key_len = 8;
plain_table_options.bloom_bits_per_key = 8; plain_table_options.bloom_bits_per_key = 8;
@ -1851,7 +1849,7 @@ TEST(PlainTableTest, BasicPlainTableProperties) {
ASSERT_EQ(1ul, props->num_data_blocks); ASSERT_EQ(1ul, props->num_data_blocks);
} }
TEST(GeneralTableTest, ApproximateOffsetOfPlain) { TEST_F(GeneralTableTest, ApproximateOffsetOfPlain) {
TableConstructor c(BytewiseComparator()); TableConstructor c(BytewiseComparator());
c.Add("k01", "hello"); c.Add("k01", "hello");
c.Add("k02", "hello2"); c.Add("k02", "hello2");
@ -1910,7 +1908,7 @@ static void DoCompressionTest(CompressionType comp) {
ASSERT_TRUE(Between(c.ApproximateOffsetOf("xyz"), 4000, 6100)); ASSERT_TRUE(Between(c.ApproximateOffsetOf("xyz"), 4000, 6100));
} }
TEST(GeneralTableTest, ApproximateOffsetOfCompressed) { TEST_F(GeneralTableTest, ApproximateOffsetOfCompressed) {
std::vector<CompressionType> compression_state; std::vector<CompressionType> compression_state;
if (!SnappyCompressionSupported()) { if (!SnappyCompressionSupported()) {
fprintf(stderr, "skipping snappy compression tests\n"); fprintf(stderr, "skipping snappy compression tests\n");
@ -1950,7 +1948,7 @@ TEST(GeneralTableTest, ApproximateOffsetOfCompressed) {
} }
} }
TEST(HarnessTest, Randomized) { TEST_F(HarnessTest, Randomized) {
std::vector<TestArgs> args = GenerateArgList(); std::vector<TestArgs> args = GenerateArgList();
for (unsigned int i = 0; i < args.size(); i++) { for (unsigned int i = 0; i < args.size(); i++) {
Init(args[i]); Init(args[i]);
@ -1971,7 +1969,7 @@ TEST(HarnessTest, Randomized) {
} }
} }
TEST(HarnessTest, RandomizedLongDB) { TEST_F(HarnessTest, RandomizedLongDB) {
Random rnd(test::RandomSeed()); Random rnd(test::RandomSeed());
TestArgs args = { DB_TEST, false, 16, kNoCompression, 0 }; TestArgs args = { DB_TEST, false, 16, kNoCompression, 0 };
Init(args); Init(args);
@ -1995,9 +1993,9 @@ TEST(HarnessTest, RandomizedLongDB) {
ASSERT_GT(files, 0); ASSERT_GT(files, 0);
} }
class MemTableTest { }; class MemTableTest : public testing::Test {};
TEST(MemTableTest, Simple) { TEST_F(MemTableTest, Simple) {
InternalKeyComparator cmp(BytewiseComparator()); InternalKeyComparator cmp(BytewiseComparator());
auto table_factory = std::make_shared<SkipListFactory>(); auto table_factory = std::make_shared<SkipListFactory>();
Options options; Options options;
@ -2030,7 +2028,7 @@ TEST(MemTableTest, Simple) {
} }
// Test the empty key // Test the empty key
TEST(HarnessTest, SimpleEmptyKey) { TEST_F(HarnessTest, SimpleEmptyKey) {
auto args = GenerateArgList(); auto args = GenerateArgList();
for (const auto& arg : args) { for (const auto& arg : args) {
Init(arg); Init(arg);
@ -2040,7 +2038,7 @@ TEST(HarnessTest, SimpleEmptyKey) {
} }
} }
TEST(HarnessTest, SimpleSingle) { TEST_F(HarnessTest, SimpleSingle) {
auto args = GenerateArgList(); auto args = GenerateArgList();
for (const auto& arg : args) { for (const auto& arg : args) {
Init(arg); Init(arg);
@ -2050,7 +2048,7 @@ TEST(HarnessTest, SimpleSingle) {
} }
} }
TEST(HarnessTest, SimpleMulti) { TEST_F(HarnessTest, SimpleMulti) {
auto args = GenerateArgList(); auto args = GenerateArgList();
for (const auto& arg : args) { for (const auto& arg : args) {
Init(arg); Init(arg);
@ -2062,7 +2060,7 @@ TEST(HarnessTest, SimpleMulti) {
} }
} }
TEST(HarnessTest, SimpleSpecialKey) { TEST_F(HarnessTest, SimpleSpecialKey) {
auto args = GenerateArgList(); auto args = GenerateArgList();
for (const auto& arg : args) { for (const auto& arg : args) {
Init(arg); Init(arg);
@ -2072,7 +2070,7 @@ TEST(HarnessTest, SimpleSpecialKey) {
} }
} }
TEST(HarnessTest, FooterTests) { TEST_F(HarnessTest, FooterTests) {
{ {
// upconvert legacy block based // upconvert legacy block based
std::string encoded; std::string encoded;
@ -2175,5 +2173,6 @@ TEST(HarnessTest, FooterTests) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { int main(int argc, char** argv) {
return rocksdb::test::RunAllTests(); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} }

@ -13,7 +13,7 @@
namespace rocksdb { namespace rocksdb {
class ReduceLevelTest { class ReduceLevelTest : public testing::Test {
public: public:
ReduceLevelTest() { ReduceLevelTest() {
dbname_ = test::TmpDir() + "/db_reduce_levels_test"; dbname_ = test::TmpDir() + "/db_reduce_levels_test";
@ -94,7 +94,7 @@ bool ReduceLevelTest::ReduceLevels(int target_level) {
return is_succeed; return is_succeed;
} }
TEST(ReduceLevelTest, Last_Level) { TEST_F(ReduceLevelTest, Last_Level) {
// create files on all levels; // create files on all levels;
ASSERT_OK(OpenDB(true, 4, 3)); ASSERT_OK(OpenDB(true, 4, 3));
ASSERT_OK(Put("aaaa", "11111")); ASSERT_OK(Put("aaaa", "11111"));
@ -113,7 +113,7 @@ TEST(ReduceLevelTest, Last_Level) {
CloseDB(); CloseDB();
} }
TEST(ReduceLevelTest, Top_Level) { TEST_F(ReduceLevelTest, Top_Level) {
// create files on all levels; // create files on all levels;
ASSERT_OK(OpenDB(true, 5, 0)); ASSERT_OK(OpenDB(true, 5, 0));
ASSERT_OK(Put("aaaa", "11111")); ASSERT_OK(Put("aaaa", "11111"));
@ -134,7 +134,7 @@ TEST(ReduceLevelTest, Top_Level) {
CloseDB(); CloseDB();
} }
TEST(ReduceLevelTest, All_Levels) { TEST_F(ReduceLevelTest, All_Levels) {
// create files on all levels; // create files on all levels;
ASSERT_OK(OpenDB(true, 5, 1)); ASSERT_OK(OpenDB(true, 5, 1));
ASSERT_OK(Put("a", "a11111")); ASSERT_OK(Put("a", "a11111"));
@ -194,5 +194,6 @@ TEST(ReduceLevelTest, All_Levels) {
} }
int main(int argc, char** argv) { int main(int argc, char** argv) {
return rocksdb::test::RunAllTests(); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} }

@ -16,9 +16,9 @@ namespace rocksdb {
namespace { namespace {
const size_t kHugePageSize = 2 * 1024 * 1024; const size_t kHugePageSize = 2 * 1024 * 1024;
} // namespace } // namespace
class ArenaTest {}; class ArenaTest : public testing::Test {};
TEST(ArenaTest, Empty) { Arena arena0; } TEST_F(ArenaTest, Empty) { Arena arena0; }
namespace { namespace {
void MemoryAllocatedBytesTest(size_t huge_page_size) { void MemoryAllocatedBytesTest(size_t huge_page_size) {
@ -166,20 +166,23 @@ static void SimpleTest(size_t huge_page_size) {
} }
} // namespace } // namespace
TEST(ArenaTest, MemoryAllocatedBytes) { TEST_F(ArenaTest, MemoryAllocatedBytes) {
MemoryAllocatedBytesTest(0); MemoryAllocatedBytesTest(0);
MemoryAllocatedBytesTest(kHugePageSize); MemoryAllocatedBytesTest(kHugePageSize);
} }
TEST(ArenaTest, ApproximateMemoryUsage) { TEST_F(ArenaTest, ApproximateMemoryUsage) {
ApproximateMemoryUsageTest(0); ApproximateMemoryUsageTest(0);
ApproximateMemoryUsageTest(kHugePageSize); ApproximateMemoryUsageTest(kHugePageSize);
} }
TEST(ArenaTest, Simple) { TEST_F(ArenaTest, Simple) {
SimpleTest(0); SimpleTest(0);
SimpleTest(kHugePageSize); SimpleTest(kHugePageSize);
} }
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { return rocksdb::test::RunAllTests(); } int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

@ -20,7 +20,7 @@ using namespace std;
namespace rocksdb { namespace rocksdb {
class AutoRollLoggerTest { class AutoRollLoggerTest : public testing::Test {
public: public:
static void InitTestDb() { static void InitTestDb() {
string deleteCmd = "rm -rf " + kTestDir; string deleteCmd = "rm -rf " + kTestDir;
@ -135,7 +135,7 @@ uint64_t AutoRollLoggerTest::RollLogFileByTimeTest(
return expected_create_time; return expected_create_time;
} }
TEST(AutoRollLoggerTest, RollLogFileBySize) { TEST_F(AutoRollLoggerTest, RollLogFileBySize) {
InitTestDb(); InitTestDb();
size_t log_max_size = 1024 * 5; size_t log_max_size = 1024 * 5;
@ -145,7 +145,7 @@ TEST(AutoRollLoggerTest, RollLogFileBySize) {
kSampleMessage + ":RollLogFileBySize"); kSampleMessage + ":RollLogFileBySize");
} }
TEST(AutoRollLoggerTest, RollLogFileByTime) { TEST_F(AutoRollLoggerTest, RollLogFileByTime) {
size_t time = 2; size_t time = 2;
size_t log_size = 1024 * 5; size_t log_size = 1024 * 5;
@ -158,8 +158,7 @@ TEST(AutoRollLoggerTest, RollLogFileByTime) {
RollLogFileByTimeTest(&logger, time, kSampleMessage + ":RollLogFileByTime"); RollLogFileByTimeTest(&logger, time, kSampleMessage + ":RollLogFileByTime");
} }
TEST(AutoRollLoggerTest, TEST_F(AutoRollLoggerTest, OpenLogFilesMultipleTimesWithOptionLog_max_size) {
OpenLogFilesMultipleTimesWithOptionLog_max_size) {
// If only 'log_max_size' options is specified, then every time // If only 'log_max_size' options is specified, then every time
// when rocksdb is restarted, a new empty log file will be created. // when rocksdb is restarted, a new empty log file will be created.
InitTestDb(); InitTestDb();
@ -184,7 +183,7 @@ TEST(AutoRollLoggerTest,
delete logger; delete logger;
} }
TEST(AutoRollLoggerTest, CompositeRollByTimeAndSizeLogger) { TEST_F(AutoRollLoggerTest, CompositeRollByTimeAndSizeLogger) {
size_t time = 2, log_max_size = 1024 * 5; size_t time = 2, log_max_size = 1024 * 5;
InitTestDb(); InitTestDb();
@ -201,7 +200,7 @@ TEST(AutoRollLoggerTest, CompositeRollByTimeAndSizeLogger) {
kSampleMessage + ":CompositeRollByTimeAndSizeLogger"); kSampleMessage + ":CompositeRollByTimeAndSizeLogger");
} }
TEST(AutoRollLoggerTest, CreateLoggerFromOptions) { TEST_F(AutoRollLoggerTest, CreateLoggerFromOptions) {
DBOptions options; DBOptions options;
shared_ptr<Logger> logger; shared_ptr<Logger> logger;
@ -246,7 +245,7 @@ TEST(AutoRollLoggerTest, CreateLoggerFromOptions) {
kSampleMessage + ":CreateLoggerFromOptions - both"); kSampleMessage + ":CreateLoggerFromOptions - both");
} }
TEST(AutoRollLoggerTest, InfoLogLevel) { TEST_F(AutoRollLoggerTest, InfoLogLevel) {
InitTestDb(); InitTestDb();
size_t log_size = 8192; size_t log_size = 8192;
@ -325,7 +324,7 @@ static size_t GetLinesCount(const string& fname, const string& pattern) {
return count; return count;
} }
TEST(AutoRollLoggerTest, LogHeaderTest) { TEST_F(AutoRollLoggerTest, LogHeaderTest) {
static const size_t MAX_HEADERS = 10; static const size_t MAX_HEADERS = 10;
static const size_t LOG_MAX_SIZE = 1024 * 5; static const size_t LOG_MAX_SIZE = 1024 * 5;
static const std::string HEADER_STR = "Log header line"; static const std::string HEADER_STR = "Log header line";
@ -368,7 +367,7 @@ TEST(AutoRollLoggerTest, LogHeaderTest) {
} }
} }
TEST(AutoRollLoggerTest, LogFileExistence) { TEST_F(AutoRollLoggerTest, LogFileExistence) {
rocksdb::DB* db; rocksdb::DB* db;
rocksdb::Options options; rocksdb::Options options;
string deleteCmd = "rm -rf " + kTestDir; string deleteCmd = "rm -rf " + kTestDir;
@ -383,5 +382,6 @@ TEST(AutoRollLoggerTest, LogFileExistence) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { int main(int argc, char** argv) {
return rocksdb::test::RunAllTests(); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} }

@ -16,10 +16,10 @@ namespace rocksdb {
using namespace std; using namespace std;
class AutoVectorTest { }; class AutoVectorTest : public testing::Test {};
const unsigned long kSize = 8; const unsigned long kSize = 8;
TEST(AutoVectorTest, PushBackAndPopBack) { TEST_F(AutoVectorTest, PushBackAndPopBack) {
autovector<size_t, kSize> vec; autovector<size_t, kSize> vec;
ASSERT_TRUE(vec.empty()); ASSERT_TRUE(vec.empty());
ASSERT_EQ(0ul, vec.size()); ASSERT_EQ(0ul, vec.size());
@ -48,7 +48,7 @@ TEST(AutoVectorTest, PushBackAndPopBack) {
ASSERT_TRUE(vec.empty()); ASSERT_TRUE(vec.empty());
} }
TEST(AutoVectorTest, EmplaceBack) { TEST_F(AutoVectorTest, EmplaceBack) {
typedef std::pair<size_t, std::string> ValType; typedef std::pair<size_t, std::string> ValType;
autovector<ValType, kSize> vec; autovector<ValType, kSize> vec;
@ -71,7 +71,7 @@ TEST(AutoVectorTest, EmplaceBack) {
ASSERT_TRUE(!vec.only_in_stack()); ASSERT_TRUE(!vec.only_in_stack());
} }
TEST(AutoVectorTest, Resize) { TEST_F(AutoVectorTest, Resize) {
autovector<size_t, kSize> vec; autovector<size_t, kSize> vec;
vec.resize(kSize); vec.resize(kSize);
@ -105,7 +105,7 @@ void AssertEqual(
} }
} // namespace } // namespace
TEST(AutoVectorTest, CopyAndAssignment) { TEST_F(AutoVectorTest, CopyAndAssignment) {
// Test both heap-allocated and stack-allocated cases. // Test both heap-allocated and stack-allocated cases.
for (auto size : { kSize / 2, kSize * 1000 }) { for (auto size : { kSize / 2, kSize * 1000 }) {
autovector<size_t, kSize> vec; autovector<size_t, kSize> vec;
@ -126,7 +126,7 @@ TEST(AutoVectorTest, CopyAndAssignment) {
} }
} }
TEST(AutoVectorTest, Iterators) { TEST_F(AutoVectorTest, Iterators) {
autovector<std::string, kSize> vec; autovector<std::string, kSize> vec;
for (size_t i = 0; i < kSize * 1000; ++i) { for (size_t i = 0; i < kSize * 1000; ++i) {
vec.push_back(ToString(i)); vec.push_back(ToString(i));
@ -246,7 +246,7 @@ size_t BenchmarkSequenceAccess(string name, size_t ops, size_t elem_size) {
// This test case only reports the performance between std::vector<string> // This test case only reports the performance between std::vector<string>
// and autovector<string>. We chose string for comparison because in most // and autovector<string>. We chose string for comparison because in most
// o our use cases we used std::vector<string>. // o our use cases we used std::vector<string>.
TEST(AutoVectorTest, PerfBench) { TEST_F(AutoVectorTest, PerfBench) {
// We run same operations for kOps times in order to get a more fair result. // We run same operations for kOps times in order to get a more fair result.
size_t kOps = 100000; size_t kOps = 100000;
@ -313,5 +313,6 @@ TEST(AutoVectorTest, PerfBench) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { int main(int argc, char** argv) {
return rocksdb::test::RunAllTests(); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} }

@ -50,7 +50,7 @@ static int NextLength(int length) {
return length; return length;
} }
class BloomTest { class BloomTest : public testing::Test {
private: private:
const FilterPolicy* policy_; const FilterPolicy* policy_;
std::string filter_; std::string filter_;
@ -119,12 +119,12 @@ class BloomTest {
} }
}; };
TEST(BloomTest, EmptyFilter) { TEST_F(BloomTest, EmptyFilter) {
ASSERT_TRUE(! Matches("hello")); ASSERT_TRUE(! Matches("hello"));
ASSERT_TRUE(! Matches("world")); ASSERT_TRUE(! Matches("world"));
} }
TEST(BloomTest, Small) { TEST_F(BloomTest, Small) {
Add("hello"); Add("hello");
Add("world"); Add("world");
ASSERT_TRUE(Matches("hello")); ASSERT_TRUE(Matches("hello"));
@ -133,7 +133,7 @@ TEST(BloomTest, Small) {
ASSERT_TRUE(! Matches("foo")); ASSERT_TRUE(! Matches("foo"));
} }
TEST(BloomTest, VaryingLengths) { TEST_F(BloomTest, VaryingLengths) {
char buffer[sizeof(int)]; char buffer[sizeof(int)];
// Count number of filters that significantly exceed the false positive rate // Count number of filters that significantly exceed the false positive rate
@ -174,7 +174,7 @@ TEST(BloomTest, VaryingLengths) {
// Different bits-per-byte // Different bits-per-byte
class FullBloomTest { class FullBloomTest : public testing::Test {
private: private:
const FilterPolicy* policy_; const FilterPolicy* policy_;
std::unique_ptr<FilterBitsBuilder> bits_builder_; std::unique_ptr<FilterBitsBuilder> bits_builder_;
@ -233,13 +233,13 @@ class FullBloomTest {
} }
}; };
TEST(FullBloomTest, FullEmptyFilter) { TEST_F(FullBloomTest, FullEmptyFilter) {
// Empty filter is not match, at this level // Empty filter is not match, at this level
ASSERT_TRUE(!Matches("hello")); ASSERT_TRUE(!Matches("hello"));
ASSERT_TRUE(!Matches("world")); ASSERT_TRUE(!Matches("world"));
} }
TEST(FullBloomTest, FullSmall) { TEST_F(FullBloomTest, FullSmall) {
Add("hello"); Add("hello");
Add("world"); Add("world");
ASSERT_TRUE(Matches("hello")); ASSERT_TRUE(Matches("hello"));
@ -248,7 +248,7 @@ TEST(FullBloomTest, FullSmall) {
ASSERT_TRUE(!Matches("foo")); ASSERT_TRUE(!Matches("foo"));
} }
TEST(FullBloomTest, FullVaryingLengths) { TEST_F(FullBloomTest, FullVaryingLengths) {
char buffer[sizeof(int)]; char buffer[sizeof(int)];
// Count number of filters that significantly exceed the false positive rate // Count number of filters that significantly exceed the false positive rate
@ -292,9 +292,10 @@ TEST(FullBloomTest, FullVaryingLengths) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
ParseCommandLineFlags(&argc, &argv, true); ParseCommandLineFlags(&argc, &argv, true);
return rocksdb::test::RunAllTests(); return RUN_ALL_TESTS();
} }
#endif // GFLAGS #endif // GFLAGS

@ -32,7 +32,7 @@ static int DecodeValue(void* v) {
return static_cast<int>(reinterpret_cast<uintptr_t>(v)); return static_cast<int>(reinterpret_cast<uintptr_t>(v));
} }
class CacheTest { class CacheTest : public testing::Test {
public: public:
static CacheTest* current_; static CacheTest* current_;
@ -113,7 +113,7 @@ namespace {
void dumbDeleter(const Slice& key, void* value) { } void dumbDeleter(const Slice& key, void* value) { }
} // namespace } // namespace
TEST(CacheTest, UsageTest) { TEST_F(CacheTest, UsageTest) {
// cache is shared_ptr and will be automatically cleaned up. // cache is shared_ptr and will be automatically cleaned up.
const uint64_t kCapacity = 100000; const uint64_t kCapacity = 100000;
auto cache = NewLRUCache(kCapacity, 8, 200); auto cache = NewLRUCache(kCapacity, 8, 200);
@ -144,7 +144,7 @@ TEST(CacheTest, UsageTest) {
ASSERT_LT(kCapacity * 0.95, cache->GetUsage()); ASSERT_LT(kCapacity * 0.95, cache->GetUsage());
} }
TEST(CacheTest, HitAndMiss) { TEST_F(CacheTest, HitAndMiss) {
ASSERT_EQ(-1, Lookup(100)); ASSERT_EQ(-1, Lookup(100));
Insert(100, 101); Insert(100, 101);
@ -167,7 +167,7 @@ TEST(CacheTest, HitAndMiss) {
ASSERT_EQ(101, deleted_values_[0]); ASSERT_EQ(101, deleted_values_[0]);
} }
TEST(CacheTest, Erase) { TEST_F(CacheTest, Erase) {
Erase(200); Erase(200);
ASSERT_EQ(0U, deleted_keys_.size()); ASSERT_EQ(0U, deleted_keys_.size());
@ -186,7 +186,7 @@ TEST(CacheTest, Erase) {
ASSERT_EQ(1U, deleted_keys_.size()); ASSERT_EQ(1U, deleted_keys_.size());
} }
TEST(CacheTest, EntriesArePinned) { TEST_F(CacheTest, EntriesArePinned) {
Insert(100, 101); Insert(100, 101);
Cache::Handle* h1 = cache_->Lookup(EncodeKey(100)); Cache::Handle* h1 = cache_->Lookup(EncodeKey(100));
ASSERT_EQ(101, DecodeValue(cache_->Value(h1))); ASSERT_EQ(101, DecodeValue(cache_->Value(h1)));
@ -216,7 +216,7 @@ TEST(CacheTest, EntriesArePinned) {
ASSERT_EQ(0U, cache_->GetUsage()); ASSERT_EQ(0U, cache_->GetUsage());
} }
TEST(CacheTest, EvictionPolicy) { TEST_F(CacheTest, EvictionPolicy) {
Insert(100, 101); Insert(100, 101);
Insert(200, 201); Insert(200, 201);
@ -230,7 +230,7 @@ TEST(CacheTest, EvictionPolicy) {
ASSERT_EQ(-1, Lookup(200)); ASSERT_EQ(-1, Lookup(200));
} }
TEST(CacheTest, EvictionPolicyRef) { TEST_F(CacheTest, EvictionPolicyRef) {
Insert(100, 101); Insert(100, 101);
Insert(101, 102); Insert(101, 102);
Insert(102, 103); Insert(102, 103);
@ -278,7 +278,7 @@ TEST(CacheTest, EvictionPolicyRef) {
cache_->Release(h204); cache_->Release(h204);
} }
TEST(CacheTest, ErasedHandleState) { TEST_F(CacheTest, ErasedHandleState) {
// insert a key and get two handles // insert a key and get two handles
Insert(100, 1000); Insert(100, 1000);
Cache::Handle* h1 = cache_->Lookup(EncodeKey(100)); Cache::Handle* h1 = cache_->Lookup(EncodeKey(100));
@ -300,7 +300,7 @@ TEST(CacheTest, ErasedHandleState) {
cache_->Release(h2); cache_->Release(h2);
} }
TEST(CacheTest, HeavyEntries) { TEST_F(CacheTest, HeavyEntries) {
// Add a bunch of light and heavy entries and then count the combined // Add a bunch of light and heavy entries and then count the combined
// size of items still in the cache, which must be approximately the // size of items still in the cache, which must be approximately the
// same as the total capacity. // same as the total capacity.
@ -327,7 +327,7 @@ TEST(CacheTest, HeavyEntries) {
ASSERT_LE(cached_weight, kCacheSize + kCacheSize/10); ASSERT_LE(cached_weight, kCacheSize + kCacheSize/10);
} }
TEST(CacheTest, NewId) { TEST_F(CacheTest, NewId) {
uint64_t a = cache_->NewId(); uint64_t a = cache_->NewId();
uint64_t b = cache_->NewId(); uint64_t b = cache_->NewId();
ASSERT_NE(a, b); ASSERT_NE(a, b);
@ -349,7 +349,7 @@ void deleter(const Slice& key, void* value) {
} }
} // namespace } // namespace
TEST(CacheTest, OverCapacity) { TEST_F(CacheTest, OverCapacity) {
size_t n = 10; size_t n = 10;
// a LRUCache with n entries and one shard only // a LRUCache with n entries and one shard only
@ -403,7 +403,7 @@ void callback(void* entry, size_t charge) {
} }
}; };
TEST(CacheTest, ApplyToAllCacheEntiresTest) { TEST_F(CacheTest, ApplyToAllCacheEntiresTest) {
std::vector<std::pair<int, int>> inserted; std::vector<std::pair<int, int>> inserted;
callback_state.clear(); callback_state.clear();
@ -421,5 +421,6 @@ TEST(CacheTest, ApplyToAllCacheEntiresTest) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { int main(int argc, char** argv) {
return rocksdb::test::RunAllTests(); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} }

@ -199,5 +199,6 @@ TEST(Coding, Strings) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { int main(int argc, char** argv) {
return rocksdb::test::RunAllTests(); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} }

@ -73,5 +73,6 @@ TEST(CRC, Mask) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { int main(int argc, char** argv) {
return rocksdb::test::RunAllTests(); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} }

@ -40,10 +40,9 @@ static Slice Key(uint64_t i, char* buffer) {
return Slice(buffer, sizeof(i)); return Slice(buffer, sizeof(i));
} }
class DynamicBloomTest { class DynamicBloomTest : public testing::Test {};
};
TEST(DynamicBloomTest, EmptyFilter) { TEST_F(DynamicBloomTest, EmptyFilter) {
Arena arena; Arena arena;
DynamicBloom bloom1(&arena, 100, 0, 2); DynamicBloom bloom1(&arena, 100, 0, 2);
ASSERT_TRUE(!bloom1.MayContain("hello")); ASSERT_TRUE(!bloom1.MayContain("hello"));
@ -54,7 +53,7 @@ TEST(DynamicBloomTest, EmptyFilter) {
ASSERT_TRUE(!bloom2.MayContain("world")); ASSERT_TRUE(!bloom2.MayContain("world"));
} }
TEST(DynamicBloomTest, Small) { TEST_F(DynamicBloomTest, Small) {
Arena arena; Arena arena;
DynamicBloom bloom1(&arena, 100, 0, 2); DynamicBloom bloom1(&arena, 100, 0, 2);
bloom1.Add("hello"); bloom1.Add("hello");
@ -86,7 +85,7 @@ static uint32_t NextNum(uint32_t num) {
return num; return num;
} }
TEST(DynamicBloomTest, VaryingLengths) { TEST_F(DynamicBloomTest, VaryingLengths) {
char buffer[sizeof(uint64_t)]; char buffer[sizeof(uint64_t)];
// Count number of filters that significantly exceed the false positive rate // Count number of filters that significantly exceed the false positive rate
@ -146,7 +145,7 @@ TEST(DynamicBloomTest, VaryingLengths) {
} }
} }
TEST(DynamicBloomTest, perf) { TEST_F(DynamicBloomTest, perf) {
StopWatchNano timer(Env::Default()); StopWatchNano timer(Env::Default());
uint32_t num_probes = static_cast<uint32_t>(FLAGS_num_probes); uint32_t num_probes = static_cast<uint32_t>(FLAGS_num_probes);
@ -215,9 +214,10 @@ TEST(DynamicBloomTest, perf) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
ParseCommandLineFlags(&argc, &argv, true); ParseCommandLineFlags(&argc, &argv, true);
return rocksdb::test::RunAllTests(); return RUN_ALL_TESTS();
} }
#endif // GFLAGS #endif // GFLAGS

@ -34,7 +34,7 @@ namespace rocksdb {
static const int kDelayMicros = 100000; static const int kDelayMicros = 100000;
class EnvPosixTest { class EnvPosixTest : public testing::Test {
private: private:
port::Mutex mu_; port::Mutex mu_;
std::string events_; std::string events_;
@ -89,14 +89,14 @@ class SleepingBackgroundTask {
bool sleeping_; bool sleeping_;
}; };
TEST(EnvPosixTest, RunImmediately) { TEST_F(EnvPosixTest, RunImmediately) {
std::atomic<bool> called(false); std::atomic<bool> called(false);
env_->Schedule(&SetBool, &called); env_->Schedule(&SetBool, &called);
Env::Default()->SleepForMicroseconds(kDelayMicros); Env::Default()->SleepForMicroseconds(kDelayMicros);
ASSERT_TRUE(called.load(std::memory_order_relaxed)); ASSERT_TRUE(called.load(std::memory_order_relaxed));
} }
TEST(EnvPosixTest, UnSchedule) { TEST_F(EnvPosixTest, UnSchedule) {
std::atomic<bool> called(false); std::atomic<bool> called(false);
env_->SetBackgroundThreads(1, Env::LOW); env_->SetBackgroundThreads(1, Env::LOW);
@ -124,7 +124,7 @@ TEST(EnvPosixTest, UnSchedule) {
ASSERT_TRUE(called.load(std::memory_order_relaxed)); ASSERT_TRUE(called.load(std::memory_order_relaxed));
} }
TEST(EnvPosixTest, RunMany) { TEST_F(EnvPosixTest, RunMany) {
std::atomic<int> last_id(0); std::atomic<int> last_id(0);
struct CB { struct CB {
@ -170,7 +170,7 @@ static void ThreadBody(void* arg) {
s->mu.Unlock(); s->mu.Unlock();
} }
TEST(EnvPosixTest, StartThread) { TEST_F(EnvPosixTest, StartThread) {
State state; State state;
state.val = 0; state.val = 0;
state.num_running = 3; state.num_running = 3;
@ -189,8 +189,7 @@ TEST(EnvPosixTest, StartThread) {
ASSERT_EQ(state.val, 3); ASSERT_EQ(state.val, 3);
} }
TEST(EnvPosixTest, TwoPools) { TEST_F(EnvPosixTest, TwoPools) {
class CB { class CB {
public: public:
CB(const std::string& pool_name, int pool_size) CB(const std::string& pool_name, int pool_size)
@ -307,7 +306,7 @@ TEST(EnvPosixTest, TwoPools) {
env_->SetBackgroundThreads(kHighPoolSize, Env::Priority::HIGH); env_->SetBackgroundThreads(kHighPoolSize, Env::Priority::HIGH);
} }
TEST(EnvPosixTest, DecreaseNumBgThreads) { TEST_F(EnvPosixTest, DecreaseNumBgThreads) {
std::vector<SleepingBackgroundTask> tasks(10); std::vector<SleepingBackgroundTask> tasks(10);
// Set number of thread to 1 first. // Set number of thread to 1 first.
@ -502,7 +501,7 @@ std::string GetOnDiskTestDir() {
} // namespace } // namespace
// Only works in linux platforms // Only works in linux platforms
TEST(EnvPosixTest, RandomAccessUniqueID) { TEST_F(EnvPosixTest, RandomAccessUniqueID) {
// Create file. // Create file.
const EnvOptions soptions; const EnvOptions soptions;
std::string fname = GetOnDiskTestDir() + "/" + "testfile"; std::string fname = GetOnDiskTestDir() + "/" + "testfile";
@ -543,7 +542,7 @@ TEST(EnvPosixTest, RandomAccessUniqueID) {
// only works in linux platforms // only works in linux platforms
#ifdef ROCKSDB_FALLOCATE_PRESENT #ifdef ROCKSDB_FALLOCATE_PRESENT
TEST(EnvPosixTest, AllocateTest) { TEST_F(EnvPosixTest, AllocateTest) {
std::string fname = GetOnDiskTestDir() + "/preallocate_testfile"; std::string fname = GetOnDiskTestDir() + "/preallocate_testfile";
// Try fallocate in a file to see whether the target file system supports it. // Try fallocate in a file to see whether the target file system supports it.
@ -622,7 +621,7 @@ bool HasPrefix(const std::unordered_set<std::string>& ss) {
} }
// Only works in linux platforms // Only works in linux platforms
TEST(EnvPosixTest, RandomAccessUniqueIDConcurrent) { TEST_F(EnvPosixTest, RandomAccessUniqueIDConcurrent) {
// Check whether a bunch of concurrently existing files have unique IDs. // Check whether a bunch of concurrently existing files have unique IDs.
const EnvOptions soptions; const EnvOptions soptions;
@ -661,7 +660,7 @@ TEST(EnvPosixTest, RandomAccessUniqueIDConcurrent) {
} }
// Only works in linux platforms // Only works in linux platforms
TEST(EnvPosixTest, RandomAccessUniqueIDDeletes) { TEST_F(EnvPosixTest, RandomAccessUniqueIDDeletes) {
const EnvOptions soptions; const EnvOptions soptions;
std::string fname = GetOnDiskTestDir() + "/" + "testfile"; std::string fname = GetOnDiskTestDir() + "/" + "testfile";
@ -697,7 +696,7 @@ TEST(EnvPosixTest, RandomAccessUniqueIDDeletes) {
} }
// Only works in linux platforms // Only works in linux platforms
TEST(EnvPosixTest, InvalidateCache) { TEST_F(EnvPosixTest, InvalidateCache) {
const EnvOptions soptions; const EnvOptions soptions;
std::string fname = test::TmpDir() + "/" + "testfile"; std::string fname = test::TmpDir() + "/" + "testfile";
@ -739,7 +738,7 @@ TEST(EnvPosixTest, InvalidateCache) {
#endif // not TRAVIS #endif // not TRAVIS
#endif // OS_LINUX #endif // OS_LINUX
TEST(EnvPosixTest, PosixRandomRWFileTest) { TEST_F(EnvPosixTest, PosixRandomRWFileTest) {
EnvOptions soptions; EnvOptions soptions;
soptions.use_mmap_writes = soptions.use_mmap_reads = false; soptions.use_mmap_writes = soptions.use_mmap_reads = false;
std::string fname = test::TmpDir() + "/" + "testfile"; std::string fname = test::TmpDir() + "/" + "testfile";
@ -797,7 +796,7 @@ class TestLogger : public Logger {
int char_0_count; int char_0_count;
}; };
TEST(EnvPosixTest, LogBufferTest) { TEST_F(EnvPosixTest, LogBufferTest) {
TestLogger test_logger; TestLogger test_logger;
test_logger.SetInfoLogLevel(InfoLogLevel::INFO_LEVEL); test_logger.SetInfoLogLevel(InfoLogLevel::INFO_LEVEL);
test_logger.log_count = 0; test_logger.log_count = 0;
@ -855,7 +854,7 @@ class TestLogger2 : public Logger {
size_t max_log_size_; size_t max_log_size_;
}; };
TEST(EnvPosixTest, LogBufferMaxSizeTest) { TEST_F(EnvPosixTest, LogBufferMaxSizeTest) {
char bytes9000[9000]; char bytes9000[9000];
std::fill_n(bytes9000, sizeof(bytes9000), '1'); std::fill_n(bytes9000, sizeof(bytes9000), '1');
bytes9000[sizeof(bytes9000) - 1] = '\0'; bytes9000[sizeof(bytes9000) - 1] = '\0';
@ -870,7 +869,7 @@ TEST(EnvPosixTest, LogBufferMaxSizeTest) {
} }
} }
TEST(EnvPosixTest, Preallocation) { TEST_F(EnvPosixTest, Preallocation) {
const std::string src = test::TmpDir() + "/" + "testfile"; const std::string src = test::TmpDir() + "/" + "testfile";
unique_ptr<WritableFile> srcfile; unique_ptr<WritableFile> srcfile;
const EnvOptions soptions; const EnvOptions soptions;
@ -903,5 +902,6 @@ TEST(EnvPosixTest, Preallocation) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { int main(int argc, char** argv) {
return rocksdb::test::RunAllTests(); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} }

@ -10,7 +10,7 @@
namespace rocksdb { namespace rocksdb {
class EventLoggerTest {}; class EventLoggerTest : public testing::Test {};
class StringLogger : public Logger { class StringLogger : public Logger {
public: public:
@ -24,7 +24,7 @@ class StringLogger : public Logger {
char buffer_[1000]; char buffer_[1000];
}; };
TEST(EventLoggerTest, SimpleTest) { TEST_F(EventLoggerTest, SimpleTest) {
StringLogger logger; StringLogger logger;
EventLogger event_logger(&logger); EventLogger event_logger(&logger);
event_logger.Log() << "id" << 5 << "event" event_logger.Log() << "id" << 5 << "event"
@ -38,5 +38,6 @@ TEST(EventLoggerTest, SimpleTest) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { int main(int argc, char** argv) {
return rocksdb::test::RunAllTests(); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} }

@ -12,7 +12,7 @@
namespace rocksdb { namespace rocksdb {
class LockTest { class LockTest : public testing::Test {
public: public:
static LockTest* current_; static LockTest* current_;
std::string file_; std::string file_;
@ -36,7 +36,7 @@ class LockTest {
}; };
LockTest* LockTest::current_; LockTest* LockTest::current_;
TEST(LockTest, LockBySameThread) { TEST_F(LockTest, LockBySameThread) {
FileLock* lock1; FileLock* lock1;
FileLock* lock2; FileLock* lock2;
@ -54,5 +54,6 @@ TEST(LockTest, LockBySameThread) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { int main(int argc, char** argv) {
return rocksdb::test::RunAllTests(); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} }

@ -9,10 +9,9 @@
namespace rocksdb { namespace rocksdb {
class HistogramTest { }; class HistogramTest : public testing::Test {};
TEST(HistogramTest, BasicOperation) {
TEST_F(HistogramTest, BasicOperation) {
HistogramImpl histogram; HistogramImpl histogram;
for (uint64_t i = 1; i <= 100; i++) { for (uint64_t i = 1; i <= 100; i++) {
histogram.Add(i); histogram.Add(i);
@ -37,14 +36,14 @@ TEST(HistogramTest, BasicOperation) {
ASSERT_EQ(histogram.Average(), 50.5); // avg is acurately caluclated. ASSERT_EQ(histogram.Average(), 50.5); // avg is acurately caluclated.
} }
TEST(HistogramTest, EmptyHistogram) { TEST_F(HistogramTest, EmptyHistogram) {
HistogramImpl histogram; HistogramImpl histogram;
ASSERT_EQ(histogram.Median(), 0.0); ASSERT_EQ(histogram.Median(), 0.0);
ASSERT_EQ(histogram.Percentile(85.0), 0.0); ASSERT_EQ(histogram.Percentile(85.0), 0.0);
ASSERT_EQ(histogram.Average(), 0.0); ASSERT_EQ(histogram.Average(), 0.0);
} }
TEST(HistogramTest, ClearHistogram) { TEST_F(HistogramTest, ClearHistogram) {
HistogramImpl histogram; HistogramImpl histogram;
for (uint64_t i = 1; i <= 100; i++) { for (uint64_t i = 1; i <= 100; i++) {
histogram.Add(i); histogram.Add(i);
@ -58,5 +57,6 @@ TEST(HistogramTest, ClearHistogram) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { int main(int argc, char** argv) {
return rocksdb::test::RunAllTests(); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} }

@ -30,7 +30,7 @@ std::string Key2(int i) {
return Key1(i) + "_xxx"; return Key1(i) + "_xxx";
} }
class ManualCompactionTest { class ManualCompactionTest : public testing::Test {
public: public:
ManualCompactionTest() { ManualCompactionTest() {
// Get rid of any state from an old run. // Get rid of any state from an old run.
@ -56,7 +56,7 @@ class DestroyAllCompactionFilter : public CompactionFilter {
} }
}; };
TEST(ManualCompactionTest, CompactTouchesAllKeys) { TEST_F(ManualCompactionTest, CompactTouchesAllKeys) {
for (int iter = 0; iter < 2; ++iter) { for (int iter = 0; iter < 2; ++iter) {
DB* db; DB* db;
Options options; Options options;
@ -92,8 +92,7 @@ TEST(ManualCompactionTest, CompactTouchesAllKeys) {
} }
} }
TEST(ManualCompactionTest, Test) { TEST_F(ManualCompactionTest, Test) {
// Open database. Disable compression since it affects the creation // Open database. Disable compression since it affects the creation
// of layers and the code below is trying to test against a very // of layers and the code below is trying to test against a very
// specific scenario. // specific scenario.
@ -150,5 +149,6 @@ TEST(ManualCompactionTest, Test) {
} // anonymous namespace } // anonymous namespace
int main(int argc, char** argv) { int main(int argc, char** argv) {
return rocksdb::test::RunAllTests(); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} }

@ -12,7 +12,7 @@
namespace rocksdb { namespace rocksdb {
class MemEnvTest { class MemEnvTest : public testing::Test {
public: public:
Env* env_; Env* env_;
const EnvOptions soptions_; const EnvOptions soptions_;
@ -25,7 +25,7 @@ class MemEnvTest {
} }
}; };
TEST(MemEnvTest, Basics) { TEST_F(MemEnvTest, Basics) {
uint64_t file_size; uint64_t file_size;
unique_ptr<WritableFile> writable_file; unique_ptr<WritableFile> writable_file;
std::vector<std::string> children; std::vector<std::string> children;
@ -86,7 +86,7 @@ TEST(MemEnvTest, Basics) {
ASSERT_OK(env_->DeleteDir("/dir")); ASSERT_OK(env_->DeleteDir("/dir"));
} }
TEST(MemEnvTest, ReadWrite) { TEST_F(MemEnvTest, ReadWrite) {
unique_ptr<WritableFile> writable_file; unique_ptr<WritableFile> writable_file;
unique_ptr<SequentialFile> seq_file; unique_ptr<SequentialFile> seq_file;
unique_ptr<RandomAccessFile> rand_file; unique_ptr<RandomAccessFile> rand_file;
@ -126,7 +126,7 @@ TEST(MemEnvTest, ReadWrite) {
ASSERT_TRUE(!rand_file->Read(1000, 5, &result, scratch).ok()); ASSERT_TRUE(!rand_file->Read(1000, 5, &result, scratch).ok());
} }
TEST(MemEnvTest, Locks) { TEST_F(MemEnvTest, Locks) {
FileLock* lock; FileLock* lock;
// These are no-ops, but we test they return success. // These are no-ops, but we test they return success.
@ -134,7 +134,7 @@ TEST(MemEnvTest, Locks) {
ASSERT_OK(env_->UnlockFile(lock)); ASSERT_OK(env_->UnlockFile(lock));
} }
TEST(MemEnvTest, Misc) { TEST_F(MemEnvTest, Misc) {
std::string test_dir; std::string test_dir;
ASSERT_OK(env_->GetTestDirectory(&test_dir)); ASSERT_OK(env_->GetTestDirectory(&test_dir));
ASSERT_TRUE(!test_dir.empty()); ASSERT_TRUE(!test_dir.empty());
@ -149,7 +149,7 @@ TEST(MemEnvTest, Misc) {
writable_file.reset(); writable_file.reset();
} }
TEST(MemEnvTest, LargeWrite) { TEST_F(MemEnvTest, LargeWrite) {
const size_t kWriteSize = 300 * 1024; const size_t kWriteSize = 300 * 1024;
char* scratch = new char[kWriteSize * 2]; char* scratch = new char[kWriteSize * 2];
@ -181,7 +181,7 @@ TEST(MemEnvTest, LargeWrite) {
delete [] scratch; delete [] scratch;
} }
TEST(MemEnvTest, DBTest) { TEST_F(MemEnvTest, DBTest) {
Options options; Options options;
options.create_if_missing = true; options.create_if_missing = true;
options.env = env_; options.env = env_;
@ -236,5 +236,6 @@ TEST(MemEnvTest, DBTest) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { int main(int argc, char** argv) {
return rocksdb::test::RunAllTests(); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} }

@ -13,7 +13,7 @@
namespace rocksdb { namespace rocksdb {
class MockEnvTest { class MockEnvTest : public testing::Test {
public: public:
Env* env_; Env* env_;
const EnvOptions soptions_; const EnvOptions soptions_;
@ -26,7 +26,7 @@ class MockEnvTest {
} }
}; };
TEST(MockEnvTest, Basics) { TEST_F(MockEnvTest, Basics) {
uint64_t file_size; uint64_t file_size;
unique_ptr<WritableFile> writable_file; unique_ptr<WritableFile> writable_file;
std::vector<std::string> children; std::vector<std::string> children;
@ -87,7 +87,7 @@ TEST(MockEnvTest, Basics) {
ASSERT_OK(env_->DeleteDir("/dir")); ASSERT_OK(env_->DeleteDir("/dir"));
} }
TEST(MockEnvTest, ReadWrite) { TEST_F(MockEnvTest, ReadWrite) {
unique_ptr<WritableFile> writable_file; unique_ptr<WritableFile> writable_file;
unique_ptr<SequentialFile> seq_file; unique_ptr<SequentialFile> seq_file;
unique_ptr<RandomAccessFile> rand_file; unique_ptr<RandomAccessFile> rand_file;
@ -127,7 +127,7 @@ TEST(MockEnvTest, ReadWrite) {
ASSERT_TRUE(!rand_file->Read(1000, 5, &result, scratch).ok()); ASSERT_TRUE(!rand_file->Read(1000, 5, &result, scratch).ok());
} }
TEST(MockEnvTest, Locks) { TEST_F(MockEnvTest, Locks) {
FileLock* lock; FileLock* lock;
// These are no-ops, but we test they return success. // These are no-ops, but we test they return success.
@ -135,7 +135,7 @@ TEST(MockEnvTest, Locks) {
ASSERT_OK(env_->UnlockFile(lock)); ASSERT_OK(env_->UnlockFile(lock));
} }
TEST(MockEnvTest, Misc) { TEST_F(MockEnvTest, Misc) {
std::string test_dir; std::string test_dir;
ASSERT_OK(env_->GetTestDirectory(&test_dir)); ASSERT_OK(env_->GetTestDirectory(&test_dir));
ASSERT_TRUE(!test_dir.empty()); ASSERT_TRUE(!test_dir.empty());
@ -150,7 +150,7 @@ TEST(MockEnvTest, Misc) {
writable_file.reset(); writable_file.reset();
} }
TEST(MockEnvTest, LargeWrite) { TEST_F(MockEnvTest, LargeWrite) {
const size_t kWriteSize = 300 * 1024; const size_t kWriteSize = 300 * 1024;
char* scratch = new char[kWriteSize * 2]; char* scratch = new char[kWriteSize * 2];
@ -182,7 +182,7 @@ TEST(MockEnvTest, LargeWrite) {
delete [] scratch; delete [] scratch;
} }
TEST(MockEnvTest, Corrupt) { TEST_F(MockEnvTest, Corrupt) {
const std::string kGood = "this is a good string, synced to disk"; const std::string kGood = "this is a good string, synced to disk";
const std::string kCorrupted = "this part may be corrupted"; const std::string kCorrupted = "this part may be corrupted";
const std::string kFileName = "/dir/f"; const std::string kFileName = "/dir/f";
@ -221,7 +221,7 @@ TEST(MockEnvTest, Corrupt) {
ASSERT_NE(result.compare(kCorrupted), 0); ASSERT_NE(result.compare(kCorrupted), 0);
} }
TEST(MockEnvTest, DBTest) { TEST_F(MockEnvTest, DBTest) {
Options options; Options options;
options.create_if_missing = true; options.create_if_missing = true;
options.env = env_; options.env = env_;
@ -267,5 +267,6 @@ TEST(MockEnvTest, DBTest) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { int main(int argc, char** argv) {
return rocksdb::test::RunAllTests(); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} }

@ -32,7 +32,7 @@ DEFINE_bool(enable_print, false, "Print options generated to console.");
namespace rocksdb { namespace rocksdb {
class OptionsTest {}; class OptionsTest : public testing::Test {};
class StderrLogger : public Logger { class StderrLogger : public Logger {
public: public:
@ -68,7 +68,7 @@ Options PrintAndGetOptions(size_t total_write_buffer_limit,
return options; return options;
} }
TEST(OptionsTest, LooseCondition) { TEST_F(OptionsTest, LooseCondition) {
Options options; Options options;
PrintAndGetOptions(static_cast<size_t>(10) * 1024 * 1024 * 1024, 100, 100); PrintAndGetOptions(static_cast<size_t>(10) * 1024 * 1024 * 1024, 100, 100);
@ -90,7 +90,7 @@ TEST(OptionsTest, LooseCondition) {
} }
#ifndef ROCKSDB_LITE // GetOptionsFromMap is not supported in ROCKSDB_LITE #ifndef ROCKSDB_LITE // GetOptionsFromMap is not supported in ROCKSDB_LITE
TEST(OptionsTest, GetOptionsFromMapTest) { TEST_F(OptionsTest, GetOptionsFromMapTest) {
std::unordered_map<std::string, std::string> cf_options_map = { std::unordered_map<std::string, std::string> cf_options_map = {
{"write_buffer_size", "1"}, {"write_buffer_size", "1"},
{"max_write_buffer_number", "2"}, {"max_write_buffer_number", "2"},
@ -284,7 +284,7 @@ TEST(OptionsTest, GetOptionsFromMapTest) {
#ifndef ROCKSDB_LITE // GetColumnFamilyOptionsFromString is not supported in #ifndef ROCKSDB_LITE // GetColumnFamilyOptionsFromString is not supported in
// ROCKSDB_LITE // ROCKSDB_LITE
TEST(OptionsTest, GetColumnFamilyOptionsFromStringTest) { TEST_F(OptionsTest, GetColumnFamilyOptionsFromStringTest) {
ColumnFamilyOptions base_cf_opt; ColumnFamilyOptions base_cf_opt;
ColumnFamilyOptions new_cf_opt; ColumnFamilyOptions new_cf_opt;
base_cf_opt.table_factory.reset(); base_cf_opt.table_factory.reset();
@ -413,7 +413,7 @@ TEST(OptionsTest, GetColumnFamilyOptionsFromStringTest) {
#endif // !ROCKSDB_LITE #endif // !ROCKSDB_LITE
#ifndef ROCKSDB_LITE // GetBlockBasedTableOptionsFromString is not supported #ifndef ROCKSDB_LITE // GetBlockBasedTableOptionsFromString is not supported
TEST(OptionsTest, GetBlockBasedTableOptionsFromString) { TEST_F(OptionsTest, GetBlockBasedTableOptionsFromString) {
BlockBasedTableOptions table_opt; BlockBasedTableOptions table_opt;
BlockBasedTableOptions new_opt; BlockBasedTableOptions new_opt;
// make sure default values are overwritten by something else // make sure default values are overwritten by something else
@ -468,7 +468,7 @@ TEST(OptionsTest, GetBlockBasedTableOptionsFromString) {
#endif // !ROCKSDB_LITE #endif // !ROCKSDB_LITE
#ifndef ROCKSDB_LITE // GetOptionsFromString is not supported in RocksDB Lite #ifndef ROCKSDB_LITE // GetOptionsFromString is not supported in RocksDB Lite
TEST(OptionsTest, GetOptionsFromStringTest) { TEST_F(OptionsTest, GetOptionsFromStringTest) {
Options base_options, new_options; Options base_options, new_options;
base_options.write_buffer_size = 20; base_options.write_buffer_size = 20;
base_options.min_write_buffer_number_to_merge = 15; base_options.min_write_buffer_number_to_merge = 15;
@ -505,7 +505,7 @@ Status StringToMap(
std::unordered_map<std::string, std::string>* opts_map); std::unordered_map<std::string, std::string>* opts_map);
#ifndef ROCKSDB_LITE // StringToMap is not supported in ROCKSDB_LITE #ifndef ROCKSDB_LITE // StringToMap is not supported in ROCKSDB_LITE
TEST(OptionsTest, StringToMapTest) { TEST_F(OptionsTest, StringToMapTest) {
std::unordered_map<std::string, std::string> opts_map; std::unordered_map<std::string, std::string> opts_map;
// Regular options // Regular options
ASSERT_OK(StringToMap("k1=v1;k2=v2;k3=v3", &opts_map)); ASSERT_OK(StringToMap("k1=v1;k2=v2;k3=v3", &opts_map));
@ -624,7 +624,7 @@ TEST(OptionsTest, StringToMapTest) {
#endif // ROCKSDB_LITE #endif // ROCKSDB_LITE
#ifndef ROCKSDB_LITE // StringToMap is not supported in ROCKSDB_LITE #ifndef ROCKSDB_LITE // StringToMap is not supported in ROCKSDB_LITE
TEST(OptionsTest, StringToMapRandomTest) { TEST_F(OptionsTest, StringToMapRandomTest) {
std::unordered_map<std::string, std::string> opts_map; std::unordered_map<std::string, std::string> opts_map;
// Make sure segfault is not hit by semi-random strings // Make sure segfault is not hit by semi-random strings
@ -670,7 +670,7 @@ TEST(OptionsTest, StringToMapRandomTest) {
} }
#endif // !ROCKSDB_LITE #endif // !ROCKSDB_LITE
TEST(OptionsTest, ConvertOptionsTest) { TEST_F(OptionsTest, ConvertOptionsTest) {
LevelDBOptions leveldb_opt; LevelDBOptions leveldb_opt;
Options converted_opt = ConvertOptions(leveldb_opt); Options converted_opt = ConvertOptions(leveldb_opt);
@ -701,8 +701,9 @@ TEST(OptionsTest, ConvertOptionsTest) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
#ifdef GFLAGS #ifdef GFLAGS
ParseCommandLineFlags(&argc, &argv, true); ParseCommandLineFlags(&argc, &argv, true);
#endif // GFLAGS #endif // GFLAGS
return rocksdb::test::RunAllTests(); return RUN_ALL_TESTS();
} }

@ -20,14 +20,13 @@
namespace rocksdb { namespace rocksdb {
class RateLimiterTest { class RateLimiterTest : public testing::Test {};
};
TEST(RateLimiterTest, StartStop) { TEST_F(RateLimiterTest, StartStop) {
std::unique_ptr<RateLimiter> limiter(new GenericRateLimiter(100, 100, 10)); std::unique_ptr<RateLimiter> limiter(new GenericRateLimiter(100, 100, 10));
} }
TEST(RateLimiterTest, Rate) { TEST_F(RateLimiterTest, Rate) {
auto* env = Env::Default(); auto* env = Env::Default();
struct Arg { struct Arg {
Arg(int32_t _target_rate, int _burst) Arg(int32_t _target_rate, int _burst)
@ -80,5 +79,6 @@ TEST(RateLimiterTest, Rate) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { int main(int argc, char** argv) {
return rocksdb::test::RunAllTests(); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} }

@ -18,9 +18,9 @@
namespace rocksdb { namespace rocksdb {
class SliceTransformTest {}; class SliceTransformTest : public testing::Test {};
TEST(SliceTransformTest, CapPrefixTransform) { TEST_F(SliceTransformTest, CapPrefixTransform) {
std::string s; std::string s;
s = "abcdefge"; s = "abcdefge";
@ -45,7 +45,7 @@ TEST(SliceTransformTest, CapPrefixTransform) {
ASSERT_EQ(transform->Transform("").ToString(), ""); ASSERT_EQ(transform->Transform("").ToString(), "");
} }
class SliceTransformDBTest { class SliceTransformDBTest : public testing::Test {
private: private:
std::string dbname_; std::string dbname_;
Env* env_; Env* env_;
@ -96,7 +96,7 @@ uint64_t TestGetTickerCount(const Options& options, Tickers ticker_type) {
} }
} // namespace } // namespace
TEST(SliceTransformDBTest, CapPrefix) { TEST_F(SliceTransformDBTest, CapPrefix) {
last_options_.prefix_extractor.reset(NewCappedPrefixTransform(8)); last_options_.prefix_extractor.reset(NewCappedPrefixTransform(8));
last_options_.statistics = rocksdb::CreateDBStatistics(); last_options_.statistics = rocksdb::CreateDBStatistics();
BlockBasedTableOptions bbto; BlockBasedTableOptions bbto;
@ -147,4 +147,7 @@ TEST(SliceTransformDBTest, CapPrefix) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { return rocksdb::test::RunAllTests(); } int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

@ -74,7 +74,7 @@ void cleanup(const std::string& file_name) {
} // namespace } // namespace
// Test for sst dump tool "raw" mode // Test for sst dump tool "raw" mode
class SSTDumpToolTest { class SSTDumpToolTest : public testing::Test {
public: public:
BlockBasedTableOptions table_options_; BlockBasedTableOptions table_options_;
@ -83,7 +83,7 @@ class SSTDumpToolTest {
~SSTDumpToolTest() {} ~SSTDumpToolTest() {}
}; };
TEST(SSTDumpToolTest, EmptyFilter) { TEST_F(SSTDumpToolTest, EmptyFilter) {
std::string file_name = "rocksdb_sst_test.sst"; std::string file_name = "rocksdb_sst_test.sst";
createSST(file_name, table_options_); createSST(file_name, table_options_);
@ -104,7 +104,7 @@ TEST(SSTDumpToolTest, EmptyFilter) {
} }
} }
TEST(SSTDumpToolTest, FilterBlock) { TEST_F(SSTDumpToolTest, FilterBlock) {
table_options_.filter_policy.reset(rocksdb::NewBloomFilterPolicy(10, true)); table_options_.filter_policy.reset(rocksdb::NewBloomFilterPolicy(10, true));
std::string file_name = "rocksdb_sst_test.sst"; std::string file_name = "rocksdb_sst_test.sst";
createSST(file_name, table_options_); createSST(file_name, table_options_);
@ -126,7 +126,7 @@ TEST(SSTDumpToolTest, FilterBlock) {
} }
} }
TEST(SSTDumpToolTest, FullFilterBlock) { TEST_F(SSTDumpToolTest, FullFilterBlock) {
table_options_.filter_policy.reset(rocksdb::NewBloomFilterPolicy(10, false)); table_options_.filter_policy.reset(rocksdb::NewBloomFilterPolicy(10, false));
std::string file_name = "rocksdb_sst_test.sst"; std::string file_name = "rocksdb_sst_test.sst";
createSST(file_name, table_options_); createSST(file_name, table_options_);
@ -148,7 +148,7 @@ TEST(SSTDumpToolTest, FullFilterBlock) {
} }
} }
TEST(SSTDumpToolTest, GetProperties) { TEST_F(SSTDumpToolTest, GetProperties) {
table_options_.filter_policy.reset(rocksdb::NewBloomFilterPolicy(10, false)); table_options_.filter_policy.reset(rocksdb::NewBloomFilterPolicy(10, false));
std::string file_name = "rocksdb_sst_test.sst"; std::string file_name = "rocksdb_sst_test.sst";
createSST(file_name, table_options_); createSST(file_name, table_options_);
@ -171,4 +171,7 @@ TEST(SSTDumpToolTest, GetProperties) {
} }
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { return rocksdb::test::RunAllTests(); } int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

@ -9,6 +9,8 @@
#pragma once #pragma once
#include <gtest/gtest.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <sstream> #include <sstream>
@ -22,22 +24,6 @@
namespace rocksdb { namespace rocksdb {
namespace test { namespace test {
// Run some of the tests registered by the TEST() macro. If the
// environment variable "ROCKSDB_TESTS" and "ROCKSDB_TESTS_FROM"
// are not set, runs all tests. Otherwise, run all tests after
// ROCKSDB_TESTS_FROM and those specified by ROCKSDB_TESTS.
// Partial name match also works for ROCKSDB_TESTS and
// ROCKSDB_TESTS_FROM. E.g., suppose the tests are:
// TEST(Foo, Hello) { ... }
// TEST(Foo, World) { ... }
// ROCKSDB_TESTS=Hello will run the first test
// ROCKSDB_TESTS=o will run both tests
// ROCKSDB_TESTS=Junk will run no tests
//
// Returns 0 if all tests pass.
// Dies or returns a non-zero value if some test fails.
extern int RunAllTests();
// Return the directory to use for temporary storage. // Return the directory to use for temporary storage.
extern std::string TmpDir(Env* env = Env::Default()); extern std::string TmpDir(Env* env = Env::Default());
@ -46,166 +32,10 @@ extern std::string TmpDir(Env* env = Env::Default());
// runs may be able to vary the seed. // runs may be able to vary the seed.
extern int RandomSeed(); extern int RandomSeed();
class TesterHelper; #define ASSERT_OK(s) ASSERT_TRUE(((s).ok()))
#define ASSERT_NOK(s) ASSERT_FALSE(((s).ok()))
// An instance of Tester is allocated to hold temporary state during #define EXPECT_OK(s) EXPECT_TRUE(((s).ok()))
// the execution of an assertion. #define EXPECT_NOK(s) EXPECT_FALSE(((s).ok()))
class Tester {
friend class TesterHelper;
private:
bool ok_;
std::stringstream ss_;
public:
Tester() : ok_(true) {}
Tester& Is(bool b, const char* msg) {
if (!b) {
ss_ << " Assertion failure " << msg;
ok_ = false;
}
return *this;
}
Tester& IsOk(const Status& s) {
if (!s.ok()) {
ss_ << " " << s.ToString();
ok_ = false;
}
return *this;
}
Tester& IsNotOk(const Status& s) {
if (s.ok()) {
ss_ << " Error status expected";
ok_ = false;
}
return *this;
}
#define BINARY_OP(name,op) \
template <class X, class Y> \
Tester& name(const X& x, const Y& y) { \
if (! (x op y)) { \
ss_ << " failed: " << x << (" " #op " ") << y; \
ok_ = false; \
} \
return *this; \
}
BINARY_OP(IsEq, ==)
BINARY_OP(IsNe, !=)
BINARY_OP(IsGe, >=)
BINARY_OP(IsGt, >)
BINARY_OP(IsLe, <=)
BINARY_OP(IsLt, <)
#undef BINARY_OP
// Attach the specified value to the error message if an error has occurred
template <class V>
Tester& operator<<(const V& value) {
if (!ok_) {
ss_ << " " << value;
}
return *this;
}
operator bool() const { return ok_; }
};
class TesterHelper {
private:
const char* fname_;
int line_;
public:
TesterHelper(const char* f, int l) : fname_(f), line_(l) {}
void operator=(const Tester& tester) {
fprintf(stderr, "%s:%d:%s\n", fname_, line_, tester.ss_.str().c_str());
port::PrintStack(2);
exit(1);
}
};
// This is trying to solve:
// * Evaluate expression
// * Abort the test if the evaluation is not successful with the evaluation
// details.
// * Support operator << with ASSERT* for extra messages provided by the user
// code of ASSERT*
//
// For the third, we need to make sure that an expression at the end of macro
// supports << operator. But since we can have multiple of << we cannot abort
// inside implementation of operator <<, as we may miss some extra message. That
// is why there is TesterHelper with operator = which has lower precedence then
// operator <<, and it will be called after all messages from use code are
// accounted by <<.
//
// operator bool is added to Tester to make possible its declaration inside if
// statement and do not pollute its outer scope with the name tester. But in C++
// we cannot do any other operations inside if statement besides declaration.
// Then in order to get inside if body there are two options: make operator
// Tester::bool return true if ok_ == false or put the body into else part.
#define TEST_EXPRESSION_(expression) \
if (::rocksdb::test::Tester& tester = (expression)) \
; \
else \
::rocksdb::test::TesterHelper(__FILE__, __LINE__) = tester
#define ASSERT_TRUE(c) TEST_EXPRESSION_(::rocksdb::test::Tester().Is((c), #c))
#define ASSERT_OK(s) TEST_EXPRESSION_(::rocksdb::test::Tester().IsOk((s)))
#define ASSERT_NOK(s) TEST_EXPRESSION_(::rocksdb::test::Tester().IsNotOk((s)))
#define ASSERT_EQ(a, b) \
TEST_EXPRESSION_(::rocksdb::test::Tester().IsEq((a), (b)))
#define ASSERT_NE(a, b) \
TEST_EXPRESSION_(::rocksdb::test::Tester().IsNe((a), (b)))
#define ASSERT_GE(a, b) \
TEST_EXPRESSION_(::rocksdb::test::Tester().IsGe((a), (b)))
#define ASSERT_GT(a, b) \
TEST_EXPRESSION_(::rocksdb::test::Tester().IsGt((a), (b)))
#define ASSERT_LE(a, b) \
TEST_EXPRESSION_(::rocksdb::test::Tester().IsLe((a), (b)))
#define ASSERT_LT(a, b) \
TEST_EXPRESSION_(::rocksdb::test::Tester().IsLt((a), (b)))
#define EXPECT_TRUE(c) TEST_EXPRESSION_(::rocksdb::test::Tester().Is((c), #c))
#define EXPECT_OK(s) TEST_EXPRESSION_(::rocksdb::test::Tester().IsOk((s)))
#define EXPECT_NOK(s) TEST_EXPRESSION_(::rocksdb::test::Tester().IsNotOk((s)))
#define EXPECT_EQ(a, b) \
TEST_EXPRESSION_(::rocksdb::test::Tester().IsEq((a), (b)))
#define EXPECT_NE(a, b) \
TEST_EXPRESSION_(::rocksdb::test::Tester().IsNe((a), (b)))
#define EXPECT_GE(a, b) \
TEST_EXPRESSION_(::rocksdb::test::Tester().IsGe((a), (b)))
#define EXPECT_GT(a, b) \
TEST_EXPRESSION_(::rocksdb::test::Tester().IsGt((a), (b)))
#define EXPECT_LE(a, b) \
TEST_EXPRESSION_(::rocksdb::test::Tester().IsLe((a), (b)))
#define EXPECT_LT(a, b) \
TEST_EXPRESSION_(::rocksdb::test::Tester().IsLt((a), (b)))
#define TCONCAT(a, b) TCONCAT1(a, b)
#define TCONCAT1(a, b) a##b
#define TEST(base, name) \
class TCONCAT(_Test_, name) : public base { \
public: \
void _Run(); \
static void _RunIt() { \
TCONCAT(_Test_, name) t; \
t._Run(); \
} \
}; \
bool TCONCAT(_Test_ignored_, name) __attribute__((__unused__)) \
= ::rocksdb::test::RegisterTest(#base, #name, \
&TCONCAT(_Test_, name)::_RunIt); \
void TCONCAT(_Test_, name)::_Run()
// Register the specified test. Typically not used directly, but
// invoked via the macro expansion of TEST.
extern bool RegisterTest(const char* base, const char* name, void (*func)());
} // namespace test } // namespace test
} // namespace rocksdb } // namespace rocksdb

@ -88,13 +88,13 @@ class SimulatedBackgroundTask {
std::atomic<int> running_count_; std::atomic<int> running_count_;
}; };
class ThreadListTest { class ThreadListTest : public testing::Test {
public: public:
ThreadListTest() { ThreadListTest() {
} }
}; };
TEST(ThreadListTest, GlobalTables) { TEST_F(ThreadListTest, GlobalTables) {
// verify the global tables for operations and states are properly indexed. // verify the global tables for operations and states are properly indexed.
for (int type = 0; type != ThreadStatus::NUM_OP_TYPES; ++type) { for (int type = 0; type != ThreadStatus::NUM_OP_TYPES; ++type) {
ASSERT_EQ(global_operation_table[type].type, type); ASSERT_EQ(global_operation_table[type].type, type);
@ -118,7 +118,7 @@ TEST(ThreadListTest, GlobalTables) {
} }
} }
TEST(ThreadListTest, SimpleColumnFamilyInfoTest) { TEST_F(ThreadListTest, SimpleColumnFamilyInfoTest) {
Env* env = Env::Default(); Env* env = Env::Default();
const int kHighPriorityThreads = 3; const int kHighPriorityThreads = 3;
const int kLowPriorityThreads = 5; const int kLowPriorityThreads = 5;
@ -211,7 +211,7 @@ namespace {
} }
} // namespace } // namespace
TEST(ThreadListTest, SimpleEventTest) { TEST_F(ThreadListTest, SimpleEventTest) {
Env* env = Env::Default(); Env* env = Env::Default();
// simulated tasks // simulated tasks
@ -338,12 +338,14 @@ TEST(ThreadListTest, SimpleEventTest) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { int main(int argc, char** argv) {
return rocksdb::test::RunAllTests(); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} }
#else #else
int main(int argc, char** argv) { int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return 0; return 0;
} }

@ -14,7 +14,7 @@
namespace rocksdb { namespace rocksdb {
class ThreadLocalTest { class ThreadLocalTest : public testing::Test {
public: public:
ThreadLocalTest() : env_(Env::Default()) {} ThreadLocalTest() : env_(Env::Default()) {}
@ -54,7 +54,7 @@ class IDChecker : public ThreadLocalPtr {
} // anonymous namespace } // anonymous namespace
TEST(ThreadLocalTest, UniqueIdTest) { TEST_F(ThreadLocalTest, UniqueIdTest) {
port::Mutex mu; port::Mutex mu;
port::CondVar cv(&mu); port::CondVar cv(&mu);
@ -101,7 +101,7 @@ TEST(ThreadLocalTest, UniqueIdTest) {
// 3, 1, 2, 0 // 3, 1, 2, 0
} }
TEST(ThreadLocalTest, SequentialReadWriteTest) { TEST_F(ThreadLocalTest, SequentialReadWriteTest) {
// global id list carries over 3, 1, 2, 0 // global id list carries over 3, 1, 2, 0
ASSERT_EQ(IDChecker::PeekId(), 0u); ASSERT_EQ(IDChecker::PeekId(), 0u);
@ -145,7 +145,7 @@ TEST(ThreadLocalTest, SequentialReadWriteTest) {
} }
} }
TEST(ThreadLocalTest, ConcurrentReadWriteTest) { TEST_F(ThreadLocalTest, ConcurrentReadWriteTest) {
// global id list carries over 3, 1, 2, 0 // global id list carries over 3, 1, 2, 0
ASSERT_EQ(IDChecker::PeekId(), 0u); ASSERT_EQ(IDChecker::PeekId(), 0u);
@ -229,7 +229,7 @@ TEST(ThreadLocalTest, ConcurrentReadWriteTest) {
ASSERT_EQ(IDChecker::PeekId(), 3u); ASSERT_EQ(IDChecker::PeekId(), 3u);
} }
TEST(ThreadLocalTest, Unref) { TEST_F(ThreadLocalTest, Unref) {
ASSERT_EQ(IDChecker::PeekId(), 0u); ASSERT_EQ(IDChecker::PeekId(), 0u);
auto unref = [](void* ptr) { auto unref = [](void* ptr) {
@ -372,7 +372,7 @@ TEST(ThreadLocalTest, Unref) {
} }
} }
TEST(ThreadLocalTest, Swap) { TEST_F(ThreadLocalTest, Swap) {
ThreadLocalPtr tls; ThreadLocalPtr tls;
tls.Reset(reinterpret_cast<void*>(1)); tls.Reset(reinterpret_cast<void*>(1));
ASSERT_EQ(reinterpret_cast<int64_t>(tls.Swap(nullptr)), 1); ASSERT_EQ(reinterpret_cast<int64_t>(tls.Swap(nullptr)), 1);
@ -381,7 +381,7 @@ TEST(ThreadLocalTest, Swap) {
ASSERT_EQ(reinterpret_cast<int64_t>(tls.Swap(reinterpret_cast<void*>(3))), 2); ASSERT_EQ(reinterpret_cast<int64_t>(tls.Swap(reinterpret_cast<void*>(3))), 2);
} }
TEST(ThreadLocalTest, Scrape) { TEST_F(ThreadLocalTest, Scrape) {
auto unref = [](void* ptr) { auto unref = [](void* ptr) {
auto& p = *static_cast<Params*>(ptr); auto& p = *static_cast<Params*>(ptr);
p.mu->Lock(); p.mu->Lock();
@ -449,7 +449,7 @@ TEST(ThreadLocalTest, Scrape) {
} }
} }
TEST(ThreadLocalTest, CompareAndSwap) { TEST_F(ThreadLocalTest, CompareAndSwap) {
ThreadLocalPtr tls; ThreadLocalPtr tls;
ASSERT_TRUE(tls.Swap(reinterpret_cast<void*>(1)) == nullptr); ASSERT_TRUE(tls.Swap(reinterpret_cast<void*>(1)) == nullptr);
void* expected = reinterpret_cast<void*>(1); void* expected = reinterpret_cast<void*>(1);
@ -468,5 +468,6 @@ TEST(ThreadLocalTest, CompareAndSwap) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { int main(int argc, char** argv) {
return rocksdb::test::RunAllTests(); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} }

@ -351,7 +351,7 @@ static void AssertEmpty(DB* db, int from, int to) {
} }
} }
class BackupableDBTest { class BackupableDBTest : public testing::Test {
public: public:
BackupableDBTest() { BackupableDBTest() {
// set up files // set up files
@ -495,7 +495,7 @@ void AppendPath(const std::string& path, std::vector<std::string>& v) {
} }
// this will make sure that backup does not copy the same file twice // this will make sure that backup does not copy the same file twice
TEST(BackupableDBTest, NoDoubleCopy) { TEST_F(BackupableDBTest, NoDoubleCopy) {
OpenBackupableDB(true, true); OpenBackupableDB(true, true);
// should write 5 DB files + LATEST_BACKUP + one meta file // should write 5 DB files + LATEST_BACKUP + one meta file
@ -566,7 +566,7 @@ TEST(BackupableDBTest, NoDoubleCopy) {
// fine // fine
// 4. Corrupted checksum value - if the checksum is not a valid uint32_t, // 4. Corrupted checksum value - if the checksum is not a valid uint32_t,
// db open should fail, otherwise, it aborts during the restore process. // db open should fail, otherwise, it aborts during the restore process.
TEST(BackupableDBTest, CorruptionsTest) { TEST_F(BackupableDBTest, CorruptionsTest) {
const int keys_iteration = 5000; const int keys_iteration = 5000;
Random rnd(6); Random rnd(6);
Status s; Status s;
@ -676,7 +676,7 @@ TEST(BackupableDBTest, CorruptionsTest) {
// This test verifies we don't delete the latest backup when read-only option is // This test verifies we don't delete the latest backup when read-only option is
// set // set
TEST(BackupableDBTest, NoDeleteWithReadOnly) { TEST_F(BackupableDBTest, NoDeleteWithReadOnly) {
const int keys_iteration = 5000; const int keys_iteration = 5000;
Random rnd(6); Random rnd(6);
Status s; Status s;
@ -708,7 +708,7 @@ TEST(BackupableDBTest, NoDeleteWithReadOnly) {
} }
// open DB, write, close DB, backup, restore, repeat // open DB, write, close DB, backup, restore, repeat
TEST(BackupableDBTest, OfflineIntegrationTest) { TEST_F(BackupableDBTest, OfflineIntegrationTest) {
// has to be a big number, so that it triggers the memtable flush // has to be a big number, so that it triggers the memtable flush
const int keys_iteration = 5000; const int keys_iteration = 5000;
const int max_key = keys_iteration * 4 + 10; const int max_key = keys_iteration * 4 + 10;
@ -755,7 +755,7 @@ TEST(BackupableDBTest, OfflineIntegrationTest) {
} }
// open DB, write, backup, write, backup, close, restore // open DB, write, backup, write, backup, close, restore
TEST(BackupableDBTest, OnlineIntegrationTest) { TEST_F(BackupableDBTest, OnlineIntegrationTest) {
// has to be a big number, so that it triggers the memtable flush // has to be a big number, so that it triggers the memtable flush
const int keys_iteration = 5000; const int keys_iteration = 5000;
const int max_key = keys_iteration * 4 + 10; const int max_key = keys_iteration * 4 + 10;
@ -818,7 +818,7 @@ TEST(BackupableDBTest, OnlineIntegrationTest) {
CloseRestoreDB(); CloseRestoreDB();
} }
TEST(BackupableDBTest, FailOverwritingBackups) { TEST_F(BackupableDBTest, FailOverwritingBackups) {
options_.write_buffer_size = 1024 * 1024 * 1024; // 1GB options_.write_buffer_size = 1024 * 1024 * 1024; // 1GB
// create backups 1, 2, 3, 4, 5 // create backups 1, 2, 3, 4, 5
OpenBackupableDB(true); OpenBackupableDB(true);
@ -853,7 +853,7 @@ TEST(BackupableDBTest, FailOverwritingBackups) {
CloseBackupableDB(); CloseBackupableDB();
} }
TEST(BackupableDBTest, NoShareTableFiles) { TEST_F(BackupableDBTest, NoShareTableFiles) {
const int keys_iteration = 5000; const int keys_iteration = 5000;
OpenBackupableDB(true, false, false); OpenBackupableDB(true, false, false);
for (int i = 0; i < 5; ++i) { for (int i = 0; i < 5; ++i) {
@ -869,7 +869,7 @@ TEST(BackupableDBTest, NoShareTableFiles) {
} }
// Verify that you can backup and restore with share_files_with_checksum on // Verify that you can backup and restore with share_files_with_checksum on
TEST(BackupableDBTest, ShareTableFilesWithChecksums) { TEST_F(BackupableDBTest, ShareTableFilesWithChecksums) {
const int keys_iteration = 5000; const int keys_iteration = 5000;
OpenBackupableDB(true, false, true, true); OpenBackupableDB(true, false, true, true);
for (int i = 0; i < 5; ++i) { for (int i = 0; i < 5; ++i) {
@ -886,7 +886,7 @@ TEST(BackupableDBTest, ShareTableFilesWithChecksums) {
// Verify that you can backup and restore using share_files_with_checksum set to // Verify that you can backup and restore using share_files_with_checksum set to
// false and then transition this option to true // false and then transition this option to true
TEST(BackupableDBTest, ShareTableFilesWithChecksumsTransition) { TEST_F(BackupableDBTest, ShareTableFilesWithChecksumsTransition) {
const int keys_iteration = 5000; const int keys_iteration = 5000;
// set share_files_with_checksum to false // set share_files_with_checksum to false
OpenBackupableDB(true, false, true, false); OpenBackupableDB(true, false, true, false);
@ -915,7 +915,7 @@ TEST(BackupableDBTest, ShareTableFilesWithChecksumsTransition) {
} }
} }
TEST(BackupableDBTest, DeleteTmpFiles) { TEST_F(BackupableDBTest, DeleteTmpFiles) {
OpenBackupableDB(); OpenBackupableDB();
CloseBackupableDB(); CloseBackupableDB();
std::string shared_tmp = backupdir_ + "/shared/00006.sst.tmp"; std::string shared_tmp = backupdir_ + "/shared/00006.sst.tmp";
@ -934,7 +934,7 @@ TEST(BackupableDBTest, DeleteTmpFiles) {
ASSERT_EQ(false, file_manager_->FileExists(private_tmp_dir)); ASSERT_EQ(false, file_manager_->FileExists(private_tmp_dir));
} }
TEST(BackupableDBTest, KeepLogFiles) { TEST_F(BackupableDBTest, KeepLogFiles) {
backupable_options_->backup_log_files = false; backupable_options_->backup_log_files = false;
// basically infinite // basically infinite
options_.WAL_ttl_seconds = 24 * 60 * 60; options_.WAL_ttl_seconds = 24 * 60 * 60;
@ -955,7 +955,7 @@ TEST(BackupableDBTest, KeepLogFiles) {
AssertBackupConsistency(0, 0, 500, 600, true); AssertBackupConsistency(0, 0, 500, 600, true);
} }
TEST(BackupableDBTest, RateLimiting) { TEST_F(BackupableDBTest, RateLimiting) {
uint64_t const KB = 1024 * 1024; uint64_t const KB = 1024 * 1024;
size_t const kMicrosPerSec = 1000 * 1000LL; size_t const kMicrosPerSec = 1000 * 1000LL;
@ -994,7 +994,7 @@ TEST(BackupableDBTest, RateLimiting) {
} }
} }
TEST(BackupableDBTest, ReadOnlyBackupEngine) { TEST_F(BackupableDBTest, ReadOnlyBackupEngine) {
DestroyDB(dbname_, Options()); DestroyDB(dbname_, Options());
OpenBackupableDB(true); OpenBackupableDB(true);
FillDB(db_.get(), 0, 100); FillDB(db_.get(), 0, 100);
@ -1031,5 +1031,6 @@ TEST(BackupableDBTest, ReadOnlyBackupEngine) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { int main(int argc, char** argv) {
return rocksdb::test::RunAllTests(); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} }

@ -13,7 +13,7 @@
namespace rocksdb { namespace rocksdb {
class DocumentDBTest { class DocumentDBTest : public testing::Test {
public: public:
DocumentDBTest() { DocumentDBTest() {
dbname_ = test::TmpDir() + "/document_db_test"; dbname_ = test::TmpDir() + "/document_db_test";
@ -64,7 +64,7 @@ class DocumentDBTest {
DocumentDB* db_; DocumentDB* db_;
}; };
TEST(DocumentDBTest, SimpleQueryTest) { TEST_F(DocumentDBTest, SimpleQueryTest) {
DocumentDBOptions options; DocumentDBOptions options;
DocumentDB::IndexDescriptor index; DocumentDB::IndexDescriptor index;
index.description = Parse("{\"name\": 1}"); index.description = Parse("{\"name\": 1}");
@ -136,7 +136,7 @@ TEST(DocumentDBTest, SimpleQueryTest) {
} }
} }
TEST(DocumentDBTest, ComplexQueryTest) { TEST_F(DocumentDBTest, ComplexQueryTest) {
DocumentDBOptions options; DocumentDBOptions options;
DocumentDB::IndexDescriptor priority_index; DocumentDB::IndexDescriptor priority_index;
priority_index.description = Parse("{'priority': 1}"); priority_index.description = Parse("{'priority': 1}");
@ -318,4 +318,7 @@ TEST(DocumentDBTest, ComplexQueryTest) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { return rocksdb::test::RunAllTests(); } int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

@ -48,7 +48,7 @@ void AssertField(const JSONDocument& json, const std::string& field,
} }
} // namespace } // namespace
class JSONDocumentTest { class JSONDocumentTest : public testing::Test {
public: public:
JSONDocumentTest() JSONDocumentTest()
: rnd_(101) : rnd_(101)
@ -104,14 +104,14 @@ class JSONDocumentTest {
Random rnd_; Random rnd_;
}; };
TEST(JSONDocumentTest, MakeNullTest) { TEST_F(JSONDocumentTest, MakeNullTest) {
JSONDocument x; JSONDocument x;
ASSERT_TRUE(x.IsNull()); ASSERT_TRUE(x.IsNull());
ASSERT_TRUE(x.IsOwner()); ASSERT_TRUE(x.IsOwner());
ASSERT_TRUE(!x.IsBool()); ASSERT_TRUE(!x.IsBool());
} }
TEST(JSONDocumentTest, MakeBoolTest) { TEST_F(JSONDocumentTest, MakeBoolTest) {
{ {
JSONDocument x(true); JSONDocument x(true);
ASSERT_TRUE(x.IsOwner()); ASSERT_TRUE(x.IsOwner());
@ -129,7 +129,7 @@ TEST(JSONDocumentTest, MakeBoolTest) {
} }
} }
TEST(JSONDocumentTest, MakeInt64Test) { TEST_F(JSONDocumentTest, MakeInt64Test) {
JSONDocument x(static_cast<int64_t>(16)); JSONDocument x(static_cast<int64_t>(16));
ASSERT_TRUE(x.IsInt64()); ASSERT_TRUE(x.IsInt64());
ASSERT_TRUE(x.IsInt64()); ASSERT_TRUE(x.IsInt64());
@ -138,7 +138,7 @@ TEST(JSONDocumentTest, MakeInt64Test) {
ASSERT_EQ(x.GetInt64(), 16); ASSERT_EQ(x.GetInt64(), 16);
} }
TEST(JSONDocumentTest, MakeStringTest) { TEST_F(JSONDocumentTest, MakeStringTest) {
JSONDocument x("string"); JSONDocument x("string");
ASSERT_TRUE(x.IsOwner()); ASSERT_TRUE(x.IsOwner());
ASSERT_TRUE(x.IsString()); ASSERT_TRUE(x.IsString());
@ -146,7 +146,7 @@ TEST(JSONDocumentTest, MakeStringTest) {
ASSERT_EQ(x.GetString(), "string"); ASSERT_EQ(x.GetString(), "string");
} }
TEST(JSONDocumentTest, MakeDoubleTest) { TEST_F(JSONDocumentTest, MakeDoubleTest) {
JSONDocument x(5.6); JSONDocument x(5.6);
ASSERT_TRUE(x.IsOwner()); ASSERT_TRUE(x.IsOwner());
ASSERT_TRUE(x.IsDouble()); ASSERT_TRUE(x.IsDouble());
@ -154,7 +154,7 @@ TEST(JSONDocumentTest, MakeDoubleTest) {
ASSERT_EQ(x.GetDouble(), 5.6); ASSERT_EQ(x.GetDouble(), 5.6);
} }
TEST(JSONDocumentTest, MakeByTypeTest) { TEST_F(JSONDocumentTest, MakeByTypeTest) {
{ {
JSONDocument x(JSONDocument::kNull); JSONDocument x(JSONDocument::kNull);
ASSERT_TRUE(x.IsNull()); ASSERT_TRUE(x.IsNull());
@ -185,7 +185,7 @@ TEST(JSONDocumentTest, MakeByTypeTest) {
} }
} }
TEST(JSONDocumentTest, Parsing) { TEST_F(JSONDocumentTest, Parsing) {
std::unique_ptr<JSONDocument> parsed_json( std::unique_ptr<JSONDocument> parsed_json(
JSONDocument::ParseJSON(kSampleJSON.c_str())); JSONDocument::ParseJSON(kSampleJSON.c_str()));
ASSERT_TRUE(parsed_json->IsOwner()); ASSERT_TRUE(parsed_json->IsOwner());
@ -208,7 +208,7 @@ TEST(JSONDocumentTest, Parsing) {
ASSERT_TRUE(JSONDocument::ParseJSON(kFaultyJSON.c_str()) == nullptr); ASSERT_TRUE(JSONDocument::ParseJSON(kFaultyJSON.c_str()) == nullptr);
} }
TEST(JSONDocumentTest, Serialization) { TEST_F(JSONDocumentTest, Serialization) {
std::unique_ptr<JSONDocument> parsed_json( std::unique_ptr<JSONDocument> parsed_json(
JSONDocument::ParseJSON(kSampleJSON.c_str())); JSONDocument::ParseJSON(kSampleJSON.c_str()));
ASSERT_TRUE(parsed_json != nullptr); ASSERT_TRUE(parsed_json != nullptr);
@ -226,7 +226,7 @@ TEST(JSONDocumentTest, Serialization) {
Slice(serialized.data(), serialized.size() - 10)) == nullptr); Slice(serialized.data(), serialized.size() - 10)) == nullptr);
} }
TEST(JSONDocumentTest, OperatorEqualsTest) { TEST_F(JSONDocumentTest, OperatorEqualsTest) {
// kNull // kNull
ASSERT_TRUE(JSONDocument() == JSONDocument()); ASSERT_TRUE(JSONDocument() == JSONDocument());
@ -274,7 +274,7 @@ TEST(JSONDocumentTest, OperatorEqualsTest) {
ASSERT_TRUE(JSONDocument(15.) == JSONDocument(15.)); ASSERT_TRUE(JSONDocument(15.) == JSONDocument(15.));
} }
TEST(JSONDocumentTest, JSONDocumentBuilderTest) { TEST_F(JSONDocumentTest, JSONDocumentBuilderTest) {
unique_ptr<JSONDocument> parsedArray( unique_ptr<JSONDocument> parsedArray(
JSONDocument::ParseJSON("[1, [123, \"a\", \"b\"], {\"b\":\"c\"}]")); JSONDocument::ParseJSON("[1, [123, \"a\", \"b\"], {\"b\":\"c\"}]"));
ASSERT_TRUE(parsedArray != nullptr); ASSERT_TRUE(parsedArray != nullptr);
@ -298,7 +298,7 @@ TEST(JSONDocumentTest, JSONDocumentBuilderTest) {
ASSERT_TRUE(*parsedArray == builder.GetJSONDocument()); ASSERT_TRUE(*parsedArray == builder.GetJSONDocument());
} }
TEST(JSONDocumentTest, OwnershipTest) { TEST_F(JSONDocumentTest, OwnershipTest) {
std::unique_ptr<JSONDocument> parsed( std::unique_ptr<JSONDocument> parsed(
JSONDocument::ParseJSON(kSampleJSON.c_str())); JSONDocument::ParseJSON(kSampleJSON.c_str()));
ASSERT_TRUE(parsed != nullptr); ASSERT_TRUE(parsed != nullptr);
@ -323,4 +323,7 @@ TEST(JSONDocumentTest, OwnershipTest) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { return rocksdb::test::RunAllTests(); } int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

@ -11,7 +11,7 @@
namespace rocksdb { namespace rocksdb {
class GeoDBTest { class GeoDBTest : public testing::Test {
public: public:
static const std::string kDefaultDbName; static const std::string kDefaultDbName;
static Options options; static Options options;
@ -39,7 +39,7 @@ const std::string GeoDBTest::kDefaultDbName = "/tmp/geodefault";
Options GeoDBTest::options = Options(); Options GeoDBTest::options = Options();
// Insert, Get and Remove // Insert, Get and Remove
TEST(GeoDBTest, SimpleTest) { TEST_F(GeoDBTest, SimpleTest) {
GeoPosition pos1(100, 101); GeoPosition pos1(100, 101);
std::string id1("id1"); std::string id1("id1");
std::string value1("value1"); std::string value1("value1");
@ -90,7 +90,7 @@ TEST(GeoDBTest, SimpleTest) {
// Search. // Search.
// Verify distances via http://www.stevemorse.org/nearest/distance.php // Verify distances via http://www.stevemorse.org/nearest/distance.php
TEST(GeoDBTest, Search) { TEST_F(GeoDBTest, Search) {
GeoPosition pos1(45, 45); GeoPosition pos1(45, 45);
std::string id1("mid1"); std::string id1("mid1");
std::string value1 = "midvalue1"; std::string value1 = "midvalue1";
@ -119,5 +119,6 @@ TEST(GeoDBTest, Search) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char* argv[]) { int main(int argc, char* argv[]) {
return rocksdb::test::RunAllTests(); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} }

@ -106,7 +106,7 @@ class StringLists {
// The class for unit-testing // The class for unit-testing
class StringAppendOperatorTest { class StringAppendOperatorTest : public testing::Test {
public: public:
StringAppendOperatorTest() { StringAppendOperatorTest() {
DestroyDB(kDbName, Options()); // Start each test with a fresh DB DestroyDB(kDbName, Options()); // Start each test with a fresh DB
@ -127,7 +127,7 @@ StringAppendOperatorTest::OpenFuncPtr StringAppendOperatorTest::OpenDb = nullptr
// THE TEST CASES BEGIN HERE // THE TEST CASES BEGIN HERE
TEST(StringAppendOperatorTest, IteratorTest) { TEST_F(StringAppendOperatorTest, IteratorTest) {
auto db_ = OpenDb(','); auto db_ = OpenDb(',');
StringLists slists(db_); StringLists slists(db_);
@ -220,7 +220,7 @@ TEST(StringAppendOperatorTest, IteratorTest) {
} }
TEST(StringAppendOperatorTest, SimpleTest) { TEST_F(StringAppendOperatorTest, SimpleTest) {
auto db = OpenDb(','); auto db = OpenDb(',');
StringLists slists(db); StringLists slists(db);
@ -235,7 +235,7 @@ TEST(StringAppendOperatorTest, SimpleTest) {
ASSERT_EQ(res, "v1,v2,v3"); ASSERT_EQ(res, "v1,v2,v3");
} }
TEST(StringAppendOperatorTest, SimpleDelimiterTest) { TEST_F(StringAppendOperatorTest, SimpleDelimiterTest) {
auto db = OpenDb('|'); auto db = OpenDb('|');
StringLists slists(db); StringLists slists(db);
@ -248,7 +248,7 @@ TEST(StringAppendOperatorTest, SimpleDelimiterTest) {
ASSERT_EQ(res, "v1|v2|v3"); ASSERT_EQ(res, "v1|v2|v3");
} }
TEST(StringAppendOperatorTest, OneValueNoDelimiterTest) { TEST_F(StringAppendOperatorTest, OneValueNoDelimiterTest) {
auto db = OpenDb('!'); auto db = OpenDb('!');
StringLists slists(db); StringLists slists(db);
@ -259,7 +259,7 @@ TEST(StringAppendOperatorTest, OneValueNoDelimiterTest) {
ASSERT_EQ(res, "single_val"); ASSERT_EQ(res, "single_val");
} }
TEST(StringAppendOperatorTest, VariousKeys) { TEST_F(StringAppendOperatorTest, VariousKeys) {
auto db = OpenDb('\n'); auto db = OpenDb('\n');
StringLists slists(db); StringLists slists(db);
@ -285,7 +285,7 @@ TEST(StringAppendOperatorTest, VariousKeys) {
} }
// Generate semi random keys/words from a small distribution. // Generate semi random keys/words from a small distribution.
TEST(StringAppendOperatorTest, RandomMixGetAppend) { TEST_F(StringAppendOperatorTest, RandomMixGetAppend) {
auto db = OpenDb(' '); auto db = OpenDb(' ');
StringLists slists(db); StringLists slists(db);
@ -336,7 +336,7 @@ TEST(StringAppendOperatorTest, RandomMixGetAppend) {
} }
TEST(StringAppendOperatorTest, BIGRandomMixGetAppend) { TEST_F(StringAppendOperatorTest, BIGRandomMixGetAppend) {
auto db = OpenDb(' '); auto db = OpenDb(' ');
StringLists slists(db); StringLists slists(db);
@ -387,8 +387,7 @@ TEST(StringAppendOperatorTest, BIGRandomMixGetAppend) {
} }
TEST_F(StringAppendOperatorTest, PersistentVariousKeys) {
TEST(StringAppendOperatorTest, PersistentVariousKeys) {
// Perform the following operations in limited scope // Perform the following operations in limited scope
{ {
auto db = OpenDb('\n'); auto db = OpenDb('\n');
@ -455,7 +454,7 @@ TEST(StringAppendOperatorTest, PersistentVariousKeys) {
} }
} }
TEST(StringAppendOperatorTest, PersistentFlushAndCompaction) { TEST_F(StringAppendOperatorTest, PersistentFlushAndCompaction) {
// Perform the following operations in limited scope // Perform the following operations in limited scope
{ {
auto db = OpenDb('\n'); auto db = OpenDb('\n');
@ -551,7 +550,7 @@ TEST(StringAppendOperatorTest, PersistentFlushAndCompaction) {
} }
} }
TEST(StringAppendOperatorTest, SimpleTestNullDelimiter) { TEST_F(StringAppendOperatorTest, SimpleTestNullDelimiter) {
auto db = OpenDb('\0'); auto db = OpenDb('\0');
StringLists slists(db); StringLists slists(db);
@ -577,19 +576,20 @@ TEST(StringAppendOperatorTest, SimpleTestNullDelimiter) {
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
// Run with regular database // Run with regular database
int result; int result;
{ {
fprintf(stderr, "Running tests with regular db and operator.\n"); fprintf(stderr, "Running tests with regular db and operator.\n");
StringAppendOperatorTest::SetOpenDbFunction(&OpenNormalDb); StringAppendOperatorTest::SetOpenDbFunction(&OpenNormalDb);
result = rocksdb::test::RunAllTests(); result = RUN_ALL_TESTS();
} }
// Run with TTL // Run with TTL
{ {
fprintf(stderr, "Running tests with ttl db and generic operator.\n"); fprintf(stderr, "Running tests with ttl db and generic operator.\n");
StringAppendOperatorTest::SetOpenDbFunction(&OpenTtlDb); StringAppendOperatorTest::SetOpenDbFunction(&OpenTtlDb);
result |= rocksdb::test::RunAllTests(); result |= RUN_ALL_TESTS();
} }
return result; return result;

@ -28,7 +28,7 @@ using namespace std;
namespace rocksdb { namespace rocksdb {
class RedisListsTest { class RedisListsTest : public testing::Test {
public: public:
static const string kDefaultDbName; static const string kDefaultDbName;
static Options options; static Options options;
@ -55,7 +55,7 @@ void AssertListEq(const std::vector<std::string>& result,
} // namespace } // namespace
// PushRight, Length, Index, Range // PushRight, Length, Index, Range
TEST(RedisListsTest, SimpleTest) { TEST_F(RedisListsTest, SimpleTest) {
RedisLists redis(kDefaultDbName, options, true); // Destructive RedisLists redis(kDefaultDbName, options, true); // Destructive
string tempv; // Used below for all Index(), PopRight(), PopLeft() string tempv; // Used below for all Index(), PopRight(), PopLeft()
@ -84,7 +84,7 @@ TEST(RedisListsTest, SimpleTest) {
} }
// PushLeft, Length, Index, Range // PushLeft, Length, Index, Range
TEST(RedisListsTest, SimpleTest2) { TEST_F(RedisListsTest, SimpleTest2) {
RedisLists redis(kDefaultDbName, options, true); // Destructive RedisLists redis(kDefaultDbName, options, true); // Destructive
string tempv; // Used below for all Index(), PopRight(), PopLeft() string tempv; // Used below for all Index(), PopRight(), PopLeft()
@ -113,7 +113,7 @@ TEST(RedisListsTest, SimpleTest2) {
} }
// Exhaustive test of the Index() function // Exhaustive test of the Index() function
TEST(RedisListsTest, IndexTest) { TEST_F(RedisListsTest, IndexTest) {
RedisLists redis(kDefaultDbName, options, true); // Destructive RedisLists redis(kDefaultDbName, options, true); // Destructive
string tempv; // Used below for all Index(), PopRight(), PopLeft() string tempv; // Used below for all Index(), PopRight(), PopLeft()
@ -172,7 +172,7 @@ TEST(RedisListsTest, IndexTest) {
// Exhaustive test of the Range() function // Exhaustive test of the Range() function
TEST(RedisListsTest, RangeTest) { TEST_F(RedisListsTest, RangeTest) {
RedisLists redis(kDefaultDbName, options, true); // Destructive RedisLists redis(kDefaultDbName, options, true); // Destructive
string tempv; // Used below for all Index(), PopRight(), PopLeft() string tempv; // Used below for all Index(), PopRight(), PopLeft()
@ -255,7 +255,7 @@ TEST(RedisListsTest, RangeTest) {
} }
// Exhaustive test for InsertBefore(), and InsertAfter() // Exhaustive test for InsertBefore(), and InsertAfter()
TEST(RedisListsTest, InsertTest) { TEST_F(RedisListsTest, InsertTest) {
RedisLists redis(kDefaultDbName, options, true); RedisLists redis(kDefaultDbName, options, true);
string tempv; // Used below for all Index(), PopRight(), PopLeft() string tempv; // Used below for all Index(), PopRight(), PopLeft()
@ -339,7 +339,7 @@ TEST(RedisListsTest, InsertTest) {
} }
// Exhaustive test of Set function // Exhaustive test of Set function
TEST(RedisListsTest, SetTest) { TEST_F(RedisListsTest, SetTest) {
RedisLists redis(kDefaultDbName, options, true); RedisLists redis(kDefaultDbName, options, true);
string tempv; // Used below for all Index(), PopRight(), PopLeft() string tempv; // Used below for all Index(), PopRight(), PopLeft()
@ -435,7 +435,7 @@ TEST(RedisListsTest, SetTest) {
} }
// Testing Insert, Push, and Set, in a mixed environment // Testing Insert, Push, and Set, in a mixed environment
TEST(RedisListsTest, InsertPushSetTest) { TEST_F(RedisListsTest, InsertPushSetTest) {
RedisLists redis(kDefaultDbName, options, true); // Destructive RedisLists redis(kDefaultDbName, options, true); // Destructive
string tempv; // Used below for all Index(), PopRight(), PopLeft() string tempv; // Used below for all Index(), PopRight(), PopLeft()
@ -527,7 +527,7 @@ TEST(RedisListsTest, InsertPushSetTest) {
} }
// Testing Trim, Pop // Testing Trim, Pop
TEST(RedisListsTest, TrimPopTest) { TEST_F(RedisListsTest, TrimPopTest) {
RedisLists redis(kDefaultDbName, options, true); // Destructive RedisLists redis(kDefaultDbName, options, true); // Destructive
string tempv; // Used below for all Index(), PopRight(), PopLeft() string tempv; // Used below for all Index(), PopRight(), PopLeft()
@ -597,7 +597,7 @@ TEST(RedisListsTest, TrimPopTest) {
} }
// Testing Remove, RemoveFirst, RemoveLast // Testing Remove, RemoveFirst, RemoveLast
TEST(RedisListsTest, RemoveTest) { TEST_F(RedisListsTest, RemoveTest) {
RedisLists redis(kDefaultDbName, options, true); // Destructive RedisLists redis(kDefaultDbName, options, true); // Destructive
string tempv; // Used below for all Index(), PopRight(), PopLeft() string tempv; // Used below for all Index(), PopRight(), PopLeft()
@ -688,8 +688,7 @@ TEST(RedisListsTest, RemoveTest) {
// Test Multiple keys and Persistence // Test Multiple keys and Persistence
TEST(RedisListsTest, PersistenceMultiKeyTest) { TEST_F(RedisListsTest, PersistenceMultiKeyTest) {
string tempv; // Used below for all Index(), PopRight(), PopLeft() string tempv; // Used below for all Index(), PopRight(), PopLeft()
// Block one: populate a single key in the database // Block one: populate a single key in the database
@ -874,11 +873,12 @@ bool found_arg(int argc, char* argv[], const char* want){
// However, if -m is specified, it will do user manual/interactive testing // However, if -m is specified, it will do user manual/interactive testing
// -m -d is manual and destructive (will clear the database before use) // -m -d is manual and destructive (will clear the database before use)
int main(int argc, char* argv[]) { int main(int argc, char* argv[]) {
::testing::InitGoogleTest(&argc, argv);
if (found_arg(argc, argv, "-m")) { if (found_arg(argc, argv, "-m")) {
bool destructive = found_arg(argc, argv, "-d"); bool destructive = found_arg(argc, argv, "-d");
return rocksdb::manual_redis_test(destructive); return rocksdb::manual_redis_test(destructive);
} else { } else {
return rocksdb::test::RunAllTests(); return RUN_ALL_TESTS();
} }
} }

@ -15,7 +15,7 @@
namespace rocksdb { namespace rocksdb {
namespace spatial { namespace spatial {
class SpatialDBTest { class SpatialDBTest : public testing::Test {
public: public:
SpatialDBTest() { SpatialDBTest() {
dbname_ = test::TmpDir() + "/spatial_db_test"; dbname_ = test::TmpDir() + "/spatial_db_test";
@ -46,7 +46,7 @@ class SpatialDBTest {
SpatialDB* db_; SpatialDB* db_;
}; };
TEST(SpatialDBTest, FeatureSetSerializeTest) { TEST_F(SpatialDBTest, FeatureSetSerializeTest) {
FeatureSet fs; FeatureSet fs;
fs.Set("a", std::string("b")); fs.Set("a", std::string("b"));
@ -93,7 +93,7 @@ TEST(SpatialDBTest, FeatureSetSerializeTest) {
ASSERT_TRUE(!deserialized.Deserialize(serialized)); ASSERT_TRUE(!deserialized.Deserialize(serialized));
} }
TEST(SpatialDBTest, TestNextID) { TEST_F(SpatialDBTest, TestNextID) {
ASSERT_OK(SpatialDB::Create( ASSERT_OK(SpatialDB::Create(
SpatialDBOptions(), dbname_, SpatialDBOptions(), dbname_,
{SpatialIndexOptions("simple", BoundingBox<double>(0, 0, 100, 100), 2)})); {SpatialIndexOptions("simple", BoundingBox<double>(0, 0, 100, 100), 2)}));
@ -116,7 +116,7 @@ TEST(SpatialDBTest, TestNextID) {
delete db_; delete db_;
} }
TEST(SpatialDBTest, FeatureSetTest) { TEST_F(SpatialDBTest, FeatureSetTest) {
ASSERT_OK(SpatialDB::Create( ASSERT_OK(SpatialDB::Create(
SpatialDBOptions(), dbname_, SpatialDBOptions(), dbname_,
{SpatialIndexOptions("simple", BoundingBox<double>(0, 0, 100, 100), 2)})); {SpatialIndexOptions("simple", BoundingBox<double>(0, 0, 100, 100), 2)}));
@ -150,7 +150,7 @@ TEST(SpatialDBTest, FeatureSetTest) {
delete db_; delete db_;
} }
TEST(SpatialDBTest, SimpleTest) { TEST_F(SpatialDBTest, SimpleTest) {
// iter 0 -- not read only // iter 0 -- not read only
// iter 1 -- read only // iter 1 -- read only
for (int iter = 0; iter < 2; ++iter) { for (int iter = 0; iter < 2; ++iter) {
@ -226,7 +226,7 @@ BoundingBox<double> ScaleBB(BoundingBox<int> b, double step) {
} // namespace } // namespace
TEST(SpatialDBTest, RandomizedTest) { TEST_F(SpatialDBTest, RandomizedTest) {
Random rnd(301); Random rnd(301);
std::vector<std::pair<std::string, BoundingBox<int>>> elements; std::vector<std::pair<std::string, BoundingBox<int>>> elements;
@ -268,4 +268,7 @@ TEST(SpatialDBTest, RandomizedTest) {
} // namespace spatial } // namespace spatial
} // namespace rocksdb } // namespace rocksdb
int main(int argc, char** argv) { return rocksdb::test::RunAllTests(); } int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

@ -38,7 +38,7 @@ class SpecialTimeEnv : public EnvWrapper {
int64_t current_time_; int64_t current_time_;
}; };
class TtlTest { class TtlTest : public testing::Test {
public: public:
TtlTest() { TtlTest() {
env_.reset(new SpecialTimeEnv(Env::Default())); env_.reset(new SpecialTimeEnv(Env::Default()));
@ -372,7 +372,7 @@ class TtlTest {
// This test opens the db 3 times with such default behavior and inserts a // This test opens the db 3 times with such default behavior and inserts a
// bunch of kvs each time. All kvs should accumulate in the db till the end // bunch of kvs each time. All kvs should accumulate in the db till the end
// Partitions the sample-size provided into 3 sets over boundary1 and boundary2 // Partitions the sample-size provided into 3 sets over boundary1 and boundary2
TEST(TtlTest, NoEffect) { TEST_F(TtlTest, NoEffect) {
MakeKVMap(kSampleSize_); MakeKVMap(kSampleSize_);
int64_t boundary1 = kSampleSize_ / 3; int64_t boundary1 = kSampleSize_ / 3;
int64_t boundary2 = 2 * boundary1; int64_t boundary2 = 2 * boundary1;
@ -394,7 +394,7 @@ TEST(TtlTest, NoEffect) {
} }
// Puts a set of values and checks its presence using Get during ttl // Puts a set of values and checks its presence using Get during ttl
TEST(TtlTest, PresentDuringTTL) { TEST_F(TtlTest, PresentDuringTTL) {
MakeKVMap(kSampleSize_); MakeKVMap(kSampleSize_);
OpenTtl(2); // T=0:Open the db with ttl = 2 OpenTtl(2); // T=0:Open the db with ttl = 2
@ -404,7 +404,7 @@ TEST(TtlTest, PresentDuringTTL) {
} }
// Puts a set of values and checks its absence using Get after ttl // Puts a set of values and checks its absence using Get after ttl
TEST(TtlTest, AbsentAfterTTL) { TEST_F(TtlTest, AbsentAfterTTL) {
MakeKVMap(kSampleSize_); MakeKVMap(kSampleSize_);
OpenTtl(1); // T=0:Open the db with ttl = 2 OpenTtl(1); // T=0:Open the db with ttl = 2
@ -415,7 +415,7 @@ TEST(TtlTest, AbsentAfterTTL) {
// Resets the timestamp of a set of kvs by updating them and checks that they // Resets the timestamp of a set of kvs by updating them and checks that they
// are not deleted according to the old timestamp // are not deleted according to the old timestamp
TEST(TtlTest, ResetTimestamp) { TEST_F(TtlTest, ResetTimestamp) {
MakeKVMap(kSampleSize_); MakeKVMap(kSampleSize_);
OpenTtl(3); OpenTtl(3);
@ -427,7 +427,7 @@ TEST(TtlTest, ResetTimestamp) {
} }
// Similar to PresentDuringTTL but uses Iterator // Similar to PresentDuringTTL but uses Iterator
TEST(TtlTest, IterPresentDuringTTL) { TEST_F(TtlTest, IterPresentDuringTTL) {
MakeKVMap(kSampleSize_); MakeKVMap(kSampleSize_);
OpenTtl(2); OpenTtl(2);
@ -437,7 +437,7 @@ TEST(TtlTest, IterPresentDuringTTL) {
} }
// Similar to AbsentAfterTTL but uses Iterator // Similar to AbsentAfterTTL but uses Iterator
TEST(TtlTest, IterAbsentAfterTTL) { TEST_F(TtlTest, IterAbsentAfterTTL) {
MakeKVMap(kSampleSize_); MakeKVMap(kSampleSize_);
OpenTtl(1); OpenTtl(1);
@ -448,7 +448,7 @@ TEST(TtlTest, IterAbsentAfterTTL) {
// Checks presence while opening the same db more than once with the same ttl // Checks presence while opening the same db more than once with the same ttl
// Note: The second open will open the same db // Note: The second open will open the same db
TEST(TtlTest, MultiOpenSamePresent) { TEST_F(TtlTest, MultiOpenSamePresent) {
MakeKVMap(kSampleSize_); MakeKVMap(kSampleSize_);
OpenTtl(2); OpenTtl(2);
@ -462,7 +462,7 @@ TEST(TtlTest, MultiOpenSamePresent) {
// Checks absence while opening the same db more than once with the same ttl // Checks absence while opening the same db more than once with the same ttl
// Note: The second open will open the same db // Note: The second open will open the same db
TEST(TtlTest, MultiOpenSameAbsent) { TEST_F(TtlTest, MultiOpenSameAbsent) {
MakeKVMap(kSampleSize_); MakeKVMap(kSampleSize_);
OpenTtl(1); OpenTtl(1);
@ -475,7 +475,7 @@ TEST(TtlTest, MultiOpenSameAbsent) {
} }
// Checks presence while opening the same db more than once with bigger ttl // Checks presence while opening the same db more than once with bigger ttl
TEST(TtlTest, MultiOpenDifferent) { TEST_F(TtlTest, MultiOpenDifferent) {
MakeKVMap(kSampleSize_); MakeKVMap(kSampleSize_);
OpenTtl(1); OpenTtl(1);
@ -488,7 +488,7 @@ TEST(TtlTest, MultiOpenDifferent) {
} }
// Checks presence during ttl in read_only mode // Checks presence during ttl in read_only mode
TEST(TtlTest, ReadOnlyPresentForever) { TEST_F(TtlTest, ReadOnlyPresentForever) {
MakeKVMap(kSampleSize_); MakeKVMap(kSampleSize_);
OpenTtl(1); // T=0:Open the db normally OpenTtl(1); // T=0:Open the db normally
@ -502,7 +502,7 @@ TEST(TtlTest, ReadOnlyPresentForever) {
// Checks whether WriteBatch works well with TTL // Checks whether WriteBatch works well with TTL
// Puts all kvs in kvmap_ in a batch and writes first, then deletes first half // Puts all kvs in kvmap_ in a batch and writes first, then deletes first half
TEST(TtlTest, WriteBatchTest) { TEST_F(TtlTest, WriteBatchTest) {
MakeKVMap(kSampleSize_); MakeKVMap(kSampleSize_);
BatchOperation batch_ops[kSampleSize_]; BatchOperation batch_ops[kSampleSize_];
for (int i = 0; i < kSampleSize_; i++) { for (int i = 0; i < kSampleSize_; i++) {
@ -521,7 +521,7 @@ TEST(TtlTest, WriteBatchTest) {
} }
// Checks user's compaction filter for correctness with TTL logic // Checks user's compaction filter for correctness with TTL logic
TEST(TtlTest, CompactionFilter) { TEST_F(TtlTest, CompactionFilter) {
MakeKVMap(kSampleSize_); MakeKVMap(kSampleSize_);
OpenTtlWithTestCompaction(1); OpenTtlWithTestCompaction(1);
@ -541,7 +541,7 @@ TEST(TtlTest, CompactionFilter) {
// Insert some key-values which KeyMayExist should be able to get and check that // Insert some key-values which KeyMayExist should be able to get and check that
// values returned are fine // values returned are fine
TEST(TtlTest, KeyMayExist) { TEST_F(TtlTest, KeyMayExist) {
MakeKVMap(kSampleSize_); MakeKVMap(kSampleSize_);
OpenTtl(); OpenTtl();
@ -552,7 +552,7 @@ TEST(TtlTest, KeyMayExist) {
CloseTtl(); CloseTtl();
} }
TEST(TtlTest, MultiGetTest) { TEST_F(TtlTest, MultiGetTest) {
MakeKVMap(kSampleSize_); MakeKVMap(kSampleSize_);
OpenTtl(); OpenTtl();
@ -563,7 +563,7 @@ TEST(TtlTest, MultiGetTest) {
CloseTtl(); CloseTtl();
} }
TEST(TtlTest, ColumnFamiliesTest) { TEST_F(TtlTest, ColumnFamiliesTest) {
DB* db; DB* db;
Options options; Options options;
options.create_if_missing = true; options.create_if_missing = true;
@ -624,5 +624,6 @@ TEST(TtlTest, ColumnFamiliesTest) {
// A black-box test for the ttl wrapper around rocksdb // A black-box test for the ttl wrapper around rocksdb
int main(int argc, char** argv) { int main(int argc, char** argv) {
return rocksdb::test::RunAllTests(); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} }

@ -69,9 +69,9 @@ struct TestHandler : public WriteBatch::Handler {
}; };
} // namespace anonymous } // namespace anonymous
class WriteBatchWithIndexTest {}; class WriteBatchWithIndexTest : public testing::Test {};
TEST(WriteBatchWithIndexTest, TestValueAsSecondaryIndex) { TEST_F(WriteBatchWithIndexTest, TestValueAsSecondaryIndex) {
Entry entries[] = {{"aaa", "0005", kPutRecord}, Entry entries[] = {{"aaa", "0005", kPutRecord},
{"b", "0002", kPutRecord}, {"b", "0002", kPutRecord},
{"cdd", "0002", kMergeRecord}, {"cdd", "0002", kMergeRecord},
@ -278,7 +278,7 @@ TEST(WriteBatchWithIndexTest, TestValueAsSecondaryIndex) {
} }
} }
TEST(WriteBatchWithIndexTest, TestComparatorForCF) { TEST_F(WriteBatchWithIndexTest, TestComparatorForCF) {
ColumnFamilyHandleImplDummy cf1(6, nullptr); ColumnFamilyHandleImplDummy cf1(6, nullptr);
ColumnFamilyHandleImplDummy reverse_cf(66, ReverseBytewiseComparator()); ColumnFamilyHandleImplDummy reverse_cf(66, ReverseBytewiseComparator());
ColumnFamilyHandleImplDummy cf2(88, BytewiseComparator()); ColumnFamilyHandleImplDummy cf2(88, BytewiseComparator());
@ -361,7 +361,7 @@ TEST(WriteBatchWithIndexTest, TestComparatorForCF) {
} }
} }
TEST(WriteBatchWithIndexTest, TestOverwriteKey) { TEST_F(WriteBatchWithIndexTest, TestOverwriteKey) {
ColumnFamilyHandleImplDummy cf1(6, nullptr); ColumnFamilyHandleImplDummy cf1(6, nullptr);
ColumnFamilyHandleImplDummy reverse_cf(66, ReverseBytewiseComparator()); ColumnFamilyHandleImplDummy reverse_cf(66, ReverseBytewiseComparator());
ColumnFamilyHandleImplDummy cf2(88, BytewiseComparator()); ColumnFamilyHandleImplDummy cf2(88, BytewiseComparator());
@ -515,7 +515,7 @@ void AssertItersEqual(Iterator* iter1, Iterator* iter2) {
} }
} // namespace } // namespace
TEST(WriteBatchWithIndexTest, TestRandomIteraratorWithBase) { TEST_F(WriteBatchWithIndexTest, TestRandomIteraratorWithBase) {
std::vector<std::string> source_strings = {"a", "b", "c", "d", "e", std::vector<std::string> source_strings = {"a", "b", "c", "d", "e",
"f", "g", "h", "i", "j"}; "f", "g", "h", "i", "j"};
for (int rand_seed = 301; rand_seed < 366; rand_seed++) { for (int rand_seed = 301; rand_seed < 366; rand_seed++) {
@ -628,7 +628,7 @@ TEST(WriteBatchWithIndexTest, TestRandomIteraratorWithBase) {
} }
} }
TEST(WriteBatchWithIndexTest, TestIteraratorWithBase) { TEST_F(WriteBatchWithIndexTest, TestIteraratorWithBase) {
ColumnFamilyHandleImplDummy cf1(6, BytewiseComparator()); ColumnFamilyHandleImplDummy cf1(6, BytewiseComparator());
ColumnFamilyHandleImplDummy cf2(2, BytewiseComparator()); ColumnFamilyHandleImplDummy cf2(2, BytewiseComparator());
WriteBatchWithIndex batch(BytewiseComparator(), 20, true); WriteBatchWithIndex batch(BytewiseComparator(), 20, true);
@ -791,7 +791,7 @@ TEST(WriteBatchWithIndexTest, TestIteraratorWithBase) {
} }
} }
TEST(WriteBatchWithIndexTest, TestIteraratorWithBaseReverseCmp) { TEST_F(WriteBatchWithIndexTest, TestIteraratorWithBaseReverseCmp) {
ColumnFamilyHandleImplDummy cf1(6, ReverseBytewiseComparator()); ColumnFamilyHandleImplDummy cf1(6, ReverseBytewiseComparator());
ColumnFamilyHandleImplDummy cf2(2, ReverseBytewiseComparator()); ColumnFamilyHandleImplDummy cf2(2, ReverseBytewiseComparator());
WriteBatchWithIndex batch(BytewiseComparator(), 20, true); WriteBatchWithIndex batch(BytewiseComparator(), 20, true);
@ -879,4 +879,7 @@ TEST(WriteBatchWithIndexTest, TestIteraratorWithBaseReverseCmp) {
} // namespace } // namespace
int main(int argc, char** argv) { return rocksdb::test::RunAllTests(); } int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

Loading…
Cancel
Save