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.

87 lines
2.4 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(cmp);
  14. std::string state;
  15. Status s = WriteBatchInternal::InsertInto(b, &mem);
  16. Iterator* iter = mem.NewIterator();
  17. for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
  18. ParsedInternalKey ikey;
  19. ASSERT_TRUE(ParseInternalKey(iter->key(), &ikey));
  20. switch (ikey.type) {
  21. case kTypeValue:
  22. state.append("Put(");
  23. state.append(ikey.user_key.ToString());
  24. state.append(", ");
  25. state.append(iter->value().ToString());
  26. state.append(")");
  27. break;
  28. case kTypeDeletion:
  29. state.append("Delete(");
  30. state.append(ikey.user_key.ToString());
  31. state.append(")");
  32. break;
  33. }
  34. state.append("@");
  35. state.append(NumberToString(ikey.sequence));
  36. }
  37. delete iter;
  38. if (!s.ok()) {
  39. state.append("ParseError()");
  40. }
  41. return state;
  42. }
  43. class WriteBatchTest { };
  44. TEST(WriteBatchTest, Empty) {
  45. WriteBatch batch;
  46. ASSERT_EQ("", PrintContents(&batch));
  47. ASSERT_EQ(0, WriteBatchInternal::Count(&batch));
  48. }
  49. TEST(WriteBatchTest, Multiple) {
  50. WriteBatch batch;
  51. batch.Put(Slice("foo"), Slice("bar"));
  52. batch.Delete(Slice("box"));
  53. batch.Put(Slice("baz"), Slice("boo"));
  54. WriteBatchInternal::SetSequence(&batch, 100);
  55. ASSERT_EQ(100, WriteBatchInternal::Sequence(&batch));
  56. ASSERT_EQ(3, WriteBatchInternal::Count(&batch));
  57. ASSERT_EQ("Put(baz, boo)@102"
  58. "Delete(box)@101"
  59. "Put(foo, bar)@100",
  60. PrintContents(&batch));
  61. }
  62. TEST(WriteBatchTest, Corruption) {
  63. WriteBatch batch;
  64. batch.Put(Slice("foo"), Slice("bar"));
  65. batch.Delete(Slice("box"));
  66. WriteBatchInternal::SetSequence(&batch, 200);
  67. Slice contents = WriteBatchInternal::Contents(&batch);
  68. WriteBatchInternal::SetContents(&batch,
  69. Slice(contents.data(),contents.size()-1));
  70. ASSERT_EQ("Put(foo, bar)@200"
  71. "ParseError()",
  72. PrintContents(&batch));
  73. }
  74. }
  75. int main(int argc, char** argv) {
  76. return leveldb::test::RunAllTests();
  77. }