Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Test] migrate-junit5-client-module and parameterized beforeEach #4518

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
[Test] migrate-junit5-client-module
sherlock-lin committed Oct 25, 2024
commit 66add879e866faba9ca1eaa1366eb905d39be6a5
Original file line number Diff line number Diff line change
@@ -20,6 +20,8 @@
*/
package org.apache.bookkeeper.client;

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
@@ -33,8 +35,7 @@
import org.apache.bookkeeper.conf.ClientConfiguration;
import org.apache.bookkeeper.meta.HierarchicalLedgerManagerFactory;
import org.apache.bookkeeper.test.BookKeeperClusterTestCase;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@@ -51,7 +52,7 @@ public ConcurrentV2RecoveryTest() {
}

@Test
public void testConcurrentOpen() throws Exception {
void concurrentOpen() throws Exception {
ClientConfiguration conf = new ClientConfiguration();
conf.setMetadataServiceUri(zkUtil.getMetadataServiceUri())
.setNumChannelsPerBookie(16)
@@ -101,7 +102,7 @@ public void testConcurrentOpen() throws Exception {
// also fine, recovery can currently fail because of metadata conflicts.
// We should fix this at some point by making the metadata immutable,
// and restarting the entire operation
Assert.assertEquals(ee.getCause().getClass(), BKException.BKLedgerRecoveryException.class);
assertEquals(BKException.BKLedgerRecoveryException.class, ee.getCause().getClass());
}
}
}
Original file line number Diff line number Diff line change
@@ -18,10 +18,11 @@
package org.apache.bookkeeper.client;

import static org.apache.bookkeeper.common.concurrent.FutureUtils.result;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
@@ -30,7 +31,7 @@
import org.apache.bookkeeper.client.api.WriteFlag;
import org.apache.bookkeeper.client.api.WriteHandle;
import org.apache.bookkeeper.net.BookieId;
import org.junit.Test;
import org.junit.jupiter.api.Test;

/**
* Client side tests on deferred sync write flag.
@@ -42,7 +43,7 @@ public class DeferredSyncTest extends MockBookKeeperTestCase {
static final int NUM_ENTRIES = 100;

@Test
public void testAddEntryLastAddConfirmedDoesNotAdvance() throws Exception {
void addEntryLastAddConfirmedDoesNotAdvance() throws Exception {
try (WriteHandle wh = result(newCreateLedgerOp()
.withEnsembleSize(3)
.withWriteQuorumSize(3)
@@ -61,7 +62,7 @@ public void testAddEntryLastAddConfirmedDoesNotAdvance() throws Exception {
}

@Test
public void testAddEntryLastAddConfirmedAdvanceWithForce() throws Exception {
void addEntryLastAddConfirmedAdvanceWithForce() throws Exception {
try (WriteHandle wh = result(newCreateLedgerOp()
.withEnsembleSize(3)
.withWriteQuorumSize(3)
@@ -82,7 +83,7 @@ public void testAddEntryLastAddConfirmedAdvanceWithForce() throws Exception {
}

@Test
public void testForceOnWriteAdvHandle() throws Exception {
void forceOnWriteAdvHandle() throws Exception {
try (WriteAdvHandle wh = result(newCreateLedgerOp()
.withEnsembleSize(3)
.withWriteQuorumSize(3)
@@ -112,7 +113,7 @@ public void testForceOnWriteAdvHandle() throws Exception {
}

@Test
public void testForceRequiresFullEnsemble() throws Exception {
void forceRequiresFullEnsemble() throws Exception {
try (WriteHandle wh = result(newCreateLedgerOp()
.withEnsembleSize(3)
.withWriteQuorumSize(2)
@@ -146,7 +147,7 @@ public void testForceRequiresFullEnsemble() throws Exception {
}

@Test
public void testForceWillAdvanceLacOnlyUpToLastAcknowledgedWrite() throws Exception {
void forceWillAdvanceLacOnlyUpToLastAcknowledgedWrite() throws Exception {
try (WriteHandle wh = result(newCreateLedgerOp()
.withEnsembleSize(3)
.withWriteQuorumSize(3)
@@ -187,7 +188,7 @@ public void testForceWillAdvanceLacOnlyUpToLastAcknowledgedWrite() throws Except
}

@Test
public void testForbiddenEnsembleChange() throws Exception {
void forbiddenEnsembleChange() throws Exception {
try (WriteHandle wh = result(newCreateLedgerOp()
.withEnsembleSize(1)
.withWriteQuorumSize(1)
@@ -218,8 +219,8 @@ public void testForbiddenEnsembleChange() throws Exception {
}
}

@Test(expected = BKException.BKLedgerClosedException.class)
public void testCannotIssueForceOnClosedLedgerHandle() throws Exception {
@Test
void cannotIssueForceOnClosedLedgerHandle() throws Exception {
WriteHandle wh = result(newCreateLedgerOp()
.withEnsembleSize(1)
.withWriteQuorumSize(1)
@@ -228,7 +229,8 @@ public void testCannotIssueForceOnClosedLedgerHandle() throws Exception {
.withWriteFlags(WriteFlag.DEFERRED_SYNC)
.execute());
wh.close();
result(wh.force());
assertThrows(BKException.BKLedgerClosedException.class, () ->
result(wh.force()));
}

}

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -17,10 +17,10 @@
*/
package org.apache.bookkeeper.client;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.fail;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
@@ -32,16 +32,16 @@
import java.util.Set;
import org.apache.bookkeeper.net.BookieId;
import org.apache.bookkeeper.test.BookKeeperClusterTestCase;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.apache.bookkeeper.util.resolvers.BeforeParameterResolver;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;

/**
* Testing a generic ensemble placement policy.
*/
@RunWith(Parameterized.class)
@ExtendWith(BeforeParameterResolver.class)
public class GenericEnsemblePlacementPolicyTest extends BookKeeperClusterTestCase {

private BookKeeper.DigestType digestType = BookKeeper.DigestType.CRC32;
@@ -51,15 +51,18 @@ public class GenericEnsemblePlacementPolicyTest extends BookKeeperClusterTestCas
private static List<Map<String, byte[]>> customMetadataOnNewEnsembleStack = new ArrayList<>();
private static List<Map<String, byte[]>> customMetadataOnReplaceBookieStack = new ArrayList<>();

@Parameters
@BeforeEach
public void init(boolean diskWeightBasedPlacementEnabled) {
baseClientConf.setDiskWeightBasedPlacementEnabled(diskWeightBasedPlacementEnabled);
}

public static Collection<Object[]> getDiskWeightBasedPlacementEnabled() {
return Arrays.asList(new Object[][] { { false }, { true } });
return Arrays.asList(new Object[][]{{false}, {true}});
}

public GenericEnsemblePlacementPolicyTest(boolean diskWeightBasedPlacementEnabled) {
public GenericEnsemblePlacementPolicyTest() {
super(0);
baseClientConf.setEnsemblePlacementPolicy(CustomEnsemblePlacementPolicy.class);
baseClientConf.setDiskWeightBasedPlacementEnabled(diskWeightBasedPlacementEnabled);
}

/**
@@ -89,14 +92,15 @@ public PlacementResult<List<BookieId>> newEnsemble(int ensembleSize, int quorumS
}
}

@Before
public void reset() {
@BeforeEach
void reset() {
customMetadataOnNewEnsembleStack.clear();
customMetadataOnReplaceBookieStack.clear();
}

@Test
public void testNewEnsemble() throws Exception {
@MethodSource("getDiskWeightBasedPlacementEnabled")
@ParameterizedTest
public void newEnsemble(boolean diskWeightBasedPlacementEnabled) throws Exception {
numBookies = 1;
startBKCluster(zkUtil.getMetadataServiceUri());
try {
@@ -112,8 +116,10 @@ public void testNewEnsemble() throws Exception {
}
}

@Test
public void testNewEnsembleWithNotEnoughBookies() throws Exception {
@MethodSource("getDiskWeightBasedPlacementEnabled")
@ParameterizedTest
public void newEnsembleWithNotEnoughBookies(boolean diskWeightBasedPlacementEnabled)
throws Exception {
numBookies = 0;
try {
startBKCluster(zkUtil.getMetadataServiceUri());
@@ -132,8 +138,9 @@ public void testNewEnsembleWithNotEnoughBookies() throws Exception {
}
}

@Test
public void testReplaceBookie() throws Exception {
@MethodSource("getDiskWeightBasedPlacementEnabled")
@ParameterizedTest
public void replaceBookie(boolean diskWeightBasedPlacementEnabled) throws Exception {
numBookies = 3;
startBKCluster(zkUtil.getMetadataServiceUri());
try {

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -17,6 +17,11 @@
*/
package org.apache.bookkeeper.client;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;

import com.google.common.collect.Lists;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
@@ -26,8 +31,7 @@
import org.apache.bookkeeper.net.BookieId;
import org.apache.bookkeeper.net.BookieSocketAddress;
import org.apache.bookkeeper.versioning.Versioned;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@@ -44,7 +48,7 @@ public class LedgerClose2Test {
private static final BookieId b5 = new BookieSocketAddress("b5", 3181).toBookieId();

@Test
public void testTryAddAfterCloseHasBeenCalled() throws Exception {
void tryAddAfterCloseHasBeenCalled() throws Exception {
MockClientContext clientCtx = MockClientContext.create();

for (int i = 0; i < 1000; i++) {
@@ -58,18 +62,18 @@ public void testTryAddAfterCloseHasBeenCalled() throws Exception {

// if it succeeds, it should be in final ledge
closeFuture.get();
Assert.assertTrue(lh.getLedgerMetadata().isClosed());
Assert.assertEquals(lh.getLedgerMetadata().getLastEntryId(), eid);
assertTrue(lh.getLedgerMetadata().isClosed());
assertEquals(lh.getLedgerMetadata().getLastEntryId(), eid);
} catch (BKException.BKLedgerClosedException bke) {
closeFuture.get();
Assert.assertTrue(lh.getLedgerMetadata().isClosed());
Assert.assertEquals(lh.getLedgerMetadata().getLastEntryId(), LedgerHandle.INVALID_ENTRY_ID);
assertTrue(lh.getLedgerMetadata().isClosed());
assertEquals(LedgerHandle.INVALID_ENTRY_ID, lh.getLedgerMetadata().getLastEntryId());
}
}
}

@Test
public void testMetadataChangedDuringClose() throws Exception {
void metadataChangedDuringClose() throws Exception {
MockClientContext clientCtx = MockClientContext.create();
Versioned<LedgerMetadata> md = ClientUtil.setupLedger(clientCtx, 10L,
LedgerMetadataBuilder.create()
@@ -105,15 +109,15 @@ public void testMetadataChangedDuringClose() throws Exception {
blockClose.complete(null);
closeFuture.get();

Assert.assertTrue(lh.getLedgerMetadata().isClosed());
Assert.assertEquals(lh.getLedgerMetadata().getAllEnsembles().size(), 2);
Assert.assertEquals(lh.getLedgerMetadata().getAllEnsembles().get(0L), Lists.newArrayList(b4, b2, b5));
Assert.assertEquals(lh.getLedgerMetadata().getAllEnsembles().get(1L), Lists.newArrayList(b1, b2, b4));
Assert.assertEquals(lh.getLedgerMetadata().getLastEntryId(), 1L);
assertTrue(lh.getLedgerMetadata().isClosed());
assertEquals(2, lh.getLedgerMetadata().getAllEnsembles().size());
assertEquals(lh.getLedgerMetadata().getAllEnsembles().get(0L), Lists.newArrayList(b4, b2, b5));
assertEquals(lh.getLedgerMetadata().getAllEnsembles().get(1L), Lists.newArrayList(b1, b2, b4));
assertEquals(1L, lh.getLedgerMetadata().getLastEntryId());
}

@Test
public void testMetadataCloseWithCorrectLengthDuringClose() throws Exception {
void metadataCloseWithCorrectLengthDuringClose() throws Exception {
MockClientContext clientCtx = MockClientContext.create();
Versioned<LedgerMetadata> md = ClientUtil.setupLedger(clientCtx, 10L,
LedgerMetadataBuilder.create()
@@ -147,15 +151,15 @@ public void testMetadataCloseWithCorrectLengthDuringClose() throws Exception {
blockClose.complete(null);
closeFuture.get();

Assert.assertTrue(lh.getLedgerMetadata().isClosed());
Assert.assertEquals(lh.getLedgerMetadata().getAllEnsembles().size(), 1);
Assert.assertEquals(lh.getLedgerMetadata().getAllEnsembles().get(0L), Lists.newArrayList(b1, b2, b3));
Assert.assertEquals(lh.getLedgerMetadata().getLastEntryId(), lac);
Assert.assertEquals(lh.getLedgerMetadata().getLength(), length);
assertTrue(lh.getLedgerMetadata().isClosed());
assertEquals(1, lh.getLedgerMetadata().getAllEnsembles().size());
assertEquals(lh.getLedgerMetadata().getAllEnsembles().get(0L), Lists.newArrayList(b1, b2, b3));
assertEquals(lh.getLedgerMetadata().getLastEntryId(), lac);
assertEquals(lh.getLedgerMetadata().getLength(), length);
}

@Test
public void testMetadataCloseWithDifferentLengthDuringClose() throws Exception {
void metadataCloseWithDifferentLengthDuringClose() throws Exception {
MockClientContext clientCtx = MockClientContext.create();
Versioned<LedgerMetadata> md = ClientUtil.setupLedger(clientCtx, 10L,
LedgerMetadataBuilder.create()
@@ -190,14 +194,14 @@ public void testMetadataCloseWithDifferentLengthDuringClose() throws Exception {
blockClose.complete(null);
try {
closeFuture.get();
Assert.fail("Close should fail. Ledger has been closed in a state we don't know how to untangle");
fail("Close should fail. Ledger has been closed in a state we don't know how to untangle");
} catch (ExecutionException ee) {
Assert.assertEquals(ee.getCause().getClass(), BKException.BKMetadataVersionException.class);
assertEquals(BKException.BKMetadataVersionException.class, ee.getCause().getClass());
}
}

@Test
public void testMetadataCloseMarkedInRecoveryWhileClosing() throws Exception {
void metadataCloseMarkedInRecoveryWhileClosing() throws Exception {
MockClientContext clientCtx = MockClientContext.create();
Versioned<LedgerMetadata> md = ClientUtil.setupLedger(clientCtx, 10L,
LedgerMetadataBuilder.create()
@@ -229,15 +233,15 @@ public void testMetadataCloseMarkedInRecoveryWhileClosing() throws Exception {
blockClose.complete(null);

closeFuture.get(); // should override in recovery, since this handle knows what it has written
Assert.assertTrue(lh.getLedgerMetadata().isClosed());
Assert.assertEquals(lh.getLedgerMetadata().getAllEnsembles().size(), 1);
Assert.assertEquals(lh.getLedgerMetadata().getAllEnsembles().get(0L), Lists.newArrayList(b1, b2, b3));
Assert.assertEquals(lh.getLedgerMetadata().getLastEntryId(), lac);
Assert.assertEquals(lh.getLedgerMetadata().getLength(), length);
assertTrue(lh.getLedgerMetadata().isClosed());
assertEquals(1, lh.getLedgerMetadata().getAllEnsembles().size());
assertEquals(lh.getLedgerMetadata().getAllEnsembles().get(0L), Lists.newArrayList(b1, b2, b3));
assertEquals(lh.getLedgerMetadata().getLastEntryId(), lac);
assertEquals(lh.getLedgerMetadata().getLength(), length);
}

@Test
public void testCloseWhileAddInProgress() throws Exception {
void closeWhileAddInProgress() throws Exception {
MockClientContext clientCtx = MockClientContext.create();
Versioned<LedgerMetadata> md = ClientUtil.setupLedger(clientCtx, 10L,
LedgerMetadataBuilder.create()
@@ -257,19 +261,19 @@ public void testCloseWhileAddInProgress() throws Exception {
lh.close();
try {
future.get();
Assert.fail("That write shouldn't have succeeded");
fail("That write shouldn't have succeeded");
} catch (ExecutionException ee) {
Assert.assertEquals(ee.getCause().getClass(), BKException.BKLedgerClosedException.class);
assertEquals(BKException.BKLedgerClosedException.class, ee.getCause().getClass());
}
Assert.assertTrue(lh.getLedgerMetadata().isClosed());
Assert.assertEquals(lh.getLedgerMetadata().getAllEnsembles().size(), 1);
Assert.assertEquals(lh.getLedgerMetadata().getAllEnsembles().get(0L), Lists.newArrayList(b1, b2, b3));
Assert.assertEquals(lh.getLedgerMetadata().getLastEntryId(), LedgerHandle.INVALID_ENTRY_ID);
Assert.assertEquals(lh.getLedgerMetadata().getLength(), 0);
assertTrue(lh.getLedgerMetadata().isClosed());
assertEquals(1, lh.getLedgerMetadata().getAllEnsembles().size());
assertEquals(lh.getLedgerMetadata().getAllEnsembles().get(0L), Lists.newArrayList(b1, b2, b3));
assertEquals(LedgerHandle.INVALID_ENTRY_ID, lh.getLedgerMetadata().getLastEntryId());
assertEquals(0, lh.getLedgerMetadata().getLength());
}

@Test
public void testDoubleCloseOnHandle() throws Exception {
void doubleCloseOnHandle() throws Exception {
long ledgerId = 123L;
MockClientContext clientCtx = MockClientContext.create();

@@ -300,8 +304,8 @@ public void testDoubleCloseOnHandle() throws Exception {
CompletableFuture<Void> secondClose = writer.closeAsync();

Thread.sleep(500); // give it a chance to complete, the request jumps around threads
Assert.assertFalse(firstClose.isDone());
Assert.assertFalse(secondClose.isDone());
assertFalse(firstClose.isDone());
assertFalse(secondClose.isDone());
}
}

Original file line number Diff line number Diff line change
@@ -18,8 +18,8 @@
package org.apache.bookkeeper.client;

import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;

import io.netty.buffer.ByteBuf;
import java.io.IOException;
@@ -43,7 +43,7 @@
import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.WriteCallback;
import org.apache.bookkeeper.test.BookKeeperClusterTestCase;
import org.apache.bookkeeper.test.TestCallbacks.AddCallbackFuture;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@@ -68,7 +68,7 @@ public LedgerCloseTest() {
}

@Test
public void testLedgerCloseWithConsistentLength() throws Exception {
void ledgerCloseWithConsistentLength() throws Exception {
ClientConfiguration conf = new ClientConfiguration();
conf.setMetadataServiceUri(zkUtil.getMetadataServiceUri());
conf.setReadTimeout(1);
@@ -87,7 +87,7 @@ public void addComplete(int rc, LedgerHandle lh, long entryId, Object ctx) {
};
lh.asyncAddEntry("Test Entry".getBytes(), cb, null);
latch.await();
assertEquals(i.get(), BKException.Code.NotEnoughBookiesException);
assertEquals(BKException.Code.NotEnoughBookiesException, i.get());
assertEquals(0, lh.getLength());
assertEquals(LedgerHandle.INVALID_ENTRY_ID, lh.getLastAddConfirmed());
startBKCluster(zkUtil.getMetadataServiceUri());
@@ -97,14 +97,14 @@ public void addComplete(int rc, LedgerHandle lh, long entryId, Object ctx) {
}

@Test
public void testLedgerCloseDuringUnrecoverableErrors() throws Exception {
void ledgerCloseDuringUnrecoverableErrors() throws Exception {
int numEntries = 3;
LedgerHandle lh = bkc.createLedger(3, 3, 3, digestType, "".getBytes());
verifyMetadataConsistency(numEntries, lh);
}

@Test
public void testLedgerCheckerShouldnotSelectInvalidLastFragments() throws Exception {
void ledgerCheckerShouldnotSelectInvalidLastFragments() throws Exception {
int numEntries = 10;
LedgerHandle lh = bkc.createLedger(3, 3, 3, digestType, "".getBytes());
// Add some entries before bookie failures
@@ -119,7 +119,7 @@ public void testLedgerCheckerShouldnotSelectInvalidLastFragments() throws Except
CheckerCallback cb = new CheckerCallback();
checker.checkLedger(lh, cb);
Set<LedgerFragment> result = cb.waitAndGetResult();
assertEquals("No fragments should be selected", 0, result.size());
assertEquals(0, result.size(), "No fragments should be selected");
}

class CheckerCallback implements GenericCallback<Set<LedgerFragment>> {
@@ -189,8 +189,8 @@ public void addComplete(int rc, LedgerHandle lh, long entryId, Object ctx) {
TimeUnit.SECONDS.sleep(5);
// open the ledger again to make sure we ge the right last confirmed.
LedgerHandle newLh = newBkc.openLedger(lh.getId(), digestType, "".getBytes());
assertEquals("Metadata should be consistent across different opened ledgers",
recoveredLh.getLastAddConfirmed(), newLh.getLastAddConfirmed());
assertEquals(recoveredLh.getLastAddConfirmed(), newLh.getLastAddConfirmed()
, "Metadata should be consistent across different opened ledgers");
}

private void startUnauthorizedBookie(ServerConfiguration conf, final CountDownLatch latch)
@@ -236,7 +236,7 @@ public void addEntry(ByteBuf entry, boolean ackBeforeSync, WriteCallback cb, Obj
}

@Test
public void testAllWritesAreCompletedOnClosedLedger() throws Exception {
void allWritesAreCompletedOnClosedLedger() throws Exception {
for (int i = 0; i < 100; i++) {
LOG.info("Iteration {}", i);

Original file line number Diff line number Diff line change
@@ -20,7 +20,7 @@
*/
package org.apache.bookkeeper.client;

import static junit.framework.TestCase.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@@ -35,7 +35,7 @@
import org.apache.bookkeeper.test.BookKeeperClusterTestCase;
import org.apache.bookkeeper.util.EntryFormatter;
import org.apache.bookkeeper.util.LedgerIdFormatter;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@@ -60,7 +60,7 @@ public LedgerCmdTest() {
* list of entry logger files that contains given ledgerId.
*/
@Test
public void testLedgerDbStorageCmd() throws Exception {
void ledgerDbStorageCmd() throws Exception {

BookKeeper bk = new BookKeeper(baseClientConf, zkc);
LOG.info("Create ledger and add entries to it");
@@ -78,7 +78,7 @@ public void testLedgerDbStorageCmd() throws Exception {
new BookieShell(LedgerIdFormatter.LONG_LEDGERID_FORMATTER, EntryFormatter.STRING_FORMATTER);
bkShell.setConf(conf);

assertEquals("Failed to return exit code!", 0, bkShell.run(argv));
assertEquals(0, bkShell.run(argv), "Failed to return exit code!");

}

Original file line number Diff line number Diff line change
@@ -19,9 +19,9 @@
package org.apache.bookkeeper.client;

import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

import com.google.common.collect.Lists;
import java.util.Base64;
@@ -31,7 +31,7 @@
import org.apache.bookkeeper.client.api.LedgerMetadata;
import org.apache.bookkeeper.net.BookieId;
import org.apache.bookkeeper.net.BookieSocketAddress;
import org.junit.Test;
import org.junit.jupiter.api.Test;

/**
* Unit test for ledger metadata.
@@ -41,7 +41,7 @@ public class LedgerMetadataTest {
private static final byte[] passwd = "testPasswd".getBytes(UTF_8);

@Test
public void testGetters() {
void getters() {
List<BookieId> ensemble = Lists.newArrayList(new BookieSocketAddress("192.0.2.1", 1234).toBookieId(),
new BookieSocketAddress("192.0.2.2", 1234).toBookieId(),
new BookieSocketAddress("192.0.2.3", 1234).toBookieId());
@@ -68,7 +68,7 @@ public void testGetters() {
}

@Test
public void testToString() {
void testToString() {
List<BookieId> ensemble = Lists.newArrayList(new BookieSocketAddress("192.0.2.1", 1234).toBookieId(),
new BookieSocketAddress("192.0.2.2", 1234).toBookieId(),
new BookieSocketAddress("192.0.2.3", 1234).toBookieId());
@@ -80,8 +80,8 @@ public void testToString() {
.withId(100L)
.build();

assertTrue("toString should contain password value",
lm1.toString().contains(Base64.getEncoder().encodeToString(passwd)));
assertTrue("toSafeString should not contain password value", lm1.toSafeString().contains("OMITTED"));
assertTrue(lm1.toString().contains(Base64.getEncoder().encodeToString(passwd)),
"toString should contain password value");
assertTrue(lm1.toSafeString().contains("OMITTED"), "toSafeString should not contain password value");
}
}
Original file line number Diff line number Diff line change
@@ -20,6 +20,10 @@
*/
package org.apache.bookkeeper.client;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;

import com.google.common.collect.Lists;
import java.nio.charset.StandardCharsets;
import java.util.List;
@@ -37,8 +41,7 @@
import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.GenericCallbackFuture;
import org.apache.bookkeeper.proto.MockBookies;
import org.apache.bookkeeper.versioning.Versioned;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@@ -82,7 +85,7 @@ private static Versioned<LedgerMetadata> setupLedger(ClientContext clientCtx, lo


@Test
public void testCantRecoverAllDown() throws Exception {
void cantRecoverAllDown() throws Exception {
MockClientContext clientCtx = MockClientContext.create();

Versioned<LedgerMetadata> md = setupLedger(clientCtx, 1L, Lists.newArrayList(b1, b2, b3));
@@ -95,14 +98,14 @@ public void testCantRecoverAllDown() throws Exception {
GenericCallbackFuture<Void> promise = new GenericCallbackFuture<>();
lh.recover(promise, null, false);
promise.get();
Assert.fail("Recovery shouldn't have been able to complete");
fail("Recovery shouldn't have been able to complete");
} catch (ExecutionException ee) {
Assert.assertEquals(BKException.BKReadException.class, ee.getCause().getClass());
assertEquals(BKException.BKReadException.class, ee.getCause().getClass());
}
}

@Test
public void testCanReadLacButCantWrite() throws Exception {
void canReadLacButCantWrite() throws Exception {
MockClientContext clientCtx = MockClientContext.create();

Versioned<LedgerMetadata> md = setupLedger(clientCtx, 1, Lists.newArrayList(b1, b2, b3));
@@ -117,14 +120,14 @@ public void testCanReadLacButCantWrite() throws Exception {
GenericCallbackFuture<Void> promise = new GenericCallbackFuture<>();
lh.recover(promise, null, false);
promise.get();
Assert.fail("Recovery shouldn't have been able to complete");
fail("Recovery shouldn't have been able to complete");
} catch (ExecutionException ee) {
Assert.assertEquals(BKException.BKNotEnoughBookiesException.class, ee.getCause().getClass());
assertEquals(BKException.BKNotEnoughBookiesException.class, ee.getCause().getClass());
}
}

@Test
public void testMetadataClosedDuringRecovery() throws Exception {
void metadataClosedDuringRecovery() throws Exception {
MockClientContext clientCtx = MockClientContext.create();

Versioned<LedgerMetadata> md = setupLedger(clientCtx, 1, Lists.newArrayList(b1, b2, b3));
@@ -156,12 +159,12 @@ public void testMetadataClosedDuringRecovery() throws Exception {

recoveryPromise.get();

Assert.assertEquals(lh.getLastAddConfirmed(), -1);
Assert.assertEquals(lh.getLength(), 0);
assertEquals(-1, lh.getLastAddConfirmed());
assertEquals(0, lh.getLength());
}

@Test
public void testNewEnsembleAddedDuringRecovery() throws Exception {
void newEnsembleAddedDuringRecovery() throws Exception {
MockClientContext clientCtx = MockClientContext.create();
clientCtx.getMockRegistrationClient().addBookies(b4).get();

@@ -200,14 +203,14 @@ public void testNewEnsembleAddedDuringRecovery() throws Exception {

try {
recoveryPromise.get();
Assert.fail("Should fail on the update");
fail("Should fail on the update");
} catch (ExecutionException ee) {
Assert.assertEquals(BKException.BKUnexpectedConditionException.class, ee.getCause().getClass());
assertEquals(BKException.BKUnexpectedConditionException.class, ee.getCause().getClass());
}
}

@Test
public void testRecoveryBookieFailedAtStart() throws Exception {
void recoveryBookieFailedAtStart() throws Exception {
MockClientContext clientCtx = MockClientContext.create();
clientCtx.getMockRegistrationClient().addBookies(b4).get();

@@ -226,13 +229,13 @@ public void testRecoveryBookieFailedAtStart() throws Exception {
lh.recover(recoveryPromise, null, false);
recoveryPromise.get();

Assert.assertEquals(lh.getLedgerMetadata().getAllEnsembles().size(), 1);
Assert.assertEquals(lh.getLedgerMetadata().getAllEnsembles().get(0L),
assertEquals(1, lh.getLedgerMetadata().getAllEnsembles().size());
assertEquals(lh.getLedgerMetadata().getAllEnsembles().get(0L),
Lists.newArrayList(b1, b4, b3));
}

@Test
public void testRecoveryOneBookieFailsDuring() throws Exception {
void recoveryOneBookieFailsDuring() throws Exception {
MockClientContext clientCtx = MockClientContext.create();
clientCtx.getMockRegistrationClient().addBookies(b4).get();

@@ -255,16 +258,16 @@ public void testRecoveryOneBookieFailsDuring() throws Exception {
lh.recover(recoveryPromise, null, false);
recoveryPromise.get();

Assert.assertEquals(lh.getLedgerMetadata().getAllEnsembles().size(), 2);
Assert.assertEquals(lh.getLedgerMetadata().getAllEnsembles().get(0L),
assertEquals(2, lh.getLedgerMetadata().getAllEnsembles().size());
assertEquals(lh.getLedgerMetadata().getAllEnsembles().get(0L),
Lists.newArrayList(b1, b2, b3));
Assert.assertEquals(lh.getLedgerMetadata().getAllEnsembles().get(1L),
assertEquals(lh.getLedgerMetadata().getAllEnsembles().get(1L),
Lists.newArrayList(b1, b4, b3));
Assert.assertEquals(lh.getLastAddConfirmed(), 1L);
assertEquals(1L, lh.getLastAddConfirmed());
}

@Test
public void testRecoveryTwoBookiesFailOnSameEntry() throws Exception {
void recoveryTwoBookiesFailOnSameEntry() throws Exception {
MockClientContext clientCtx = MockClientContext.create();
clientCtx.getMockRegistrationClient().addBookies(b4, b5).get();

@@ -286,11 +289,11 @@ public void testRecoveryTwoBookiesFailOnSameEntry() throws Exception {
lh.recover(recoveryPromise, null, false);
recoveryPromise.get();

Assert.assertEquals(lh.getLedgerMetadata().getAllEnsembles().size(), 1);
Assert.assertTrue(lh.getLedgerMetadata().getAllEnsembles().get(0L).contains(b3));
Assert.assertTrue(lh.getLedgerMetadata().getAllEnsembles().get(0L).contains(b4));
Assert.assertTrue(lh.getLedgerMetadata().getAllEnsembles().get(0L).contains(b5));
Assert.assertEquals(lh.getLastAddConfirmed(), 0L);
assertEquals(1, lh.getLedgerMetadata().getAllEnsembles().size());
assertTrue(lh.getLedgerMetadata().getAllEnsembles().get(0L).contains(b3));
assertTrue(lh.getLedgerMetadata().getAllEnsembles().get(0L).contains(b4));
assertTrue(lh.getLedgerMetadata().getAllEnsembles().get(0L).contains(b5));
assertEquals(0L, lh.getLastAddConfirmed());
}

/**
@@ -302,7 +305,7 @@ public void testRecoveryTwoBookiesFailOnSameEntry() throws Exception {
* been to fence on recovery reads also.
*/
@Test
public void testFirstWriterCannotCommitWriteAfter2ndWriterCloses() throws Exception {
void firstWriterCannotCommitWriteAfter2ndWriterCloses() throws Exception {
/*
This test uses CompletableFutures to control the sequence of actions performed by
two writers. There are different sets of futures:
@@ -484,20 +487,20 @@ public void testFirstWriterCannotCommitWriteAfter2ndWriterCloses() throws Except
// Step 10. w1 write fails to reach AckQuorum
try {
w1WriteFuture.get(200, TimeUnit.MILLISECONDS);
Assert.fail("The write to b2 should have failed as it was fenced by the recovery read of step 7");
fail("The write to b2 should have failed as it was fenced by the recovery read of step 7");
} catch (ExecutionException e) {
Assert.assertTrue(e.getCause() instanceof BKException.BKLedgerFencedException);
assertTrue(e.getCause() instanceof BKException.BKLedgerFencedException);
}

// w1 received negative acknowledgement of e2 being written
Assert.assertEquals(1, w1.getLedgerMetadata().getAllEnsembles().size());
Assert.assertEquals(2, writeResult.get());
Assert.assertEquals(1L, w1.getLastAddConfirmed());
assertEquals(1, w1.getLedgerMetadata().getAllEnsembles().size());
assertEquals(2, writeResult.get());
assertEquals(1L, w1.getLastAddConfirmed());

// w2 closed the ledger with only the original entries, not the third one
// i.e there is no divergence between w1m, w2 and metadata
Assert.assertEquals(1, w2.getLedgerMetadata().getAllEnsembles().size());
Assert.assertEquals(1L, w2.getLastAddConfirmed());
assertEquals(1, w2.getLedgerMetadata().getAllEnsembles().size());
assertEquals(1L, w2.getLastAddConfirmed());
}

private void stepBlock(CompletableFuture<Void> reachedStepFuture) {
@@ -516,7 +519,7 @@ private void stepBlock(CompletableFuture<Void> reachedStepFuture) {
* of the recovery phase rather than accept a value of -1 that might be returned by the LAC reads.
*/
@Test
public void testRecoveryWhenSecondEnsembleReturnsLacMinusOne() throws Exception {
void recoveryWhenSecondEnsembleReturnsLacMinusOne() throws Exception {
MockClientContext clientCtx = MockClientContext.create();
clientCtx.getMockRegistrationClient().addBookies(b4).get();

@@ -568,14 +571,14 @@ public void testRecoveryWhenSecondEnsembleReturnsLacMinusOne() throws Exception
recoveryPromise.get();

// The recovery process is successfully able to complete recovery, with the expected ensembles.
Assert.assertEquals(lh.getLedgerMetadata().getAllEnsembles().size(), 2);
Assert.assertTrue(lh.getLedgerMetadata().getAllEnsembles().get(0L).contains(b1));
Assert.assertTrue(lh.getLedgerMetadata().getAllEnsembles().get(0L).contains(b2));
Assert.assertTrue(lh.getLedgerMetadata().getAllEnsembles().get(1L).contains(b1));
Assert.assertTrue(lh.getLedgerMetadata().getAllEnsembles().get(1L).contains(b4));
assertEquals(2, lh.getLedgerMetadata().getAllEnsembles().size());
assertTrue(lh.getLedgerMetadata().getAllEnsembles().get(0L).contains(b1));
assertTrue(lh.getLedgerMetadata().getAllEnsembles().get(0L).contains(b2));
assertTrue(lh.getLedgerMetadata().getAllEnsembles().get(1L).contains(b1));
assertTrue(lh.getLedgerMetadata().getAllEnsembles().get(1L).contains(b4));

// the ledger is closed with entry id 1
Assert.assertEquals(lh.getLastAddConfirmed(), 1L);
Assert.assertEquals(lh.getLedgerMetadata().getLastEntryId(), 1L);
assertEquals(1L, lh.getLastAddConfirmed());
assertEquals(1L, lh.getLedgerMetadata().getLastEntryId());
}
}
}
Original file line number Diff line number Diff line change
@@ -20,10 +20,10 @@
*/
package org.apache.bookkeeper.client;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;

import io.netty.buffer.ByteBuf;
import java.io.IOException;
@@ -43,7 +43,7 @@
import org.apache.bookkeeper.proto.BookieProtocol;
import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.WriteCallback;
import org.apache.bookkeeper.test.BookKeeperClusterTestCase;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@@ -83,28 +83,28 @@ private void testInternal(int numEntries) throws Exception {
/*
* Check if has recovered properly.
*/
assertEquals("Has not recovered correctly", numEntries - 1, afterlh.getLastAddConfirmed());
assertEquals("Has not set the length correctly", length, afterlh.getLength());
assertEquals(numEntries - 1, afterlh.getLastAddConfirmed(), "Has not recovered correctly");
assertEquals(length, afterlh.getLength(), "Has not set the length correctly");
}

@Test
public void testLedgerRecovery() throws Exception {
void ledgerRecovery() throws Exception {
testInternal(100);

}

@Test
public void testEmptyLedgerRecoveryOne() throws Exception {
void emptyLedgerRecoveryOne() throws Exception {
testInternal(1);
}

@Test
public void testEmptyLedgerRecovery() throws Exception {
void emptyLedgerRecovery() throws Exception {
testInternal(0);
}

@Test
public void testLedgerRecoveryWithWrongPassword() throws Exception {
void ledgerRecoveryWithWrongPassword() throws Exception {
// Create a ledger
byte[] ledgerPassword = "aaaa".getBytes();
LedgerHandle lh = bkc.createLedger(digestType, ledgerPassword);
@@ -128,7 +128,7 @@ public void testLedgerRecoveryWithWrongPassword() throws Exception {
}

@Test
public void testLedgerRecoveryWithNotEnoughBookies() throws Exception {
void ledgerRecoveryWithNotEnoughBookies() throws Exception {
int numEntries = 3;

// Create a ledger
@@ -165,7 +165,7 @@ public void testLedgerRecoveryWithNotEnoughBookies() throws Exception {
}

@Test
public void testLedgerRecoveryWithSlowBookie() throws Exception {
void testLedgerRecoveryWithSlowBookie() throws Exception {
for (int i = 0; i < 3; i++) {
LOG.info("TestLedgerRecoveryWithAckQuorum @ slow bookie {}", i);
ledgerRecoveryWithSlowBookie(3, 3, 2, 1, i);
@@ -235,7 +235,7 @@ public void addEntry(ByteBuf entry, boolean ackBeforeSync, WriteCallback cb, Obj
* 8. Ledger recovery starts (ledger is now unavailable)
*/
@Test
public void testLedgerRecoveryWithRollingRestart() throws Exception {
void ledgerRecoveryWithRollingRestart() throws Exception {
LedgerHandle lhbefore = bkc.createLedger(numBookies, 2, digestType, "".getBytes());
for (int i = 0; i < (numBookies * 3) + 1; i++) {
lhbefore.addEntry("data".getBytes());
@@ -288,15 +288,15 @@ public void openComplete(int rc, LedgerHandle lh, Object ctx) {
}
}
}, null);
assertTrue("Open call should have completed", openLatch.await(5, TimeUnit.SECONDS));
assertFalse("Open should not have succeeded", returnCode.get() == BKException.Code.OK);
assertTrue(openLatch.await(5, TimeUnit.SECONDS), "Open call should have completed");
assertFalse(returnCode.get() == BKException.Code.OK, "Open should not have succeeded");

startAndAddBookie(conf2);

LedgerHandle lhafter = bkc.openLedger(lhbefore.getId(), digestType,
"".getBytes());
assertEquals("Fenced ledger should have correct lastAddConfirmed",
lhbefore.getLastAddConfirmed(), lhafter.getLastAddConfirmed());
assertEquals(lhbefore.getLastAddConfirmed(), lhafter.getLastAddConfirmed()
, "Fenced ledger should have correct lastAddConfirmed");
}

/**
@@ -313,7 +313,7 @@ public void openComplete(int rc, LedgerHandle lh, Object ctx) {
* 8. Another client trying to recover the same ledger.
*/
@Test
public void testBookieFailureDuringRecovery() throws Exception {
void bookieFailureDuringRecovery() throws Exception {
LedgerHandle lhbefore = bkc.createLedger(numBookies, 2, digestType, "".getBytes());
for (int i = 0; i < (numBookies * 3) + 1; i++) {
lhbefore.addEntry("data".getBytes());
@@ -348,16 +348,16 @@ public void recoveryAddEntry(ByteBuf entry, WriteCallback cb, Object ctx, byte[]
startNewBookie();
LedgerHandle lhafter = bkc.openLedger(lhbefore.getId(), digestType,
"".getBytes());
assertEquals("Fenced ledger should have correct lastAddConfirmed",
lhbefore.getLastAddConfirmed(), lhafter.getLastAddConfirmed());
assertEquals(lhbefore.getLastAddConfirmed(), lhafter.getLastAddConfirmed()
, "Fenced ledger should have correct lastAddConfirmed");
}

/**
* Verify that it doesn't break the recovery when changing ensemble in
* recovery add.
*/
@Test
public void testEnsembleChangeDuringRecovery() throws Exception {
void ensembleChangeDuringRecovery() throws Exception {
LedgerHandle lh = bkc.createLedger(numBookies, 2, 2, digestType, "".getBytes());
int numEntries = (numBookies * 3) + 1;
final AtomicInteger numPendingAdds = new AtomicInteger(numEntries);
@@ -398,8 +398,9 @@ public void addComplete(int rc, LedgerHandle lh, long entryId, Object ctx) {
// two dead bookies are put in the ensemble which would cause ensemble
// change
LedgerHandle recoveredLh = bkc.openLedger(lh.getId(), digestType, "".getBytes());
assertEquals("Fenced ledger should have correct lastAddConfirmed", lh.getLastAddConfirmed(),
recoveredLh.getLastAddConfirmed());
assertEquals(lh.getLastAddConfirmed(),
recoveredLh.getLastAddConfirmed(),
"Fenced ledger should have correct lastAddConfirmed");
}

private void startDeadBookie(ServerConfiguration conf) throws Exception {
@@ -415,12 +416,12 @@ public void recoveryAddEntry(ByteBuf entry, WriteCallback cb, Object ctx, byte[]
}

@Test
public void testBatchRecoverySize3() throws Exception {
void batchRecoverySize3() throws Exception {
batchRecovery(3);
}

@Test
public void testBatchRecoverySize13() throws Exception {
void batchRecoverySize13() throws Exception {
batchRecovery(13);
}

Original file line number Diff line number Diff line change
@@ -16,15 +16,15 @@
*/
package org.apache.bookkeeper.client;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.fail;

import java.util.Iterator;
import org.apache.bookkeeper.client.BookKeeper.DigestType;
import org.apache.bookkeeper.conf.ClientConfiguration;
import org.apache.bookkeeper.test.BookKeeperClusterTestCase;
import org.junit.Test;
import org.junit.jupiter.api.Test;

/**
* Test ListLedgers.
@@ -33,14 +33,14 @@ public class ListLedgersTest extends BookKeeperClusterTestCase {

private final DigestType digestType;

public ListLedgersTest () {
public ListLedgersTest() {
super(4);
this.digestType = DigestType.CRC32;
}

@Test
public void testListLedgers()
throws Exception {
void listLedgers()
throws Exception {
int numOfLedgers = 10;

ClientConfiguration conf = new ClientConfiguration();
@@ -49,38 +49,37 @@ public void testListLedgers()
BookKeeper bkc = new BookKeeper(conf);
for (int i = 0; i < numOfLedgers; i++) {
bkc.createLedger(digestType, "testPasswd".
getBytes()).close();
getBytes()).close();
}

BookKeeperAdmin admin = new BookKeeperAdmin(zkUtil.
getZooKeeperConnectString());
getZooKeeperConnectString());
Iterable<Long> iterable = admin.listLedgers();

int counter = 0;
for (Long lId: iterable) {
for (Long lId : iterable) {
counter++;
}

assertTrue("Wrong number of ledgers: " + numOfLedgers,
counter == numOfLedgers);
assertEquals(counter, numOfLedgers, "Wrong number of ledgers: " + numOfLedgers);
}

@Test
public void testEmptyList()
throws Exception {
void emptyList()
throws Exception {
ClientConfiguration conf = new ClientConfiguration();
conf.setMetadataServiceUri(zkUtil.getMetadataServiceUri());

BookKeeperAdmin admin = new BookKeeperAdmin(zkUtil.
getZooKeeperConnectString());
getZooKeeperConnectString());
Iterable<Long> iterable = admin.listLedgers();

assertFalse("There should be no ledger", iterable.iterator().hasNext());
assertFalse(iterable.iterator().hasNext(), "There should be no ledger");
}

@Test
public void testRemoveNotSupported()
throws Exception {
void removeNotSupported()
throws Exception {
int numOfLedgers = 1;

ClientConfiguration conf = new ClientConfiguration();
@@ -89,11 +88,11 @@ public void testRemoveNotSupported()
BookKeeper bkc = new BookKeeper(conf);
for (int i = 0; i < numOfLedgers; i++) {
bkc.createLedger(digestType, "testPasswd".
getBytes()).close();
getBytes()).close();
}

BookKeeperAdmin admin = new BookKeeperAdmin(zkUtil.
getZooKeeperConnectString());
getZooKeeperConnectString());
Iterator<Long> iterator = admin.listLedgers().iterator();
iterator.next();
try {
Original file line number Diff line number Diff line change
@@ -21,10 +21,10 @@

package org.apache.bookkeeper.client;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.hasItem;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.AdditionalAnswers.answerVoid;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
@@ -46,10 +46,9 @@
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.appender.NullAppender;
import org.hamcrest.CoreMatchers;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;


/**
@@ -97,7 +96,7 @@ public void assertLogWithMdc(String mdc, String msgSubstring) {
)));
}

@Before
@BeforeEach
public void setUp() throws Exception {
super.setUp();
ClientConfiguration conf = new ClientConfiguration();
@@ -128,7 +127,7 @@ public void setUp() throws Exception {
))).when(mockAppender).append(any());
}

@After
@AfterEach
public void tearDown() throws Exception {
lh.close();
bkc.close();
@@ -141,19 +140,19 @@ public void tearDown() throws Exception {
}

@Test
public void testLedgerCreateFails() throws Exception {
void ledgerCreateFails() throws Exception {
ThreadContext.put(MDC_REQUEST_ID, "ledger_create_fail");
try {
bkc.createLedgerAdv(99, 3, 2, BookKeeper.DigestType.CRC32, new byte[]{});
Assert.fail("should not get here");
fail("should not get here");
} catch (BKException bke) {
// expected
}
assertLogWithMdc("ledger_create_fail", "Not enough bookies to create ledger");
}

@Test
public void testSimpleAdd() throws Exception {
void simpleAdd() throws Exception {
ThreadContext.put(MDC_REQUEST_ID, "ledger_add_entry");
lh.addEntry(0, entry);

@@ -164,7 +163,7 @@ public void testSimpleAdd() throws Exception {
}

@Test
public void testAddWithEnsembleChange() throws Exception {
void addWithEnsembleChange() throws Exception {
lh.addEntry(0, entry);
startNewBookie();
killBookie(0);
@@ -179,7 +178,7 @@ public void testAddWithEnsembleChange() throws Exception {
}

@Test
public void testAddFailsWithReadOnlyBookie() throws Exception {
void addFailsWithReadOnlyBookie() throws Exception {
for (int i = 0; i < 3; ++i) {
Bookie bookie = serverByIndex(i).getBookie();
File[] ledgerDirs = confByIndex(i).getLedgerDirs();
@@ -190,7 +189,7 @@ public void testAddFailsWithReadOnlyBookie() throws Exception {
ThreadContext.put(MDC_REQUEST_ID, "ledger_add_entry");
try {
lh.addEntry(0, entry);
Assert.fail("should not get here");
fail("should not get here");
} catch (BKException bke) {
// expected, pass
}
@@ -204,13 +203,13 @@ public void testAddFailsWithReadOnlyBookie() throws Exception {
}

@Test
public void testAddFailsDuplicateEntry() throws Exception {
void addFailsDuplicateEntry() throws Exception {
lh.addEntry(0, entry);

ThreadContext.put(MDC_REQUEST_ID, "ledger_add_duplicate_entry");
try {
lh.addEntry(0, entry);
Assert.fail("should not get here");
fail("should not get here");
} catch (BKException bke) {
// expected, pass
}
@@ -220,7 +219,7 @@ public void testAddFailsDuplicateEntry() throws Exception {
}

@Test
public void testReadEntryBeyondLac() throws Exception {
void readEntryBeyondLac() throws Exception {
ThreadContext.put(MDC_REQUEST_ID, "ledger_read_entry");

try {
@@ -233,7 +232,7 @@ public void testReadEntryBeyondLac() throws Exception {
}

@Test
public void testReadFromDeletedLedger() throws Exception {
void readFromDeletedLedger() throws Exception {
lh.addEntry(0, entry);
lh.close();
bkc.deleteLedger(lh.ledgerId);
Original file line number Diff line number Diff line change
@@ -19,6 +19,10 @@
*/
package org.apache.bookkeeper.client;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.spy;
@@ -46,8 +50,7 @@
import org.apache.bookkeeper.versioning.Version;
import org.apache.bookkeeper.versioning.Versioned;
import org.apache.commons.lang3.tuple.Triple;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@@ -61,7 +64,7 @@ public class MetadataUpdateLoopTest {
* Test that we can update the metadata using the update loop.
*/
@Test
public void testBasicUpdate() throws Exception {
void basicUpdate() throws Exception {
try (LedgerManager lm = new MockLedgerManager()) {
long ledgerId = 1234L;
LedgerMetadata initMeta = LedgerMetadataBuilder.create()
@@ -92,8 +95,8 @@ public void testBasicUpdate() throws Exception {
reference::compareAndSet);
loop.run().get();

Assert.assertNotEquals(reference.get(), writtenMetadata);
Assert.assertEquals(reference.get().getValue().getEnsembleAt(0L).get(0), newAddress);
assertNotEquals(reference.get(), writtenMetadata);
assertEquals(reference.get().getValue().getEnsembleAt(0L).get(0), newAddress);
}
}

@@ -102,7 +105,7 @@ public void testBasicUpdate() throws Exception {
* both will eventually succeed, and both updates will be reflected in the final metadata.
*/
@Test
public void testConflictOnWrite() throws Exception {
void conflictOnWrite() throws Exception {
try (BlockableMockLedgerManager lm = spy(new BlockableMockLedgerManager())) {
lm.blockWrites();

@@ -149,16 +152,16 @@ public void testConflictOnWrite() throws Exception {
Versioned<LedgerMetadata> l1meta = loop1.get();
Versioned<LedgerMetadata> l2meta = loop2.get();

Assert.assertEquals(l1meta, reference1.get());
Assert.assertEquals(l2meta, reference2.get());
assertEquals(l1meta, reference1.get());
assertEquals(l2meta, reference2.get());

Assert.assertEquals(l1meta.getVersion().compare(l2meta.getVersion()), Version.Occurred.BEFORE);
assertEquals(Version.Occurred.BEFORE, l1meta.getVersion().compare(l2meta.getVersion()));

Assert.assertEquals(l1meta.getValue().getEnsembleAt(0L).get(0), b2);
Assert.assertEquals(l1meta.getValue().getEnsembleAt(0L).get(1), b1);
assertEquals(l1meta.getValue().getEnsembleAt(0L).get(0), b2);
assertEquals(l1meta.getValue().getEnsembleAt(0L).get(1), b1);

Assert.assertEquals(l2meta.getValue().getEnsembleAt(0L).get(0), b2);
Assert.assertEquals(l2meta.getValue().getEnsembleAt(0L).get(1), b3);
assertEquals(l2meta.getValue().getEnsembleAt(0L).get(0), b2);
assertEquals(l2meta.getValue().getEnsembleAt(0L).get(1), b3);

verify(lm, times(3)).writeLedgerMetadata(anyLong(), any(), any());
}
@@ -170,7 +173,7 @@ public void testConflictOnWrite() throws Exception {
* try to write again, as the value is now correct.
*/
@Test
public void testConflictOnWriteBothWritingSame() throws Exception {
void conflictOnWriteBothWritingSame() throws Exception {
try (BlockableMockLedgerManager lm = spy(new BlockableMockLedgerManager())) {
lm.blockWrites();

@@ -210,11 +213,11 @@ public void testConflictOnWriteBothWritingSame() throws Exception {

lm.releaseWrites();

Assert.assertEquals(loop1.get(), loop2.get());
Assert.assertEquals(loop1.get(), reference.get());
assertEquals(loop1.get(), loop2.get());
assertEquals(loop1.get(), reference.get());

Assert.assertEquals(reference.get().getValue().getEnsembleAt(0L).get(0), b2);
Assert.assertEquals(reference.get().getValue().getEnsembleAt(0L).get(1), b1);
assertEquals(reference.get().getValue().getEnsembleAt(0L).get(0), b2);
assertEquals(reference.get().getValue().getEnsembleAt(0L).get(1), b1);

verify(lm, times(2)).writeLedgerMetadata(anyLong(), any(), any());
}
@@ -225,7 +228,7 @@ public void testConflictOnWriteBothWritingSame() throws Exception {
* updating the local value.
*/
@Test
public void testConflictOnLocalUpdate() throws Exception {
void conflictOnLocalUpdate() throws Exception {
try (DeferCallbacksMockLedgerManager lm = spy(new DeferCallbacksMockLedgerManager(1))) {
long ledgerId = 1234L;
BookieId b0 = BookieId.parse("0.0.0.0:3181");
@@ -263,14 +266,14 @@ public void testConflictOnLocalUpdate() throws Exception {
return LedgerMetadataBuilder.from(currentMetadata).replaceEnsembleEntry(0L, ensemble).build();
},
reference::compareAndSet).run();
Assert.assertEquals(loop2.get(), reference.get());
assertEquals(loop2.get(), reference.get());

lm.runDeferred();

Assert.assertEquals(loop1.get(), reference.get());
assertEquals(loop1.get(), reference.get());

Assert.assertEquals(reference.get().getValue().getEnsembleAt(0L).get(0), b2);
Assert.assertEquals(reference.get().getValue().getEnsembleAt(0L).get(1), b3);
assertEquals(reference.get().getValue().getEnsembleAt(0L).get(0), b2);
assertEquals(reference.get().getValue().getEnsembleAt(0L).get(1), b3);

verify(lm, times(3)).writeLedgerMetadata(anyLong(), any(), any());
}
@@ -290,7 +293,7 @@ private static BookieId address(String s) {
* and that the final metadata reflects all the updates.
*/
@Test
public void testHammer() throws Exception {
void hammer() throws Exception {
try (NonDeterministicMockLedgerManager lm = new NonDeterministicMockLedgerManager()) {
long ledgerId = 1234L;

@@ -326,7 +329,7 @@ public void testHammer() throws Exception {

loops.forEach((l) -> l.join());

Assert.assertEquals(reference.get().getValue().getEnsembleAt(0L), replacementBookies);
assertEquals(reference.get().getValue().getEnsembleAt(0L), replacementBookies);
}
}

@@ -335,7 +338,7 @@ public void testHammer() throws Exception {
* The other will throw an exception.
*/
@Test
public void testNewestValueCannotBeUsedAfterReadBack() throws Exception {
void newestValueCannotBeUsedAfterReadBack() throws Exception {
try (BlockableMockLedgerManager lm = spy(new BlockableMockLedgerManager())) {
lm.blockWrites();

@@ -355,10 +358,8 @@ public void testNewestValueCannotBeUsedAfterReadBack() throws Exception {
ledgerId,
reference::get,
(currentMetadata) -> !currentMetadata.isClosed(),
(currentMetadata) -> {
return LedgerMetadataBuilder.from(currentMetadata)
.withClosedState().withLastEntryId(10L).withLength(100L).build();
},
(currentMetadata) -> LedgerMetadataBuilder.from(currentMetadata)
.withClosedState().withLastEntryId(10L).withLength(100L).build(),
reference::compareAndSet).run();
CompletableFuture<Versioned<LedgerMetadata>> loop2 = new MetadataUpdateLoop(
lm,
@@ -382,13 +383,13 @@ public void testNewestValueCannotBeUsedAfterReadBack() throws Exception {
Versioned<LedgerMetadata> l1meta = loop1.get();
try {
loop2.get();
Assert.fail("Update loop should have failed");
fail("Update loop should have failed");
} catch (ExecutionException ee) {
Assert.assertEquals(ee.getCause().getClass(), BKException.BKLedgerClosedException.class);
assertEquals(BKException.BKLedgerClosedException.class, ee.getCause().getClass());
}
Assert.assertEquals(l1meta, reference.get());
Assert.assertEquals(l1meta.getValue().getEnsembleAt(0L).get(0), b0);
Assert.assertTrue(l1meta.getValue().isClosed());
assertEquals(l1meta, reference.get());
assertEquals(l1meta.getValue().getEnsembleAt(0L).get(0), b0);
assertTrue(l1meta.getValue().isClosed());

verify(lm, times(2)).writeLedgerMetadata(anyLong(), any(), any());
}
@@ -482,7 +483,7 @@ synchronized void blockWrites() {

synchronized void releaseWrites() {
blocking = false;
reqs.forEach((r) -> {
reqs.forEach((r) ->
super.writeLedgerMetadata(r.getLedgerId(), r.getMetadata(),
r.getCurrentVersion())
.whenComplete((written, exception) -> {
@@ -491,8 +492,7 @@ synchronized void releaseWrites() {
} else {
r.getPromise().complete(written);
}
});
});
}));
}

@Override
Original file line number Diff line number Diff line change
@@ -16,21 +16,21 @@
*/
package org.apache.bookkeeper.client;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.util.Enumeration;
import org.apache.bookkeeper.client.BookKeeper.DigestType;
import org.junit.Test;
import org.junit.jupiter.api.Test;

/**
* Test the mocked BookKeeper client.
*/
public class MockBookKeeperTest {

@Test
public void testMockedBookKeeper() throws Exception {
void mockedBookKeeper() throws Exception {
BookKeeper bkc = new MockBookKeeper(null);

LedgerHandle lh = bkc.createLedger(DigestType.CRC32, new byte[0]);
Original file line number Diff line number Diff line change
@@ -75,8 +75,6 @@
import org.apache.bookkeeper.versioning.LongVersion;
import org.apache.bookkeeper.versioning.Version;
import org.apache.bookkeeper.versioning.Versioned;
import org.junit.After;
import org.junit.Before;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.mockito.invocation.InvocationOnMock;
@@ -144,7 +142,6 @@ public MockEntry(byte[] payload, long lastAddConfirmed) {
}

@BeforeEach
@Before
public void setup() throws Exception {
maxNumberOfAvailableBookies = Integer.MAX_VALUE;
deferredBookieForceLedgerResponses = new ConcurrentHashMap<>();
@@ -268,7 +265,6 @@ private DigestManager getDigestType(long ledgerId) throws GeneralSecurityExcepti
}

@AfterEach
@After
public void tearDown() {
scheduler.shutdown();
executor.shutdown();
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.bookkeeper.util.resolvers;

import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.TestInfo;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolutionException;
import org.junit.jupiter.api.extension.ParameterResolver;
import org.junit.jupiter.engine.execution.BeforeEachMethodAdapter;
import org.junit.jupiter.engine.extension.ExtensionRegistry;

public class BeforeParameterResolver implements BeforeEachMethodAdapter, ParameterResolver {

private ParameterResolver parameterisedTestParameterResolver = null;

@Override
public void invokeBeforeEachMethod(ExtensionContext context, ExtensionRegistry registry) {
Optional<ParameterResolver> resolverOptional = registry
.getExtensions(ParameterResolver.class)
.stream()
.filter(parameterResolver -> parameterResolver.getClass().getName()
.contains("ParameterizedTestParameterResolver"))
.findFirst();
if (!resolverOptional.isPresent()) {
throw new IllegalStateException(
"ParameterizedTestParameterResolver missed in the registry. Probably it's not a Parameterized Test");
} else {
parameterisedTestParameterResolver = resolverOptional.get();
}
}

@Override
public boolean supportsParameter(ParameterContext parameterContext,
ExtensionContext extensionContext) throws ParameterResolutionException {

if (parameterContext.getParameter().getType() == TestInfo.class) {
return false;
}

if (isExecutedOnBeforeMethod(parameterContext)) {
ParameterContext pContext = getMappedContext(parameterContext, extensionContext);
return parameterisedTestParameterResolver.supportsParameter(pContext, extensionContext);
}
return false;
}

private MappedParameterContext getMappedContext(ParameterContext parameterContext,
ExtensionContext extensionContext) {
return new MappedParameterContext(
parameterContext.getIndex(),
extensionContext.getRequiredTestMethod().getParameters()[parameterContext.getIndex()],
Optional.of(parameterContext.getTarget()));
}


private boolean isExecutedOnBeforeMethod(ParameterContext parameterContext) {
return Arrays.stream(parameterContext.getDeclaringExecutable().getDeclaredAnnotations())
.anyMatch(this::isBeforeEachAnnotation);
}

private boolean isBeforeEachAnnotation(Annotation annotation) {
return annotation.annotationType() == BeforeEach.class;
}

@Override
public Object resolveParameter(ParameterContext parameterContext,
ExtensionContext extensionContext) throws ParameterResolutionException {
return parameterisedTestParameterResolver
.resolveParameter(getMappedContext(parameterContext, extensionContext),
extensionContext);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.bookkeeper.util.resolvers;

import java.lang.annotation.Annotation;
import java.lang.reflect.Parameter;
import java.util.List;
import java.util.Optional;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.platform.commons.util.AnnotationUtils;

@AllArgsConstructor
@Getter
public class MappedParameterContext implements ParameterContext {

private final int index;
private final Parameter parameter;
private final Optional<Object> target;

@Override
public boolean isAnnotated(Class<? extends Annotation> annotationType) {
return AnnotationUtils.isAnnotated(parameter, annotationType);
}

@Override
public <T extends Annotation> Optional<T> findAnnotation(Class<T> annotationType) {
return AnnotationUtils.findAnnotation(parameter, annotationType);
}

@Override
public <T extends Annotation> List<T> findRepeatableAnnotations(Class<T> annotationType) {
return AnnotationUtils.findRepeatableAnnotations(parameter, annotationType);
}
}