#include "gtest/gtest.h" #include "leveldb/env.h" #include "leveldb/db.h" // 这个头文件是为了EncodeFixed32 #include "util/coding.h" using namespace leveldb; constexpr int value_size = 2048; constexpr int data_size = 128 << 20; Status OpenDB(std::string dbName, DB **db) { Options options; options.create_if_missing = true; return DB::Open(options, dbName, db); } //测试多字段-橙 TEST(TestSchema, Basic) { DB *db; if(OpenDB("testdb", &db).ok() == false) { std::cerr << "open db failed" << std::endl; abort(); } std::string key = "k_1"; FieldArray fields = { {"name", "Customer#000000001"}, {"address", "IVhzIApeRb"}, {"phone", "25-989-741-2988"} }; db->Put_fields(WriteOptions(), key, fields); db->Get_fields(ReadOptions(), key, &fields); //清理数据库 delete db; } // 测试 FindKeysByField 函数 /* 1.在测试中创建多个键值对,验证 FindKeysByField 能否正确地查找并返回匹配的键。 2.使用 FindKeysByField 查找字段值,检查它是否能够找到匹配的键。 */ TEST(TestSchema, FindKeysByFieldTest) { DB *db; if (OpenDB("testdb", &db).ok() == false) { std::cerr << "open db failed" << std::endl; abort(); } // 插入多个键值对 std::string key1 = "k_1"; FieldArray fields1 = { {"name", "Customer#000000001"}, {"address", "IVhzIApeRb"}, {"phone", "25-989-741-2988"} }; db->Put_fields(WriteOptions(), key1, fields1); std::string key2 = "k_2"; FieldArray fields2 = { {"name", "Customer#000000002"}, {"address", "IVhzIApeRb"}, {"phone", "25-123-456-7890"} }; db->Put_fields(WriteOptions(), key2, fields2); std::string key3 = "k_3"; FieldArray fields3 = { {"name", "Customer#000000003"}, {"address", "TXkjZEdIrZ"}, {"phone", "25-555-888-1234"} }; db->Put_fields(WriteOptions(), key3, fields3); // 测试 FindKeysByField Field search_field = {"address", "IVhzIApeRb"}; std::vector matching_keys = db->FindKeysByField(db, search_field); EXPECT_EQ(matching_keys.size(), 2); EXPECT_TRUE(std::find(matching_keys.begin(), matching_keys.end(), key1) != matching_keys.end()); EXPECT_TRUE(std::find(matching_keys.begin(), matching_keys.end(), key2) != matching_keys.end()); // 清理数据库 delete db; } int main(int argc, char** argv) { // All tests currently run with the same read-only file limits. testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }