作者: 韩晨旭 10225101440 李畅 10225102463
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

89 lines
2.5 KiB

  1. // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file. See the AUTHORS file for names of contributors.
  4. #include "leveldb/db.h"
  5. #include "db/memtable.h"
  6. #include "db/write_batch_internal.h"
  7. #include "leveldb/env.h"
  8. #include "util/logging.h"
  9. #include "util/testharness.h"
  10. namespace leveldb {
  11. static std::string PrintContents(WriteBatch* b) {
  12. InternalKeyComparator cmp(BytewiseComparator());
  13. MemTable* mem = new MemTable(cmp);
  14. mem->Ref();
  15. std::string state;
  16. Status s = WriteBatchInternal::InsertInto(b, mem);
  17. Iterator* iter = mem->NewIterator();
  18. for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
  19. ParsedInternalKey ikey;
  20. ASSERT_TRUE(ParseInternalKey(iter->key(), &ikey));
  21. switch (ikey.type) {
  22. case kTypeValue:
  23. state.append("Put(");
  24. state.append(ikey.user_key.ToString());
  25. state.append(", ");
  26. state.append(iter->value().ToString());
  27. state.append(")");
  28. break;
  29. case kTypeDeletion:
  30. state.append("Delete(");
  31. state.append(ikey.user_key.ToString());
  32. state.append(")");
  33. break;
  34. }
  35. state.append("@");
  36. state.append(NumberToString(ikey.sequence));
  37. }
  38. delete iter;
  39. if (!s.ok()) {
  40. state.append("ParseError()");
  41. }
  42. mem->Unref();
  43. return state;
  44. }
  45. class WriteBatchTest { };
  46. TEST(WriteBatchTest, Empty) {
  47. WriteBatch batch;
  48. ASSERT_EQ("", PrintContents(&batch));
  49. ASSERT_EQ(0, WriteBatchInternal::Count(&batch));
  50. }
  51. TEST(WriteBatchTest, Multiple) {
  52. WriteBatch batch;
  53. batch.Put(Slice("foo"), Slice("bar"));
  54. batch.Delete(Slice("box"));
  55. batch.Put(Slice("baz"), Slice("boo"));
  56. WriteBatchInternal::SetSequence(&batch, 100);
  57. ASSERT_EQ(100, WriteBatchInternal::Sequence(&batch));
  58. ASSERT_EQ(3, WriteBatchInternal::Count(&batch));
  59. ASSERT_EQ("Put(baz, boo)@102"
  60. "Delete(box)@101"
  61. "Put(foo, bar)@100",
  62. PrintContents(&batch));
  63. }
  64. TEST(WriteBatchTest, Corruption) {
  65. WriteBatch batch;
  66. batch.Put(Slice("foo"), Slice("bar"));
  67. batch.Delete(Slice("box"));
  68. WriteBatchInternal::SetSequence(&batch, 200);
  69. Slice contents = WriteBatchInternal::Contents(&batch);
  70. WriteBatchInternal::SetContents(&batch,
  71. Slice(contents.data(),contents.size()-1));
  72. ASSERT_EQ("Put(foo, bar)@200"
  73. "ParseError()",
  74. PrintContents(&batch));
  75. }
  76. } // namespace leveldb
  77. int main(int argc, char** argv) {
  78. return leveldb::test::RunAllTests();
  79. }