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.
5 #include "leveldb/db.h"
7 #include "db/memtable.h"
8 #include "db/write_batch_internal.h"
9 #include "leveldb/env.h"
10 #include "util/logging.h"
11 #include "util/testharness.h"
15 static std::string PrintContents(WriteBatch* b) {
16 InternalKeyComparator cmp(BytewiseComparator());
17 MemTable* mem = new MemTable(cmp);
20 Status s = WriteBatchInternal::InsertInto(b, mem);
22 Iterator* iter = mem->NewIterator();
23 for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
24 ParsedInternalKey ikey;
25 ASSERT_TRUE(ParseInternalKey(iter->key(), &ikey));
29 state.append(ikey.user_key.ToString());
31 state.append(iter->value().ToString());
36 state.append("Delete(");
37 state.append(ikey.user_key.ToString());
43 state.append(NumberToString(ikey.sequence));
47 state.append("ParseError()");
48 } else if (count != WriteBatchInternal::Count(b)) {
49 state.append("CountMismatch()");
55 class WriteBatchTest { };
57 TEST(WriteBatchTest, Empty) {
59 ASSERT_EQ("", PrintContents(&batch));
60 ASSERT_EQ(0, WriteBatchInternal::Count(&batch));
63 TEST(WriteBatchTest, Multiple) {
65 batch.Put(Slice("foo"), Slice("bar"));
66 batch.Delete(Slice("box"));
67 batch.Put(Slice("baz"), Slice("boo"));
68 WriteBatchInternal::SetSequence(&batch, 100);
69 ASSERT_EQ(100, WriteBatchInternal::Sequence(&batch));
70 ASSERT_EQ(3, WriteBatchInternal::Count(&batch));
71 ASSERT_EQ("Put(baz, boo)@102"
74 PrintContents(&batch));
77 TEST(WriteBatchTest, Corruption) {
79 batch.Put(Slice("foo"), Slice("bar"));
80 batch.Delete(Slice("box"));
81 WriteBatchInternal::SetSequence(&batch, 200);
82 Slice contents = WriteBatchInternal::Contents(&batch);
83 WriteBatchInternal::SetContents(&batch,
84 Slice(contents.data(),contents.size()-1));
85 ASSERT_EQ("Put(foo, bar)@200"
87 PrintContents(&batch));
90 TEST(WriteBatchTest, Append) {
92 WriteBatchInternal::SetSequence(&b1, 200);
93 WriteBatchInternal::SetSequence(&b2, 300);
94 WriteBatchInternal::Append(&b1, &b2);
98 WriteBatchInternal::Append(&b1, &b2);
99 ASSERT_EQ("Put(a, va)@200",
103 WriteBatchInternal::Append(&b1, &b2);
104 ASSERT_EQ("Put(a, va)@200"
108 WriteBatchInternal::Append(&b1, &b2);
109 ASSERT_EQ("Put(a, va)@200"
116 } // namespace leveldb
118 int main(int argc, char** argv) {
119 return leveldb::test::RunAllTests();