1 // Copyright (c) 2011-present, Facebook, Inc. All rights reserved. 2 // This source code is licensed under both the GPLv2 (found in the 3 // COPYING file in the root directory) and Apache 2.0 License 4 // (found in the LICENSE.Apache file in the root directory). 5 6 package org.rocksdb; 7 8 import java.util.Arrays; 9 import java.util.List; 10 11 import org.junit.ClassRule; 12 import org.junit.Test; 13 import org.rocksdb.util.CapturingWriteBatchHandler; 14 import org.rocksdb.util.CapturingWriteBatchHandler.Event; 15 16 import static org.assertj.core.api.Assertions.assertThat; 17 import static org.rocksdb.util.CapturingWriteBatchHandler.Action.*; 18 19 20 public class WriteBatchHandlerTest { 21 @ClassRule 22 public static final RocksNativeLibraryResource ROCKS_NATIVE_LIBRARY_RESOURCE = 23 new RocksNativeLibraryResource(); 24 25 @Test 26 public void writeBatchHandler() throws RocksDBException { 27 // setup test data 28 final List<Event> testEvents = Arrays.asList( 29 new Event(DELETE, "k0".getBytes(), null), 30 new Event(PUT, "k1".getBytes(), "v1".getBytes()), 31 new Event(PUT, "k2".getBytes(), "v2".getBytes()), 32 new Event(PUT, "k3".getBytes(), "v3".getBytes()), 33 new Event(LOG, null, "log1".getBytes()), 34 new Event(MERGE, "k2".getBytes(), "v22".getBytes()), startDb()35 new Event(DELETE, "k3".getBytes(), null) 36 ); 37 38 // load test data to the write batch setSnapshot()39 try (final WriteBatch batch = new WriteBatch()) { 40 for (final Event testEvent : testEvents) { 41 switch (testEvent.action) { 42 43 case PUT: 44 batch.put(testEvent.key, testEvent.value); 45 break; 46 47 case MERGE: 48 batch.merge(testEvent.key, testEvent.value); 49 break; 50 51 case DELETE: 52 batch.delete(testEvent.key); 53 break; 54 55 case LOG: 56 batch.putLogData(testEvent.value); 57 break; 58 } 59 } 60 61 // attempt to read test data back from the WriteBatch by iterating 62 // with a handler 63 try (final CapturingWriteBatchHandler handler = 64 new CapturingWriteBatchHandler()) { 65 batch.iterate(handler); 66 67 // compare the results to the test data 68 final List<Event> actualEvents = 69 handler.getEvents(); 70 assertThat(testEvents.size()).isSameAs(actualEvents.size()); 71 72 assertThat(testEvents).isEqualTo(actualEvents); 73 } 74 } 75 } 76 } 77