diff --git a/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/ConcurrentV2RecoveryTest.java b/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/ConcurrentV2RecoveryTest.java index 2a8a57735f8..cc44a3d8713 100644 --- a/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/ConcurrentV2RecoveryTest.java +++ b/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/ConcurrentV2RecoveryTest.java @@ -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()); } } } diff --git a/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/DeferredSyncTest.java b/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/DeferredSyncTest.java index a49b5775945..a2461cc4a68 100644 --- a/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/DeferredSyncTest.java +++ b/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/DeferredSyncTest.java @@ -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())); } } diff --git a/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/ExplicitLacTest.java b/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/ExplicitLacTest.java index 42d1aebf6ac..ccb8b58a954 100644 --- a/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/ExplicitLacTest.java +++ b/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/ExplicitLacTest.java @@ -19,9 +19,9 @@ package org.apache.bookkeeper.client; -import static org.junit.Assert.assertEquals; -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.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.util.Arrays; import java.util.Collection; @@ -35,320 +35,356 @@ import org.apache.bookkeeper.conf.ClientConfiguration; import org.apache.bookkeeper.test.BookKeeperClusterTestCase; import org.apache.bookkeeper.util.TestUtils; -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; /** * Test cases for `Explicit Lac` feature. */ -@RunWith(Parameterized.class) +@ExtendWith(BeforeParameterResolver.class) public class ExplicitLacTest extends BookKeeperClusterTestCase { - private final DigestType digestType; - - public ExplicitLacTest(Class storageClass) { - super(1); - this.digestType = DigestType.CRC32; - baseConf.setLedgerStorageClass(storageClass.getName()); - /* - * to persist explicitLac, journalFormatVersionToWrite should be atleast - * V6 and fileInfoFormatVersionToWrite should be atleast V1 - */ - baseConf.setJournalFormatVersionToWrite(6); - baseConf.setFileInfoFormatVersionToWrite(1); + private DigestType digestType; + + public ExplicitLacTest() { + super(1); + this.digestType = DigestType.CRC32; + /* + * to persist explicitLac, journalFormatVersionToWrite should be atleast + * V6 and fileInfoFormatVersionToWrite should be atleast V1 + */ + baseConf.setJournalFormatVersionToWrite(6); + baseConf.setFileInfoFormatVersionToWrite(1); + } + + @BeforeEach + public void init(Class storageClass) { + baseConf.setLedgerStorageClass(storageClass.getName()); + } + + public static Collection configs() { + return Arrays.asList(new Object[][]{ + {InterleavedLedgerStorage.class}, + {SortedLedgerStorage.class}, + {DbLedgerStorage.class}, + }); + } + + @MethodSource("configs") + @ParameterizedTest + public void readHandleWithNoExplicitLAC(Class storageClass) + throws Exception { + ClientConfiguration confWithNoExplicitLAC = new ClientConfiguration(); + confWithNoExplicitLAC.setMetadataServiceUri(zkUtil.getMetadataServiceUri()); + confWithNoExplicitLAC.setExplictLacInterval(0); + + BookKeeper bkcWithNoExplicitLAC = new BookKeeper(confWithNoExplicitLAC); + + LedgerHandle wlh = bkcWithNoExplicitLAC.createLedger( + 1, 1, 1, + digestType, "testPasswd".getBytes()); + long ledgerId = wlh.getId(); + int numOfEntries = 5; + for (int i = 0; i < numOfEntries; i++) { + wlh.addEntry(("foobar" + i).getBytes()); } - @Parameters - public static Collection configs() { - return Arrays.asList(new Object[][] { - { InterleavedLedgerStorage.class }, - { SortedLedgerStorage.class }, - { DbLedgerStorage.class }, - }); + LedgerHandle rlh = bkcWithNoExplicitLAC + .openLedgerNoRecovery(ledgerId, digestType, "testPasswd".getBytes()); + assertTrue( + (rlh.getLastAddConfirmed() == (numOfEntries - 2)), + "Expected LAC of rlh: " + (numOfEntries - 2) + " actual LAC of rlh: " + rlh + .getLastAddConfirmed()); + + Enumeration entries = rlh.readEntries(0, numOfEntries - 2); + int entryId = 0; + while (entries.hasMoreElements()) { + LedgerEntry entry = entries.nextElement(); + String entryString = new String(entry.getEntry()); + assertEquals(entryString, "foobar" + entryId, + "Expected entry String: " + ("foobar" + entryId) + " actual entry String: " + + entryString); + entryId++; } - @Test - public void testReadHandleWithNoExplicitLAC() throws Exception { - ClientConfiguration confWithNoExplicitLAC = new ClientConfiguration(); - confWithNoExplicitLAC.setMetadataServiceUri(zkUtil.getMetadataServiceUri()); - confWithNoExplicitLAC.setExplictLacInterval(0); - - BookKeeper bkcWithNoExplicitLAC = new BookKeeper(confWithNoExplicitLAC); - - LedgerHandle wlh = bkcWithNoExplicitLAC.createLedger( - 1, 1, 1, - digestType, "testPasswd".getBytes()); - long ledgerId = wlh.getId(); - int numOfEntries = 5; - for (int i = 0; i < numOfEntries; i++) { - wlh.addEntry(("foobar" + i).getBytes()); - } - - LedgerHandle rlh = bkcWithNoExplicitLAC.openLedgerNoRecovery(ledgerId, digestType, "testPasswd".getBytes()); - assertTrue( - "Expected LAC of rlh: " + (numOfEntries - 2) + " actual LAC of rlh: " + rlh.getLastAddConfirmed(), - (rlh.getLastAddConfirmed() == (numOfEntries - 2))); - - Enumeration entries = rlh.readEntries(0, numOfEntries - 2); - int entryId = 0; - while (entries.hasMoreElements()) { - LedgerEntry entry = entries.nextElement(); - String entryString = new String(entry.getEntry()); - assertTrue("Expected entry String: " + ("foobar" + entryId) + " actual entry String: " + entryString, - entryString.equals("foobar" + entryId)); - entryId++; - } - - for (int i = numOfEntries; i < 2 * numOfEntries; i++) { - wlh.addEntry(("foobar" + i).getBytes()); - } - - TestUtils.waitUntilLacUpdated(rlh, numOfEntries - 2); - - assertTrue( - "Expected LAC of wlh: " + (2 * numOfEntries - 1) + " actual LAC of rlh: " + wlh.getLastAddConfirmed(), - (wlh.getLastAddConfirmed() == (2 * numOfEntries - 1))); - assertTrue( - "Expected LAC of rlh: " + (numOfEntries - 2) + " actual LAC of rlh: " + rlh.getLastAddConfirmed(), - (rlh.getLastAddConfirmed() == (numOfEntries - 2))); - - // since explicitlacflush policy is not enabled for writeledgerhandle, when we try - // to read explicitlac for rlh, it will be reading up to the piggyback value. - long explicitlac = rlh.readExplicitLastConfirmed(); - assertTrue( - "Expected Explicit LAC of rlh: " + (numOfEntries - 2) + " actual ExplicitLAC of rlh: " + explicitlac, - (explicitlac == (2 * numOfEntries - 2))); - - try { - rlh.readEntries(2 * numOfEntries - 1, 2 * numOfEntries - 1); - fail("rlh readEntries beyond " + (2 * numOfEntries - 2) + " should fail with ReadException"); - } catch (BKException.BKReadException readException) { - } - - rlh.close(); - wlh.close(); - bkcWithNoExplicitLAC.close(); + for (int i = numOfEntries; i < 2 * numOfEntries; i++) { + wlh.addEntry(("foobar" + i).getBytes()); } - @Test - public void testExplicitLACIsPersisted() throws Exception { - ClientConfiguration confWithNoExplicitLAC = new ClientConfiguration(); - confWithNoExplicitLAC.setMetadataServiceUri(zkUtil.getMetadataServiceUri()); - // enable explicitLacFlush by setting non-zero value for - // explictLacInterval - confWithNoExplicitLAC.setExplictLacInterval(50); - - BookKeeper bkcWithExplicitLAC = new BookKeeper(confWithNoExplicitLAC); - - LedgerHandle wlh = bkcWithExplicitLAC.createLedger(1, 1, 1, digestType, "testPasswd".getBytes()); - long ledgerId = wlh.getId(); - int numOfEntries = 5; - for (int i = 0; i < numOfEntries; i++) { - wlh.addEntry(("foobar" + i).getBytes()); - } - - LedgerHandle rlh = bkcWithExplicitLAC.openLedgerNoRecovery(ledgerId, digestType, "testPasswd".getBytes()); - assertEquals("LAC of rlh", (long) numOfEntries - 2, rlh.getLastAddConfirmed()); - - for (int i = numOfEntries; i < 2 * numOfEntries; i++) { - wlh.addEntry(("foobar" + i).getBytes()); - } - - assertEquals("LAC of wlh", (2 * numOfEntries - 1), wlh.getLastAddConfirmed()); - assertEquals("LAC of rlh", (long) numOfEntries - 2, rlh.getLastAddConfirmed()); - assertEquals("Read LAC of rlh", (2 * numOfEntries - 2), rlh.readLastAddConfirmed()); - assertEquals("Read explicit LAC of rlh", (2 * numOfEntries - 2), rlh.readExplicitLastConfirmed()); - - // we need to wait for atleast 2 explicitlacintervals, - // since in writehandle for the first call - // lh.getExplicitLastAddConfirmed() will be < - // lh.getPiggyBackedLastAddConfirmed(), - // so it wont make explicit writelac in the first run - long readExplicitLastConfirmed = TestUtils.waitUntilExplicitLacUpdated(rlh, 2 * numOfEntries - 1); - assertEquals("Read explicit LAC of rlh after wait for explicitlacflush", (2 * numOfEntries - 1), - readExplicitLastConfirmed); - - // bookies have to be restarted - restartBookies(); - - /* - * since explicitLac is persisted we should be able to read explicitLac - * from the bookies. - */ - LedgerHandle rlh2 = bkcWithExplicitLAC.openLedgerNoRecovery(ledgerId, digestType, "testPasswd".getBytes()); - assertEquals("Read explicit LAC of rlh2 after bookies restart", (2 * numOfEntries - 1), - rlh2.readExplicitLastConfirmed()); - bkcWithExplicitLAC.close(); + TestUtils.waitUntilLacUpdated(rlh, numOfEntries - 2); + + assertTrue( + (wlh.getLastAddConfirmed() == (2 * numOfEntries - 1)), + "Expected LAC of wlh: " + (2 * numOfEntries - 1) + " actual LAC of rlh: " + wlh + .getLastAddConfirmed()); + assertTrue( + (rlh.getLastAddConfirmed() == (numOfEntries - 2)), + "Expected LAC of rlh: " + (numOfEntries - 2) + " actual LAC of rlh: " + rlh + .getLastAddConfirmed()); + + // since explicitlacflush policy is not enabled for writeledgerhandle, when we try + // to read explicitlac for rlh, it will be reading up to the piggyback value. + long explicitlac = rlh.readExplicitLastConfirmed(); + assertTrue( + (explicitlac == (2 * numOfEntries - 2)), + "Expected Explicit LAC of rlh: " + (numOfEntries - 2) + " actual ExplicitLAC of rlh: " + + explicitlac); + + try { + rlh.readEntries(2 * numOfEntries - 1, 2 * numOfEntries - 1); + fail("rlh readEntries beyond " + (2 * numOfEntries - 2) + " should fail with ReadException"); + } catch (BKException.BKReadException readException) { } - @Test - public void testReadHandleWithExplicitLAC() throws Exception { - ClientConfiguration confWithExplicitLAC = new ClientConfiguration(); - confWithExplicitLAC.setMetadataServiceUri(zkUtil.getMetadataServiceUri()); - int explicitLacIntervalMillis = 1000; - confWithExplicitLAC.setExplictLacInterval(explicitLacIntervalMillis); - - BookKeeper bkcWithExplicitLAC = new BookKeeper(confWithExplicitLAC); - - LedgerHandle wlh = bkcWithExplicitLAC.createLedger( - 1, 1, 1, - digestType, "testPasswd".getBytes()); - long ledgerId = wlh.getId(); - int numOfEntries = 5; - for (int i = 0; i < numOfEntries; i++) { - wlh.addEntry(("foobar" + i).getBytes()); - } - - LedgerHandle rlh = bkcWithExplicitLAC.openLedgerNoRecovery(ledgerId, digestType, "testPasswd".getBytes()); - - assertTrue( - "Expected LAC of rlh: " + (numOfEntries - 2) + " actual LAC of rlh: " + rlh.getLastAddConfirmed(), - (rlh.getLastAddConfirmed() == (numOfEntries - 2))); - - for (int i = numOfEntries; i < 2 * numOfEntries; i++) { - wlh.addEntry(("foobar" + i).getBytes()); - } - - // we need to wait for atleast 2 explicitlacintervals, - // since in writehandle for the first call - // lh.getExplicitLastAddConfirmed() will be < - // lh.getPiggyBackedLastAddConfirmed(), - // so it wont make explicit writelac in the first run - TestUtils.waitUntilLacUpdated(rlh, 2 * numOfEntries - 2); - - assertTrue( - "Expected LAC of wlh: " + (2 * numOfEntries - 1) + " actual LAC of wlh: " + wlh.getLastAddConfirmed(), - (wlh.getLastAddConfirmed() == (2 * numOfEntries - 1))); - // readhandle's lastaddconfirmed wont be updated until readExplicitLastConfirmed call is made - assertTrue( - "Expected LAC of rlh: " + (2 * numOfEntries - 2) + " actual LAC of rlh: " + rlh.getLastAddConfirmed(), - (rlh.getLastAddConfirmed() == (2 * numOfEntries - 2))); - - long explicitlac = TestUtils.waitUntilExplicitLacUpdated(rlh, 2 * numOfEntries - 1); - assertTrue("Expected Explicit LAC of rlh: " + (2 * numOfEntries - 1) - + " actual ExplicitLAC of rlh: " + explicitlac, - (explicitlac == (2 * numOfEntries - 1))); - // readExplicitLastConfirmed updates the lac of rlh. - assertTrue( - "Expected LAC of rlh: " + (2 * numOfEntries - 1) + " actual LAC of rlh: " + rlh.getLastAddConfirmed(), - (rlh.getLastAddConfirmed() == (2 * numOfEntries - 1))); - - Enumeration entries = rlh.readEntries(numOfEntries, 2 * numOfEntries - 1); - int entryId = numOfEntries; - while (entries.hasMoreElements()) { - LedgerEntry entry = entries.nextElement(); - String entryString = new String(entry.getEntry()); - assertTrue("Expected entry String: " + ("foobar" + entryId) + " actual entry String: " + entryString, - entryString.equals("foobar" + entryId)); - entryId++; - } - - rlh.close(); - wlh.close(); - bkcWithExplicitLAC.close(); + rlh.close(); + wlh.close(); + bkcWithNoExplicitLAC.close(); + } + + @MethodSource("configs") + @ParameterizedTest + public void explicitLACIsPersisted(Class storageClass) throws Exception { + ClientConfiguration confWithNoExplicitLAC = new ClientConfiguration(); + confWithNoExplicitLAC.setMetadataServiceUri(zkUtil.getMetadataServiceUri()); + // enable explicitLacFlush by setting non-zero value for + // explictLacInterval + confWithNoExplicitLAC.setExplictLacInterval(50); + + BookKeeper bkcWithExplicitLAC = new BookKeeper(confWithNoExplicitLAC); + + LedgerHandle wlh = bkcWithExplicitLAC + .createLedger(1, 1, 1, digestType, "testPasswd".getBytes()); + long ledgerId = wlh.getId(); + int numOfEntries = 5; + for (int i = 0; i < numOfEntries; i++) { + wlh.addEntry(("foobar" + i).getBytes()); } - @Test - public void testReadHandleWithExplicitLACAndDeferredSync() throws Exception { - ClientConfiguration confWithExplicitLAC = new ClientConfiguration(); - confWithExplicitLAC.setMetadataServiceUri(zkUtil.getMetadataServiceUri()); - int explicitLacIntervalMillis = 1000; - confWithExplicitLAC.setExplictLacInterval(explicitLacIntervalMillis); - - BookKeeper bkcWithExplicitLAC = new BookKeeper(confWithExplicitLAC); - - LedgerHandle wlh = (LedgerHandle) bkcWithExplicitLAC.newCreateLedgerOp() - .withEnsembleSize(1) - .withWriteQuorumSize(1) - .withAckQuorumSize(1) - .withWriteFlags(WriteFlag.DEFERRED_SYNC) - .withDigestType(digestType.toApiDigestType()) - .withPassword("testPasswd".getBytes()) - .execute() - .get(); - long ledgerId = wlh.getId(); - - // start like testReadHandleWithExplicitLAC - int numOfEntries = 5; - for (int i = 0; i < numOfEntries; i++) { - // if you perform force() + addEntry() you will piggy back LAC as usual - wlh.force().get(); - wlh.addEntry(("foobar" + i).getBytes()); - } - - LedgerHandle rlh = bkcWithExplicitLAC.openLedgerNoRecovery(ledgerId, digestType, "testPasswd".getBytes()); - - assertTrue( - "Expected LAC of rlh: " + (numOfEntries - 2) + " actual LAC of rlh: " + rlh.getLastAddConfirmed(), - (rlh.getLastAddConfirmed() == (numOfEntries - 2))); - - for (int i = numOfEntries; i < 2 * numOfEntries; i++) { - wlh.addEntry(("foobar" + i).getBytes()); - } - - // running a force() will update local LAC on the writer - // ExplicitLAC timer will send the value even without writes - wlh.force().get(); - - // wait for explicit lac to be sent to bookies - TestUtils.waitUntilExplicitLacUpdated(rlh, 2 * numOfEntries - 2); - - // we need to wait for atleast 2 explicitlacintervals, - // since in writehandle for the first call - // lh.getExplicitLastAddConfirmed() will be < - // lh.getPiggyBackedLastAddConfirmed(), - // so it wont make explicit writelac in the first run - TestUtils.waitUntilLacUpdated(rlh, 2 * numOfEntries - 2); - - assertTrue( - "Expected LAC of wlh: " + (2 * numOfEntries - 1) + " actual LAC of wlh: " + wlh.getLastAddConfirmed(), - (wlh.getLastAddConfirmed() == (2 * numOfEntries - 1))); - - long explicitlac = TestUtils.waitUntilExplicitLacUpdated(rlh, 2 * numOfEntries - 1); - assertTrue("Expected Explicit LAC of rlh: " + (2 * numOfEntries - 1) - + " actual ExplicitLAC of rlh: " + explicitlac, - (explicitlac == (2 * numOfEntries - 1))); - // readExplicitLastConfirmed updates the lac of rlh. - assertTrue( - "Expected LAC of rlh: " + (2 * numOfEntries - 1) + " actual LAC of rlh: " + rlh.getLastAddConfirmed(), - (rlh.getLastAddConfirmed() == (2 * numOfEntries - 1))); - - Enumeration entries = rlh.readEntries(numOfEntries, 2 * numOfEntries - 1); - int entryId = numOfEntries; - while (entries.hasMoreElements()) { - LedgerEntry entry = entries.nextElement(); - String entryString = new String(entry.getEntry()); - assertTrue("Expected entry String: " + ("foobar" + entryId) + " actual entry String: " + entryString, - entryString.equals("foobar" + entryId)); - entryId++; - } - - rlh.close(); - wlh.close(); - bkcWithExplicitLAC.close(); + LedgerHandle rlh = bkcWithExplicitLAC + .openLedgerNoRecovery(ledgerId, digestType, "testPasswd".getBytes()); + assertEquals((long) numOfEntries - 2, rlh.getLastAddConfirmed(), "LAC of rlh"); + + for (int i = numOfEntries; i < 2 * numOfEntries; i++) { + wlh.addEntry(("foobar" + i).getBytes()); + } + + assertEquals((2 * numOfEntries - 1), wlh.getLastAddConfirmed(), "LAC of wlh"); + assertEquals((long) numOfEntries - 2, rlh.getLastAddConfirmed(), "LAC of rlh"); + assertEquals((2 * numOfEntries - 2), rlh.readLastAddConfirmed(), "Read LAC of rlh"); + assertEquals((2 * numOfEntries - 2), rlh.readExplicitLastConfirmed(), + "Read explicit LAC of rlh"); + + // we need to wait for atleast 2 explicitlacintervals, + // since in writehandle for the first call + // lh.getExplicitLastAddConfirmed() will be < + // lh.getPiggyBackedLastAddConfirmed(), + // so it wont make explicit writelac in the first run + long readExplicitLastConfirmed = TestUtils + .waitUntilExplicitLacUpdated(rlh, 2 * numOfEntries - 1); + assertEquals((2 * numOfEntries - 1), + readExplicitLastConfirmed, + "Read explicit LAC of rlh after wait for explicitlacflush"); + + // bookies have to be restarted + restartBookies(); + + /* + * since explicitLac is persisted we should be able to read explicitLac + * from the bookies. + */ + LedgerHandle rlh2 = bkcWithExplicitLAC + .openLedgerNoRecovery(ledgerId, digestType, "testPasswd".getBytes()); + assertEquals((2 * numOfEntries - 1), + rlh2.readExplicitLastConfirmed(), + "Read explicit LAC of rlh2 after bookies restart"); + bkcWithExplicitLAC.close(); + } + + @MethodSource("configs") + @ParameterizedTest + public void readHandleWithExplicitLAC(Class storageClass) + throws Exception { + ClientConfiguration confWithExplicitLAC = new ClientConfiguration(); + confWithExplicitLAC.setMetadataServiceUri(zkUtil.getMetadataServiceUri()); + int explicitLacIntervalMillis = 1000; + confWithExplicitLAC.setExplictLacInterval(explicitLacIntervalMillis); + + BookKeeper bkcWithExplicitLAC = new BookKeeper(confWithExplicitLAC); + + LedgerHandle wlh = bkcWithExplicitLAC.createLedger( + 1, 1, 1, + digestType, "testPasswd".getBytes()); + long ledgerId = wlh.getId(); + int numOfEntries = 5; + for (int i = 0; i < numOfEntries; i++) { + wlh.addEntry(("foobar" + i).getBytes()); + } + + LedgerHandle rlh = bkcWithExplicitLAC + .openLedgerNoRecovery(ledgerId, digestType, "testPasswd".getBytes()); + + assertTrue( + (rlh.getLastAddConfirmed() == (numOfEntries - 2)), + "Expected LAC of rlh: " + (numOfEntries - 2) + " actual LAC of rlh: " + rlh + .getLastAddConfirmed()); + + for (int i = numOfEntries; i < 2 * numOfEntries; i++) { + wlh.addEntry(("foobar" + i).getBytes()); + } + + // we need to wait for atleast 2 explicitlacintervals, + // since in writehandle for the first call + // lh.getExplicitLastAddConfirmed() will be < + // lh.getPiggyBackedLastAddConfirmed(), + // so it wont make explicit writelac in the first run + TestUtils.waitUntilLacUpdated(rlh, 2 * numOfEntries - 2); + + assertTrue( + (wlh.getLastAddConfirmed() == (2 * numOfEntries - 1)), + "Expected LAC of wlh: " + (2 * numOfEntries - 1) + " actual LAC of wlh: " + wlh + .getLastAddConfirmed()); + // readhandle's lastaddconfirmed wont be updated until readExplicitLastConfirmed call is made + assertTrue( + (rlh.getLastAddConfirmed() == (2 * numOfEntries - 2)), + "Expected LAC of rlh: " + (2 * numOfEntries - 2) + " actual LAC of rlh: " + rlh + .getLastAddConfirmed()); + + long explicitlac = TestUtils.waitUntilExplicitLacUpdated(rlh, 2 * numOfEntries - 1); + assertTrue((explicitlac == (2 * numOfEntries - 1)), + "Expected Explicit LAC of rlh: " + (2 * numOfEntries - 1) + + " actual ExplicitLAC of rlh: " + explicitlac); + // readExplicitLastConfirmed updates the lac of rlh. + assertTrue( + (rlh.getLastAddConfirmed() == (2 * numOfEntries - 1)), + "Expected LAC of rlh: " + (2 * numOfEntries - 1) + " actual LAC of rlh: " + rlh + .getLastAddConfirmed()); + + Enumeration entries = rlh.readEntries(numOfEntries, 2 * numOfEntries - 1); + int entryId = numOfEntries; + while (entries.hasMoreElements()) { + LedgerEntry entry = entries.nextElement(); + String entryString = new String(entry.getEntry()); + assertEquals(entryString, "foobar" + entryId, + "Expected entry String: " + ("foobar" + entryId) + " actual entry String: " + + entryString); + entryId++; + } + + rlh.close(); + wlh.close(); + bkcWithExplicitLAC.close(); + } + + @MethodSource("configs") + @ParameterizedTest + public void readHandleWithExplicitLACAndDeferredSync(Class storageClass) + throws Exception { + ClientConfiguration confWithExplicitLAC = new ClientConfiguration(); + confWithExplicitLAC.setMetadataServiceUri(zkUtil.getMetadataServiceUri()); + int explicitLacIntervalMillis = 1000; + confWithExplicitLAC.setExplictLacInterval(explicitLacIntervalMillis); + + BookKeeper bkcWithExplicitLAC = new BookKeeper(confWithExplicitLAC); + + LedgerHandle wlh = (LedgerHandle) bkcWithExplicitLAC.newCreateLedgerOp() + .withEnsembleSize(1) + .withWriteQuorumSize(1) + .withAckQuorumSize(1) + .withWriteFlags(WriteFlag.DEFERRED_SYNC) + .withDigestType(digestType.toApiDigestType()) + .withPassword("testPasswd".getBytes()) + .execute() + .get(); + long ledgerId = wlh.getId(); + + // start like testReadHandleWithExplicitLAC + int numOfEntries = 5; + for (int i = 0; i < numOfEntries; i++) { + // if you perform force() + addEntry() you will piggy back LAC as usual + wlh.force().get(); + wlh.addEntry(("foobar" + i).getBytes()); + } + + LedgerHandle rlh = bkcWithExplicitLAC + .openLedgerNoRecovery(ledgerId, digestType, "testPasswd".getBytes()); + + assertTrue( + (rlh.getLastAddConfirmed() == (numOfEntries - 2)), + "Expected LAC of rlh: " + (numOfEntries - 2) + " actual LAC of rlh: " + rlh + .getLastAddConfirmed()); + + for (int i = numOfEntries; i < 2 * numOfEntries; i++) { + wlh.addEntry(("foobar" + i).getBytes()); } - @Test - public void fallbackV3() throws Exception { - ClientConfiguration v2Conf = new ClientConfiguration(); - v2Conf.setUseV2WireProtocol(true); - v2Conf.setMetadataServiceUri(zkUtil.getMetadataServiceUri()); - v2Conf.setExplictLacInterval(10); - - BookKeeper bookKeeper = new BookKeeper(v2Conf); - LedgerHandle write = (LedgerHandle) bookKeeper.createLedger(1, - 1, - 1, - DigestType.MAC, - "pass".getBytes()); - write.addEntry("test".getBytes()); - TestUtils.waitUntilExplicitLacUpdated(write, 0); - long lac = write.readExplicitLastConfirmed(); - assertEquals(0, lac); - write.close(); - bookKeeper.close(); + // running a force() will update local LAC on the writer + // ExplicitLAC timer will send the value even without writes + wlh.force().get(); + + // wait for explicit lac to be sent to bookies + TestUtils.waitUntilExplicitLacUpdated(rlh, 2 * numOfEntries - 2); + + // we need to wait for atleast 2 explicitlacintervals, + // since in writehandle for the first call + // lh.getExplicitLastAddConfirmed() will be < + // lh.getPiggyBackedLastAddConfirmed(), + // so it wont make explicit writelac in the first run + TestUtils.waitUntilLacUpdated(rlh, 2 * numOfEntries - 2); + + assertTrue( + (wlh.getLastAddConfirmed() == (2 * numOfEntries - 1)), + "Expected LAC of wlh: " + (2 * numOfEntries - 1) + " actual LAC of wlh: " + wlh + .getLastAddConfirmed()); + + long explicitlac = TestUtils.waitUntilExplicitLacUpdated(rlh, 2 * numOfEntries - 1); + assertTrue((explicitlac == (2 * numOfEntries - 1)), + "Expected Explicit LAC of rlh: " + (2 * numOfEntries - 1) + + " actual ExplicitLAC of rlh: " + explicitlac); + // readExplicitLastConfirmed updates the lac of rlh. + assertTrue( + (rlh.getLastAddConfirmed() == (2 * numOfEntries - 1)), + "Expected LAC of rlh: " + (2 * numOfEntries - 1) + " actual LAC of rlh: " + rlh + .getLastAddConfirmed()); + + Enumeration entries = rlh.readEntries(numOfEntries, 2 * numOfEntries - 1); + int entryId = numOfEntries; + while (entries.hasMoreElements()) { + LedgerEntry entry = entries.nextElement(); + String entryString = new String(entry.getEntry()); + assertEquals(entryString, "foobar" + entryId, + "Expected entry String: " + ("foobar" + entryId) + " actual entry String: " + + entryString); + entryId++; } + rlh.close(); + wlh.close(); + bkcWithExplicitLAC.close(); + } + + @MethodSource("configs") + @ParameterizedTest + public void fallbackV3(Class storageClass) throws Exception { + ClientConfiguration v2Conf = new ClientConfiguration(); + v2Conf.setUseV2WireProtocol(true); + v2Conf.setMetadataServiceUri(zkUtil.getMetadataServiceUri()); + v2Conf.setExplictLacInterval(10); + + BookKeeper bookKeeper = new BookKeeper(v2Conf); + LedgerHandle write = (LedgerHandle) bookKeeper.createLedger(1, + 1, + 1, + DigestType.MAC, + "pass".getBytes()); + write.addEntry("test".getBytes()); + TestUtils.waitUntilExplicitLacUpdated(write, 0); + long lac = write.readExplicitLastConfirmed(); + assertEquals(0, lac); + write.close(); + bookKeeper.close(); + } + } diff --git a/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/GenericEnsemblePlacementPolicyTest.java b/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/GenericEnsemblePlacementPolicyTest.java index 9a30b5930d0..06bee56eb81 100644 --- a/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/GenericEnsemblePlacementPolicyTest.java +++ b/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/GenericEnsemblePlacementPolicyTest.java @@ -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> customMetadataOnNewEnsembleStack = new ArrayList<>(); private static List> customMetadataOnReplaceBookieStack = new ArrayList<>(); - @Parameters + @BeforeEach + public void init(boolean diskWeightBasedPlacementEnabled) { + baseClientConf.setDiskWeightBasedPlacementEnabled(diskWeightBasedPlacementEnabled); + } + public static Collection 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> 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 { diff --git a/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/HandleFailuresTest.java b/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/HandleFailuresTest.java index d1182668e9c..4075fe27d04 100644 --- a/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/HandleFailuresTest.java +++ b/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/HandleFailuresTest.java @@ -21,6 +21,10 @@ package org.apache.bookkeeper.client; import static org.apache.bookkeeper.util.TestUtils.assertEventuallyTrue; +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 static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.times; @@ -39,8 +43,8 @@ import org.apache.bookkeeper.net.BookieSocketAddress; import org.apache.bookkeeper.proto.MockBookieClient; import org.apache.bookkeeper.versioning.Versioned; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -48,26 +52,28 @@ * Ledger recovery tests using mocks rather than a real cluster. */ public class HandleFailuresTest { - private static final Logger log = LoggerFactory.getLogger(LedgerRecovery2Test.class); + + private static final Logger log = LoggerFactory.getLogger(HandleFailuresTest.class); private static final BookieId b1 = new BookieSocketAddress("b1", 3181).toBookieId(); private static final BookieId b2 = new BookieSocketAddress("b2", 3181).toBookieId(); private static final BookieId b3 = new BookieSocketAddress("b3", 3181).toBookieId(); - private static final BookieId b4 = new BookieSocketAddress("b4", 3181).toBookieId(); +g'i't private static final BookieId b4 = new BookieSocketAddress("b4", 3181).toBookieId(); private static final BookieId b5 = new BookieSocketAddress("b5", 3181).toBookieId(); - @Test(timeout = 30000) - public void testChangeTriggeredOneTimeForOneFailure() throws Exception { + @Test + @Timeout(value = 30000, unit = TimeUnit.MILLISECONDS) + void changeTriggeredOneTimeForOneFailure() throws Exception { MockClientContext clientCtx = MockClientContext.create(); Versioned md = ClientUtil.setupLedger(clientCtx, 10L, - LedgerMetadataBuilder.create().newEnsembleEntry( - 0L, Lists.newArrayList(b1, b2, b3))); + LedgerMetadataBuilder.create().newEnsembleEntry( + 0L, Lists.newArrayList(b1, b2, b3))); clientCtx.getMockRegistrationClient().addBookies(b4).get(); clientCtx.getMockBookieClient().errorBookies(b1); LedgerHandle lh = new LedgerHandle(clientCtx, 10L, md, BookKeeper.DigestType.CRC32C, - ClientUtil.PASSWD, WriteFlag.NONE); + ClientUtil.PASSWD, WriteFlag.NONE); lh.appendAsync("entry1".getBytes()); lh.appendAsync("entry2".getBytes()); lh.appendAsync("entry3".getBytes()); @@ -75,40 +81,41 @@ public void testChangeTriggeredOneTimeForOneFailure() throws Exception { lh.appendAsync("entry5".getBytes()).get(); verify(clientCtx.getLedgerManager(), times(1)).writeLedgerMetadata(anyLong(), any(), any()); - Assert.assertEquals(lh.getLedgerMetadata().getAllEnsembles().size(), 1); - Assert.assertEquals(lh.getLedgerMetadata().getAllEnsembles().get(0L), Lists.newArrayList(b4, b2, b3)); + assertEquals(1, lh.getLedgerMetadata().getAllEnsembles().size()); + assertEquals(lh.getLedgerMetadata().getAllEnsembles().get(0L), Lists.newArrayList(b4, b2, b3)); } - @Test(timeout = 30000) - public void testSecondFailureOccursWhileFirstBeingHandled() throws Exception { + @Test + @Timeout(value = 30000, unit = TimeUnit.MILLISECONDS) + void secondFailureOccursWhileFirstBeingHandled() throws Exception { MockClientContext clientCtx = MockClientContext.create(); Versioned md = ClientUtil.setupLedger(clientCtx, 10L, - LedgerMetadataBuilder.create() - .withEnsembleSize(3).withWriteQuorumSize(3).withAckQuorumSize(3) - .newEnsembleEntry(0L, Lists.newArrayList(b1, b2, b3))); + LedgerMetadataBuilder.create() + .withEnsembleSize(3).withWriteQuorumSize(3).withAckQuorumSize(3) + .newEnsembleEntry(0L, Lists.newArrayList(b1, b2, b3))); clientCtx.getMockRegistrationClient().addBookies(b4, b5).get(); CompletableFuture b2blocker = new CompletableFuture<>(); clientCtx.getMockBookieClient().setPreWriteHook( - (bookie, ledgerId, entryId) -> { - if (bookie.equals(b1)) { - return FutureUtils.exception(new BKException.BKWriteException()); - } else if (bookie.equals(b2)) { - return b2blocker; - } else { - return FutureUtils.value(null); - } - }); + (bookie, ledgerId, entryId) -> { + if (bookie.equals(b1)) { + return FutureUtils.exception(new BKException.BKWriteException()); + } else if (bookie.equals(b2)) { + return b2blocker; + } else { + return FutureUtils.value(null); + } + }); CompletableFuture metadataNotifier = new CompletableFuture<>(); CompletableFuture metadataBlocker = new CompletableFuture<>(); clientCtx.getMockLedgerManager().setPreWriteHook( - (ledgerId, metadata) -> { - metadataNotifier.complete(null); - return metadataBlocker; - }); + (ledgerId, metadata) -> { + metadataNotifier.complete(null); + return metadataBlocker; + }); LedgerHandle lh = new LedgerHandle(clientCtx, 10L, md, BookKeeper.DigestType.CRC32C, - ClientUtil.PASSWD, WriteFlag.NONE); + ClientUtil.PASSWD, WriteFlag.NONE); lh.appendAsync("entry1".getBytes()); lh.appendAsync("entry2".getBytes()); lh.appendAsync("entry3".getBytes()); @@ -121,133 +128,140 @@ public void testSecondFailureOccursWhileFirstBeingHandled() throws Exception { future.get(); verify(clientCtx.getLedgerManager(), times(2)).writeLedgerMetadata(anyLong(), any(), any()); - 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)); + 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)); } - @Test(timeout = 30000) - public void testHandlingFailuresOneBookieFailsImmediately() throws Exception { + @Test + @Timeout(value = 30000, unit = TimeUnit.MILLISECONDS) + void handlingFailuresOneBookieFailsImmediately() throws Exception { MockClientContext clientCtx = MockClientContext.create(); Versioned md = ClientUtil.setupLedger(clientCtx, 10L, - LedgerMetadataBuilder.create() - .withEnsembleSize(3).withWriteQuorumSize(3).withAckQuorumSize(3) - .newEnsembleEntry(0L, Lists.newArrayList(b1, b2, b3))); + LedgerMetadataBuilder.create() + .withEnsembleSize(3).withWriteQuorumSize(3).withAckQuorumSize(3) + .newEnsembleEntry(0L, Lists.newArrayList(b1, b2, b3))); clientCtx.getMockRegistrationClient().addBookies(b4).get(); clientCtx.getMockBookieClient().errorBookies(b1); LedgerHandle lh = new LedgerHandle(clientCtx, 10L, md, BookKeeper.DigestType.CRC32C, - ClientUtil.PASSWD, WriteFlag.NONE); + ClientUtil.PASSWD, WriteFlag.NONE); lh.append("entry1".getBytes()); lh.close(); - Assert.assertTrue(lh.getLedgerMetadata().isClosed()); - Assert.assertEquals(lh.getLedgerMetadata().getAllEnsembles().size(), 1); - Assert.assertEquals(lh.getLedgerMetadata().getAllEnsembles().get(0L), Lists.newArrayList(b4, b2, b3)); + assertTrue(lh.getLedgerMetadata().isClosed()); + assertEquals(1, lh.getLedgerMetadata().getAllEnsembles().size()); + assertEquals(lh.getLedgerMetadata().getAllEnsembles().get(0L), Lists.newArrayList(b4, b2, b3)); } - @Test(timeout = 30000) - public void testHandlingFailuresOneBookieFailsAfterOneEntry() throws Exception { + @Test + @Timeout(value = 30000, unit = TimeUnit.MILLISECONDS) + void handlingFailuresOneBookieFailsAfterOneEntry() throws Exception { MockClientContext clientCtx = MockClientContext.create(); Versioned md = ClientUtil.setupLedger(clientCtx, 10L, - LedgerMetadataBuilder.create() - .withEnsembleSize(3).withWriteQuorumSize(3).withAckQuorumSize(3) - .newEnsembleEntry(0L, Lists.newArrayList(b1, b2, b3))); + LedgerMetadataBuilder.create() + .withEnsembleSize(3).withWriteQuorumSize(3).withAckQuorumSize(3) + .newEnsembleEntry(0L, Lists.newArrayList(b1, b2, b3))); clientCtx.getMockRegistrationClient().addBookies(b4).get(); LedgerHandle lh = new LedgerHandle(clientCtx, 10L, md, BookKeeper.DigestType.CRC32C, - ClientUtil.PASSWD, WriteFlag.NONE); + ClientUtil.PASSWD, WriteFlag.NONE); lh.append("entry1".getBytes()); clientCtx.getMockBookieClient().errorBookies(b1); lh.append("entry2".getBytes()); lh.close(); - Assert.assertTrue(lh.getLedgerMetadata().isClosed()); - Assert.assertEquals(lh.getLedgerMetadata().getAllEnsembles().size(), 2); - Assert.assertEquals(lh.getLedgerMetadata().getAllEnsembles().get(0L), Lists.newArrayList(b1, b2, b3)); - Assert.assertEquals(lh.getLedgerMetadata().getAllEnsembles().get(1L), Lists.newArrayList(b4, b2, b3)); - Assert.assertEquals(lh.getLedgerMetadata().getLastEntryId(), 1L); + assertTrue(lh.getLedgerMetadata().isClosed()); + assertEquals(2, lh.getLedgerMetadata().getAllEnsembles().size()); + assertEquals(lh.getLedgerMetadata().getAllEnsembles().get(0L), Lists.newArrayList(b1, b2, b3)); + assertEquals(lh.getLedgerMetadata().getAllEnsembles().get(1L), Lists.newArrayList(b4, b2, b3)); + assertEquals(1L, lh.getLedgerMetadata().getLastEntryId()); } - @Test(timeout = 30000) - public void testHandlingFailuresMultipleBookieFailImmediatelyNotEnoughoReplace() throws Exception { + @Test + @Timeout(value = 30000, unit = TimeUnit.MILLISECONDS) + void handlingFailuresMultipleBookieFailImmediatelyNotEnoughoReplace() throws Exception { MockClientContext clientCtx = MockClientContext.create(); Versioned md = ClientUtil.setupLedger(clientCtx, 10L, - LedgerMetadataBuilder.create() - .withEnsembleSize(3).withWriteQuorumSize(3).withAckQuorumSize(3) - .newEnsembleEntry(0L, Lists.newArrayList(b1, b2, b3))); + LedgerMetadataBuilder.create() + .withEnsembleSize(3).withWriteQuorumSize(3).withAckQuorumSize(3) + .newEnsembleEntry(0L, Lists.newArrayList(b1, b2, b3))); clientCtx.getMockBookieClient().errorBookies(b1, b2); LedgerHandle lh = new LedgerHandle(clientCtx, 10L, md, BookKeeper.DigestType.CRC32C, - ClientUtil.PASSWD, WriteFlag.NONE); + ClientUtil.PASSWD, WriteFlag.NONE); try { lh.append("entry1".getBytes()); - Assert.fail("Shouldn't have been able to add"); + fail("Shouldn't have been able to add"); } catch (BKException.BKNotEnoughBookiesException bke) { // correct behaviour assertEventuallyTrue("Failure to add should trigger ledger closure", - () -> lh.getLedgerMetadata().isClosed()); - Assert.assertEquals("Ledger should be empty", - lh.getLedgerMetadata().getLastEntryId(), LedgerHandle.INVALID_ENTRY_ID); - Assert.assertEquals("Should be only one ensemble", lh.getLedgerMetadata().getAllEnsembles().size(), 1); - Assert.assertEquals("Ensemble shouldn't have changed", lh.getLedgerMetadata().getAllEnsembles().get(0L), - Lists.newArrayList(b1, b2, b3)); + () -> lh.getLedgerMetadata().isClosed()); + assertEquals(LedgerHandle.INVALID_ENTRY_ID, lh.getLedgerMetadata().getLastEntryId() + , "Ledger should be empty"); + assertEquals(1, lh.getLedgerMetadata().getAllEnsembles().size(), "Should be only one ensemble"); + assertEquals(lh.getLedgerMetadata().getAllEnsembles().get(0L), + Lists.newArrayList(b1, b2, b3), + "Ensemble shouldn't have changed"); } } - @Test(timeout = 30000) - public void testHandlingFailuresMultipleBookieFailAfterOneEntryNotEnoughoReplace() throws Exception { + @Test + @Timeout(value = 30000, unit = TimeUnit.MILLISECONDS) + void handlingFailuresMultipleBookieFailAfterOneEntryNotEnoughoReplace() throws Exception { MockClientContext clientCtx = MockClientContext.create(); Versioned md = ClientUtil.setupLedger(clientCtx, 10L, - LedgerMetadataBuilder.create() - .withEnsembleSize(3).withWriteQuorumSize(3).withAckQuorumSize(3) - .newEnsembleEntry(0L, Lists.newArrayList(b1, b2, b3))); + LedgerMetadataBuilder.create() + .withEnsembleSize(3).withWriteQuorumSize(3).withAckQuorumSize(3) + .newEnsembleEntry(0L, Lists.newArrayList(b1, b2, b3))); LedgerHandle lh = new LedgerHandle(clientCtx, 10L, md, BookKeeper.DigestType.CRC32C, - ClientUtil.PASSWD, WriteFlag.NONE); + ClientUtil.PASSWD, WriteFlag.NONE); lh.append("entry1".getBytes()); clientCtx.getMockBookieClient().errorBookies(b1, b2); try { lh.append("entry2".getBytes()); - Assert.fail("Shouldn't have been able to add"); + fail("Shouldn't have been able to add"); } catch (BKException.BKNotEnoughBookiesException bke) { // correct behaviour assertEventuallyTrue("Failure to add should trigger ledger closure", - () -> lh.getLedgerMetadata().isClosed()); - Assert.assertEquals("Ledger should be empty", lh.getLedgerMetadata().getLastEntryId(), 0L); - Assert.assertEquals("Should be only one ensemble", lh.getLedgerMetadata().getAllEnsembles().size(), 1); - Assert.assertEquals("Ensemble shouldn't have changed", lh.getLedgerMetadata().getAllEnsembles().get(0L), - Lists.newArrayList(b1, b2, b3)); + () -> lh.getLedgerMetadata().isClosed()); + assertEquals(0L, lh.getLedgerMetadata().getLastEntryId(), "Ledger should be empty"); + assertEquals(1, lh.getLedgerMetadata().getAllEnsembles().size(), "Should be only one ensemble"); + assertEquals(lh.getLedgerMetadata().getAllEnsembles().get(0L), + Lists.newArrayList(b1, b2, b3), + "Ensemble shouldn't have changed"); } } - @Test(timeout = 30000) - public void testClientClosesWhileFailureHandlerInProgress() throws Exception { + @Test + @Timeout(value = 30000, unit = TimeUnit.MILLISECONDS) + void clientClosesWhileFailureHandlerInProgress() throws Exception { MockClientContext clientCtx = MockClientContext.create(); Versioned md = ClientUtil.setupLedger(clientCtx, 10L, - LedgerMetadataBuilder.create() - .withEnsembleSize(3).withWriteQuorumSize(3).withAckQuorumSize(3) - .newEnsembleEntry(0L, Lists.newArrayList(b1, b2, b3))); + LedgerMetadataBuilder.create() + .withEnsembleSize(3).withWriteQuorumSize(3).withAckQuorumSize(3) + .newEnsembleEntry(0L, Lists.newArrayList(b1, b2, b3))); clientCtx.getMockRegistrationClient().addBookies(b4).get(); clientCtx.getMockBookieClient().errorBookies(b2); CompletableFuture changeInProgress = new CompletableFuture<>(); CompletableFuture blockEnsembleChange = new CompletableFuture<>(); clientCtx.getMockLedgerManager().setPreWriteHook((ledgerId, metadata) -> { - // block the write trying to replace b2 with b4 - if (metadata.getAllEnsembles().get(0L).get(1).equals(b4)) { - changeInProgress.complete(null); - return blockEnsembleChange; - } else { - return FutureUtils.value(null); - } - }); + // block the write trying to replace b2 with b4 + if (metadata.getAllEnsembles().get(0L).get(1).equals(b4)) { + changeInProgress.complete(null); + return blockEnsembleChange; + } else { + return FutureUtils.value(null); + } + }); LedgerHandle lh = new LedgerHandle(clientCtx, 10L, md, BookKeeper.DigestType.CRC32C, - ClientUtil.PASSWD, WriteFlag.NONE); + ClientUtil.PASSWD, WriteFlag.NONE); CompletableFuture future = lh.appendAsync("entry1".getBytes()); changeInProgress.get(); @@ -256,134 +270,136 @@ public void testClientClosesWhileFailureHandlerInProgress() throws Exception { blockEnsembleChange.complete(null); // allow ensemble change to continue try { future.get(); - Assert.fail("Add shouldn't have succeeded"); + fail("Add 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); + 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()); } - @Test(timeout = 30000) - public void testMetadataSetToClosedDuringFailureHandler() throws Exception { + @Test + @Timeout(value = 30000, unit = TimeUnit.MILLISECONDS) + void metadataSetToClosedDuringFailureHandler() throws Exception { MockClientContext clientCtx = MockClientContext.create(); Versioned md = ClientUtil.setupLedger(clientCtx, 10L, - LedgerMetadataBuilder.create() - .withEnsembleSize(3).withWriteQuorumSize(3).withAckQuorumSize(3) - .newEnsembleEntry(0L, Lists.newArrayList(b1, b2, b3))); + LedgerMetadataBuilder.create() + .withEnsembleSize(3).withWriteQuorumSize(3).withAckQuorumSize(3) + .newEnsembleEntry(0L, Lists.newArrayList(b1, b2, b3))); clientCtx.getMockRegistrationClient().addBookies(b4).get(); clientCtx.getMockBookieClient().errorBookies(b2); CompletableFuture changeInProgress = new CompletableFuture<>(); CompletableFuture blockEnsembleChange = new CompletableFuture<>(); clientCtx.getMockLedgerManager().setPreWriteHook((ledgerId, metadata) -> { - if (metadata.getAllEnsembles().get(0L).get(1).equals(b4)) { - // block the write trying to replace b2 with b4 - changeInProgress.complete(null); - return blockEnsembleChange; - } else { - return FutureUtils.value(null); - } - }); + if (metadata.getAllEnsembles().get(0L).get(1).equals(b4)) { + // block the write trying to replace b2 with b4 + changeInProgress.complete(null); + return blockEnsembleChange; + } else { + return FutureUtils.value(null); + } + }); LedgerHandle lh = new LedgerHandle(clientCtx, 10L, md, BookKeeper.DigestType.CRC32C, - ClientUtil.PASSWD, WriteFlag.NONE); + ClientUtil.PASSWD, WriteFlag.NONE); CompletableFuture future = lh.appendAsync("entry1".getBytes()); changeInProgress.get(); ClientUtil.transformMetadata(clientCtx, 10L, - (metadata) -> LedgerMetadataBuilder.from(metadata) - .withClosedState().withLastEntryId(1234L).withLength(10L).build()); + (metadata) -> LedgerMetadataBuilder.from(metadata) + .withClosedState().withLastEntryId(1234L).withLength(10L).build()); blockEnsembleChange.complete(null); // allow ensemble change to continue try { future.get(); - Assert.fail("Add shouldn't have succeeded"); + fail("Add 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(), 1234L); + assertTrue(lh.getLedgerMetadata().isClosed()); + assertEquals(1, lh.getLedgerMetadata().getAllEnsembles().size()); + assertEquals(lh.getLedgerMetadata().getAllEnsembles().get(0L), Lists.newArrayList(b1, b2, b3)); + assertEquals(1234L, lh.getLedgerMetadata().getLastEntryId()); } - @Test(timeout = 30000) - public void testMetadataSetToInRecoveryDuringFailureHandler() throws Exception { + @Test + @Timeout(value = 30000, unit = TimeUnit.MILLISECONDS) + void metadataSetToInRecoveryDuringFailureHandler() throws Exception { MockClientContext clientCtx = MockClientContext.create(); Versioned md = ClientUtil.setupLedger(clientCtx, 10L, - LedgerMetadataBuilder.create() - .withEnsembleSize(3).withWriteQuorumSize(3).withAckQuorumSize(3) - .newEnsembleEntry(0L, Lists.newArrayList(b1, b2, b3))); + LedgerMetadataBuilder.create() + .withEnsembleSize(3).withWriteQuorumSize(3).withAckQuorumSize(3) + .newEnsembleEntry(0L, Lists.newArrayList(b1, b2, b3))); clientCtx.getMockRegistrationClient().addBookies(b4).get(); clientCtx.getMockBookieClient().errorBookies(b2); CompletableFuture changeInProgress = new CompletableFuture<>(); CompletableFuture blockEnsembleChange = new CompletableFuture<>(); clientCtx.getMockLedgerManager().setPreWriteHook((ledgerId, metadata) -> { - if (metadata.getAllEnsembles().get(0L).get(1).equals(b4)) { - // block the write trying to replace b2 with b4 - changeInProgress.complete(null); - return blockEnsembleChange; - } else { - return FutureUtils.value(null); - } - }); + if (metadata.getAllEnsembles().get(0L).get(1).equals(b4)) { + // block the write trying to replace b2 with b4 + changeInProgress.complete(null); + return blockEnsembleChange; + } else { + return FutureUtils.value(null); + } + }); LedgerHandle lh = new LedgerHandle(clientCtx, 10L, md, BookKeeper.DigestType.CRC32C, - ClientUtil.PASSWD, WriteFlag.NONE); + ClientUtil.PASSWD, WriteFlag.NONE); CompletableFuture future = lh.appendAsync("entry1".getBytes()); changeInProgress.get(); ClientUtil.transformMetadata(clientCtx, 10L, - (metadata) -> LedgerMetadataBuilder.from(metadata).withInRecoveryState().build()); + (metadata) -> LedgerMetadataBuilder.from(metadata).withInRecoveryState().build()); blockEnsembleChange.complete(null); // allow ensemble change to continue try { future.get(); - Assert.fail("Add shouldn't have succeeded"); + fail("Add shouldn't have succeeded"); } catch (ExecutionException ee) { - Assert.assertEquals(ee.getCause().getClass(), BKException.BKLedgerFencedException.class); + assertEquals(BKException.BKLedgerFencedException.class, ee.getCause().getClass()); } - Assert.assertFalse(lh.getLedgerMetadata().isClosed()); - Assert.assertEquals(lh.getLedgerMetadata().getAllEnsembles().size(), 1); - Assert.assertEquals(lh.getLedgerMetadata().getAllEnsembles().get(0L), Lists.newArrayList(b1, b2, b3)); + assertFalse(lh.getLedgerMetadata().isClosed()); + assertEquals(1, lh.getLedgerMetadata().getAllEnsembles().size()); + assertEquals(lh.getLedgerMetadata().getAllEnsembles().get(0L), Lists.newArrayList(b1, b2, b3)); } - @Test(timeout = 30000) - public void testOldEnsembleChangedDuringFailureHandler() throws Exception { + @Test + @Timeout(value = 30000, unit = TimeUnit.MILLISECONDS) + void oldEnsembleChangedDuringFailureHandler() throws Exception { MockClientContext clientCtx = MockClientContext.create(); Versioned md = ClientUtil.setupLedger(clientCtx, 10L, - LedgerMetadataBuilder.create() - .withEnsembleSize(3).withWriteQuorumSize(3).withAckQuorumSize(3) - .newEnsembleEntry(0L, Lists.newArrayList(b1, b2, b3))); + LedgerMetadataBuilder.create() + .withEnsembleSize(3).withWriteQuorumSize(3).withAckQuorumSize(3) + .newEnsembleEntry(0L, Lists.newArrayList(b1, b2, b3))); LedgerHandle lh = new LedgerHandle(clientCtx, 10L, md, BookKeeper.DigestType.CRC32C, - ClientUtil.PASSWD, WriteFlag.NONE); + ClientUtil.PASSWD, WriteFlag.NONE); lh.append("entry1".getBytes()); clientCtx.getMockRegistrationClient().addBookies(b4).get(); clientCtx.getMockBookieClient().errorBookies(b3); lh.append("entry2".getBytes()); - Assert.assertEquals(lh.getLedgerMetadata().getAllEnsembles().size(), 2); - Assert.assertEquals(lh.getLedgerMetadata().getAllEnsembles().get(0L), Lists.newArrayList(b1, b2, b3)); - Assert.assertEquals(lh.getLedgerMetadata().getAllEnsembles().get(1L), Lists.newArrayList(b1, b2, b4)); - + assertEquals(2, lh.getLedgerMetadata().getAllEnsembles().size()); + assertEquals(lh.getLedgerMetadata().getAllEnsembles().get(0L), Lists.newArrayList(b1, b2, b3)); + assertEquals(lh.getLedgerMetadata().getAllEnsembles().get(1L), Lists.newArrayList(b1, b2, b4)); CompletableFuture changeInProgress = new CompletableFuture<>(); CompletableFuture blockEnsembleChange = new CompletableFuture<>(); clientCtx.getMockLedgerManager().setPreWriteHook((ledgerId, metadata) -> { - // block the write trying to replace b1 with b5 - if (metadata.getAllEnsembles().size() > 2 - && metadata.getAllEnsembles().get(2L).get(0).equals(b5)) { - changeInProgress.complete(null); - return blockEnsembleChange; - } else { - return FutureUtils.value(null); - } - }); + // block the write trying to replace b1 with b5 + if (metadata.getAllEnsembles().size() > 2 + && metadata.getAllEnsembles().get(2L).get(0).equals(b5)) { + changeInProgress.complete(null); + return blockEnsembleChange; + } else { + return FutureUtils.value(null); + } + }); clientCtx.getMockRegistrationClient().addBookies(b5).get(); clientCtx.getMockBookieClient().errorBookies(b1); @@ -392,89 +408,91 @@ public void testOldEnsembleChangedDuringFailureHandler() throws Exception { changeInProgress.get(); ClientUtil.transformMetadata(clientCtx, 10L, - (metadata) -> LedgerMetadataBuilder.from(metadata).replaceEnsembleEntry( - 0L, Lists.newArrayList(b4, b2, b5)).build()); + (metadata) -> LedgerMetadataBuilder.from(metadata).replaceEnsembleEntry( + 0L, Lists.newArrayList(b4, b2, b5)).build()); blockEnsembleChange.complete(null); // allow ensemble change to continue future.get(); - Assert.assertFalse(lh.getLedgerMetadata().isClosed()); - Assert.assertEquals(lh.getLedgerMetadata().getAllEnsembles().size(), 3); - 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().getAllEnsembles().get(2L), Lists.newArrayList(b5, b2, b4)); + assertFalse(lh.getLedgerMetadata().isClosed()); + assertEquals(3, 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(lh.getLedgerMetadata().getAllEnsembles().get(2L), Lists.newArrayList(b5, b2, b4)); } - @Test(timeout = 30000) - public void testNoAddsAreCompletedWhileFailureHandlingInProgress() throws Exception { + @Test + @Timeout(value = 30000, unit = TimeUnit.MILLISECONDS) + void noAddsAreCompletedWhileFailureHandlingInProgress() throws Exception { MockClientContext clientCtx = MockClientContext.create(); Versioned md = ClientUtil.setupLedger(clientCtx, 10L, - LedgerMetadataBuilder.create() - .withEnsembleSize(3).withWriteQuorumSize(3).withAckQuorumSize(2) - .newEnsembleEntry(0L, Lists.newArrayList(b1, b2, b3))); + LedgerMetadataBuilder.create() + .withEnsembleSize(3).withWriteQuorumSize(3).withAckQuorumSize(2) + .newEnsembleEntry(0L, Lists.newArrayList(b1, b2, b3))); clientCtx.getMockRegistrationClient().addBookies(b4).get(); clientCtx.getMockBookieClient().errorBookies(b3); LedgerHandle lh = new LedgerHandle(clientCtx, 10L, md, BookKeeper.DigestType.CRC32C, - ClientUtil.PASSWD, WriteFlag.NONE); + ClientUtil.PASSWD, WriteFlag.NONE); lh.append("entry1".getBytes()); CompletableFuture changeInProgress = new CompletableFuture<>(); CompletableFuture blockEnsembleChange = new CompletableFuture<>(); clientCtx.getMockLedgerManager().setPreWriteHook((ledgerId, metadata) -> { - // block the write trying to replace b3 with b4 - if (metadata.getAllEnsembles().get(1L).get(2).equals(b4)) { - changeInProgress.complete(null); - return blockEnsembleChange; - } else { - return FutureUtils.value(null); - } - }); + // block the write trying to replace b3 with b4 + if (metadata.getAllEnsembles().get(1L).get(2).equals(b4)) { + changeInProgress.complete(null); + return blockEnsembleChange; + } else { + return FutureUtils.value(null); + } + }); CompletableFuture future = lh.appendAsync("entry2".getBytes()); changeInProgress.get(); try { future.get(1, TimeUnit.SECONDS); - Assert.fail("Shouldn't complete"); + fail("Shouldn't complete"); } catch (TimeoutException te) { } blockEnsembleChange.complete(null); future.get(); - Assert.assertEquals(lh.getLedgerMetadata().getAllEnsembles().size(), 2); - Assert.assertEquals(lh.getLedgerMetadata().getAllEnsembles().get(0L), Lists.newArrayList(b1, b2, b3)); - Assert.assertEquals(lh.getLedgerMetadata().getAllEnsembles().get(1L), Lists.newArrayList(b1, b2, b4)); + assertEquals(2, lh.getLedgerMetadata().getAllEnsembles().size()); + assertEquals(lh.getLedgerMetadata().getAllEnsembles().get(0L), Lists.newArrayList(b1, b2, b3)); + assertEquals(lh.getLedgerMetadata().getAllEnsembles().get(1L), Lists.newArrayList(b1, b2, b4)); } - @Test(timeout = 30000) - public void testHandleFailureBookieNotInWriteSet() throws Exception { + @Test + @Timeout(value = 30000, unit = TimeUnit.MILLISECONDS) + void handleFailureBookieNotInWriteSet() throws Exception { MockClientContext clientCtx = MockClientContext.create(); Versioned md = ClientUtil.setupLedger(clientCtx, 10L, - LedgerMetadataBuilder.create() - .withEnsembleSize(3).withWriteQuorumSize(2).withAckQuorumSize(1) - .newEnsembleEntry(0L, Lists.newArrayList(b1, b2, b3))); + LedgerMetadataBuilder.create() + .withEnsembleSize(3).withWriteQuorumSize(2).withAckQuorumSize(1) + .newEnsembleEntry(0L, Lists.newArrayList(b1, b2, b3))); clientCtx.getMockRegistrationClient().addBookies(b4).get(); CompletableFuture b1Delay = new CompletableFuture<>(); // Delay the first write to b1, then error it clientCtx.getMockBookieClient().setPreWriteHook((bookie, ledgerId, entryId) -> { - if (bookie.equals(b1)) { - return b1Delay; - } else { - return FutureUtils.value(null); - } - }); + if (bookie.equals(b1)) { + return b1Delay; + } else { + return FutureUtils.value(null); + } + }); CompletableFuture changeInProgress = new CompletableFuture<>(); CompletableFuture blockEnsembleChange = new CompletableFuture<>(); clientCtx.getMockLedgerManager().setPreWriteHook((ledgerId, metadata) -> { - changeInProgress.complete(null); - return blockEnsembleChange; - }); + changeInProgress.complete(null); + return blockEnsembleChange; + }); LedgerHandle lh = new LedgerHandle(clientCtx, 10L, md, BookKeeper.DigestType.CRC32C, - ClientUtil.PASSWD, WriteFlag.NONE); + ClientUtil.PASSWD, WriteFlag.NONE); log.info("b2 should be enough to complete first add"); lh.append("entry1".getBytes()); @@ -487,11 +505,11 @@ public void testHandleFailureBookieNotInWriteSet() throws Exception { // Execute appendAsync at the same thread of preWriteHook exception thread. So that the // `delayedWriteFailedBookies` could update before appendAsync invoke. ((MockBookieClient) clientCtx.getBookieClient()).getExecutor() - .chooseThread(lh.ledgerId) - .execute(() -> e2.set(lh.appendAsync("entry2".getBytes()))); + .chooseThread(lh.ledgerId) + .execute(() -> e2.set(lh.appendAsync("entry2".getBytes()))); changeInProgress.get(); assertEventuallyTrue("e2 should eventually complete", () -> lh.pendingAddOps.peek().completed); - Assert.assertFalse("e2 shouldn't be completed to client", e2.get().isDone()); + assertFalse(e2.get().isDone(), "e2 shouldn't be completed to client"); blockEnsembleChange.complete(null); // allow ensemble change to continue log.info("e2 should complete"); diff --git a/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/LedgerClose2Test.java b/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/LedgerClose2Test.java index 40f69304828..31d794d5e29 100644 --- a/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/LedgerClose2Test.java +++ b/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/LedgerClose2Test.java @@ -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 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 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 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 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 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 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()); } } diff --git a/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/LedgerCloseTest.java b/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/LedgerCloseTest.java index 496e61f8b44..dcac0b687d7 100644 --- a/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/LedgerCloseTest.java +++ b/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/LedgerCloseTest.java @@ -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 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> { @@ -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); diff --git a/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/LedgerCmdTest.java b/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/LedgerCmdTest.java index 6900dfbc13d..62451eb8f42 100644 --- a/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/LedgerCmdTest.java +++ b/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/LedgerCmdTest.java @@ -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!"); } diff --git a/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/LedgerMetadataTest.java b/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/LedgerMetadataTest.java index 4444dd5b767..91303fb637e 100644 --- a/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/LedgerMetadataTest.java +++ b/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/LedgerMetadataTest.java @@ -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 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 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"); } } diff --git a/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/LedgerRecovery2Test.java b/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/LedgerRecovery2Test.java index 22112cbc608..ec26154e4ca 100644 --- a/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/LedgerRecovery2Test.java +++ b/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/LedgerRecovery2Test.java @@ -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 setupLedger(ClientContext clientCtx, lo @Test - public void testCantRecoverAllDown() throws Exception { + void cantRecoverAllDown() throws Exception { MockClientContext clientCtx = MockClientContext.create(); Versioned md = setupLedger(clientCtx, 1L, Lists.newArrayList(b1, b2, b3)); @@ -95,14 +98,14 @@ public void testCantRecoverAllDown() throws Exception { GenericCallbackFuture 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 md = setupLedger(clientCtx, 1, Lists.newArrayList(b1, b2, b3)); @@ -117,14 +120,14 @@ public void testCanReadLacButCantWrite() throws Exception { GenericCallbackFuture 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 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 reachedStepFuture) { @@ -516,7 +519,7 @@ private void stepBlock(CompletableFuture 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()); } -} \ No newline at end of file +} diff --git a/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/LedgerRecoveryTest.java b/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/LedgerRecoveryTest.java index 4a9e65a6534..50cbefe42f5 100644 --- a/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/LedgerRecoveryTest.java +++ b/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/LedgerRecoveryTest.java @@ -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,8 +348,8 @@ 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"); } /** @@ -357,7 +357,7 @@ public void recoveryAddEntry(ByteBuf entry, WriteCallback cb, Object ctx, byte[] * 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); } diff --git a/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/ListLedgersTest.java b/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/ListLedgersTest.java index 8bb23684bc7..08bd5d013a9 100644 --- a/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/ListLedgersTest.java +++ b/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/ListLedgersTest.java @@ -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 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 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 iterator = admin.listLedgers().iterator(); iterator.next(); try { diff --git a/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/MdcContextTest.java b/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/MdcContextTest.java index 2a7a15ca253..83ceb7658fa 100644 --- a/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/MdcContextTest.java +++ b/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/MdcContextTest.java @@ -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,11 +140,11 @@ 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 } @@ -153,7 +152,7 @@ public void testLedgerCreateFails() throws Exception { } @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); diff --git a/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/MetadataUpdateLoopTest.java b/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/MetadataUpdateLoopTest.java index ed97b4af52a..edbb94b7be5 100644 --- a/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/MetadataUpdateLoopTest.java +++ b/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/MetadataUpdateLoopTest.java @@ -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 l1meta = loop1.get(); Versioned 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> loop2 = new MetadataUpdateLoop( lm, @@ -382,13 +383,13 @@ public void testNewestValueCannotBeUsedAfterReadBack() throws Exception { Versioned 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 diff --git a/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/MockBookKeeperTest.java b/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/MockBookKeeperTest.java index a7405934715..055c53cd9e6 100644 --- a/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/MockBookKeeperTest.java +++ b/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/MockBookKeeperTest.java @@ -16,13 +16,13 @@ */ 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. @@ -30,7 +30,7 @@ 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]); diff --git a/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/MockBookKeeperTestCase.java b/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/MockBookKeeperTestCase.java index b1def134d45..8fc95767b9d 100644 --- a/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/MockBookKeeperTestCase.java +++ b/bookkeeper-server/src/test/java/org/apache/bookkeeper/client/MockBookKeeperTestCase.java @@ -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(); diff --git a/bookkeeper-server/src/test/java/org/apache/bookkeeper/util/resolvers/BeforeParameterResolver.java b/bookkeeper-server/src/test/java/org/apache/bookkeeper/util/resolvers/BeforeParameterResolver.java new file mode 100644 index 00000000000..9a16a9eb556 --- /dev/null +++ b/bookkeeper-server/src/test/java/org/apache/bookkeeper/util/resolvers/BeforeParameterResolver.java @@ -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 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); + } +} diff --git a/bookkeeper-server/src/test/java/org/apache/bookkeeper/util/resolvers/MappedParameterContext.java b/bookkeeper-server/src/test/java/org/apache/bookkeeper/util/resolvers/MappedParameterContext.java new file mode 100644 index 00000000000..653586791fb --- /dev/null +++ b/bookkeeper-server/src/test/java/org/apache/bookkeeper/util/resolvers/MappedParameterContext.java @@ -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 target; + + @Override + public boolean isAnnotated(Class annotationType) { + return AnnotationUtils.isAnnotated(parameter, annotationType); + } + + @Override + public Optional findAnnotation(Class annotationType) { + return AnnotationUtils.findAnnotation(parameter, annotationType); + } + + @Override + public List findRepeatableAnnotations(Class annotationType) { + return AnnotationUtils.findRepeatableAnnotations(parameter, annotationType); + } +}