diff --git a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/EntryCacheManagerTest.java b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/EntryCacheManagerTest.java index 69c23e323439e..8971e11ac3d9d 100644 --- a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/EntryCacheManagerTest.java +++ b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/EntryCacheManagerTest.java @@ -21,6 +21,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import java.util.List; @@ -29,8 +30,6 @@ import org.apache.bookkeeper.common.util.OrderedScheduler; import org.apache.bookkeeper.mledger.Entry; import org.apache.bookkeeper.mledger.ManagedCursor; -import org.apache.bookkeeper.mledger.ManagedLedger; -import org.apache.bookkeeper.mledger.ManagedLedgerFactory; import org.apache.bookkeeper.mledger.ManagedLedgerFactoryConfig; import org.apache.bookkeeper.test.MockedBookKeeperTestCase; import org.testng.annotations.BeforeClass; @@ -128,13 +127,13 @@ void doubleInsert() throws Exception { EntryCacheManager cacheManager = factory.getEntryCacheManager(); EntryCache cache1 = cacheManager.getEntryCache(ml1); - assertEquals(cache1.insert(EntryImpl.create(1, 1, new byte[4])), true); - assertEquals(cache1.insert(EntryImpl.create(1, 0, new byte[3])), true); + assertTrue(cache1.insert(EntryImpl.create(1, 1, new byte[4]))); + assertTrue(cache1.insert(EntryImpl.create(1, 0, new byte[3]))); assertEquals(cache1.getSize(), 7); assertEquals(cacheManager.getSize(), 7); - assertEquals(cache1.insert(EntryImpl.create(1, 0, new byte[5])), false); + assertFalse(cache1.insert(EntryImpl.create(1, 0, new byte[5]))); assertEquals(cache1.getSize(), 7); assertEquals(cacheManager.getSize(), 7); diff --git a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedCursorConcurrencyTest.java b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedCursorConcurrencyTest.java index 852abcd8d842e..856a7e8b1248d 100644 --- a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedCursorConcurrencyTest.java +++ b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedCursorConcurrencyTest.java @@ -19,7 +19,9 @@ package org.apache.bookkeeper.mledger.impl; import static org.apache.bookkeeper.mledger.util.SafeRun.safeRun; -import static org.testng.Assert.*; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNull; import com.google.common.collect.Lists; import java.util.List; @@ -126,7 +128,7 @@ public void run() { counter.await(); - assertEquals(gotException.get(), false); + assertFalse(gotException.get()); } @Test @@ -210,7 +212,7 @@ public void closeFailed(ManagedLedgerException exception, Object ctx) { counter.await(); - assertEquals(gotException.get(), false); + assertFalse(gotException.get()); assertEquals(closeFuture.get(), CLOSED); } @@ -266,7 +268,7 @@ public void testAckAndClose() throws Exception { counter.await(); - assertEquals(gotException.get(), false); + assertFalse(gotException.get()); } @Test(timeOut = 30000) @@ -312,7 +314,7 @@ public void testConcurrentIndividualDeletes() throws Exception { counter.await(); - assertEquals(gotException.get(), false); + assertFalse(gotException.get()); assertEquals(cursor.getMarkDeletedPosition(), addedEntries.get(addedEntries.size() - 1)); } @@ -338,7 +340,7 @@ public void testConcurrentReadOfSameEntry() throws Exception { final CyclicBarrier barrier = new CyclicBarrier(numCursors); final CountDownLatch counter = new CountDownLatch(numCursors); - AtomicReference result = new AtomicReference(); + AtomicReference result = new AtomicReference<>(); for (int i = 0; i < numCursors; i++) { final int cursorIndex = i; diff --git a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedCursorContainerTest.java b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedCursorContainerTest.java index dfd233a2184f4..60d3dc9e7b898 100644 --- a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedCursorContainerTest.java +++ b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedCursorContainerTest.java @@ -18,7 +18,11 @@ */ package org.apache.bookkeeper.mledger.impl; -import static org.testng.Assert.*; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; +import static org.testng.Assert.fail; import com.google.common.base.Predicate; import com.google.common.collect.Lists; @@ -309,7 +313,7 @@ public double getThrottleMarkDelete() { @Test void simple() throws Exception { ManagedCursorContainer container = new ManagedCursorContainer(); - assertEquals(container.getSlowestReaderPosition(), null); + assertNull(container.getSlowestReaderPosition()); ManagedCursor cursor1 = new MockManagedCursor(container, "test1", new PositionImpl(5, 5)); container.add(cursor1); @@ -350,7 +354,7 @@ void simple() throws Exception { assertFalse(container.isEmpty()); container.removeCursor(cursor4.getName()); - assertEquals(container.getSlowestReaderPosition(), null); + assertNull(container.getSlowestReaderPosition()); assertTrue(container.isEmpty()); @@ -409,7 +413,7 @@ void removingCursor() throws Exception { assertEquals(container, Lists.newArrayList(cursor1, cursor3)); - assertEquals(container.get("test2"), null); + assertNull(container.get("test2")); assertEquals(container.getSlowestReaderPosition(), new PositionImpl(1, 1)); diff --git a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedCursorTest.java b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedCursorTest.java index fc3a8cb129c2e..4f2cce5950eb6 100644 --- a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedCursorTest.java +++ b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedCursorTest.java @@ -23,7 +23,12 @@ import static org.mockito.Mockito.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import static org.testng.Assert.*; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotEquals; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; +import static org.testng.Assert.fail; import com.google.common.base.Charsets; import com.google.common.collect.Lists; @@ -221,19 +226,19 @@ void testNumberOfEntries() throws Exception { ManagedCursor c5 = ledger.openCursor("c5"); assertEquals(c1.getNumberOfEntries(), 4); - assertEquals(c1.hasMoreEntries(), true); + assertTrue(c1.hasMoreEntries()); assertEquals(c2.getNumberOfEntries(), 3); - assertEquals(c2.hasMoreEntries(), true); + assertTrue(c2.hasMoreEntries()); assertEquals(c3.getNumberOfEntries(), 2); - assertEquals(c3.hasMoreEntries(), true); + assertTrue(c3.hasMoreEntries()); assertEquals(c4.getNumberOfEntries(), 1); - assertEquals(c4.hasMoreEntries(), true); + assertTrue(c4.hasMoreEntries()); assertEquals(c5.getNumberOfEntries(), 0); - assertEquals(c5.hasMoreEntries(), false); + assertFalse(c5.hasMoreEntries()); List entries = c1.readEntries(2); assertEquals(entries.size(), 2); @@ -331,13 +336,13 @@ void testNumberOfEntriesWithReopen() throws Exception { c3 = ledger.openCursor("c3"); assertEquals(c1.getNumberOfEntries(), 2); - assertEquals(c1.hasMoreEntries(), true); + assertTrue(c1.hasMoreEntries()); assertEquals(c2.getNumberOfEntries(), 1); - assertEquals(c2.hasMoreEntries(), true); + assertTrue(c2.hasMoreEntries()); assertEquals(c3.getNumberOfEntries(), 0); - assertEquals(c3.hasMoreEntries(), false); + assertFalse(c3.hasMoreEntries()); factory2.shutdown(); } @@ -538,7 +543,7 @@ void testResetCursor() throws Exception { } assertTrue(moveStatus.get()); - assertTrue(cursor.getReadPosition().equals(resetPosition)); + assertEquals(resetPosition, cursor.getReadPosition()); cursor.close(); ledger.close(); } @@ -571,7 +576,7 @@ public void resetFailed(ManagedLedgerException exception, Object ctx) { }); countDownLatch.await(); assertTrue(moveStatus.get()); - assertTrue(cursor.getReadPosition().equals(resetPosition)); + assertEquals(resetPosition, cursor.getReadPosition()); cursor.close(); ledger.close(); } @@ -624,7 +629,7 @@ public void resetFailed(ManagedLedgerException exception, Object ctx) { } }); countDownLatch.await(); - assertTrue(cursor.getReadPosition().equals(resetPosition)); + assertEquals(resetPosition, cursor.getReadPosition()); cursor.close(); return moveStatus; @@ -779,7 +784,7 @@ void markDeleteSkippingMessage() throws Exception { assertEquals(cursor.getNumberOfEntries(), 4); cursor.markDelete(p1); - assertEquals(cursor.hasMoreEntries(), true); + assertTrue(cursor.hasMoreEntries()); assertEquals(cursor.getNumberOfEntries(), 3); assertEquals(cursor.getReadPosition(), p2); @@ -790,7 +795,7 @@ void markDeleteSkippingMessage() throws Exception { entries.forEach(e -> e.release()); cursor.markDelete(p4); - assertEquals(cursor.hasMoreEntries(), false); + assertFalse(cursor.hasMoreEntries()); assertEquals(cursor.getNumberOfEntries(), 0); assertEquals(cursor.getReadPosition(), new PositionImpl(p4.getLedgerId(), p4.getEntryId() + 1)); @@ -1371,7 +1376,7 @@ void testSkipEntries(boolean useOpenRangeSet) throws Exception { // skip more than the current set of entries c1.skipEntries(10, IndividualDeletedEntries.Exclude); assertEquals(c1.getNumberOfEntries(), 0); - assertEquals(c1.hasMoreEntries(), false); + assertFalse(c1.hasMoreEntries()); assertEquals(c1.getReadPosition(), pos.getNext()); assertEquals(c1.getMarkDeletedPosition(), pos); } @@ -1426,22 +1431,22 @@ void testClearBacklog(boolean useOpenRangeSet) throws Exception { assertEquals(c1.getNumberOfEntriesInBacklog(), 3); assertEquals(c1.getNumberOfEntries(), 3); - assertEquals(c1.hasMoreEntries(), true); + assertTrue(c1.hasMoreEntries()); c1.clearBacklog(); c3.clearBacklog(); assertEquals(c1.getNumberOfEntriesInBacklog(), 0); assertEquals(c1.getNumberOfEntries(), 0); - assertEquals(c1.hasMoreEntries(), false); + assertFalse(c1.hasMoreEntries()); assertEquals(c2.getNumberOfEntriesInBacklog(), 2); assertEquals(c2.getNumberOfEntries(), 2); - assertEquals(c2.hasMoreEntries(), true); + assertTrue(c2.hasMoreEntries()); assertEquals(c3.getNumberOfEntriesInBacklog(), 0); assertEquals(c3.getNumberOfEntries(), 0); - assertEquals(c3.hasMoreEntries(), false); + assertFalse(c3.hasMoreEntries()); ManagedLedgerFactory factory2 = new ManagedLedgerFactoryImpl(bkc, bkc.getZkHandle()); ledger = factory2.open("my_test_ledger", new ManagedLedgerConfig().setMaxEntriesPerLedger(1)); @@ -1452,15 +1457,15 @@ void testClearBacklog(boolean useOpenRangeSet) throws Exception { assertEquals(c1.getNumberOfEntriesInBacklog(), 0); assertEquals(c1.getNumberOfEntries(), 0); - assertEquals(c1.hasMoreEntries(), false); + assertFalse(c1.hasMoreEntries()); assertEquals(c2.getNumberOfEntriesInBacklog(), 2); assertEquals(c2.getNumberOfEntries(), 2); - assertEquals(c2.hasMoreEntries(), true); + assertTrue(c2.hasMoreEntries()); assertEquals(c3.getNumberOfEntriesInBacklog(), 0); assertEquals(c3.getNumberOfEntries(), 0); - assertEquals(c3.hasMoreEntries(), false); + assertFalse(c3.hasMoreEntries()); factory2.shutdown(); } @@ -1803,9 +1808,8 @@ void testFindNewestMatchingEdgeCase1() throws Exception { ManagedLedger ledger = factory.open("my_test_ledger"); ManagedCursorImpl c1 = (ManagedCursorImpl) ledger.openCursor("c1"); - assertEquals( - c1.findNewestMatching(entry -> Arrays.equals(entry.getDataAndRelease(), "expired".getBytes(Encoding))), - null); + assertNull(c1.findNewestMatching( + entry -> Arrays.equals(entry.getDataAndRelease(), "expired".getBytes(Encoding)))); } @Test(timeOut = 20000) @@ -2353,7 +2357,7 @@ void cancelReadOperation() throws Exception { ManagedCursor c1 = ledger.openCursor("c1"); // No read request so far - assertEquals(c1.cancelPendingReadRequest(), false); + assertFalse(c1.cancelPendingReadRequest()); CountDownLatch counter = new CountDownLatch(1); @@ -2369,7 +2373,7 @@ public void readEntriesFailed(ManagedLedgerException exception, Object ctx) { } }, null); - assertEquals(c1.cancelPendingReadRequest(), true); + assertTrue(c1.cancelPendingReadRequest()); CountDownLatch counter2 = new CountDownLatch(1); @@ -2390,7 +2394,7 @@ public void readEntriesFailed(ManagedLedgerException exception, Object ctx) { Thread.sleep(100); // Read operation should have already been completed - assertEquals(c1.cancelPendingReadRequest(), false); + assertFalse(c1.cancelPendingReadRequest()); counter2.await(); } diff --git a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerErrorsTest.java b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerErrorsTest.java index 0f0d78917ab13..d9ad5c59b056c 100644 --- a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerErrorsTest.java +++ b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerErrorsTest.java @@ -18,7 +18,10 @@ */ package org.apache.bookkeeper.mledger.impl; -import static org.testng.Assert.*; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.fail; import java.util.List; import java.util.concurrent.CountDownLatch; @@ -49,7 +52,7 @@ public void removingCursor() throws Exception { ManagedLedger ledger = factory.open("my_test_ledger"); ManagedCursor c1 = ledger.openCursor("c1"); - assertEquals(zkc.exists("/managed-ledgers/my_test_ledger/c1", false) != null, true); + assertNotNull(zkc.exists("/managed-ledgers/my_test_ledger/c1", false)); zkc.failNow(Code.BADVERSION); @@ -65,7 +68,7 @@ public void removingCursor() throws Exception { // Cursor ledger deletion will fail, but that should not prevent the deleteCursor to fail ledger.deleteCursor("c1"); - assertEquals(zkc.exists("/managed-ledgers/my_test_ledger/c1", false) != null, false); + assertNull(zkc.exists("/managed-ledgers/my_test_ledger/c1", false)); assertEquals(bkc.getLedgers().size(), 2); } diff --git a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerSingleBookieTest.java b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerSingleBookieTest.java index f663de522141d..5b2c34d5adeeb 100644 --- a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerSingleBookieTest.java +++ b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerSingleBookieTest.java @@ -19,6 +19,8 @@ package org.apache.bookkeeper.mledger.impl; import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertTrue; import com.google.common.base.Charsets; import java.nio.charset.Charset; @@ -57,12 +59,12 @@ public void simple() throws Exception { ManagedCursor cursor = ledger.openCursor("c1"); - assertEquals(cursor.hasMoreEntries(), false); + assertFalse(cursor.hasMoreEntries()); assertEquals(cursor.readEntries(100), new ArrayList()); ledger.addEntry("dummy-entry-2".getBytes(Encoding)); - assertEquals(cursor.hasMoreEntries(), true); + assertTrue(cursor.hasMoreEntries()); List entries = cursor.readEntries(100); assertEquals(entries.size(), 1); diff --git a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerTerminationTest.java b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerTerminationTest.java index 052c9fb5b68cf..2fb4964010c92 100644 --- a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerTerminationTest.java +++ b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerTerminationTest.java @@ -19,6 +19,8 @@ package org.apache.bookkeeper.mledger.impl; import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import java.util.Collections; @@ -103,10 +105,10 @@ public void terminateWithCursorReadOrWait() throws Exception { Position p0 = ledger.addEntry("entry-0".getBytes()); Position p1 = ledger.addEntry("entry-1".getBytes()); - assertEquals(ledger.isTerminated(), false); + assertFalse(ledger.isTerminated()); Position lastPosition = ledger.terminate(); - assertEquals(ledger.isTerminated(), true); + assertTrue(ledger.isTerminated()); assertEquals(lastPosition, p1); List entries = c1.readEntries(10); @@ -133,10 +135,10 @@ public void terminateWithNonDurableCursor() throws Exception { Position p0 = ledger.addEntry("entry-0".getBytes()); Position p1 = ledger.addEntry("entry-1".getBytes()); - assertEquals(ledger.isTerminated(), false); + assertFalse(ledger.isTerminated()); Position lastPosition = ledger.terminate(); - assertEquals(ledger.isTerminated(), true); + assertTrue(ledger.isTerminated()); assertEquals(lastPosition, p1); ManagedCursor c1 = ledger.newNonDurableCursor(PositionImpl.earliest); diff --git a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerTest.java b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerTest.java index baaa6f6316e7e..40726c940a3e8 100644 --- a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerTest.java +++ b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerTest.java @@ -27,6 +27,7 @@ import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertSame; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; @@ -163,14 +164,14 @@ public void simple() throws Exception { ManagedCursor cursor = ledger.openCursor("c1"); - assertEquals(cursor.hasMoreEntries(), false); + assertFalse(cursor.hasMoreEntries()); assertEquals(cursor.getNumberOfEntries(), 0); assertEquals(cursor.getNumberOfEntriesInBacklog(), 0); assertEquals(cursor.readEntries(100), new ArrayList()); ledger.addEntry("dummy-entry-2".getBytes(Encoding)); - assertEquals(cursor.hasMoreEntries(), true); + assertTrue(cursor.hasMoreEntries()); assertEquals(cursor.getNumberOfEntries(), 1); assertEquals(cursor.getNumberOfEntriesInBacklog(), 1); assertEquals(ledger.getNumberOfActiveEntries(), 1); @@ -226,14 +227,14 @@ public void acknowledge1() throws Exception { ledger.addEntry("dummy-entry-1".getBytes(Encoding)); ledger.addEntry("dummy-entry-2".getBytes(Encoding)); - assertEquals(cursor.hasMoreEntries(), true); + assertTrue(cursor.hasMoreEntries()); List entries = cursor.readEntries(2); assertEquals(entries.size(), 2); assertEquals(cursor.getNumberOfEntries(), 0); assertEquals(cursor.getNumberOfEntriesInBacklog(), 2); - assertEquals(cursor.hasMoreEntries(), false); + assertFalse(cursor.hasMoreEntries()); assertEquals(ledger.getNumberOfEntries(), 2); assertEquals(ledger.getNumberOfActiveEntries(), 2); @@ -242,7 +243,7 @@ public void acknowledge1() throws Exception { assertEquals(cursor.getNumberOfEntries(), 0); assertEquals(cursor.getNumberOfEntriesInBacklog(), 1); - assertEquals(cursor.hasMoreEntries(), false); + assertFalse(cursor.hasMoreEntries()); assertEquals(ledger.getNumberOfActiveEntries(), 1); ledger.close(); @@ -257,7 +258,7 @@ public void acknowledge1() throws Exception { assertEquals(cursor.getNumberOfEntries(), 1); assertEquals(cursor.getNumberOfEntriesInBacklog(), 1); - assertEquals(cursor.hasMoreEntries(), true); + assertTrue(cursor.hasMoreEntries()); entries = cursor.readEntries(100); assertEquals(entries.size(), 1); @@ -305,7 +306,7 @@ public void readEntriesComplete(List entries, Object ctx) { public void markDeleteComplete(Object ctx) { log.debug("Mark delete complete"); ManagedCursor cursor = (ManagedCursor) ctx; - assertEquals(cursor.hasMoreEntries(), false); + assertFalse(cursor.hasMoreEntries()); counter.countDown(); } @@ -366,7 +367,7 @@ public void spanningMultipleLedgers() throws Exception { List entries = cursor.readEntries(100); assertEquals(entries.size(), 11); - assertEquals(cursor.hasMoreEntries(), false); + assertFalse(cursor.hasMoreEntries()); PositionImpl first = (PositionImpl) entries.get(0).getPosition(); PositionImpl last = (PositionImpl) entries.get(entries.size() - 1).getPosition(); @@ -380,7 +381,7 @@ public void spanningMultipleLedgers() throws Exception { // Read again, from next ledger id entries = cursor.readEntries(100); assertEquals(entries.size(), 0); - assertEquals(cursor.hasMoreEntries(), false); + assertFalse(cursor.hasMoreEntries()); ledger.close(); } @@ -406,7 +407,7 @@ public void spanningMultipleLedgersWithSize() throws Exception { List entries = cursor.readEntries(100); assertEquals(entries.size(), 3); - assertEquals(cursor.hasMoreEntries(), false); + assertFalse(cursor.hasMoreEntries()); PositionImpl first = (PositionImpl) entries.get(0).getPosition(); PositionImpl last = (PositionImpl) entries.get(entries.size() - 1).getPosition(); @@ -415,7 +416,7 @@ public void spanningMultipleLedgersWithSize() throws Exception { // Read again, from next ledger id entries = cursor.readEntries(100); assertEquals(entries.size(), 0); - assertEquals(cursor.hasMoreEntries(), false); + assertFalse(cursor.hasMoreEntries()); entries.forEach(e -> e.release()); log.info("First={} Last={}", first, last); @@ -484,7 +485,7 @@ public void deleteAndReopenWithCursors() throws Exception { ledger = factory.open("my_test_ledger"); assertEquals(ledger.getNumberOfEntries(), 0); ManagedCursor cursor = ledger.openCursor("test-cursor"); - assertEquals(cursor.hasMoreEntries(), false); + assertFalse(cursor.hasMoreEntries()); ledger.close(); } @@ -689,7 +690,7 @@ public void readFromOlderLedger() throws Exception { ledger.addEntry("entry-1".getBytes(Encoding)); ledger.addEntry("entry-2".getBytes(Encoding)); - assertEquals(cursor.hasMoreEntries(), true); + assertTrue(cursor.hasMoreEntries()); } @Test(timeOut = 20000) @@ -702,14 +703,14 @@ public void readFromOlderLedgers() throws Exception { ledger.addEntry("entry-2".getBytes(Encoding)); ledger.addEntry("entry-3".getBytes(Encoding)); - assertEquals(cursor.hasMoreEntries(), true); + assertTrue(cursor.hasMoreEntries()); cursor.readEntries(1).forEach(e -> e.release()); - assertEquals(cursor.hasMoreEntries(), true); + assertTrue(cursor.hasMoreEntries()); cursor.readEntries(1).forEach(e -> e.release()); - assertEquals(cursor.hasMoreEntries(), true); + assertTrue(cursor.hasMoreEntries()); cursor.readEntries(1).forEach(e -> e.release()); - assertEquals(cursor.hasMoreEntries(), false); + assertFalse(cursor.hasMoreEntries()); } @Test(timeOut = 20000) @@ -722,15 +723,15 @@ public void triggerLedgerDeletion() throws Exception { ledger.addEntry("entry-2".getBytes(Encoding)); ledger.addEntry("entry-3".getBytes(Encoding)); - assertEquals(cursor.hasMoreEntries(), true); + assertTrue(cursor.hasMoreEntries()); List entries = cursor.readEntries(1); assertEquals(entries.size(), 1); assertEquals(ledger.getNumberOfEntries(), 3); entries.forEach(e -> e.release()); - assertEquals(cursor.hasMoreEntries(), true); + assertTrue(cursor.hasMoreEntries()); entries = cursor.readEntries(1); - assertEquals(cursor.hasMoreEntries(), true); + assertTrue(cursor.hasMoreEntries()); cursor.markDelete(entries.get(0).getPosition()); entries.forEach(e -> e.release()); @@ -852,7 +853,7 @@ public void moveCursorToNextLedger() throws Exception { ledger.addEntry("entry-3".getBytes(Encoding)); log.debug("Added 3nd message"); - assertEquals(cursor.hasMoreEntries(), true); + assertTrue(cursor.hasMoreEntries()); assertEquals(cursor.getNumberOfEntries(), 2); entries = cursor.readEntries(2); @@ -880,7 +881,7 @@ public void differentSessions() throws Exception { assertEquals(ledger.getNumberOfEntries(), 1); assertEquals(ledger.getTotalSize(), "dummy-entry-1".getBytes(Encoding).length); - assertEquals(cursor.hasMoreEntries(), true); + assertTrue(cursor.hasMoreEntries()); assertEquals(cursor.getNumberOfEntries(), 1); ledger.close(); @@ -895,7 +896,7 @@ public void differentSessions() throws Exception { cursor = ledger.openCursor("c1"); - assertEquals(cursor.hasMoreEntries(), true); + assertTrue(cursor.hasMoreEntries()); assertEquals(cursor.getNumberOfEntries(), 1); ledger.addEntry("dummy-entry-2".getBytes(Encoding)); @@ -903,7 +904,7 @@ public void differentSessions() throws Exception { assertEquals(ledger.getNumberOfEntries(), 2); assertEquals(ledger.getTotalSize(), "dummy-entry-1".getBytes(Encoding).length * 2); - assertEquals(cursor.hasMoreEntries(), true); + assertTrue(cursor.hasMoreEntries()); assertEquals(cursor.getNumberOfEntries(), 2); ledger.close(); @@ -1235,7 +1236,7 @@ public void doubleOpen() throws Exception { ManagedLedger ledger1 = factory.open("my_test_ledger"); ManagedLedger ledger2 = factory.open("my_test_ledger"); - assertTrue(ledger1 == ledger2); + assertSame(ledger1, ledger2); } @Test @@ -1437,12 +1438,12 @@ public void cursorReadsWithDiscardedEmptyLedgers() throws Exception { c1 = ledger.openCursor("c1"); assertEquals(c1.getNumberOfEntries(), 0); - assertEquals(c1.hasMoreEntries(), false); + assertFalse(c1.hasMoreEntries()); ledger.addEntry("entry".getBytes()); assertEquals(c1.getNumberOfEntries(), 1); - assertEquals(c1.hasMoreEntries(), true); + assertTrue(c1.hasMoreEntries()); assertEquals(ledger.getLedgersInfoAsList().size(), 1); @@ -1450,11 +1451,11 @@ public void cursorReadsWithDiscardedEmptyLedgers() throws Exception { assertEquals(entries.size(), 1); entries.forEach(e -> e.release()); - assertEquals(c1.hasMoreEntries(), false); + assertFalse(c1.hasMoreEntries()); assertEquals(c1.readEntries(1).size(), 0); c1.seek(p1); - assertEquals(c1.hasMoreEntries(), true); + assertTrue(c1.hasMoreEntries()); assertEquals(c1.getNumberOfEntries(), 1); entries = c1.readEntries(1); @@ -1523,14 +1524,14 @@ public void operationFailed(MetaStoreException e) { c1 = ledger.openCursor("c1"); assertEquals(c1.getNumberOfEntries(), 1); - assertEquals(c1.hasMoreEntries(), true); + assertTrue(c1.hasMoreEntries()); assertEquals(ledger.getLedgersInfoAsList().size(), 2); List entries = c1.readEntries(10); assertEquals(entries.size(), 1); entries.forEach(e -> e.release()); - assertEquals(c1.hasMoreEntries(), false); + assertFalse(c1.hasMoreEntries()); entries = c1.readEntries(1); assertEquals(entries.size(), 0); entries.forEach(e -> e.release()); diff --git a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/NonDurableCursorTest.java b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/NonDurableCursorTest.java index 8039a50c6d5e3..1579a7a71d20e 100644 --- a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/NonDurableCursorTest.java +++ b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/NonDurableCursorTest.java @@ -18,7 +18,12 @@ */ package org.apache.bookkeeper.mledger.impl; -import static org.testng.Assert.*; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; +import static org.testng.Assert.fail; import com.google.common.base.Charsets; import com.google.common.collect.Iterables; @@ -179,19 +184,19 @@ void testNumberOfEntries() throws Exception { ManagedCursor c5 = ledger.newNonDurableCursor(PositionImpl.latest); assertEquals(c1.getNumberOfEntries(), 4); - assertEquals(c1.hasMoreEntries(), true); + assertTrue(c1.hasMoreEntries()); assertEquals(c2.getNumberOfEntries(), 3); - assertEquals(c2.hasMoreEntries(), true); + assertTrue(c2.hasMoreEntries()); assertEquals(c3.getNumberOfEntries(), 2); - assertEquals(c3.hasMoreEntries(), true); + assertTrue(c3.hasMoreEntries()); assertEquals(c4.getNumberOfEntries(), 1); - assertEquals(c4.hasMoreEntries(), true); + assertTrue(c4.hasMoreEntries()); assertEquals(c5.getNumberOfEntries(), 0); - assertEquals(c5.hasMoreEntries(), false); + assertFalse(c5.hasMoreEntries()); List entries = c1.readEntries(2); assertEquals(entries.size(), 2); @@ -311,7 +316,7 @@ void testResetCursor() throws Exception { } assertTrue(moveStatus.get()); - assertTrue(cursor.getReadPosition().equals(resetPosition)); + assertEquals(resetPosition, cursor.getReadPosition()); cursor.close(); ledger.close(); } @@ -344,7 +349,7 @@ public void resetFailed(ManagedLedgerException exception, Object ctx) { }); countDownLatch.await(); assertTrue(moveStatus.get()); - assertTrue(cursor.getReadPosition().equals(resetPosition)); + assertEquals(resetPosition, cursor.getReadPosition()); cursor.close(); ledger.close(); } @@ -413,7 +418,7 @@ void markDeleteSkippingMessage() throws Exception { assertEquals(cursor.getNumberOfEntries(), 4); cursor.markDelete(p1); - assertEquals(cursor.hasMoreEntries(), true); + assertTrue(cursor.hasMoreEntries()); assertEquals(cursor.getNumberOfEntries(), 3); assertEquals(cursor.getReadPosition(), p2); @@ -424,7 +429,7 @@ void markDeleteSkippingMessage() throws Exception { entries.forEach(e -> e.release()); cursor.markDelete(p4); - assertEquals(cursor.hasMoreEntries(), false); + assertFalse(cursor.hasMoreEntries()); assertEquals(cursor.getNumberOfEntries(), 0); assertEquals(cursor.getReadPosition(), new PositionImpl(p4.getLedgerId(), p4.getEntryId() + 1)); diff --git a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/OffloadLedgerDeleteTest.java b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/OffloadLedgerDeleteTest.java index b574d906179b1..0dd7c30c299e7 100644 --- a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/OffloadLedgerDeleteTest.java +++ b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/OffloadLedgerDeleteTest.java @@ -20,7 +20,6 @@ import static org.apache.bookkeeper.mledger.impl.OffloadPrefixTest.assertEventuallyTrue; -import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; diff --git a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/OffloadPrefixTest.java b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/OffloadPrefixTest.java index 9ccc515819214..b4739e17d5abd 100644 --- a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/OffloadPrefixTest.java +++ b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/OffloadPrefixTest.java @@ -19,7 +19,10 @@ package org.apache.bookkeeper.mledger.impl; import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotEquals; import static org.testng.Assert.assertTrue; +import static org.testng.Assert.fail; import com.google.common.collect.ImmutableSet; @@ -51,7 +54,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.testng.Assert; import org.testng.annotations.Test; public class OffloadPrefixTest extends MockedBookKeeperTestCase { @@ -70,7 +72,7 @@ public void testNullOffloader() throws Exception { String content = "entry-" + i; ledger.addEntry(content.getBytes()); } - Assert.assertEquals(ledger.getLedgersInfoAsList().size(), 3); + assertEquals(ledger.getLedgersInfoAsList().size(), 3); Position p = ledger.getLastConfirmedEntry(); @@ -78,17 +80,17 @@ public void testNullOffloader() throws Exception { String content = "entry-" + i; ledger.addEntry(content.getBytes()); } - Assert.assertEquals(ledger.getLedgersInfoAsList().size(), 5); - Assert.assertEquals(ledger.getLedgersInfoAsList().stream() + assertEquals(ledger.getLedgersInfoAsList().size(), 5); + assertEquals(ledger.getLedgersInfoAsList().stream() .filter(e -> e.getOffloadContext().getComplete()).count(), 0); try { ledger.offloadPrefix(p); - Assert.fail("Should have thrown an exception"); + fail("Should have thrown an exception"); } catch (ManagedLedgerException e) { - Assert.assertEquals(e.getCause().getClass(), CompletionException.class); + assertEquals(e.getCause().getClass(), CompletionException.class); } - Assert.assertEquals(ledger.getLedgersInfoAsList().size(), 5); - Assert.assertEquals(ledger.getLedgersInfoAsList().stream() + assertEquals(ledger.getLedgersInfoAsList().size(), 5); + assertEquals(ledger.getLedgersInfoAsList().stream() .filter(e -> e.getOffloadContext().getComplete()).count(), 0); // add more entries to ensure we can update the ledger list @@ -96,8 +98,8 @@ public void testNullOffloader() throws Exception { String content = "entry-" + i; ledger.addEntry(content.getBytes()); } - Assert.assertEquals(ledger.getLedgersInfoAsList().size(), 6); - Assert.assertEquals(ledger.getLedgersInfoAsList().stream() + assertEquals(ledger.getLedgersInfoAsList().size(), 6); + assertEquals(ledger.getLedgersInfoAsList().stream() .filter(e -> e.getOffloadContext().getComplete()).count(), 0); } @@ -116,12 +118,12 @@ public void testOffload() throws Exception { String content = "entry-" + i; ledger.addEntry(content.getBytes()); } - Assert.assertEquals(ledger.getLedgersInfoAsList().size(), 3); + assertEquals(ledger.getLedgersInfoAsList().size(), 3); ledger.offloadPrefix(ledger.getLastConfirmedEntry()); - Assert.assertEquals(ledger.getLedgersInfoAsList().size(), 3); - Assert.assertEquals(ledger.getLedgersInfoAsList().stream() + assertEquals(ledger.getLedgersInfoAsList().size(), 3); + assertEquals(ledger.getLedgersInfoAsList().stream() .filter(e -> e.getOffloadContext().getComplete()) .map(e -> e.getLedgerId()).collect(Collectors.toSet()), offloader.offloadedLedgers()); @@ -142,24 +144,24 @@ public void testPositionOutOfRange() throws Exception { String content = "entry-" + i; ledger.addEntry(content.getBytes()); } - Assert.assertEquals(ledger.getLedgersInfoAsList().size(), 3); + assertEquals(ledger.getLedgersInfoAsList().size(), 3); try { ledger.offloadPrefix(PositionImpl.earliest); - Assert.fail("Should have thrown an exception"); + fail("Should have thrown an exception"); } catch (ManagedLedgerException.InvalidCursorPositionException e) { // expected } try { ledger.offloadPrefix(PositionImpl.latest); - Assert.fail("Should have thrown an exception"); + fail("Should have thrown an exception"); } catch (ManagedLedgerException.InvalidCursorPositionException e) { // expected } - Assert.assertEquals(ledger.getLedgersInfoAsList().stream() + assertEquals(ledger.getLedgersInfoAsList().stream() .filter(e -> e.getOffloadContext().getComplete()).count(), 0); - Assert.assertEquals(offloader.offloadedLedgers().size(), 0); + assertEquals(offloader.offloadedLedgers().size(), 0); } @Test @@ -177,36 +179,36 @@ public void testPositionOnEdgeOfLedger() throws Exception { String content = "entry-" + i; ledger.addEntry(content.getBytes()); } - Assert.assertEquals(ledger.getLedgersInfoAsList().size(), 2); + assertEquals(ledger.getLedgersInfoAsList().size(), 2); Position p = ledger.getLastConfirmedEntry(); // position at end of second ledger ledger.addEntry("entry-blah".getBytes()); - Assert.assertEquals(ledger.getLedgersInfoAsList().size(), 3); + assertEquals(ledger.getLedgersInfoAsList().size(), 3); PositionImpl firstUnoffloaded = (PositionImpl)ledger.offloadPrefix(p); // only the first ledger should have been offloaded - Assert.assertEquals(ledger.getLedgersInfoAsList().size(), 3); - Assert.assertEquals(offloader.offloadedLedgers().size(), 1); - Assert.assertTrue(offloader.offloadedLedgers().contains(ledger.getLedgersInfoAsList().get(0).getLedgerId())); - Assert.assertTrue(ledger.getLedgersInfoAsList().get(0).getOffloadContext().getComplete()); - Assert.assertEquals(ledger.getLedgersInfoAsList().stream() + assertEquals(ledger.getLedgersInfoAsList().size(), 3); + assertEquals(offloader.offloadedLedgers().size(), 1); + assertTrue(offloader.offloadedLedgers().contains(ledger.getLedgersInfoAsList().get(0).getLedgerId())); + assertTrue(ledger.getLedgersInfoAsList().get(0).getOffloadContext().getComplete()); + assertEquals(ledger.getLedgersInfoAsList().stream() .filter(e -> e.getOffloadContext().getComplete()).count(), 1); - Assert.assertEquals(firstUnoffloaded.getLedgerId(), ledger.getLedgersInfoAsList().get(1).getLedgerId()); - Assert.assertEquals(firstUnoffloaded.getEntryId(), 0); + assertEquals(firstUnoffloaded.getLedgerId(), ledger.getLedgersInfoAsList().get(1).getLedgerId()); + assertEquals(firstUnoffloaded.getEntryId(), 0); // offload again, with the position in the third ledger PositionImpl firstUnoffloaded2 = (PositionImpl)ledger.offloadPrefix(ledger.getLastConfirmedEntry()); - Assert.assertEquals(ledger.getLedgersInfoAsList().size(), 3); - Assert.assertEquals(offloader.offloadedLedgers().size(), 2); - Assert.assertTrue(offloader.offloadedLedgers().contains(ledger.getLedgersInfoAsList().get(0).getLedgerId())); - Assert.assertTrue(offloader.offloadedLedgers().contains(ledger.getLedgersInfoAsList().get(1).getLedgerId())); - Assert.assertTrue(ledger.getLedgersInfoAsList().get(0).getOffloadContext().getComplete()); - Assert.assertTrue(ledger.getLedgersInfoAsList().get(1).getOffloadContext().getComplete()); - Assert.assertEquals(ledger.getLedgersInfoAsList().stream() + assertEquals(ledger.getLedgersInfoAsList().size(), 3); + assertEquals(offloader.offloadedLedgers().size(), 2); + assertTrue(offloader.offloadedLedgers().contains(ledger.getLedgersInfoAsList().get(0).getLedgerId())); + assertTrue(offloader.offloadedLedgers().contains(ledger.getLedgersInfoAsList().get(1).getLedgerId())); + assertTrue(ledger.getLedgersInfoAsList().get(0).getOffloadContext().getComplete()); + assertTrue(ledger.getLedgersInfoAsList().get(1).getOffloadContext().getComplete()); + assertEquals(ledger.getLedgersInfoAsList().stream() .filter(e -> e.getOffloadContext().getComplete()).count(), 2); - Assert.assertEquals(firstUnoffloaded2.getLedgerId(), ledger.getLedgersInfoAsList().get(2).getLedgerId()); + assertEquals(firstUnoffloaded2.getLedgerId(), ledger.getLedgersInfoAsList().get(2).getLedgerId()); } @Test @@ -228,7 +230,7 @@ public void testPositionOnLastEmptyLedger() throws Exception { ledger.close(); ledger = (ManagedLedgerImpl)factory.open("my_test_ledger", config); - Assert.assertEquals(ledger.getLedgersInfoAsList().size(), 2); + assertEquals(ledger.getLedgersInfoAsList().size(), 2); assertTrue(ledger.getLedgersInfoAsList().get(0).getSize() > 0); assertEquals(ledger.getLedgersInfoAsList().get(1).getSize(), 0); @@ -239,14 +241,14 @@ public void testPositionOnLastEmptyLedger() throws Exception { PositionImpl firstUnoffloaded = (PositionImpl)ledger.offloadPrefix(p); // only the first ledger should have been offloaded - Assert.assertEquals(ledger.getLedgersInfoAsList().size(), 2); - Assert.assertEquals(offloader.offloadedLedgers().size(), 1); - Assert.assertTrue(offloader.offloadedLedgers().contains(ledger.getLedgersInfoAsList().get(0).getLedgerId())); - Assert.assertTrue(ledger.getLedgersInfoAsList().get(0).getOffloadContext().getComplete()); - Assert.assertEquals(ledger.getLedgersInfoAsList().stream() + assertEquals(ledger.getLedgersInfoAsList().size(), 2); + assertEquals(offloader.offloadedLedgers().size(), 1); + assertTrue(offloader.offloadedLedgers().contains(ledger.getLedgersInfoAsList().get(0).getLedgerId())); + assertTrue(ledger.getLedgersInfoAsList().get(0).getOffloadContext().getComplete()); + assertEquals(ledger.getLedgersInfoAsList().stream() .filter(e -> e.getOffloadContext().getComplete()).count(), 1); - Assert.assertEquals(firstUnoffloaded.getLedgerId(), ledger.getLedgersInfoAsList().get(1).getLedgerId()); - Assert.assertEquals(firstUnoffloaded.getEntryId(), 0); + assertEquals(firstUnoffloaded.getLedgerId(), ledger.getLedgersInfoAsList().get(1).getLedgerId()); + assertEquals(firstUnoffloaded.getEntryId(), 0); } @Test @@ -276,7 +278,7 @@ public CompletableFuture offload(ReadHandle ledger, String content = "entry-" + i; ledger.addEntry(content.getBytes()); } - Assert.assertEquals(ledger.getLedgersInfoAsList().size(), 3); + assertEquals(ledger.getLedgersInfoAsList().size(), 3); PositionImpl startOfSecondLedger = PositionImpl.get(ledger.getLedgersInfoAsList().get(1).getLedgerId(), 0); PositionImpl startOfThirdLedger = PositionImpl.get(ledger.getLedgersInfoAsList().get(2).getLedgerId(), 0); @@ -289,19 +291,19 @@ public CompletableFuture offload(ReadHandle ledger, // trim first ledger cursor.markDelete(startOfSecondLedger, new HashMap<>()); assertEventuallyTrue(() -> ledger.getLedgersInfoAsList().size() == 2); - Assert.assertEquals(ledger.getLedgersInfoAsList().stream() + assertEquals(ledger.getLedgersInfoAsList().stream() .filter(e -> e.getOffloadContext().getComplete()).count(), 0); // complete offloading blocker.complete(null); cbPromise.get(); - Assert.assertEquals(ledger.getLedgersInfoAsList().size(), 2); - Assert.assertEquals(ledger.getLedgersInfoAsList().stream() + assertEquals(ledger.getLedgersInfoAsList().size(), 2); + assertEquals(ledger.getLedgersInfoAsList().stream() .filter(e -> e.getOffloadContext().getComplete()).count(), 1); - Assert.assertTrue(ledger.getLedgersInfoAsList().get(0).getOffloadContext().getComplete()); - Assert.assertEquals(offloader.offloadedLedgers().size(), 1); - Assert.assertTrue(offloader.offloadedLedgers().contains(ledger.getLedgersInfoAsList().get(0).getLedgerId())); + assertTrue(ledger.getLedgersInfoAsList().get(0).getOffloadContext().getComplete()); + assertEquals(offloader.offloadedLedgers().size(), 1); + assertTrue(offloader.offloadedLedgers().contains(ledger.getLedgersInfoAsList().get(0).getLedgerId())); } @Test @@ -339,7 +341,7 @@ public CompletableFuture offload(ReadHandle ledger, String content = "entry-" + i; ledger.addEntry(content.getBytes()); } - Assert.assertEquals(ledger.getLedgersInfoAsList().size(), 3); + assertEquals(ledger.getLedgersInfoAsList().size(), 3); PositionImpl startOfSecondLedger = PositionImpl.get(ledger.getLedgersInfoAsList().get(1).getLedgerId(), 0); PositionImpl startOfThirdLedger = PositionImpl.get(ledger.getLedgersInfoAsList().get(2).getLedgerId(), 0); @@ -353,21 +355,21 @@ public CompletableFuture offload(ReadHandle ledger, long trimmedLedger = ledger.getLedgersInfoAsList().get(0).getLedgerId(); cursor.markDelete(startOfSecondLedger, new HashMap<>()); assertEventuallyTrue(() -> ledger.getLedgersInfoAsList().size() == 2); - Assert.assertEquals(ledger.getLedgersInfoAsList().stream() + assertEquals(ledger.getLedgersInfoAsList().stream() .filter(e -> e.getLedgerId() == trimmedLedger).count(), 0); - Assert.assertEquals(ledger.getLedgersInfoAsList().stream() + assertEquals(ledger.getLedgersInfoAsList().stream() .filter(e -> e.getOffloadContext().getComplete()).count(), 0); // complete offloading blocker.complete(trimmedLedger); cbPromise.get(); - Assert.assertEquals(ledger.getLedgersInfoAsList().size(), 2); - Assert.assertEquals(ledger.getLedgersInfoAsList().stream() + assertEquals(ledger.getLedgersInfoAsList().size(), 2); + assertEquals(ledger.getLedgersInfoAsList().stream() .filter(e -> e.getOffloadContext().getComplete()).count(), 1); - Assert.assertTrue(ledger.getLedgersInfoAsList().get(0).getOffloadContext().getComplete()); - Assert.assertEquals(offloader.offloadedLedgers().size(), 1); - Assert.assertTrue(offloader.offloadedLedgers().contains(ledger.getLedgersInfoAsList().get(0).getLedgerId())); + assertTrue(ledger.getLedgersInfoAsList().get(0).getOffloadContext().getComplete()); + assertEquals(offloader.offloadedLedgers().size(), 1); + assertTrue(offloader.offloadedLedgers().contains(ledger.getLedgersInfoAsList().get(0).getLedgerId())); } @Test @@ -390,15 +392,15 @@ public void testOffloadClosedManagedLedger() throws Exception { try { ledger.offloadPrefix(p); - Assert.fail("Should fail because ML is closed"); + fail("Should fail because ML is closed"); } catch (ManagedLedgerException.ManagedLedgerAlreadyClosedException e) { // expected } - Assert.assertEquals(ledger.getLedgersInfoAsList().size(), 3); - Assert.assertEquals(ledger.getLedgersInfoAsList().stream() + assertEquals(ledger.getLedgersInfoAsList().size(), 3); + assertEquals(ledger.getLedgersInfoAsList().stream() .filter(e -> e.getOffloadContext().getComplete()).count(), 0); - Assert.assertEquals(offloader.offloadedLedgers().size(), 0); + assertEquals(offloader.offloadedLedgers().size(), 0); } @Test @@ -416,20 +418,20 @@ public void testOffloadSamePositionTwice() throws Exception { String content = "entry-" + i; ledger.addEntry(content.getBytes()); } - Assert.assertEquals(ledger.getLedgersInfoAsList().size(), 3); + assertEquals(ledger.getLedgersInfoAsList().size(), 3); ledger.offloadPrefix(ledger.getLastConfirmedEntry()); - Assert.assertEquals(ledger.getLedgersInfoAsList().size(), 3); - Assert.assertEquals(ledger.getLedgersInfoAsList().stream() + assertEquals(ledger.getLedgersInfoAsList().size(), 3); + assertEquals(ledger.getLedgersInfoAsList().stream() .filter(e -> e.getOffloadContext().getComplete()) .map(e -> e.getLedgerId()).collect(Collectors.toSet()), offloader.offloadedLedgers()); ledger.offloadPrefix(ledger.getLastConfirmedEntry()); - Assert.assertEquals(ledger.getLedgersInfoAsList().size(), 3); - Assert.assertEquals(ledger.getLedgersInfoAsList().stream() + assertEquals(ledger.getLedgersInfoAsList().size(), 3); + assertEquals(ledger.getLedgersInfoAsList().stream() .filter(e -> e.getOffloadContext().getComplete()) .map(e -> e.getLedgerId()).collect(Collectors.toSet()), offloader.offloadedLedgers()); @@ -451,7 +453,7 @@ public void offloadThreeOneFails(int failIndex) throws Exception { String content = "entry-" + i; ledger.addEntry(content.getBytes()); } - Assert.assertEquals(ledger.getLedgersInfoAsList().size(), 4); + assertEquals(ledger.getLedgersInfoAsList().size(), 4); // mark ledgers to fail promise.complete(ImmutableSet.of(ledger.getLedgersInfoAsList().get(failIndex).getLedgerId())); @@ -459,17 +461,17 @@ public void offloadThreeOneFails(int failIndex) throws Exception { try { ledger.offloadPrefix(ledger.getLastConfirmedEntry()); } catch (ManagedLedgerException e) { - Assert.assertEquals(e.getCause().getClass(), CompletionException.class); + assertEquals(e.getCause().getClass(), CompletionException.class); } - Assert.assertEquals(ledger.getLedgersInfoAsList().size(), 4); - Assert.assertEquals(ledger.getLedgersInfoAsList().stream() + assertEquals(ledger.getLedgersInfoAsList().size(), 4); + assertEquals(ledger.getLedgersInfoAsList().stream() .filter(e -> e.getOffloadContext().getComplete()) .map(e -> e.getLedgerId()).collect(Collectors.toSet()), offloader.offloadedLedgers()); - Assert.assertEquals(ledger.getLedgersInfoAsList().stream() + assertEquals(ledger.getLedgersInfoAsList().stream() .filter(e -> e.getOffloadContext().getComplete()).count(), 2); - Assert.assertFalse(ledger.getLedgersInfoAsList().get(failIndex).getOffloadContext().getComplete()); + assertFalse(ledger.getLedgersInfoAsList().get(failIndex).getOffloadContext().getComplete()); } @Test @@ -506,9 +508,9 @@ public void testOffloadNewML() throws Exception { ledger.addEntry("foobar".getBytes()); Position p = ledger.getLastConfirmedEntry(); - Assert.assertEquals(p, ledger.offloadPrefix(ledger.getLastConfirmedEntry())); - Assert.assertEquals(ledger.getLedgersInfoAsList().size(), 1); - Assert.assertEquals(offloader.offloadedLedgers().size(), 0); + assertEquals(p, ledger.offloadPrefix(ledger.getLastConfirmedEntry())); + assertEquals(ledger.getLedgersInfoAsList().size(), 1); + assertEquals(offloader.offloadedLedgers().size(), 0); } @Test @@ -563,28 +565,28 @@ public CompletableFuture deleteOffloaded(long ledgerId, UUID uuid, } catch (ManagedLedgerException e) { // expected } - Assert.assertTrue(errorSet.isEmpty()); - Assert.assertEquals(failedOffloads.size(), 1); - Assert.assertEquals(deleted.size(), 0); + assertTrue(errorSet.isEmpty()); + assertEquals(failedOffloads.size(), 1); + assertEquals(deleted.size(), 0); long expectedFailedLedger = ledger.getLedgersInfoAsList().get(0).getLedgerId(); UUID expectedFailedUUID = new UUID(ledger.getLedgersInfoAsList().get(0).getOffloadContext().getUidMsb(), ledger.getLedgersInfoAsList().get(0).getOffloadContext().getUidLsb()); - Assert.assertEquals(failedOffloads.stream().findFirst().get(), + assertEquals(failedOffloads.stream().findFirst().get(), Pair.of(expectedFailedLedger, expectedFailedUUID)); - Assert.assertFalse(ledger.getLedgersInfoAsList().get(0).getOffloadContext().getComplete()); + assertFalse(ledger.getLedgersInfoAsList().get(0).getOffloadContext().getComplete()); // try offload again ledger.offloadPrefix(ledger.getLastConfirmedEntry()); - Assert.assertEquals(failedOffloads.size(), 1); - Assert.assertEquals(deleted.size(), 1); - Assert.assertEquals(deleted.stream().findFirst().get(), + assertEquals(failedOffloads.size(), 1); + assertEquals(deleted.size(), 1); + assertEquals(deleted.stream().findFirst().get(), Pair.of(expectedFailedLedger, expectedFailedUUID)); UUID successUUID = new UUID(ledger.getLedgersInfoAsList().get(0).getOffloadContext().getUidMsb(), ledger.getLedgersInfoAsList().get(0).getOffloadContext().getUidLsb()); - Assert.assertFalse(successUUID.equals(expectedFailedUUID)); - Assert.assertTrue(ledger.getLedgersInfoAsList().get(0).getOffloadContext().getComplete()); + assertNotEquals(expectedFailedUUID, successUUID); + assertTrue(ledger.getLedgersInfoAsList().get(0).getOffloadContext().getComplete()); } @Test @@ -606,19 +608,19 @@ public void testOffloadDelete() throws Exception { ledger.addEntry(content.getBytes()); } - Assert.assertEquals(ledger.getLedgersInfoAsList().size(), 2); + assertEquals(ledger.getLedgersInfoAsList().size(), 2); ledger.offloadPrefix(ledger.getLastConfirmedEntry()); - Assert.assertEquals(ledger.getLedgersInfoAsList().size(), 2); + assertEquals(ledger.getLedgersInfoAsList().size(), 2); - Assert.assertEquals(ledger.getLedgersInfoAsList().stream() + assertEquals(ledger.getLedgersInfoAsList().stream() .filter(e -> e.getOffloadContext().getComplete()).count(), 1); - Assert.assertTrue(ledger.getLedgersInfoAsList().get(0).getOffloadContext().getComplete()); + assertTrue(ledger.getLedgersInfoAsList().get(0).getOffloadContext().getComplete()); long firstLedger = ledger.getLedgersInfoAsList().get(0).getLedgerId(); long secondLedger = ledger.getLedgersInfoAsList().get(1).getLedgerId(); cursor.markDelete(ledger.getLastConfirmedEntry()); assertEventuallyTrue(() -> ledger.getLedgersInfoAsList().size() == 1); - Assert.assertEquals(ledger.getLedgersInfoAsList().get(0).getLedgerId(), secondLedger); + assertEquals(ledger.getLedgersInfoAsList().get(0).getLedgerId(), secondLedger); assertEventuallyTrue(() -> offloader.deletedOffloads().contains(firstLedger)); } @@ -654,27 +656,27 @@ public CompletableFuture offload(ReadHandle ledger, ledger.addEntry(content.getBytes()); } - Assert.assertEquals(ledger.getLedgersInfoAsList().size(), 2); + assertEquals(ledger.getLedgersInfoAsList().size(), 2); try { ledger.offloadPrefix(ledger.getLastConfirmedEntry()); } catch (ManagedLedgerException mle) { // expected } - Assert.assertEquals(ledger.getLedgersInfoAsList().size(), 2); + assertEquals(ledger.getLedgersInfoAsList().size(), 2); - Assert.assertEquals(ledger.getLedgersInfoAsList().stream() + assertEquals(ledger.getLedgersInfoAsList().stream() .filter(e -> e.getOffloadContext().getComplete()).count(), 0); - Assert.assertEquals(ledger.getLedgersInfoAsList().stream() + assertEquals(ledger.getLedgersInfoAsList().stream() .filter(e -> e.getOffloadContext().hasUidMsb()).count(), 1); - Assert.assertTrue(ledger.getLedgersInfoAsList().get(0).getOffloadContext().hasUidMsb()); + assertTrue(ledger.getLedgersInfoAsList().get(0).getOffloadContext().hasUidMsb()); long firstLedger = ledger.getLedgersInfoAsList().get(0).getLedgerId(); long secondLedger = ledger.getLedgersInfoAsList().get(1).getLedgerId(); cursor.markDelete(ledger.getLastConfirmedEntry()); assertEventuallyTrue(() -> ledger.getLedgersInfoAsList().size() == 1); - Assert.assertEquals(ledger.getLedgersInfoAsList().get(0).getLedgerId(), secondLedger); + assertEquals(ledger.getLedgersInfoAsList().get(0).getLedgerId(), secondLedger); assertEventuallyTrue(() -> offloader.deletedOffloads().contains(firstLedger)); } @@ -694,7 +696,7 @@ public void testDontOffloadEmpty() throws Exception { String content = "entry-" + i; ledger.addEntry(content.getBytes()); } - Assert.assertEquals(ledger.getLedgersInfoAsList().size(), 4); + assertEquals(ledger.getLedgersInfoAsList().size(), 4); long firstLedgerId = ledger.getLedgersInfoAsList().get(0).getLedgerId(); long secondLedgerId = ledger.getLedgersInfoAsList().get(1).getLedgerId(); @@ -709,15 +711,15 @@ public void testDontOffloadEmpty() throws Exception { ledgers.get(secondLedgerId).toBuilder().setEntries(0).setSize(0).build()); PositionImpl firstUnoffloaded = (PositionImpl)ledger.offloadPrefix(ledger.getLastConfirmedEntry()); - Assert.assertEquals(firstUnoffloaded.getLedgerId(), fourthLedgerId); - Assert.assertEquals(firstUnoffloaded.getEntryId(), 0); + assertEquals(firstUnoffloaded.getLedgerId(), fourthLedgerId); + assertEquals(firstUnoffloaded.getEntryId(), 0); - Assert.assertEquals(ledger.getLedgersInfoAsList().size(), 4); - Assert.assertEquals(ledger.getLedgersInfoAsList().stream() + assertEquals(ledger.getLedgersInfoAsList().size(), 4); + assertEquals(ledger.getLedgersInfoAsList().stream() .filter(e -> e.getOffloadContext().getComplete()) .map(e -> e.getLedgerId()).collect(Collectors.toSet()), offloader.offloadedLedgers()); - Assert.assertEquals(offloader.offloadedLedgers(), ImmutableSet.of(firstLedgerId, thirdLedgerId)); + assertEquals(offloader.offloadedLedgers(), ImmutableSet.of(firstLedgerId, thirdLedgerId)); } private static byte[] buildEntry(int size, String pattern) { @@ -746,11 +748,11 @@ public void testAutoTriggerOffload() throws Exception { ledger.addEntry(buildEntry(10, "entry-" + i)); } - Assert.assertEquals(ledger.getLedgersInfoAsList().size(), 3); + assertEquals(ledger.getLedgersInfoAsList().size(), 3); // offload should eventually be triggered assertEventuallyTrue(() -> offloader.offloadedLedgers().size() == 1); - Assert.assertEquals(offloader.offloadedLedgers(), + assertEquals(offloader.offloadedLedgers(), ImmutableSet.of(ledger.getLedgersInfoAsList().get(0).getLedgerId())); } @@ -789,7 +791,7 @@ public CompletableFuture offload(ReadHandle ledger, try { ledger.offloadPrefix(p); - Assert.fail("Shouldn't have succeeded"); + fail("Shouldn't have succeeded"); } catch (ManagedLedgerException.OffloadInProgressException e) { // expected } @@ -798,7 +800,7 @@ public CompletableFuture offload(ReadHandle ledger, // eventually all over threshold will be offloaded assertEventuallyTrue(() -> offloader.offloadedLedgers().size() == 3); - Assert.assertEquals(offloader.offloadedLedgers(), + assertEquals(offloader.offloadedLedgers(), ImmutableSet.of(ledger.getLedgersInfoAsList().get(0).getLedgerId(), ledger.getLedgersInfoAsList().get(1).getLedgerId(), ledger.getLedgersInfoAsList().get(2).getLedgerId())); @@ -806,8 +808,8 @@ public CompletableFuture offload(ReadHandle ledger, // then a manual offload can run and offload the one ledger under the threshold ledger.offloadPrefix(p); - Assert.assertEquals(offloader.offloadedLedgers().size(), 4); - Assert.assertEquals(offloader.offloadedLedgers(), + assertEquals(offloader.offloadedLedgers().size(), 4); + assertEquals(offloader.offloadedLedgers(), ImmutableSet.of(ledger.getLedgersInfoAsList().get(0).getLedgerId(), ledger.getLedgersInfoAsList().get(1).getLedgerId(), ledger.getLedgersInfoAsList().get(2).getLedgerId(), @@ -854,12 +856,12 @@ public CompletableFuture offload(ReadHandle ledger, // allow the manual offload to complete slowOffload.complete(null); - Assert.assertEquals(cbPromise.join(), + assertEquals(cbPromise.join(), PositionImpl.get(ledger.getLedgersInfoAsList().get(1).getLedgerId(), 0)); // auto trigger should eventually offload everything else over threshold assertEventuallyTrue(() -> offloader.offloadedLedgers().size() == 2); - Assert.assertEquals(offloader.offloadedLedgers(), + assertEquals(offloader.offloadedLedgers(), ImmutableSet.of(ledger.getLedgersInfoAsList().get(0).getLedgerId(), ledger.getLedgersInfoAsList().get(1).getLedgerId())); } @@ -903,7 +905,7 @@ public CompletableFuture offload(ReadHandle ledger, slowOffload.complete(null); assertEventuallyTrue(() -> offloader.offloadedLedgers().size() == 3); - Assert.assertEquals(offloader.offloadedLedgers(), + assertEquals(offloader.offloadedLedgers(), ImmutableSet.of(ledger.getLedgersInfoAsList().get(0).getLedgerId(), ledger.getLedgersInfoAsList().get(1).getLedgerId(), ledger.getLedgersInfoAsList().get(2).getLedgerId())); @@ -926,7 +928,7 @@ public void offloadAsSoonAsClosed() throws Exception { } assertEventuallyTrue(() -> offloader.offloadedLedgers().size() == 1); - Assert.assertEquals(offloader.offloadedLedgers(), + assertEquals(offloader.offloadedLedgers(), ImmutableSet.of(ledger.getLedgersInfoAsList().get(0).getLedgerId())); for (int i = 0; i < 10; i++) { @@ -934,7 +936,7 @@ public void offloadAsSoonAsClosed() throws Exception { } assertEventuallyTrue(() -> offloader.offloadedLedgers().size() == 2); - Assert.assertEquals(offloader.offloadedLedgers(), + assertEquals(offloader.offloadedLedgers(), ImmutableSet.of(ledger.getLedgersInfoAsList().get(0).getLedgerId(), ledger.getLedgersInfoAsList().get(1).getLedgerId())); } @@ -945,7 +947,7 @@ static void assertEventuallyTrue(BooleanSupplier predicate) throws Exception { for (int i = 0; i < 30 && !predicate.getAsBoolean(); i++) { Thread.sleep(100); } - Assert.assertTrue(predicate.getAsBoolean()); + assertTrue(predicate.getAsBoolean()); } static class OffloadCallbackPromise extends CompletableFuture implements OffloadCallback { diff --git a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/PositionTest.java b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/PositionTest.java index fe2fcdaf18fa9..659796d92db3e 100644 --- a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/PositionTest.java +++ b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/PositionTest.java @@ -19,7 +19,7 @@ package org.apache.bookkeeper.mledger.impl; import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotEquals; import org.apache.bookkeeper.mledger.proto.MLDataFormats.PositionInfo; import org.testng.annotations.Test; @@ -37,9 +37,9 @@ public void simpleTest() { assertEquals(pos.getEntryId(), 2); assertEquals(pos, new PositionImpl(1, 2)); - assertFalse(pos.equals(new PositionImpl(1, 3))); - assertFalse(pos.equals(new PositionImpl(3, 2))); - assertFalse(pos.equals("1:2")); + assertNotEquals(new PositionImpl(1, 3), pos); + assertNotEquals(new PositionImpl(3, 2), pos); + assertNotEquals(pos, "1:2"); } @Test diff --git a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/util/RangeCacheTest.java b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/util/RangeCacheTest.java index 27e63815c0107..7dcafa6438787 100644 --- a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/util/RangeCacheTest.java +++ b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/util/RangeCacheTest.java @@ -19,6 +19,9 @@ package org.apache.bookkeeper.mledger.util; import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import com.google.common.collect.Lists; @@ -83,7 +86,7 @@ void simple() { s1.release(); s2.release(); - assertEquals(cache.get(2), null); + assertNull(cache.get(2)); cache.put(2, new RefString("2")); cache.put(8, new RefString("8")); @@ -145,7 +148,7 @@ void doubleInsert() { RefString s0 = new RefString("zero"); assertEquals(s0.refCnt(), 1); - assertEquals(cache.put(0, s0), true); + assertTrue(cache.put(0, s0)); assertEquals(s0.refCnt(), 1); cache.put(1, new RefString("one")); @@ -158,7 +161,7 @@ void doubleInsert() { RefString s1 = new RefString("uno"); assertEquals(s1.refCnt(), 1); - assertEquals(cache.put(1, s1), false); + assertFalse(cache.put(1, s1)); assertEquals(s1.refCnt(), 1); s1.release(); @@ -203,18 +206,18 @@ void eviction() { assertEquals(cache.getNumberOfEntries(), 2); assertEquals(cache.getSize(), 8); - assertEquals(cache.get(0), null); - assertEquals(cache.get(1), null); + assertNull(cache.get(0)); + assertNull(cache.get(1)); assertEquals(cache.get(2).s, "two"); assertEquals(cache.get(3).s, "three"); assertEquals(cache.evictLeastAccessedEntries(100), Pair.of(2, (long) 8)); assertEquals(cache.getNumberOfEntries(), 0); assertEquals(cache.getSize(), 0); - assertEquals(cache.get(0), null); - assertEquals(cache.get(1), null); - assertEquals(cache.get(2), null); - assertEquals(cache.get(3), null); + assertNull(cache.get(0)); + assertNull(cache.get(1)); + assertNull(cache.get(2)); + assertNull(cache.get(3)); try { cache.evictLeastAccessedEntries(0); diff --git a/pulsar-broker-auth-sasl/src/test/java/org/apache/pulsar/broker/authentication/SaslAuthenticateTest.java b/pulsar-broker-auth-sasl/src/test/java/org/apache/pulsar/broker/authentication/SaslAuthenticateTest.java index 1a734f9130948..fad255f28d5ee 100644 --- a/pulsar-broker-auth-sasl/src/test/java/org/apache/pulsar/broker/authentication/SaslAuthenticateTest.java +++ b/pulsar-broker-auth-sasl/src/test/java/org/apache/pulsar/broker/authentication/SaslAuthenticateTest.java @@ -19,6 +19,11 @@ package org.apache.pulsar.broker.authentication; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; +import static org.testng.Assert.fail; + import java.io.File; import java.io.FileWriter; import java.net.URI; @@ -49,7 +54,6 @@ import org.apache.pulsar.client.impl.auth.AuthenticationSasl; import org.apache.pulsar.common.api.AuthData; import org.apache.pulsar.common.sasl.SaslConstants; -import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; @@ -152,8 +156,8 @@ public static void stopMiniKdc() { } FileUtils.deleteQuietly(kdcDir); FileUtils.deleteQuietly(kerberosWorkDir); - Assert.assertFalse(kdcDir.exists()); - Assert.assertFalse(kerberosWorkDir.exists()); + assertFalse(kdcDir.exists()); + assertFalse(kerberosWorkDir.exists()); } @BeforeMethod @@ -257,19 +261,19 @@ public void testSaslServerAndClientAuth() throws Exception { AuthData initData1 = dataProvider.authenticate(AuthData.of(AuthData.INIT_AUTH_DATA)); AuthData serverData1 = authState.authenticate(initData1); boolean complete = authState.isComplete(); - Assert.assertEquals(complete, false); + assertFalse(complete); // second time auth, completed AuthData initData2 = dataProvider.authenticate(serverData1); AuthData serverData2 = authState.authenticate(initData2); complete = authState.isComplete(); - Assert.assertEquals(complete, true); - Assert.assertEquals(serverData2.getBytes(), null); + assertTrue(complete); + assertNull(serverData2.getBytes()); // if completed, server could not auth again. try { authState.authenticate(initData2); - Assert.fail("Expected fail because auth completed for authState"); + fail("Expected fail because auth completed for authState"); } catch (Exception e) { // expected } @@ -278,7 +282,7 @@ public void testSaslServerAndClientAuth() throws Exception { try { AuthenticationState authState2 = saslServer.newAuthState(null, null, null); AuthData serverData3 = authState2.authenticate(initData1); - Assert.fail("Expected fail. server is auth old client data"); + fail("Expected fail. server is auth old client data"); } catch (Exception e) { // expected } diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/PulsarBrokerStarterTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/PulsarBrokerStarterTest.java index 5ccea59f3301e..ba4b212571a91 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/PulsarBrokerStarterTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/PulsarBrokerStarterTest.java @@ -18,6 +18,9 @@ */ package org.apache.pulsar; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import com.google.common.collect.Sets; @@ -29,9 +32,7 @@ import java.io.PrintWriter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -import org.apache.bookkeeper.bookie.LedgerDirsManager; import org.apache.pulsar.broker.ServiceConfiguration; -import org.testng.Assert; import org.testng.annotations.Test; /** @@ -98,35 +99,34 @@ public void testLoadConfig() throws SecurityException, NoSuchMethodException, IO Object returnValue = targetMethod.invoke(PulsarBrokerStarter.class, testConfigFile.getAbsolutePath()); - Assert.assertTrue(ServiceConfiguration.class.isInstance(returnValue)); + assertTrue(returnValue instanceof ServiceConfiguration); ServiceConfiguration serviceConfig = (ServiceConfiguration) returnValue; - Assert.assertEquals(serviceConfig.getZookeeperServers(), "z1.example.com,z2.example.com,z3.example.com"); - Assert.assertEquals(serviceConfig.getConfigurationStoreServers(), - "gz1.example.com,gz2.example.com,gz3.example.com/foo"); - Assert.assertFalse(serviceConfig.isBrokerDeleteInactiveTopicsEnabled()); - Assert.assertEquals(serviceConfig.getStatusFilePath(), "/tmp/status.html"); - Assert.assertEquals(serviceConfig.getBacklogQuotaDefaultLimitGB(), 18); - Assert.assertEquals(serviceConfig.getClusterName(), "usc"); - Assert.assertEquals(serviceConfig.getBrokerClientAuthenticationPlugin(), "test.xyz.client.auth.plugin"); - Assert.assertEquals(serviceConfig.getBrokerClientAuthenticationParameters(), "role:my-role"); - Assert.assertEquals(serviceConfig.getSuperUserRoles(), Sets.newHashSet("appid1", "appid2")); - Assert.assertEquals(serviceConfig.getManagedLedgerCursorRolloverTimeInSeconds(), 3000); - Assert.assertEquals(serviceConfig.getManagedLedgerMaxEntriesPerLedger(), 25); - Assert.assertEquals(serviceConfig.getManagedLedgerCursorMaxEntriesPerLedger(), 50); - Assert.assertTrue(serviceConfig.isClientLibraryVersionCheckEnabled()); - Assert.assertEquals(serviceConfig.getManagedLedgerMinLedgerRolloverTimeMinutes(), 34); - Assert.assertEquals(serviceConfig.isBacklogQuotaCheckEnabled(), true); - Assert.assertEquals(serviceConfig.getManagedLedgerDefaultMarkDeleteRateLimit(), 5.0); - Assert.assertEquals(serviceConfig.getReplicationProducerQueueSize(), 50); - Assert.assertEquals(serviceConfig.isReplicationMetricsEnabled(), false); - Assert.assertEquals(serviceConfig.isBookkeeperClientHealthCheckEnabled(), true); - Assert.assertEquals(serviceConfig.getBookkeeperClientHealthCheckErrorThresholdPerInterval(), 5); - Assert.assertEquals(serviceConfig.isBookkeeperClientRackawarePolicyEnabled(), true); - Assert.assertEquals(serviceConfig.isBookkeeperClientRegionawarePolicyEnabled(), false); - Assert.assertEquals(serviceConfig.isBookkeeperClientReorderReadSequenceEnabled(), false); - Assert.assertEquals(serviceConfig.getBookkeeperClientIsolationGroups(), "group1,group2"); - Assert.assertEquals(serviceConfig.getBookkeeperClientSpeculativeReadTimeoutInMillis(), 3000); - Assert.assertEquals(serviceConfig.getBookkeeperClientTimeoutInSeconds(), 12345); + assertEquals(serviceConfig.getZookeeperServers(), "z1.example.com,z2.example.com,z3.example.com"); + assertEquals(serviceConfig.getConfigurationStoreServers(), "gz1.example.com,gz2.example.com,gz3.example.com/foo"); + assertFalse(serviceConfig.isBrokerDeleteInactiveTopicsEnabled()); + assertEquals(serviceConfig.getStatusFilePath(), "/tmp/status.html"); + assertEquals(serviceConfig.getBacklogQuotaDefaultLimitGB(), 18); + assertEquals(serviceConfig.getClusterName(), "usc"); + assertEquals(serviceConfig.getBrokerClientAuthenticationPlugin(), "test.xyz.client.auth.plugin"); + assertEquals(serviceConfig.getBrokerClientAuthenticationParameters(), "role:my-role"); + assertEquals(serviceConfig.getSuperUserRoles(), Sets.newHashSet("appid1", "appid2")); + assertEquals(serviceConfig.getManagedLedgerCursorRolloverTimeInSeconds(), 3000); + assertEquals(serviceConfig.getManagedLedgerMaxEntriesPerLedger(), 25); + assertEquals(serviceConfig.getManagedLedgerCursorMaxEntriesPerLedger(), 50); + assertTrue(serviceConfig.isClientLibraryVersionCheckEnabled()); + assertEquals(serviceConfig.getManagedLedgerMinLedgerRolloverTimeMinutes(), 34); + assertTrue(serviceConfig.isBacklogQuotaCheckEnabled()); + assertEquals(serviceConfig.getManagedLedgerDefaultMarkDeleteRateLimit(), 5.0); + assertEquals(serviceConfig.getReplicationProducerQueueSize(), 50); + assertFalse(serviceConfig.isReplicationMetricsEnabled()); + assertTrue(serviceConfig.isBookkeeperClientHealthCheckEnabled()); + assertEquals(serviceConfig.getBookkeeperClientHealthCheckErrorThresholdPerInterval(), 5); + assertTrue(serviceConfig.isBookkeeperClientRackawarePolicyEnabled()); + assertFalse(serviceConfig.isBookkeeperClientRegionawarePolicyEnabled()); + assertFalse(serviceConfig.isBookkeeperClientReorderReadSequenceEnabled()); + assertEquals(serviceConfig.getBookkeeperClientIsolationGroups(), "group1,group2"); + assertEquals(serviceConfig.getBookkeeperClientSpeculativeReadTimeoutInMillis(), 3000); + assertEquals(serviceConfig.getBookkeeperClientTimeoutInSeconds(), 12345); } @Test @@ -153,7 +153,7 @@ public void testLoadConfigWithException() throws Exception { fail("Should fail w/ illegal argument exception"); } catch (InvocationTargetException e) { // OK, expected - Assert.assertTrue(e.getTargetException() instanceof IllegalArgumentException); + assertTrue(e.getTargetException() instanceof IllegalArgumentException); } } @@ -194,16 +194,16 @@ public void testLoadBalancerConfig() throws SecurityException, NoSuchMethodExcep targetMethod.setAccessible(true); Object returnValue = targetMethod.invoke(PulsarBrokerStarter.class, testConfigFile.getAbsolutePath()); - Assert.assertTrue(ServiceConfiguration.class.isInstance(returnValue)); + assertTrue(returnValue instanceof ServiceConfiguration); ServiceConfiguration serviceConfig = (ServiceConfiguration) returnValue; - Assert.assertEquals(serviceConfig.isLoadBalancerEnabled(), false); - Assert.assertEquals(serviceConfig.getLoadBalancerHostUsageCheckIntervalMinutes(), 4); - Assert.assertEquals(serviceConfig.getLoadBalancerReportUpdateThresholdPercentage(), 15); - Assert.assertEquals(serviceConfig.getLoadBalancerReportUpdateMaxIntervalMinutes(), 20); - Assert.assertEquals(serviceConfig.getLoadBalancerBrokerOverloadedThresholdPercentage(), 80); - Assert.assertEquals(serviceConfig.getLoadBalancerBrokerUnderloadedThresholdPercentage(), 40); - Assert.assertEquals(serviceConfig.getLoadBalancerSheddingIntervalMinutes(), 8); - Assert.assertEquals(serviceConfig.getLoadBalancerSheddingGracePeriodMinutes(), 29); + assertFalse(serviceConfig.isLoadBalancerEnabled()); + assertEquals(serviceConfig.getLoadBalancerHostUsageCheckIntervalMinutes(), 4); + assertEquals(serviceConfig.getLoadBalancerReportUpdateThresholdPercentage(), 15); + assertEquals(serviceConfig.getLoadBalancerReportUpdateMaxIntervalMinutes(), 20); + assertEquals(serviceConfig.getLoadBalancerBrokerOverloadedThresholdPercentage(), 80); + assertEquals(serviceConfig.getLoadBalancerBrokerUnderloadedThresholdPercentage(), 40); + assertEquals(serviceConfig.getLoadBalancerSheddingIntervalMinutes(), 8); + assertEquals(serviceConfig.getLoadBalancerSheddingGracePeriodMinutes(), 29); } /** @@ -249,22 +249,22 @@ public void testGlobalZooKeeperConfig() throws SecurityException, NoSuchMethodEx Object returnValue = targetMethod.invoke(PulsarBrokerStarter.class, testConfigFile.getAbsolutePath()); - Assert.assertTrue(ServiceConfiguration.class.isInstance(returnValue)); + assertTrue(returnValue instanceof ServiceConfiguration); ServiceConfiguration serviceConfig = (ServiceConfiguration) returnValue; - Assert.assertEquals(serviceConfig.getZookeeperServers(), "z1.example.com,z2.example.com,z3.example.com"); - Assert.assertEquals(serviceConfig.getConfigurationStoreServers(), "z1.example.com,z2.example.com,z3.example.com"); - Assert.assertFalse(serviceConfig.isBrokerDeleteInactiveTopicsEnabled()); - Assert.assertEquals(serviceConfig.getStatusFilePath(), "/tmp/status.html"); - Assert.assertEquals(serviceConfig.getBacklogQuotaDefaultLimitGB(), 18); - Assert.assertEquals(serviceConfig.getClusterName(), "usc"); - Assert.assertEquals(serviceConfig.getBrokerClientAuthenticationPlugin(), "test.xyz.client.auth.plugin"); - Assert.assertEquals(serviceConfig.getBrokerClientAuthenticationParameters(), "role:my-role"); - Assert.assertEquals(serviceConfig.getSuperUserRoles(), Sets.newHashSet("appid1", "appid2")); - Assert.assertEquals(serviceConfig.getManagedLedgerCursorRolloverTimeInSeconds(), 3000); - Assert.assertEquals(serviceConfig.getManagedLedgerMaxEntriesPerLedger(), 25); - Assert.assertEquals(serviceConfig.getManagedLedgerCursorMaxEntriesPerLedger(), 50); - Assert.assertTrue(serviceConfig.isClientLibraryVersionCheckEnabled()); - Assert.assertEquals(serviceConfig.getReplicationConnectionsPerBroker(), 12); + assertEquals(serviceConfig.getZookeeperServers(), "z1.example.com,z2.example.com,z3.example.com"); + assertEquals(serviceConfig.getConfigurationStoreServers(), "z1.example.com,z2.example.com,z3.example.com"); + assertFalse(serviceConfig.isBrokerDeleteInactiveTopicsEnabled()); + assertEquals(serviceConfig.getStatusFilePath(), "/tmp/status.html"); + assertEquals(serviceConfig.getBacklogQuotaDefaultLimitGB(), 18); + assertEquals(serviceConfig.getClusterName(), "usc"); + assertEquals(serviceConfig.getBrokerClientAuthenticationPlugin(), "test.xyz.client.auth.plugin"); + assertEquals(serviceConfig.getBrokerClientAuthenticationParameters(), "role:my-role"); + assertEquals(serviceConfig.getSuperUserRoles(), Sets.newHashSet("appid1", "appid2")); + assertEquals(serviceConfig.getManagedLedgerCursorRolloverTimeInSeconds(), 3000); + assertEquals(serviceConfig.getManagedLedgerMaxEntriesPerLedger(), 25); + assertEquals(serviceConfig.getManagedLedgerCursorMaxEntriesPerLedger(), 50); + assertTrue(serviceConfig.isClientLibraryVersionCheckEnabled()); + assertEquals(serviceConfig.getReplicationConnectionsPerBroker(), 12); } /** @@ -274,7 +274,7 @@ public void testGlobalZooKeeperConfig() throws SecurityException, NoSuchMethodEx public void testMainWithNoArgument() throws Exception { try { PulsarBrokerStarter.main(new String[0]); - Assert.fail("No argument to main should've raised FileNotFoundException for no broker config!"); + fail("No argument to main should've raised FileNotFoundException for no broker config!"); } catch (FileNotFoundException e) { // code should reach here. } @@ -290,11 +290,11 @@ public void testMainRunBookieAndAutoRecoveryNoConfig() throws Exception { File testConfigFile = createValidBrokerConfigFile(); String[] args = {"-c", testConfigFile.getAbsolutePath(), "-rb", "-ra", "-bc", ""}; PulsarBrokerStarter.main(args); - Assert.fail("No Config file for bookie auto recovery should've raised IllegalArgumentException!"); + fail("No Config file for bookie auto recovery should've raised IllegalArgumentException!"); } catch (IllegalArgumentException e) { // code should reach here. e.printStackTrace(); - Assert.assertEquals(e.getMessage(), "No configuration file for Bookie"); + assertEquals(e.getMessage(), "No configuration file for Bookie"); } } @@ -308,10 +308,10 @@ public void testMainRunBookieRecoveryNoConfig() throws Exception { File testConfigFile = createValidBrokerConfigFile(); String[] args = {"-c", testConfigFile.getAbsolutePath(), "-ra", "-bc", ""}; PulsarBrokerStarter.main(args); - Assert.fail("No Config file for bookie auto recovery should've raised IllegalArgumentException!"); + fail("No Config file for bookie auto recovery should've raised IllegalArgumentException!"); } catch (IllegalArgumentException e) { // code should reach here. - Assert.assertEquals(e.getMessage(), "No configuration file for Bookie"); + assertEquals(e.getMessage(), "No configuration file for Bookie"); } } @@ -324,10 +324,10 @@ public void testMainRunBookieNoConfig() throws Exception { File testConfigFile = createValidBrokerConfigFile(); String[] args = {"-c", testConfigFile.getAbsolutePath(), "-rb", "-bc", ""}; PulsarBrokerStarter.main(args); - Assert.fail("No Config file for bookie should've raised IllegalArgumentException!"); + fail("No Config file for bookie should've raised IllegalArgumentException!"); } catch (IllegalArgumentException e) { // code should reach here - Assert.assertEquals(e.getMessage(), "No configuration file for Bookie"); + assertEquals(e.getMessage(), "No configuration file for Bookie"); } } @@ -340,7 +340,7 @@ public void testMainEnableRunBookieThroughBrokerConfig() throws Exception { File testConfigFile = createValidBrokerConfigFile(); String[] args = {"-c", testConfigFile.getAbsolutePath()}; PulsarBrokerStarter.main(args); - Assert.fail("No argument to main should've raised IllegalArgumentException for no bookie config!"); + fail("No argument to main should've raised IllegalArgumentException for no bookie config!"); } catch (IllegalArgumentException e) { // code should reach here. } diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApiGetLastMessageIdTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApiGetLastMessageIdTest.java index cc5cf0e91e150..c9e14fd6532c5 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApiGetLastMessageIdTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApiGetLastMessageIdTest.java @@ -23,7 +23,6 @@ import org.apache.pulsar.broker.auth.MockedPulsarServiceBaseTest; import org.apache.pulsar.broker.authentication.AuthenticationDataHttps; import org.apache.pulsar.broker.web.PulsarWebResource; -import org.apache.pulsar.client.api.Consumer; import org.apache.pulsar.client.api.MessageId; import org.apache.pulsar.client.api.MessageRoutingMode; import org.apache.pulsar.client.api.Producer; @@ -38,11 +37,6 @@ import javax.ws.rs.core.UriInfo; import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.concurrent.Future; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApiSchemaValidationEnforced.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApiSchemaValidationEnforced.java index cf197121181d2..970fa3f449e76 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApiSchemaValidationEnforced.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApiSchemaValidationEnforced.java @@ -18,6 +18,11 @@ */ package org.apache.pulsar.broker.admin; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertTrue; +import static org.testng.Assert.fail; + import com.google.common.collect.Sets; import lombok.extern.slf4j.Slf4j; import org.apache.pulsar.broker.auth.MockedPulsarServiceBaseTest; @@ -31,7 +36,6 @@ import org.apache.pulsar.common.schema.SchemaInfo; import org.apache.pulsar.common.schema.SchemaType; import org.slf4j.Logger; -import org.testng.Assert; import org.slf4j.LoggerFactory; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; @@ -66,12 +70,12 @@ public void testDisableSchemaValidationEnforcedNoSchema() throws Exception { admin.namespaces().createNamespace("schema-validation-enforced/default-no-schema"); String namespace = "schema-validation-enforced/default-no-schema"; String topicName = "persistent://schema-validation-enforced/default-no-schema/test"; - Assert.assertEquals(admin.namespaces().getSchemaValidationEnforced(namespace), false); + assertFalse(admin.namespaces().getSchemaValidationEnforced(namespace)); admin.namespaces().setSchemaValidationEnforced(namespace, false); try { admin.schemas().getSchemaInfo(topicName); } catch (PulsarAdminException.NotFoundException e) { - Assert.assertTrue(e.getMessage().contains("HTTP 404 Not Found")); + assertTrue(e.getMessage().contains("HTTP 404 Not Found")); } try (Producer p = pulsarClient.newProducer().topic(topicName).create()) { p.send("test schemaValidationEnforced".getBytes()); @@ -83,12 +87,12 @@ public void testDisableSchemaValidationEnforcedHasSchema() throws Exception { admin.namespaces().createNamespace("schema-validation-enforced/default-has-schema"); String namespace = "schema-validation-enforced/default-has-schema"; String topicName = "persistent://schema-validation-enforced/default-has-schema/test"; - Assert.assertEquals(admin.namespaces().getSchemaValidationEnforced(namespace), false); + assertFalse(admin.namespaces().getSchemaValidationEnforced(namespace)); admin.namespaces().setSchemaValidationEnforced(namespace, false); try { admin.schemas().getSchemaInfo(topicName); } catch (PulsarAdminException.NotFoundException e) { - Assert.assertTrue(e.getMessage().contains("HTTP 404 Not Found")); + assertTrue(e.getMessage().contains("HTTP 404 Not Found")); } Map properties = Maps.newHashMap(); SchemaInfo schemaInfo = new SchemaInfo(); @@ -101,7 +105,7 @@ public void testDisableSchemaValidationEnforcedHasSchema() throws Exception { try (Producer p = pulsarClient.newProducer().topic(topicName).create()) { p.send("test schemaValidationEnforced".getBytes()); } - Assert.assertEquals(admin.schemas().getSchemaInfo(topicName), schemaInfo); + assertEquals(admin.schemas().getSchemaInfo(topicName), schemaInfo); } @@ -110,12 +114,12 @@ public void testEnableSchemaValidationEnforcedNoSchema() throws Exception { admin.namespaces().createNamespace("schema-validation-enforced/enable-no-schema"); String namespace = "schema-validation-enforced/enable-no-schema"; String topicName = "persistent://schema-validation-enforced/enable-no-schema/test"; - Assert.assertEquals(admin.namespaces().getSchemaValidationEnforced(namespace), false); + assertFalse(admin.namespaces().getSchemaValidationEnforced(namespace)); admin.namespaces().setSchemaValidationEnforced(namespace,true); try { admin.schemas().getSchemaInfo(topicName); } catch (PulsarAdminException.NotFoundException e) { - Assert.assertTrue(e.getMessage().contains("HTTP 404 Not Found")); + assertTrue(e.getMessage().contains("HTTP 404 Not Found")); } try (Producer p = pulsarClient.newProducer().topic(topicName).create()) { p.send("test schemaValidationEnforced".getBytes()); @@ -127,15 +131,15 @@ public void testEnableSchemaValidationEnforcedHasSchemaMismatch() throws Excepti admin.namespaces().createNamespace("schema-validation-enforced/enable-has-schema-mismatch"); String namespace = "schema-validation-enforced/enable-has-schema-mismatch"; String topicName = "persistent://schema-validation-enforced/enable-has-schema-mismatch/test"; - Assert.assertEquals(admin.namespaces().getSchemaValidationEnforced(namespace), false); + assertFalse(admin.namespaces().getSchemaValidationEnforced(namespace)); admin.namespaces().setSchemaValidationEnforced(namespace,true); - Assert.assertEquals(admin.namespaces().getSchemaValidationEnforced(namespace), true); + assertTrue(admin.namespaces().getSchemaValidationEnforced(namespace)); admin.topics().createNonPartitionedTopic(topicName); admin.topics().getStats(topicName); try { admin.schemas().getSchemaInfo(topicName); } catch (PulsarAdminException.NotFoundException e) { - Assert.assertTrue(e.getMessage().contains("HTTP 404 Not Found")); + assertTrue(e.getMessage().contains("HTTP 404 Not Found")); } Map properties = Maps.newHashMap(); properties.put("key1", "value1"); @@ -147,12 +151,12 @@ public void testEnableSchemaValidationEnforcedHasSchemaMismatch() throws Excepti PostSchemaPayload postSchemaPayload = new PostSchemaPayload("STRING", "{'key':'value'}", properties); admin.schemas().createSchema(topicName, postSchemaPayload); try (Producer p = pulsarClient.newProducer().topic(topicName).create()) { - Assert.fail("Client no schema, but topic has schema, should fail"); + fail("Client no schema, but topic has schema, should fail"); } catch (PulsarClientException e) { - Assert.assertTrue(e.getMessage().contains("IncompatibleSchemaException")); + assertTrue(e.getMessage().contains("IncompatibleSchemaException")); } - Assert.assertEquals(admin.schemas().getSchemaInfo(topicName).getName(), schemaInfo.getName()); - Assert.assertEquals(admin.schemas().getSchemaInfo(topicName).getType(), schemaInfo.getType()); + assertEquals(admin.schemas().getSchemaInfo(topicName).getName(), schemaInfo.getName()); + assertEquals(admin.schemas().getSchemaInfo(topicName).getType(), schemaInfo.getType()); } @Test @@ -160,11 +164,11 @@ public void testEnableSchemaValidationEnforcedHasSchemaMatch() throws Exception admin.namespaces().createNamespace("schema-validation-enforced/enable-has-schema-match"); String namespace = "schema-validation-enforced/enable-has-schema-match"; String topicName = "persistent://schema-validation-enforced/enable-has-schema-match/test"; - Assert.assertEquals(admin.namespaces().getSchemaValidationEnforced(namespace), false); + assertFalse(admin.namespaces().getSchemaValidationEnforced(namespace)); try { admin.schemas().getSchemaInfo(topicName); } catch (PulsarAdminException.NotFoundException e) { - Assert.assertTrue(e.getMessage().contains("HTTP 404 Not Found")); + assertTrue(e.getMessage().contains("HTTP 404 Not Found")); } admin.namespaces().setSchemaValidationEnforced(namespace,true); Map properties = Maps.newHashMap(); @@ -178,8 +182,8 @@ public void testEnableSchemaValidationEnforcedHasSchemaMatch() throws Exception try (Producer p = pulsarClient.newProducer(Schema.STRING).topic(topicName).create()) { p.send("test schemaValidationEnforced"); } - Assert.assertEquals(admin.schemas().getSchemaInfo(topicName).getName(), schemaInfo.getName()); - Assert.assertEquals(admin.schemas().getSchemaInfo(topicName).getType(), schemaInfo.getType()); + assertEquals(admin.schemas().getSchemaInfo(topicName).getName(), schemaInfo.getName()); + assertEquals(admin.schemas().getSchemaInfo(topicName).getType(), schemaInfo.getType()); } } diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApiTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApiTest.java index 47f3ce6314dca..4e03bc52f34ae 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApiTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApiTest.java @@ -26,6 +26,7 @@ import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotEquals; import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; @@ -1440,7 +1441,7 @@ public void testJacksonWithTypeDifferencies() throws Exception { .readValue(expectedJson); assertEquals(r1.allowedClusters, Sets.newHashSet("test", "usw")); assertEquals(r1.someNewIntField, 0); - assertEquals(r1.someNewString, null); + assertNull(r1.someNewString); } @Test @@ -1458,7 +1459,7 @@ public void testBackwardCompatiblity() throws Exception { assertEquals(result.allowedClusters, Sets.newHashSet("test")); assertEquals(result.someNewIntField, 0); - assertEquals(result.someNewString, null); + assertNull(result.someNewString); admin.namespaces().deleteNamespace("prop-xyz/ns1"); admin.tenants().deleteTenant("prop-xyz"); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApiTest2.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApiTest2.java index 5c39eec38390e..babf86f72e092 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApiTest2.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApiTest2.java @@ -22,6 +22,7 @@ import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; @@ -68,7 +69,6 @@ import org.apache.pulsar.common.policies.data.ConsumerStats; import org.apache.pulsar.common.policies.data.FailureDomain; import org.apache.pulsar.common.policies.data.NamespaceIsolationData; -import org.apache.pulsar.common.policies.data.NonPersistentTopicStats; import org.apache.pulsar.common.policies.data.PartitionedTopicStats; import org.apache.pulsar.common.policies.data.PersistencePolicies; import org.apache.pulsar.common.policies.data.PersistentTopicInternalStats; @@ -134,7 +134,6 @@ public Object[][] namespaceNameProvider() { * * * - * @param topicName * @throws Exception */ @Test @@ -568,14 +567,14 @@ public void testPeerCluster() throws Exception { admin.clusters().updatePeerClusterNames("us-west1", Sets.newLinkedHashSet(Lists.newArrayList("us-west2"))); assertEquals(admin.clusters().getCluster("us-west1").getPeerClusterNames(), Lists.newArrayList("us-west2")); - assertEquals(admin.clusters().getCluster("us-west2").getPeerClusterNames(), null); + assertNull(admin.clusters().getCluster("us-west2").getPeerClusterNames()); // update cluster with duplicate peer-clusters in the list admin.clusters().updatePeerClusterNames("us-west1", Sets.newLinkedHashSet( Lists.newArrayList("us-west2", "us-east1", "us-west2", "us-east1", "us-west2", "us-east1"))); assertEquals(admin.clusters().getCluster("us-west1").getPeerClusterNames(), Lists.newArrayList("us-west2", "us-east1")); admin.clusters().updatePeerClusterNames("us-west1", null); - assertEquals(admin.clusters().getCluster("us-west1").getPeerClusterNames(), null); + assertNull(admin.clusters().getCluster("us-west1").getPeerClusterNames()); // Check name validation try { @@ -832,7 +831,7 @@ public void testTenantNameWithInvalidCharacters() throws Exception { @Test public void testTenantWithNonexistentClusters() throws Exception { // Check non-existing cluster - assertTrue(!admin.clusters().getClusters().contains("cluster-non-existing")); + assertFalse(admin.clusters().getClusters().contains("cluster-non-existing")); Set allowedClusters = Sets.newHashSet("cluster-non-existing"); TenantInfo tenantInfo = new TenantInfo(Sets.newHashSet("role1", "role2"), allowedClusters); @@ -845,7 +844,7 @@ public void testTenantWithNonexistentClusters() throws Exception { assertEquals(e.getStatusCode(), Status.PRECONDITION_FAILED.getStatusCode()); } - assertTrue(!admin.tenants().getTenants().contains("test-tenant")); + assertFalse(admin.tenants().getTenants().contains("test-tenant")); // Check existing tenant assertTrue(admin.tenants().getTenants().contains("prop-xyz")); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminTest.java index 77e1f2fe3014f..41bd8770d6500 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminTest.java @@ -28,6 +28,7 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNotSame; import static org.testng.Assert.assertTrue; @@ -43,7 +44,6 @@ import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; -import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CountDownLatch; @@ -547,8 +547,8 @@ void resourceQuotas() throws Exception { quota.setBandwidthIn(defaultBandwidth); quota.setBandwidthOut(defaultBandwidth); resourceQuotas.setDefaultResourceQuota(quota); - assertTrue(resourceQuotas.getDefaultResourceQuota().getBandwidthIn() == defaultBandwidth); - assertTrue(resourceQuotas.getDefaultResourceQuota().getBandwidthOut() == defaultBandwidth); + assertEquals(defaultBandwidth, resourceQuotas.getDefaultResourceQuota().getBandwidthIn()); + assertEquals(defaultBandwidth, resourceQuotas.getDefaultResourceQuota().getBandwidthOut()); String property = "prop-xyz"; String cluster = "use"; @@ -593,8 +593,8 @@ void resourceQuotas() throws Exception { // remove quota which sets to default quota resourceQuotas.removeNamespaceBundleResourceQuota(property, cluster, namespace, bundleRange); bundleQuota = resourceQuotas.getNamespaceBundleResourceQuota(property, cluster, namespace, bundleRange); - assertTrue(bundleQuota.getBandwidthIn() == defaultBandwidth); - assertTrue(bundleQuota.getBandwidthOut() == defaultBandwidth); + assertEquals(defaultBandwidth, bundleQuota.getBandwidthIn()); + assertEquals(defaultBandwidth, bundleQuota.getBandwidthOut()); } @Test @@ -606,7 +606,7 @@ void brokerStats() throws Exception { assertNotNull(loadReport); assertNotNull(loadReport.getCpu()); Collection mBeans = brokerStats.getMBeans(); - assertTrue(!mBeans.isEmpty()); + assertFalse(mBeans.isEmpty()); AllocatorStats allocatorStats = brokerStats.getAllocatorStats("default"); assertNotNull(allocatorStats); Map> bookieOpsStats = brokerStats.getPendingBookieOpsStats(); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/NamespacesTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/NamespacesTest.java index a12ef501e1ccf..0b22d2c84e9e2 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/NamespacesTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/NamespacesTest.java @@ -786,10 +786,10 @@ public void testSplitBundles() throws Exception { // verify split bundles BundlesData bundlesData = namespaces.getBundlesData(testTenant, testLocalCluster, bundledNsLocal); assertNotNull(bundlesData); - assertTrue(bundlesData.boundaries.size() == 3); - assertTrue(bundlesData.boundaries.get(0).equals("0x00000000")); - assertTrue(bundlesData.boundaries.get(1).equals("0x7fffffff")); - assertTrue(bundlesData.boundaries.get(2).equals("0xffffffff")); + assertEquals(bundlesData.boundaries.size(), 3); + assertEquals(bundlesData.boundaries.get(0), "0x00000000"); + assertEquals(bundlesData.boundaries.get(1), "0x7fffffff"); + assertEquals(bundlesData.boundaries.get(2), "0xffffffff"); } catch (RestException re) { assertEquals(re.getResponse().getStatus(), Status.PRECONDITION_FAILED.getStatusCode()); } diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/v1/V1_AdminApiTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/v1/V1_AdminApiTest.java index 3d32716664386..b98cbc6db3e41 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/v1/V1_AdminApiTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/v1/V1_AdminApiTest.java @@ -26,6 +26,7 @@ import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotEquals; import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; @@ -1416,7 +1417,7 @@ public void testJacksonWithTypeDifferencies() throws Exception { .readValue(expectedJson); assertEquals(r1.allowedClusters, Sets.newHashSet("use", "usw")); assertEquals(r1.someNewIntField, 0); - assertEquals(r1.someNewString, null); + assertNull(r1.someNewString); } @Test @@ -1434,7 +1435,7 @@ public void testBackwardCompatiblity() throws Exception { assertEquals(result.allowedClusters, Sets.newHashSet("use")); assertEquals(result.someNewIntField, 0); - assertEquals(result.someNewString, null); + assertNull(result.someNewString); admin.namespaces().deleteNamespace("prop-xyz/use/ns1"); admin.tenants().deleteTenant("prop-xyz"); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/v1/V1_AdminApiTest2.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/v1/V1_AdminApiTest2.java index 176c851c9762f..76244dfd5dff9 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/v1/V1_AdminApiTest2.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/v1/V1_AdminApiTest2.java @@ -22,6 +22,7 @@ import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; @@ -562,14 +563,14 @@ public void testPeerCluster() throws Exception { admin.clusters().updatePeerClusterNames("us-west1", Sets.newLinkedHashSet(Lists.newArrayList("us-west2"))); assertEquals(admin.clusters().getCluster("us-west1").getPeerClusterNames(), Lists.newArrayList("us-west2")); - assertEquals(admin.clusters().getCluster("us-west2").getPeerClusterNames(), null); + assertNull(admin.clusters().getCluster("us-west2").getPeerClusterNames()); // update cluster with duplicate peer-clusters in the list admin.clusters().updatePeerClusterNames("us-west1", Sets.newLinkedHashSet( Lists.newArrayList("us-west2", "us-east1", "us-west2", "us-east1", "us-west2", "us-east1"))); assertEquals(admin.clusters().getCluster("us-west1").getPeerClusterNames(), Lists.newArrayList("us-west2", "us-east1")); admin.clusters().updatePeerClusterNames("us-west1", null); - assertEquals(admin.clusters().getCluster("us-west1").getPeerClusterNames(), null); + assertNull(admin.clusters().getCluster("us-west1").getPeerClusterNames()); // Check name validation try { diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/auth/AuthorizationTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/auth/AuthorizationTest.java index b6b7f246f7250..1ab5cc9891e39 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/auth/AuthorizationTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/auth/AuthorizationTest.java @@ -18,7 +18,8 @@ */ package org.apache.pulsar.broker.auth; -import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import java.util.EnumSet; @@ -33,7 +34,6 @@ import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; -import com.google.common.collect.Lists; import com.google.common.collect.Sets; @Test @@ -63,7 +63,7 @@ protected void cleanup() throws Exception { void simple() throws Exception { AuthorizationService auth = pulsar.getBrokerService().getAuthorizationService(); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "my-role", null), false); + assertFalse(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "my-role", null)); admin.clusters().createCluster("c1", new ClusterData()); admin.tenants().createTenant("p1", new TenantInfo(Sets.newHashSet("role1"), Sets.newHashSet("c1"))); @@ -71,69 +71,69 @@ void simple() throws Exception { admin.namespaces().createNamespace("p1/c1/ns1"); waitForChange(); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "my-role", null), false); + assertFalse(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "my-role", null)); admin.namespaces().grantPermissionOnNamespace("p1/c1/ns1", "my-role", EnumSet.of(AuthAction.produce)); waitForChange(); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "my-role", null), true); - assertEquals(auth.canProduce(TopicName.get("persistent://p1/c1/ns1/ds1"), "my-role", null), true); + assertTrue(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "my-role", null)); + assertTrue(auth.canProduce(TopicName.get("persistent://p1/c1/ns1/ds1"), "my-role", null)); admin.topics().grantPermission("persistent://p1/c1/ns1/ds2", "other-role", EnumSet.of(AuthAction.consume)); waitForChange(); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds2"), "other-role", null), true); - assertEquals(auth.canProduce(TopicName.get("persistent://p1/c1/ns1/ds1"), "my-role", null), true); - assertEquals(auth.canProduce(TopicName.get("persistent://p1/c1/ns1/ds2"), "other-role", null), false); - assertEquals(auth.canConsume(TopicName.get("persistent://p1/c1/ns1/ds2"), "other-role", null, null), true); - assertEquals(auth.canConsume(TopicName.get("persistent://p1/c1/ns1/ds2"), "no-access-role", null, null), false); + assertTrue(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds2"), "other-role", null)); + assertTrue(auth.canProduce(TopicName.get("persistent://p1/c1/ns1/ds1"), "my-role", null)); + assertFalse(auth.canProduce(TopicName.get("persistent://p1/c1/ns1/ds2"), "other-role", null)); + assertTrue(auth.canConsume(TopicName.get("persistent://p1/c1/ns1/ds2"), "other-role", null, null)); + assertFalse(auth.canConsume(TopicName.get("persistent://p1/c1/ns1/ds2"), "no-access-role", null, null)); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "no-access-role", null), false); + assertFalse(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "no-access-role", null)); admin.namespaces().grantPermissionOnNamespace("p1/c1/ns1", "my-role", EnumSet.allOf(AuthAction.class)); waitForChange(); - assertEquals(auth.canProduce(TopicName.get("persistent://p1/c1/ns1/ds1"), "my-role", null), true); - assertEquals(auth.canConsume(TopicName.get("persistent://p1/c1/ns1/ds1"), "my-role", null, null), true); + assertTrue(auth.canProduce(TopicName.get("persistent://p1/c1/ns1/ds1"), "my-role", null)); + assertTrue(auth.canConsume(TopicName.get("persistent://p1/c1/ns1/ds1"), "my-role", null, null)); // test for wildcard // namespace prefix match - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "my.role.1", null), false); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "my.role.2", null), false); - assertEquals(auth.canProduce(TopicName.get("persistent://p1/c1/ns1/ds1"), "my.role.1", null), false); - assertEquals(auth.canConsume(TopicName.get("persistent://p1/c1/ns1/ds1"), "my.role.1", null, null), false); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "other.role.1", null), false); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "other.role.2", null), false); + assertFalse(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "my.role.1", null)); + assertFalse(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "my.role.2", null)); + assertFalse(auth.canProduce(TopicName.get("persistent://p1/c1/ns1/ds1"), "my.role.1", null)); + assertFalse(auth.canConsume(TopicName.get("persistent://p1/c1/ns1/ds1"), "my.role.1", null, null)); + assertFalse(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "other.role.1", null)); + assertFalse(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "other.role.2", null)); admin.namespaces().grantPermissionOnNamespace("p1/c1/ns1", "my.role.*", EnumSet.of(AuthAction.produce)); waitForChange(); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "my.role.1", null), true); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "my.role.2", null), true); - assertEquals(auth.canProduce(TopicName.get("persistent://p1/c1/ns1/ds1"), "my.role.1", null), true); - assertEquals(auth.canConsume(TopicName.get("persistent://p1/c1/ns1/ds1"), "my.role.1", null, null), false); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "other.role.1", null), false); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "other.role.2", null), false); + assertTrue(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "my.role.1", null)); + assertTrue(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "my.role.2", null)); + assertTrue(auth.canProduce(TopicName.get("persistent://p1/c1/ns1/ds1"), "my.role.1", null)); + assertFalse(auth.canConsume(TopicName.get("persistent://p1/c1/ns1/ds1"), "my.role.1", null, null)); + assertFalse(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "other.role.1", null)); + assertFalse(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "other.role.2", null)); // namespace suffix match - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "1.role.my", null), false); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "2.role.my", null), false); - assertEquals(auth.canProduce(TopicName.get("persistent://p1/c1/ns1/ds1"), "1.role.my", null), false); - assertEquals(auth.canConsume(TopicName.get("persistent://p1/c1/ns1/ds1"), "1.role.my", null, null), false); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "2.role.other", null), false); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "2.role.other", null), false); + assertFalse(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "1.role.my", null)); + assertFalse(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "2.role.my", null)); + assertFalse(auth.canProduce(TopicName.get("persistent://p1/c1/ns1/ds1"), "1.role.my", null)); + assertFalse(auth.canConsume(TopicName.get("persistent://p1/c1/ns1/ds1"), "1.role.my", null, null)); + assertFalse(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "2.role.other", null)); + assertFalse(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "2.role.other", null)); admin.namespaces().grantPermissionOnNamespace("p1/c1/ns1", "*.role.my", EnumSet.of(AuthAction.consume)); waitForChange(); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "1.role.my", null), true); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "2.role.my", null), true); - assertEquals(auth.canProduce(TopicName.get("persistent://p1/c1/ns1/ds1"), "1.role.my", null), false); - assertEquals(auth.canConsume(TopicName.get("persistent://p1/c1/ns1/ds1"), "1.role.my", null, null), true); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "2.role.other", null), false); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "2.role.other", null), false); + assertTrue(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "1.role.my", null)); + assertTrue(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "2.role.my", null)); + assertFalse(auth.canProduce(TopicName.get("persistent://p1/c1/ns1/ds1"), "1.role.my", null)); + assertTrue(auth.canConsume(TopicName.get("persistent://p1/c1/ns1/ds1"), "1.role.my", null, null)); + assertFalse(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "2.role.other", null)); + assertFalse(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "2.role.other", null)); // revoke for next test admin.namespaces().revokePermissionsOnNamespace("p1/c1/ns1", "my.role.*"); @@ -141,50 +141,50 @@ void simple() throws Exception { waitForChange(); // topic prefix match - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "my.role.1", null), false); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "my.role.2", null), false); - assertEquals(auth.canProduce(TopicName.get("persistent://p1/c1/ns1/ds1"), "my.role.1", null), false); - assertEquals(auth.canConsume(TopicName.get("persistent://p1/c1/ns1/ds1"), "my.role.1", null, null), false); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "other.role.1", null), false); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "other.role.2", null), false); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds2"), "my.role.1", null), false); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds2"), "my.role.2", null), false); + assertFalse(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "my.role.1", null)); + assertFalse(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "my.role.2", null)); + assertFalse(auth.canProduce(TopicName.get("persistent://p1/c1/ns1/ds1"), "my.role.1", null)); + assertFalse(auth.canConsume(TopicName.get("persistent://p1/c1/ns1/ds1"), "my.role.1", null, null)); + assertFalse(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "other.role.1", null)); + assertFalse(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "other.role.2", null)); + assertFalse(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds2"), "my.role.1", null)); + assertFalse(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds2"), "my.role.2", null)); admin.topics().grantPermission("persistent://p1/c1/ns1/ds1", "my.*", EnumSet.of(AuthAction.produce)); waitForChange(); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "my.role.1", null), true); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "my.role.2", null), true); - assertEquals(auth.canProduce(TopicName.get("persistent://p1/c1/ns1/ds1"), "my.role.1", null), true); - assertEquals(auth.canConsume(TopicName.get("persistent://p1/c1/ns1/ds1"), "my.role.1", null, null), false); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "other.role.1", null), false); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "other.role.2", null), false); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds2"), "my.role.1", null), false); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds2"), "my.role.2", null), false); + assertTrue(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "my.role.1", null)); + assertTrue(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "my.role.2", null)); + assertTrue(auth.canProduce(TopicName.get("persistent://p1/c1/ns1/ds1"), "my.role.1", null)); + assertFalse(auth.canConsume(TopicName.get("persistent://p1/c1/ns1/ds1"), "my.role.1", null, null)); + assertFalse(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "other.role.1", null)); + assertFalse(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "other.role.2", null)); + assertFalse(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds2"), "my.role.1", null)); + assertFalse(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds2"), "my.role.2", null)); // topic suffix match - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "1.role.my", null), false); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "2.role.my", null), false); - assertEquals(auth.canProduce(TopicName.get("persistent://p1/c1/ns1/ds1"), "1.role.my", null), false); - assertEquals(auth.canConsume(TopicName.get("persistent://p1/c1/ns1/ds1"), "1.role.my", null, null), false); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "2.role.other", null), false); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "2.role.other", null), false); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds2"), "1.role.my", null), false); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds2"), "2.role.my", null), false); + assertFalse(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "1.role.my", null)); + assertFalse(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "2.role.my", null)); + assertFalse(auth.canProduce(TopicName.get("persistent://p1/c1/ns1/ds1"), "1.role.my", null)); + assertFalse(auth.canConsume(TopicName.get("persistent://p1/c1/ns1/ds1"), "1.role.my", null, null)); + assertFalse(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "2.role.other", null)); + assertFalse(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "2.role.other", null)); + assertFalse(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds2"), "1.role.my", null)); + assertFalse(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds2"), "2.role.my", null)); admin.topics().grantPermission("persistent://p1/c1/ns1/ds1", "*.my", EnumSet.of(AuthAction.consume)); waitForChange(); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "1.role.my", null), true); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "2.role.my", null), true); - assertEquals(auth.canProduce(TopicName.get("persistent://p1/c1/ns1/ds1"), "1.role.my", null), false); - assertEquals(auth.canConsume(TopicName.get("persistent://p1/c1/ns1/ds1"), "1.role.my", null, null), true); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "2.role.other", null), false); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "2.role.other", null), false); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds2"), "1.role.my", null), false); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds2"), "2.role.my", null), false); + assertTrue(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "1.role.my", null)); + assertTrue(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "2.role.my", null)); + assertFalse(auth.canProduce(TopicName.get("persistent://p1/c1/ns1/ds1"), "1.role.my", null)); + assertTrue(auth.canConsume(TopicName.get("persistent://p1/c1/ns1/ds1"), "1.role.my", null, null)); + assertFalse(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "2.role.other", null)); + assertFalse(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "2.role.other", null)); + assertFalse(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds2"), "1.role.my", null)); + assertFalse(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds2"), "2.role.my", null)); admin.topics().revokePermissions("persistent://p1/c1/ns1/ds1", "my.*"); admin.topics().revokePermissions("persistent://p1/c1/ns1/ds1", "*.my"); @@ -194,20 +194,20 @@ void simple() throws Exception { admin.namespaces().setSubscriptionAuthMode("p1/c1/ns1", SubscriptionAuthMode.Prefix); waitForChange(); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "role1", null), true); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "role2", null), true); + assertTrue(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "role1", null)); + assertTrue(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "role2", null)); try { - assertEquals(auth.canConsume(TopicName.get("persistent://p1/c1/ns1/ds1"), "role1", null, "sub1"), false); + assertFalse(auth.canConsume(TopicName.get("persistent://p1/c1/ns1/ds1"), "role1", null, "sub1")); fail(); } catch (Exception e) {} try { - assertEquals(auth.canConsume(TopicName.get("persistent://p1/c1/ns1/ds1"), "role2", null, "sub2"), false); + assertFalse(auth.canConsume(TopicName.get("persistent://p1/c1/ns1/ds1"), "role2", null, "sub2")); fail(); } catch (Exception e) {} - assertEquals(auth.canConsume(TopicName.get("persistent://p1/c1/ns1/ds1"), "role1", null, "role1-sub1"), true); - assertEquals(auth.canConsume(TopicName.get("persistent://p1/c1/ns1/ds1"), "role2", null, "role2-sub2"), true); - assertEquals(auth.canConsume(TopicName.get("persistent://p1/c1/ns1/ds1"), "pulsar.super_user", null, "role3-sub1"), true); + assertTrue(auth.canConsume(TopicName.get("persistent://p1/c1/ns1/ds1"), "role1", null, "role1-sub1")); + assertTrue(auth.canConsume(TopicName.get("persistent://p1/c1/ns1/ds1"), "role2", null, "role2-sub2")); + assertTrue(auth.canConsume(TopicName.get("persistent://p1/c1/ns1/ds1"), "pulsar.super_user", null, "role3-sub1")); admin.namespaces().deleteNamespace("p1/c1/ns1"); admin.tenants().deleteTenant("p1"); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/delayed/InMemoryDeliveryTrackerTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/delayed/InMemoryDeliveryTrackerTest.java index 6f2cdf05c2ca4..b6f958d7da233 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/delayed/InMemoryDeliveryTrackerTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/delayed/InMemoryDeliveryTrackerTest.java @@ -18,7 +18,12 @@ */ package org.apache.pulsar.broker.delayed; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyLong; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; @@ -56,7 +61,7 @@ public void test() throws Exception { @Cleanup InMemoryDelayedDeliveryTracker tracker = new InMemoryDelayedDeliveryTracker(dispatcher, timer, 1, clock); - assertEquals(tracker.hasMessageAvailable(), false); + assertFalse(tracker.hasMessageAvailable()); assertTrue(tracker.addMessage(2, 2, 20)); assertTrue(tracker.addMessage(1, 1, 10)); @@ -64,7 +69,7 @@ public void test() throws Exception { assertTrue(tracker.addMessage(5, 5, 50)); assertTrue(tracker.addMessage(4, 4, 40)); - assertEquals(tracker.hasMessageAvailable(), false); + assertFalse(tracker.hasMessageAvailable()); assertEquals(tracker.getNumberOfDelayedMessages(), 5); assertEquals(tracker.getScheduledMessages(10), Collections.emptySet()); @@ -76,7 +81,7 @@ public void test() throws Exception { assertFalse(tracker.addMessage(6, 6, 10)); assertEquals(tracker.getNumberOfDelayedMessages(), 5); - assertEquals(tracker.hasMessageAvailable(), true); + assertTrue(tracker.hasMessageAvailable()); Set scheduled = tracker.getScheduledMessages(10); assertEquals(scheduled.size(), 1); @@ -84,17 +89,17 @@ public void test() throws Exception { clockTime.set(60); assertEquals(tracker.getNumberOfDelayedMessages(), 4); - assertEquals(tracker.hasMessageAvailable(), true); + assertTrue(tracker.hasMessageAvailable()); scheduled = tracker.getScheduledMessages(1); assertEquals(scheduled.size(), 1); assertEquals(tracker.getNumberOfDelayedMessages(), 3); - assertEquals(tracker.hasMessageAvailable(), true); + assertTrue(tracker.hasMessageAvailable()); scheduled = tracker.getScheduledMessages(3); assertEquals(scheduled.size(), 3); assertEquals(tracker.getNumberOfDelayedMessages(), 0); - assertEquals(tracker.hasMessageAvailable(), false); + assertFalse(tracker.hasMessageAvailable()); assertEquals(tracker.getScheduledMessages(10), Collections.emptySet()); } diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/AntiAffinityNamespaceGroupTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/AntiAffinityNamespaceGroupTest.java index cb9f98f56a457..2c335388c8d04 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/AntiAffinityNamespaceGroupTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/AntiAffinityNamespaceGroupTest.java @@ -41,7 +41,6 @@ import org.apache.pulsar.broker.loadbalance.impl.ModularLoadManagerImpl; import org.apache.pulsar.broker.loadbalance.impl.ModularLoadManagerWrapper; import org.apache.pulsar.client.admin.PulsarAdmin; -import org.apache.pulsar.client.api.Authentication; import org.apache.pulsar.client.api.Producer; import org.apache.pulsar.client.api.PulsarClient; import org.apache.pulsar.common.naming.NamespaceBundle; @@ -65,7 +64,6 @@ import com.beust.jcommander.internal.Maps; import com.google.common.collect.BoundType; -import com.google.common.collect.Lists; import com.google.common.collect.Range; import com.google.common.collect.Sets; import com.google.common.hash.Hashing; diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/LoadBalancerTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/LoadBalancerTest.java index 3c15a8d311114..a7102a06a419b 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/LoadBalancerTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/LoadBalancerTest.java @@ -30,6 +30,8 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; @@ -176,7 +178,7 @@ private LeaderBroker loopUntilLeaderChanges(LeaderElectionService les, LeaderBro int loopCount = 0; while (loopCount < MAX_RETRIES) { - Thread.sleep(1000 * 1); + Thread.sleep(1000); // Check if the new leader is elected. If yes, break without incrementing the loopCount newLeader = les.getCurrentLeader(); if (newLeader.equals(oldLeader) == false) { @@ -227,7 +229,7 @@ public void testLoadReportsWrittenOnZK() throws Exception { TopicName topicName = TopicName.get("persistent://pulsar/use/primary-ns/test-topic"); ResourceUnit found = pulsarServices[i].getLoadManager().get() .getLeastLoaded(pulsarServices[i].getNamespaceService().getBundle(topicName)).get(); - assertTrue(found != null); + assertNotNull(found); } } catch (InterruptedException | KeeperException e) { fail("Unable to read the data from Zookeeper - [{}]", e); @@ -812,7 +814,7 @@ public void testGetLeastLoadedBasic() throws Exception { LocalZooKeeperCache originalLZK2 = (LocalZooKeeperCache) zkCacheField.get(pulsarServices[1]); zkCacheField.set(pulsarServices[0], mockCache); zkCacheField.set(pulsarServices[1], mockCache); - LoadManager loadManager = new SimpleLoadManagerImpl(pulsarServices[0]); + SimpleLoadManagerImpl loadManager = new SimpleLoadManagerImpl(pulsarServices[0]); // TODO move to its own test PulsarResourceDescription rd = new PulsarResourceDescription(); @@ -832,8 +834,7 @@ public void testGetLeastLoadedBasic() throws Exception { sortedRankings.setAccessible(true); sortedRankings.set(loadManager, sortedRankingsInstance); - ResourceUnit found = ((SimpleLoadManagerImpl) loadManager) - .getLeastLoaded(NamespaceName.get("pulsar/use/primary-ns.10")).get(); + ResourceUnit found = loadManager.getLeastLoaded(NamespaceName.get("pulsar/use/primary-ns.10")).get(); assertEquals("http://prod1-broker1.messaging.use.example.com:8080", found.getResourceId()); zkCacheField.set(pulsarServices[0], originalLZK1); @@ -962,8 +963,8 @@ void testLoadBalanceDiscardingInactiveBrokersInSelection() throws Exception { } String inactiveBroker = "prod1-broker3.messaging.use.example.com:8080"; // check owner list contains only two entries, broker-3 should not be in - assertTrue(namespaceOwner.size() == 2); - assertTrue(!namespaceOwner.containsKey(inactiveBroker)); + assertEquals(namespaceOwner.size(), 2); + assertFalse(namespaceOwner.containsKey(inactiveBroker)); } @Test(enabled = false) diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/ModularLoadManagerImplTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/ModularLoadManagerImplTest.java index 50b7229e86438..e3e380a1195ae 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/ModularLoadManagerImplTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/ModularLoadManagerImplTest.java @@ -26,7 +26,6 @@ import java.lang.reflect.Field; import java.lang.reflect.Method; -import java.net.InetAddress; import java.net.URL; import java.util.Map; import java.util.Optional; diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/SimpleLoadManagerImplTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/SimpleLoadManagerImplTest.java index 69e2864c704f5..20d1926471023 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/SimpleLoadManagerImplTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/SimpleLoadManagerImplTest.java @@ -351,7 +351,7 @@ public void testResourceDescription() { rd1.put("bandwidthIn", new ResourceUsage(550 * 1024, 1024 * 1024)); rd1.put("bandwidthOut", new ResourceUsage(850 * 1024, 1024 * 1024)); - assertTrue(rd.compareTo(rd1) == 1); + assertEquals(rd.compareTo(rd1), 1); assertTrue(rd1.calculateRank() > rd.calculateRank()); SimpleLoadCalculatorImpl calc = new SimpleLoadCalculatorImpl(); @@ -477,12 +477,12 @@ public void testNamespaceBundleStats() { nsb2.msgRateIn = 5000; nsb2.msgThroughputIn = 110000.0; nsb2.msgThroughputOut = 110000.0; - assertTrue(nsb1.compareTo(nsb2) == -1); - assertTrue(nsb1.compareByMsgRate(nsb2) == -1); - assertTrue(nsb1.compareByTopicConnections(nsb2) == -1); - assertTrue(nsb1.compareByCacheSize(nsb2) == -1); - assertTrue(nsb1.compareByBandwidthOut(nsb2) == -1); - assertTrue(nsb1.compareByBandwidthIn(nsb2) == -1); + assertEquals(-1, nsb1.compareTo(nsb2)); + assertEquals(-1, nsb1.compareByMsgRate(nsb2)); + assertEquals(-1, nsb1.compareByTopicConnections(nsb2)); + assertEquals(-1, nsb1.compareByCacheSize(nsb2)); + assertEquals(-1, nsb1.compareByBandwidthOut(nsb2)); + assertEquals(-1, nsb1.compareByBandwidthIn(nsb2)); } @Test diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/lookup/http/HttpTopicLookupv2Test.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/lookup/http/HttpTopicLookupv2Test.java index 6ddfc796ccc82..7089a4cc45b12 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/lookup/http/HttpTopicLookupv2Test.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/lookup/http/HttpTopicLookupv2Test.java @@ -59,7 +59,6 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; -import com.google.common.collect.Lists; import com.google.common.collect.Sets; /** diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/namespace/NamespaceServiceTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/namespace/NamespaceServiceTest.java index 6d9d3984f3505..cade6edb90f2c 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/namespace/NamespaceServiceTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/namespace/NamespaceServiceTest.java @@ -26,6 +26,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; +import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; @@ -141,11 +142,11 @@ public void testSplitAndOwnBundles() throws Exception { byte[] content = this.pulsar.getLocalZkCache().getZooKeeper().getData(path, null, new Stat()); Policies policies = ObjectMapperFactory.getThreadLocal().readValue(content, Policies.class); NamespaceBundles localZkBundles = bundleFactory.getBundles(nsname, policies.bundles); - assertTrue(updatedNsBundles.equals(localZkBundles)); + assertEquals(localZkBundles, updatedNsBundles); log.info("Policies: {}", policies); // (3) validate ownership of new split bundles by local owner - bundleList.stream().forEach(b -> { + bundleList.forEach(b -> { try { byte[] data = this.pulsar.getLocalZkCache().getZooKeeper().getData(ServiceUnitZkUtils.path(b), null, new Stat()); @@ -203,8 +204,9 @@ public void testSplitMapWithRefreshedStatMap() throws Exception { // status-map should be updated with new split bundles NamespaceBundle splitBundle = pulsar.getNamespaceService().getBundle(topicName); - assertTrue(!CollectionUtils.isEmpty( - this.pulsar.getBrokerService().getAllTopicsFromNamespaceBundle(nspace, splitBundle.toString()))); + assertFalse(CollectionUtils.isEmpty( + this.pulsar.getBrokerService() + .getAllTopicsFromNamespaceBundle(nspace, splitBundle.toString()))); } @@ -411,11 +413,11 @@ public void testCreateNamespaceWithDefaultNumberOfBundles() throws Exception { byte[] content = this.pulsar.getLocalZkCache().getZooKeeper().getData(path, null, new Stat()); Policies policies = ObjectMapperFactory.getThreadLocal().readValue(content, Policies.class); NamespaceBundles localZkBundles = bundleFactory.getBundles(nsname, policies.bundles); - assertTrue(updatedNsBundles.equals(localZkBundles)); + assertEquals(localZkBundles, updatedNsBundles); log.info("Policies: {}", policies); // (3) validate ownership of new split bundles by local owner - bundleList.stream().forEach(b -> { + bundleList.forEach(b -> { try { byte[] data = this.pulsar.getLocalZkCache().getZooKeeper().getData(ServiceUnitZkUtils.path(b), null, new Stat()); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/namespace/OwnershipCacheTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/namespace/OwnershipCacheTest.java index 172f56ddca496..50b5395b3b035 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/namespace/OwnershipCacheTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/namespace/OwnershipCacheTest.java @@ -119,7 +119,7 @@ public void testDisableOwnership() throws Exception { assertFalse(cache.getOwnerAsync(testBundle).get().isPresent()); NamespaceEphemeralData data1 = cache.tryAcquiringOwnership(testBundle).get(); - assertTrue(!data1.isDisabled()); + assertFalse(data1.isDisabled()); cache.disableOwnership(testBundle); // force the next read to get directly from ZK // localCache.ownerInfoCache().invalidate(ServiceUnitZkUtils.path(testNs)); @@ -136,7 +136,7 @@ public void testGetOrSetOwner() throws Exception { NamespaceEphemeralData data1 = cache.tryAcquiringOwnership(testFullBundle).get(); assertEquals(data1.getNativeUrl(), selfBrokerUrl); - assertTrue(!data1.isDisabled()); + assertFalse(data1.isDisabled()); // case 2: the local broker owned the namespace and disabled, getOrSetOwner() should not change it OwnedBundle nsObj = cache.getOwnedBundle(testFullBundle); // this would disable the ownership @@ -154,7 +154,7 @@ public void testGetOrSetOwner() throws Exception { data1 = cache.tryAcquiringOwnership(testFullBundle).get(); assertEquals(data1.getNativeUrl(), "pulsar://otherhost:8881"); assertEquals(data1.getNativeUrlTls(), "pulsar://otherhost:8884"); - assertTrue(!data1.isDisabled()); + assertFalse(data1.isDisabled()); } @@ -174,7 +174,7 @@ public void testGetOwner() throws Exception { assertEquals(data1.getNativeUrl(), "pulsar://otherhost:8881"); assertEquals(data1.getNativeUrlTls(), "pulsar://otherhost:8884"); - assertTrue(!data1.isDisabled()); + assertFalse(data1.isDisabled()); // Now do getOwner and compare w/ the returned values NamespaceEphemeralData readOnlyData = cache.getOwnerAsync(testBundle).get().get(); assertEquals(data1, readOnlyData); @@ -217,7 +217,7 @@ public void testGetOwnedServiceUnit() throws Exception { NamespaceEphemeralData data1 = cache.tryAcquiringOwnership(testBundle).get(); assertEquals(data1.getNativeUrl(), "pulsar://otherhost:8881"); assertEquals(data1.getNativeUrlTls(), "pulsar://otherhost:8884"); - assertTrue(!data1.isDisabled()); + assertFalse(data1.isDisabled()); try { checkNotNull(cache.getOwnedBundle(testBundle)); fail("Should have failed"); @@ -231,7 +231,7 @@ public void testGetOwnedServiceUnit() throws Exception { localCache.ownerInfoCache().invalidate(ServiceUnitZkUtils.path(testBundle)); data1 = cache.tryAcquiringOwnership(testBundle).get(); assertEquals(data1.getNativeUrl(), selfBrokerUrl); - assertTrue(!data1.isDisabled()); + assertFalse(data1.isDisabled()); assertNotNull(cache.getOwnedBundle(testBundle)); } @@ -257,7 +257,7 @@ public void testGetOwnedServiceUnits() throws Exception { NamespaceEphemeralData data1 = cache.tryAcquiringOwnership(testBundle).get(); assertEquals(data1.getNativeUrl(), "pulsar://otherhost:8881"); assertEquals(data1.getNativeUrlTls(), "pulsar://otherhost:8884"); - assertTrue(!data1.isDisabled()); + assertFalse(data1.isDisabled()); assertTrue(cache.getOwnedBundles().isEmpty()); // case 3: this broker owns the namespace // delete the ephemeral node by others @@ -266,8 +266,8 @@ public void testGetOwnedServiceUnits() throws Exception { localCache.ownerInfoCache().invalidate(ServiceUnitZkUtils.path(testBundle)); data1 = cache.tryAcquiringOwnership(testBundle).get(); assertEquals(data1.getNativeUrl(), selfBrokerUrl); - assertTrue(!data1.isDisabled()); - assertTrue(cache.getOwnedBundles().size() == 1); + assertFalse(data1.isDisabled()); + assertEquals(cache.getOwnedBundles().size(), 1); } @Test @@ -284,8 +284,8 @@ public void testRemoveOwnership() throws Exception { // case 2: this broker owns the namespace NamespaceEphemeralData data1 = cache.tryAcquiringOwnership(bundle).get(); assertEquals(data1.getNativeUrl(), selfBrokerUrl); - assertTrue(!data1.isDisabled()); - assertTrue(cache.getOwnedBundles().size() == 1); + assertFalse(data1.isDisabled()); + assertEquals(cache.getOwnedBundles().size(), 1); cache.removeOwnership(bundle); Thread.sleep(500); assertTrue(cache.getOwnedBundles().isEmpty()); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/BacklogQuotaManagerTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/BacklogQuotaManagerTest.java index fdbc0fc851982..2268d5cfd008f 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/BacklogQuotaManagerTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/BacklogQuotaManagerTest.java @@ -19,7 +19,9 @@ package org.apache.pulsar.broker.service; import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; +import static org.testng.Assert.fail; import java.net.URL; import java.util.Optional; @@ -45,12 +47,10 @@ import org.apache.pulsar.zookeeper.LocalBookkeeperEnsemble; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; -import com.google.common.collect.Maps; import com.google.common.collect.Sets; /** @@ -106,7 +106,7 @@ void setup() throws Exception { admin.namespaces().setNamespaceReplicationClusters("prop/quotaholdasync", Sets.newHashSet("usc")); } catch (Throwable t) { LOG.error("Error setting up broker test", t); - Assert.fail("Broker test setup failed"); + fail("Broker test setup failed"); } } @@ -118,7 +118,7 @@ void shutdown() throws Exception { bkEnsemble.stop(); } catch (Throwable t) { LOG.error("Error cleaning up broker test setup state", t); - Assert.fail("Broker test cleanup failed"); + fail("Broker test cleanup failed"); } } @@ -154,7 +154,7 @@ public void testConsumerBacklogEviction() throws Exception { rolloverStats(); TopicStats stats = admin.topics().getStats(topic1); - Assert.assertTrue(stats.storageSize < 10 * 1024, "Storage size is [" + stats.storageSize + "]"); + assertTrue(stats.storageSize < 10 * 1024, "Storage size is [" + stats.storageSize + "]"); client.close(); } @@ -186,7 +186,7 @@ public void testConsumerBacklogEvictionWithAck() throws Exception { rolloverStats(); TopicStats stats = admin.topics().getStats(topic1); - Assert.assertTrue(stats.storageSize <= 10 * 1024, "Storage size is [" + stats.storageSize + "]"); + assertTrue(stats.storageSize <= 10 * 1024, "Storage size is [" + stats.storageSize + "]"); client.close(); } @@ -253,12 +253,12 @@ public void run() { // test hangs without timeout since there is nothing to consume due to eviction counter.await(20, TimeUnit.SECONDS); - assertTrue(!gotException.get()); + assertFalse(gotException.get()); Thread.sleep((TIME_TO_CHECK_BACKLOG_QUOTA + 1) * 1000); rolloverStats(); TopicStats stats = admin.topics().getStats(topic1); - Assert.assertTrue(stats.storageSize <= 10 * 1024, "Storage size is [" + stats.storageSize + "]"); + assertTrue(stats.storageSize <= 10 * 1024, "Storage size is [" + stats.storageSize + "]"); client.close(); client2.close(); } @@ -324,7 +324,7 @@ public void run() { producerThread.start(); ConsumerThread.start(); counter.await(); - assertTrue(!gotException.get()); + assertFalse(gotException.get()); client.close(); client2.close(); } @@ -427,12 +427,12 @@ public void run() { ConsumerThread1.start(); ConsumerThread2.start(); counter.await(20, TimeUnit.SECONDS); - assertTrue(!gotException.get()); + assertFalse(gotException.get()); Thread.sleep((TIME_TO_CHECK_BACKLOG_QUOTA + 1) * 1000); rolloverStats(); TopicStats stats = admin.topics().getStats(topic1); - Assert.assertTrue(stats.storageSize <= 15 * 1024, "Storage size is [" + stats.storageSize + "]"); + assertTrue(stats.storageSize <= 15 * 1024, "Storage size is [" + stats.storageSize + "]"); client.close(); client2.close(); client3.close(); @@ -472,7 +472,7 @@ public void testAheadProducerOnHold() throws Exception { Thread.sleep((TIME_TO_CHECK_BACKLOG_QUOTA + 1) * 1000); rolloverStats(); TopicStats stats = admin.topics().getStats(topic1); - Assert.assertEquals(stats.publishers.size(), 0, + assertEquals(stats.publishers.size(), 0, "Number of producers on topic " + topic1 + " are [" + stats.publishers.size() + "]"); client.close(); } @@ -503,12 +503,12 @@ public void testAheadProducerOnHoldTimeout() throws Exception { // try to send over backlog quota and make sure it fails producer.send(content); producer.send(content); - Assert.fail("backlog quota did not exceed"); + fail("backlog quota did not exceed"); } catch (PulsarClientException.TimeoutException te) { gotException = true; } - Assert.assertTrue(gotException, "timeout did not occur"); + assertTrue(gotException, "timeout did not occur"); client.close(); } @@ -538,14 +538,14 @@ public void testProducerException() throws Exception { // try to send over backlog quota and make sure it fails producer.send(content); producer.send(content); - Assert.fail("backlog quota did not exceed"); + fail("backlog quota did not exceed"); } catch (PulsarClientException ce) { - Assert.assertTrue(ce instanceof PulsarClientException.ProducerBlockedQuotaExceededException + assertTrue(ce instanceof PulsarClientException.ProducerBlockedQuotaExceededException || ce instanceof PulsarClientException.TimeoutException, ce.getMessage()); gotException = true; } - Assert.assertTrue(gotException, "backlog exceeded exception did not occur"); + assertTrue(gotException, "backlog exceeded exception did not occur"); client.close(); } @@ -575,14 +575,14 @@ public void testProducerExceptionAndThenUnblock() throws Exception { // try to send over backlog quota and make sure it fails producer.send(content); producer.send(content); - Assert.fail("backlog quota did not exceed"); + fail("backlog quota did not exceed"); } catch (PulsarClientException ce) { - Assert.assertTrue(ce instanceof PulsarClientException.ProducerBlockedQuotaExceededException + assertTrue(ce instanceof PulsarClientException.ProducerBlockedQuotaExceededException || ce instanceof PulsarClientException.TimeoutException, ce.getMessage()); gotException = true; } - Assert.assertTrue(gotException, "backlog exceeded exception did not occur"); + assertTrue(gotException, "backlog exceeded exception did not occur"); // now remove backlog and ensure that producer is unblockedrolloverStats(); TopicStats stats = admin.topics().getStats(topic1); @@ -604,7 +604,7 @@ public void testProducerExceptionAndThenUnblock() throws Exception { gotException = true; sendException = e; } - Assert.assertFalse(gotException, "unable to publish due to " + sendException); + assertFalse(gotException, "unable to publish due to " + sendException); client.close(); } diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/BrokerBookieIsolationTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/BrokerBookieIsolationTest.java index edad08c33b4ea..3b9edc9088eb7 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/BrokerBookieIsolationTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/BrokerBookieIsolationTest.java @@ -32,7 +32,6 @@ import org.apache.bookkeeper.bookie.Bookie; import org.apache.bookkeeper.client.BookKeeper; -import org.apache.bookkeeper.client.EnsemblePlacementPolicy; import org.apache.bookkeeper.client.api.LedgerMetadata; import org.apache.bookkeeper.meta.LedgerManager; import org.apache.bookkeeper.mledger.impl.ManagedLedgerFactoryImpl.EnsemblePlacementPolicyConfig; diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/BrokerServiceThrottlingTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/BrokerServiceThrottlingTest.java index 8a2bb1c65185a..0ae6c910c1f38 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/BrokerServiceThrottlingTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/BrokerServiceThrottlingTest.java @@ -19,7 +19,6 @@ package org.apache.pulsar.broker.service; import static org.apache.pulsar.broker.service.BrokerService.BROKER_SERVICE_CONFIGURATION_PATH; -import static org.mockito.Mockito.doReturn; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotEquals; import static org.testng.Assert.fail; @@ -42,7 +41,6 @@ import org.apache.pulsar.common.util.ObjectMapperFactory; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.ZooDefs; -import org.mockito.Mockito; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/PeerReplicatorTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/PeerReplicatorTest.java index 771ed5032bd46..28429340bfb9b 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/PeerReplicatorTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/PeerReplicatorTest.java @@ -22,6 +22,7 @@ import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; import static org.testng.Assert.fail; import java.util.LinkedHashSet; @@ -166,7 +167,7 @@ public void testGetPeerClusters() throws Exception { admin1.clusters().updatePeerClusterNames("r3", null); final String mainClusterName = "r1"; - assertEquals(admin1.clusters().getPeerClusterNames(mainClusterName), null); + assertNull(admin1.clusters().getPeerClusterNames(mainClusterName)); LinkedHashSet peerClusters = Sets.newLinkedHashSet(Lists.newArrayList("r2", "r3")); admin1.clusters().updatePeerClusterNames(mainClusterName, peerClusters); retryStrategically((test) -> { diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/PersistentDispatcherFailoverConsumerTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/PersistentDispatcherFailoverConsumerTest.java index ab96fd57a0f59..886018bc11875 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/PersistentDispatcherFailoverConsumerTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/PersistentDispatcherFailoverConsumerTest.java @@ -33,6 +33,7 @@ import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNull; import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertSame; import static org.testng.AssertJUnit.assertTrue; import io.netty.buffer.ByteBuf; @@ -276,7 +277,7 @@ public void testConsumerGroupChangesWithOldNewConsumers() throws Exception { "Cons1"/* consumer name */, 50000, serverCnxWithOldVersion, "myrole-1", Collections.emptyMap(), false, InitialPosition.Latest); pdfc.addConsumer(consumer1); List consumers = pdfc.getConsumers(); - assertTrue(consumers.get(0).consumerName() == consumer1.consumerName()); + assertSame(consumers.get(0).consumerName(), consumer1.consumerName()); assertEquals(1, consumers.size()); assertNull(consumerChanges.poll()); @@ -287,7 +288,7 @@ public void testConsumerGroupChangesWithOldNewConsumers() throws Exception { "Cons2"/* consumer name */, 50000, serverCnx, "myrole-1", Collections.emptyMap(), false, InitialPosition.Latest); pdfc.addConsumer(consumer2); consumers = pdfc.getConsumers(); - assertTrue(consumers.get(0).consumerName() == consumer1.consumerName()); + assertSame(consumers.get(0).consumerName(), consumer1.consumerName()); assertEquals(2, consumers.size()); CommandActiveConsumerChange change = consumerChanges.take(); @@ -316,7 +317,7 @@ public void testAddRemoveConsumer() throws Exception { false /* read compacted */, InitialPosition.Latest)); pdfc.addConsumer(consumer1); List consumers = pdfc.getConsumers(); - assertTrue(consumers.get(0).consumerName() == consumer1.consumerName()); + assertSame(consumers.get(0).consumerName(), consumer1.consumerName()); assertEquals(1, consumers.size()); CommandActiveConsumerChange change = consumerChanges.take(); verifyActiveConsumerChange(change, 1, true); @@ -325,11 +326,11 @@ public void testAddRemoveConsumer() throws Exception { // 3. Add again, duplicate allowed pdfc.addConsumer(consumer1); consumers = pdfc.getConsumers(); - assertTrue(consumers.get(0).consumerName() == consumer1.consumerName()); + assertSame(consumers.get(0).consumerName(), consumer1.consumerName()); assertEquals(2, consumers.size()); // 4. Verify active consumer - assertTrue(pdfc.getActiveConsumer().consumerName() == consumer1.consumerName()); + assertSame(pdfc.getActiveConsumer().consumerName(), consumer1.consumerName()); // get the notified with who is the leader change = consumerChanges.take(); verifyActiveConsumerChange(change, 1, true); @@ -340,7 +341,7 @@ public void testAddRemoveConsumer() throws Exception { 50000, serverCnx, "myrole-1", Collections.emptyMap(), false /* read compacted */, InitialPosition.Latest)); pdfc.addConsumer(consumer2); consumers = pdfc.getConsumers(); - assertTrue(pdfc.getActiveConsumer().consumerName() == consumer1.consumerName()); + assertSame(pdfc.getActiveConsumer().consumerName(), consumer1.consumerName()); assertEquals(3, consumers.size()); // get notified with who is the leader change = consumerChanges.take(); @@ -354,7 +355,7 @@ public void testAddRemoveConsumer() throws Exception { false /* read compacted */, InitialPosition.Latest)); pdfc.addConsumer(consumer0); consumers = pdfc.getConsumers(); - assertTrue(pdfc.getActiveConsumer().consumerName() == consumer0.consumerName()); + assertSame(pdfc.getActiveConsumer().consumerName(), consumer0.consumerName()); assertEquals(4, consumers.size()); // all consumers will receive notifications @@ -375,7 +376,7 @@ public void testAddRemoveConsumer() throws Exception { // 7. Remove last consumer pdfc.removeConsumer(consumer2); consumers = pdfc.getConsumers(); - assertTrue(pdfc.getActiveConsumer().consumerName() == consumer1.consumerName()); + assertSame(pdfc.getActiveConsumer().consumerName(), consumer1.consumerName()); assertEquals(3, consumers.size()); // not consumer group changes assertNull(consumerChanges.poll()); @@ -386,7 +387,7 @@ public void testAddRemoveConsumer() throws Exception { // 9. Remove active consumer pdfc.removeConsumer(consumer0); consumers = pdfc.getConsumers(); - assertTrue(pdfc.getActiveConsumer().consumerName() == consumer1.consumerName()); + assertSame(pdfc.getActiveConsumer().consumerName(), consumer1.consumerName()); assertEquals(2, consumers.size()); // the remaining consumers will receive notifications @@ -407,7 +408,7 @@ public void testAddRemoveConsumer() throws Exception { // 11. Remove active consumer pdfc.removeConsumer(consumer1); consumers = pdfc.getConsumers(); - assertTrue(pdfc.getActiveConsumer().consumerName() == consumer1.consumerName()); + assertSame(pdfc.getActiveConsumer().consumerName(), consumer1.consumerName()); assertEquals(1, consumers.size()); // not consumer group changes assertNull(consumerChanges.poll()); @@ -438,7 +439,7 @@ public void testAddRemoveConsumerNonPartitionedTopic() throws Exception { pdfc.addConsumer(consumer1); List consumers = pdfc.getConsumers(); assertEquals(1, consumers.size()); - assertTrue(pdfc.getActiveConsumer().consumerName() == consumer1.consumerName()); + assertSame(pdfc.getActiveConsumer().consumerName(), consumer1.consumerName()); // 3. Add a consumer with same priority level and consumer name is smaller in lexicographic order. Consumer consumer2 = spy(new Consumer(sub, SubType.Failover, topic.getName(), 2 /* consumer id */, 1, @@ -451,7 +452,7 @@ public void testAddRemoveConsumerNonPartitionedTopic() throws Exception { assertEquals(2, consumers.size()); CommandActiveConsumerChange change = consumerChanges.take(); verifyActiveConsumerChange(change, 2, false); - assertTrue(pdfc.getActiveConsumer().consumerName() == consumer1.consumerName()); + assertSame(pdfc.getActiveConsumer().consumerName(), consumer1.consumerName()); verify(consumer2, times(1)).notifyActiveConsumerChange(same(consumer1)); // 5. Add another consumer which has higher priority level @@ -462,7 +463,7 @@ public void testAddRemoveConsumerNonPartitionedTopic() throws Exception { assertEquals(3, consumers.size()); change = consumerChanges.take(); verifyActiveConsumerChange(change, 3, false); - assertTrue(pdfc.getActiveConsumer().consumerName() == consumer1.consumerName()); + assertSame(pdfc.getActiveConsumer().consumerName(), consumer1.consumerName()); verify(consumer3, times(1)).notifyActiveConsumerChange(same(consumer1)); // 7. Remove first consumer and active consumer should change to consumer2 since it's added before consumer3 @@ -472,7 +473,7 @@ public void testAddRemoveConsumerNonPartitionedTopic() throws Exception { assertEquals(2, consumers.size()); change = consumerChanges.take(); verifyActiveConsumerChange(change, 2, true); - assertTrue(pdfc.getActiveConsumer().consumerName() == consumer2.consumerName()); + assertSame(pdfc.getActiveConsumer().consumerName(), consumer2.consumerName()); verify(consumer2, times(1)).notifyActiveConsumerChange(same(consumer2)); verify(consumer3, times(1)).notifyActiveConsumerChange(same(consumer2)); } @@ -546,7 +547,7 @@ public void testFewBlockedConsumerSamePriority() throws Exception{ Assert.assertEquals(getNextConsumer(dispatcher), consumer2); Assert.assertEquals(getNextConsumer(dispatcher), consumer3); Assert.assertEquals(getNextConsumer(dispatcher), consumer4); - Assert.assertEquals(getNextConsumer(dispatcher), null); + assertNull(getNextConsumer(dispatcher)); } @Test @@ -600,7 +601,7 @@ public void testFewBlockedConsumerDifferentPriority() throws Exception { Assert.assertEquals(getNextConsumer(dispatcher), consumer13); Assert.assertEquals(getNextConsumer(dispatcher), consumer10); Assert.assertEquals(getNextConsumer(dispatcher), consumer12); - Assert.assertEquals(getNextConsumer(dispatcher), null); + assertNull(getNextConsumer(dispatcher)); } @Test @@ -625,7 +626,7 @@ public void testFewBlockedConsumerDifferentPriority2() throws Exception { Assert.assertEquals(getNextConsumer(dispatcher), consumer5); Assert.assertEquals(getNextConsumer(dispatcher), consumer4); Assert.assertEquals(getNextConsumer(dispatcher), consumer6); - Assert.assertEquals(getNextConsumer(dispatcher), null); + assertNull(getNextConsumer(dispatcher)); } @SuppressWarnings("unchecked") diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/PersistentMessageFinderTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/PersistentMessageFinderTest.java index 377e0ec1b765a..ae30b29e83166 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/PersistentMessageFinderTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/PersistentMessageFinderTest.java @@ -20,6 +20,8 @@ import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import io.netty.buffer.ByteBuf; @@ -146,20 +148,20 @@ void testPersistentMessageFinder() throws Exception { CompletableFuture future = findMessage(result, c1, timestamp); future.get(); - assertEquals(result.exception, null); - assertTrue(result.position != null); + assertNull(result.exception); + assertNotNull(result.position); assertEquals(result.position, newPosition); result.reset(); future = findMessage(result, c1, beginTimestamp); future.get(); - assertEquals(result.exception, null); + assertNull(result.exception); assertEquals(result.position, c1.getFirstPosition()); result.reset(); future = findMessage(result, c1, endTimestamp); future.get(); - assertEquals(result.exception, null); + assertNull(result.exception); assertNotEquals(result.position, null); assertEquals(result.position, lastPosition); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/PersistentTopicConcurrentTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/PersistentTopicConcurrentTest.java index d50a5b2a81c01..e135785ae1d7a 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/PersistentTopicConcurrentTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/PersistentTopicConcurrentTest.java @@ -23,7 +23,7 @@ import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; -import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; import java.lang.reflect.Method; import java.util.Collections; @@ -43,9 +43,6 @@ import org.apache.pulsar.broker.PulsarService; import org.apache.pulsar.broker.ServiceConfiguration; import org.apache.pulsar.broker.namespace.NamespaceService; -import org.apache.pulsar.broker.service.BrokerService; -import org.apache.pulsar.broker.service.Consumer; -import org.apache.pulsar.broker.service.ServerCnx; import org.apache.pulsar.broker.service.persistent.PersistentSubscription; import org.apache.pulsar.broker.service.persistent.PersistentTopic; import org.apache.pulsar.common.api.proto.PulsarApi; @@ -170,7 +167,7 @@ public void run() { unsubscriber.start(); counter.await(); - assertEquals(gotException.get(), false); + assertFalse(gotException.get()); } // @Test @@ -233,7 +230,7 @@ public void run() { unsubscriber.start(); counter.await(); - assertEquals(gotException.get(), false); + assertFalse(gotException.get()); } // @Test @@ -292,7 +289,7 @@ public void run() { unsubscriber.start(); counter.await(); - assertEquals(gotException.get(), false); + assertFalse(gotException.get()); } // @Test @@ -351,6 +348,6 @@ public void run() { unsubscriber.start(); counter.await(); - assertEquals(gotException.get(), false); + assertFalse(gotException.get()); } } diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/PersistentTopicE2ETest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/PersistentTopicE2ETest.java index e06b2497ff72e..04442c9b657c8 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/PersistentTopicE2ETest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/PersistentTopicE2ETest.java @@ -316,7 +316,7 @@ public void testActiveSubscriptionWithCache() throws Exception { // (5.1) Validate: active-consumer must be empty assertFalse(ledger.getActiveCursors().iterator().hasNext()); // (5.2) Validate: Entry-cache must be cleared - assertTrue(entryCache.getSize() == 0); + assertEquals(entryCache.getSize(), 0); } @@ -557,7 +557,7 @@ public void testUnloadNamespace() throws Exception { pulsarClient.newProducer().topic(topic).create(); pulsarClient.close(); - assertTrue(pulsar.getBrokerService().getTopicReference(topic) != null); + assertNotNull(pulsar.getBrokerService().getTopicReference(topic)); assertTrue(((ManagedLedgerFactoryImpl) pulsar.getManagedLedgerFactory()).getManagedLedgers() .containsKey(topicName.getPersistenceNamingEncoding())); @@ -1350,7 +1350,7 @@ public void testMessageRedelivery() throws Exception { } } // Make sure that first 10 messages that we didn't acknowledge get redelivered. - assertTrue(unackedMessages.size() == 0); + assertEquals(unackedMessages.size(), 0); // Verify no other messages are redelivered msg = consumer.receive(100, TimeUnit.MILLISECONDS); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/PersistentTopicTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/PersistentTopicTest.java index 5d7bbafe95ca6..3000c27314d6c 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/PersistentTopicTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/PersistentTopicTest.java @@ -95,7 +95,6 @@ import org.apache.pulsar.common.api.proto.PulsarApi.CommandSubscribe.InitialPosition; import org.apache.pulsar.common.api.proto.PulsarApi.CommandSubscribe.SubType; import org.apache.pulsar.common.api.proto.PulsarApi.MessageMetadata; -import org.apache.pulsar.common.naming.NamespaceBundle; import org.apache.pulsar.common.naming.TopicName; import org.apache.pulsar.common.policies.data.Policies; import org.apache.pulsar.common.protocol.schema.SchemaVersion; @@ -806,7 +805,7 @@ public void run() { unsubscriber.start(); counter.await(); - assertEquals(gotException.get(), false); + assertFalse(gotException.get()); } // @Test @@ -866,7 +865,7 @@ public void run() { unsubscriber.start(); counter.await(); - assertEquals(gotException.get(), false); + assertFalse(gotException.get()); } @Test diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ReplicatorTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ReplicatorTest.java index 6f7731baa7b0d..eddb7cd1201f9 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ReplicatorTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ReplicatorTest.java @@ -454,7 +454,7 @@ public void testReplicatorClearBacklog() throws Exception { replicator.updateRates(); // for code-coverage replicator.expireMessages(1); // for code-coverage ReplicatorStats status = replicator.getStats(); - assertTrue(status.replicationBacklog == 0); + assertEquals(status.replicationBacklog, 0); } @Test(enabled = true, timeOut = 30000) @@ -721,7 +721,7 @@ public void testCloseReplicatorStartProducer() throws Exception { producerField.setAccessible(true); @SuppressWarnings("unchecked") ProducerImpl replicatorProducer = (ProducerImpl) producerField.get(replicator); - assertEquals(replicatorProducer, null); + assertNull(replicatorProducer); } @Test(timeOut = 30000) diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ResendRequestTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ResendRequestTest.java index 049dabab7ddb1..e6bdd71ad4de5 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ResendRequestTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ResendRequestTest.java @@ -20,6 +20,7 @@ import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import java.lang.reflect.Field; @@ -142,7 +143,7 @@ public void testExclusiveSingleAckedNormalTopic() throws Exception { // 9. Calling resend after acking all messages - expectin 0 messages consumer.redeliverUnacknowledgedMessages(); - assertEquals(consumer.receive(2000, TimeUnit.MILLISECONDS), null); + assertNull(consumer.receive(2000, TimeUnit.MILLISECONDS)); // 10. Checking message contents for (int i = 0; i < totalMessages; i++) { @@ -711,8 +712,8 @@ public void testFailoverInactiveConsumer() throws Exception { message1 = consumer1.receive(500, TimeUnit.MILLISECONDS); message2 = consumer2.receive(500, TimeUnit.MILLISECONDS); - assertEquals(message1, null); - assertEquals(message2, null); + assertNull(message1); + assertNull(message2); } @SuppressWarnings("unchecked") diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ServerCnxTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ServerCnxTest.java index f715ddabbc49c..d1fa866761730 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ServerCnxTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ServerCnxTest.java @@ -25,7 +25,6 @@ import static org.mockito.Mockito.matches; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.testng.Assert.assertEquals; @@ -1008,7 +1007,7 @@ public void testSubscribeTimeout() throws Exception { assertEquals(((CommandError) response).getRequestId(), 5); // We should receive response for 1st producer, since it was not cancelled by the close - assertTrue(!channel.outboundMessages().isEmpty()); + assertFalse(channel.outboundMessages().isEmpty()); assertTrue(channel.isActive()); response = getResponse(); assertEquals(response.getClass(), CommandSuccess.class); @@ -1167,7 +1166,7 @@ public void testUnsupportedBatchMsgSubscribeCommand() throws Exception { channel.writeInbound(clientCommand); Object response = getResponse(); assertTrue(response instanceof CommandError); - assertTrue(((CommandError) response).getError().equals(ServerError.UnsupportedVersionError)); + assertEquals(ServerError.UnsupportedVersionError, ((CommandError) response).getError()); // Server will not close the connection assertTrue(channel.isOpen()); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/persistent/DelayedDeliveryTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/persistent/DelayedDeliveryTest.java index de8c6a61be900..6dab836c2b033 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/persistent/DelayedDeliveryTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/persistent/DelayedDeliveryTest.java @@ -19,6 +19,7 @@ package org.apache.pulsar.broker.service.persistent; import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import java.util.Set; @@ -88,7 +89,7 @@ public void testDelayedDelivery() // Failover consumer will receive the messages immediately while // the shared consumer will get them after the delay Message msg = sharedConsumer.receive(100, TimeUnit.MILLISECONDS); - assertEquals(msg, null); + assertNull(msg); for (int i = 0; i < 10; i++) { msg = failoverConsumer.receive(100, TimeUnit.MILLISECONDS); @@ -194,7 +195,7 @@ public void testEverythingFilteredInMultipleReads() } Message msg = sharedConsumer.receive(100, TimeUnit.MILLISECONDS); - assertEquals(msg, null); + assertNull(msg); Set receivedMsgs = new TreeSet<>(); for (int i = 0; i < 20; i++) { diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/persistent/PersistentSubscriptionTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/persistent/PersistentSubscriptionTest.java index 2d1d092069f34..94a558a2de578 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/persistent/PersistentSubscriptionTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/persistent/PersistentSubscriptionTest.java @@ -169,7 +169,7 @@ public void testCanAcknowledgeAndCommitForTransaction() throws TransactionConfli }).when(cursorMock).asyncDelete(any(List.class), any(AsyncCallbacks.DeleteCallback.class), any()); doAnswer((invocationOnMock) -> { - assertTrue(((PositionImpl)invocationOnMock.getArguments()[0]).compareTo(new PositionImpl(3, 100)) == 0); + assertEquals(((PositionImpl) invocationOnMock.getArguments()[0]).compareTo(new PositionImpl(3, 100)), 0); ((AsyncCallbacks.MarkDeleteCallback) invocationOnMock.getArguments()[2]) .markDeleteComplete(invocationOnMock.getArguments()[3]); return null; diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/stats/BookieClientsStatsGeneratorTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/stats/BookieClientsStatsGeneratorTest.java index 332bc07889511..67733a6c7feb7 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/stats/BookieClientsStatsGeneratorTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/stats/BookieClientsStatsGeneratorTest.java @@ -19,12 +19,12 @@ package org.apache.pulsar.broker.stats; import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertTrue; import java.util.Map; import org.apache.bookkeeper.mledger.proto.PendingBookieOpsStats; import org.apache.pulsar.broker.service.BrokerTestBase; -import org.apache.pulsar.broker.stats.BookieClientStatsGenerator; import org.apache.pulsar.common.stats.JvmMetrics; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; @@ -53,7 +53,7 @@ protected void cleanup() throws Exception { public void testBookieClientStatsGenerator() throws Exception { // should not generate any NPE or other exceptions.. Map> stats = BookieClientStatsGenerator.generate(super.getPulsar()); - assertEquals((boolean) stats.isEmpty(), true); + assertTrue(stats.isEmpty()); } @Test diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/stats/PrometheusMetricsTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/stats/PrometheusMetricsTest.java index 90a4bd881da60..ac8e8023e7a77 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/stats/PrometheusMetricsTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/stats/PrometheusMetricsTest.java @@ -20,6 +20,7 @@ import static com.google.common.base.Preconditions.checkArgument; import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNull; import java.io.ByteArrayOutputStream; import java.util.List; @@ -122,13 +123,13 @@ public void testPerNamespaceStats() throws Exception { // There should be 1 metric aggregated per namespace List cm = (List) metrics.get("pulsar_storage_write_latency_le_1"); assertEquals(cm.size(), 1); - assertEquals(cm.get(0).tags.get("topic"), null); + assertNull(cm.get(0).tags.get("topic")); assertEquals(cm.get(0).tags.get("namespace"), "my-property/use/my-ns"); cm = (List) metrics.get("pulsar_producers_count"); assertEquals(cm.size(), 2); assertEquals(cm.get(1).value, 2.0); - assertEquals(cm.get(1).tags.get("topic"), null); + assertNull(cm.get(1).tags.get("topic")); assertEquals(cm.get(1).tags.get("namespace"), "my-property/use/my-ns"); p1.close(); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/zookeeper/ZooKeeperClientAspectJTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/zookeeper/ZooKeeperClientAspectJTest.java index d0927e96df0b7..4abfa13a37b55 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/zookeeper/ZooKeeperClientAspectJTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/zookeeper/ZooKeeperClientAspectJTest.java @@ -20,6 +20,7 @@ import static org.mockito.Mockito.doReturn; import static org.testng.Assert.assertNotEquals; +import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import java.io.Closeable; @@ -115,7 +116,7 @@ public void testInitZk() throws Exception { assertNotEquals(chrootZkc.getState(), States.CONNECTEDREADONLY); chrootZkc.close(); - assertTrue(localZkc.exists("/prefix", false) != null); + assertNotNull(localZkc.exists("/prefix", false)); } finally { if (localZkc != null) { localZkc.close(); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/client/api/BrokerServiceLookupTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/client/api/BrokerServiceLookupTest.java index 51459fc96d90e..ec83272f8be1e 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/client/api/BrokerServiceLookupTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/client/api/BrokerServiceLookupTest.java @@ -23,7 +23,7 @@ import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; @@ -869,7 +869,7 @@ public void testSplitUnloadLookupTest() throws Exception { .subscribe(); NamespaceBundle bundleInBroker1AfterSplit = pulsar2.getNamespaceService().getBundle(TopicName.get(topic2)); - assertFalse(bundleInBroker1AfterSplit.equals(unsplitBundle)); + assertNotEquals(unsplitBundle, bundleInBroker1AfterSplit); consumer1.close(); consumer2.close(); @@ -1000,7 +1000,7 @@ public void testModularLoadManagerSplitBundle() throws Exception { .subscribe(); NamespaceBundle bundleInBroker1AfterSplit = pulsar2.getNamespaceService().getBundle(TopicName.get(topic2)); - assertFalse(bundleInBroker1AfterSplit.equals(unsplitBundle)); + assertNotEquals(unsplitBundle, bundleInBroker1AfterSplit); consumer1.close(); consumer2.close(); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/client/api/ClientErrorsTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/client/api/ClientErrorsTest.java index 025d42d7e8023..f8ac75b819ec0 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/client/api/ClientErrorsTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/client/api/ClientErrorsTest.java @@ -598,7 +598,7 @@ public void testProducerReconnect() throws Exception { producer.send(new byte[0]); - assertEquals(msgSent.get(), true); + assertTrue(msgSent.get()); assertTrue(numOfConnections.get() >= 3); mockBrokerService.resetHandleConnect(); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/client/api/PartitionedProducerConsumerTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/client/api/PartitionedProducerConsumerTest.java index 4ab650ce81212..982005640b55c 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/client/api/PartitionedProducerConsumerTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/client/api/PartitionedProducerConsumerTest.java @@ -315,7 +315,7 @@ public void testPauseAndResume() throws Exception { for (int i = 0; i < numMessages * 2; i++) producer.send(("my-message-" + i).getBytes()); log.info("Waiting for message listener to ack " + numMessages + " messages"); - assertEquals(latch.get().await(numMessages, TimeUnit.SECONDS), true, "Timed out waiting for message listener acks"); + assertTrue(latch.get().await(numMessages, TimeUnit.SECONDS), "Timed out waiting for message listener acks"); log.info("Giving message listener an opportunity to receive messages while paused"); Thread.sleep(2000); // hopefully this is long enough @@ -326,7 +326,7 @@ public void testPauseAndResume() throws Exception { consumer.resume(); log.info("Waiting for message listener to ack all messages"); - assertEquals(latch.get().await(numMessages, TimeUnit.SECONDS), true, "Timed out waiting for message listener acks"); + assertTrue(latch.get().await(numMessages, TimeUnit.SECONDS), "Timed out waiting for message listener acks"); consumer.close(); producer.close(); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/client/api/SimpleProducerConsumerStatTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/client/api/SimpleProducerConsumerStatTest.java index 85946c596b78c..62b4aec3a4a09 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/client/api/SimpleProducerConsumerStatTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/client/api/SimpleProducerConsumerStatTest.java @@ -46,7 +46,6 @@ import com.google.common.collect.Sets; import com.google.common.util.concurrent.RateLimiter; import com.google.gson.JsonArray; -import com.google.gson.JsonElement; import com.google.gson.JsonObject; public class SimpleProducerConsumerStatTest extends ProducerConsumerBase { @@ -280,7 +279,7 @@ public void testMessageListener(int batchMessageDelayMs) throws Exception { } Thread.sleep(5000); log.info("Waiting for message listener to ack all messages"); - assertEquals(latch.await(numMessages, TimeUnit.SECONDS), true, "Timed out waiting for message listener acks"); + assertTrue(latch.await(numMessages, TimeUnit.SECONDS),"Timed out waiting for message listener acks"); consumer.close(); producer.close(); validatingLogInfo(consumer, producer, true); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/client/api/SimpleProducerConsumerTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/client/api/SimpleProducerConsumerTest.java index d01e6ac83ce60..901bb5a086f72 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/client/api/SimpleProducerConsumerTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/client/api/SimpleProducerConsumerTest.java @@ -375,7 +375,7 @@ public void testMessageListener(int batchMessageDelayMs) throws Exception { } log.info("Waiting for message listener to ack all messages"); - assertEquals(latch.await(numMessages, TimeUnit.SECONDS), true, "Timed out waiting for message listener acks"); + assertTrue(latch.await(numMessages, TimeUnit.SECONDS), "Timed out waiting for message listener acks"); consumer.close(); log.info("-- Exiting {} test --", methodName); } @@ -408,7 +408,7 @@ public void testPauseAndResume() throws Exception { for (int i = 0; i < receiverQueueSize * 2; i++) producer.send(("my-message-" + i).getBytes()); log.info("Waiting for message listener to ack " + receiverQueueSize + " messages"); - assertEquals(latch.get().await(receiverQueueSize, TimeUnit.SECONDS), true, "Timed out waiting for message listener acks"); + assertTrue(latch.get().await(receiverQueueSize, TimeUnit.SECONDS), "Timed out waiting for message listener acks"); log.info("Giving message listener an opportunity to receive messages while paused"); Thread.sleep(2000); // hopefully this is long enough @@ -419,7 +419,7 @@ public void testPauseAndResume() throws Exception { consumer.resume(); log.info("Waiting for message listener to ack all messages"); - assertEquals(latch.get().await(receiverQueueSize, TimeUnit.SECONDS), true, "Timed out waiting for message listener acks"); + assertTrue(latch.get().await(receiverQueueSize, TimeUnit.SECONDS), "Timed out waiting for message listener acks"); consumer.close(); producer.close(); @@ -960,7 +960,7 @@ public void testActiveAndInActiveConsumerEntryCacheBehavior() throws Exception { retryStrategically((test) -> entryCache.getSize() == 0, 5, 100); // Verify: EntryCache should be cleared - assertTrue(entryCache.getSize() == 0); + assertEquals(entryCache.getSize(), 0); subscriber1.close(); log.info("-- Exiting {} test --", methodName); } diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/client/api/v1/V1_ProducerConsumerTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/client/api/v1/V1_ProducerConsumerTest.java index 8fd33bd14ac1e..24fb5a7562942 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/client/api/v1/V1_ProducerConsumerTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/client/api/v1/V1_ProducerConsumerTest.java @@ -23,7 +23,6 @@ import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotEquals; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; @@ -239,7 +238,7 @@ public void testMessageListener(int batchMessageDelayMs) throws Exception { } log.info("Waiting for message listener to ack all messages"); - assertEquals(latch.await(numMessages, TimeUnit.SECONDS), true, "Timed out waiting for message listener acks"); + assertTrue(latch.await(numMessages, TimeUnit.SECONDS), "Timed out waiting for message listener acks"); consumer.close(); log.info("-- Exiting {} test --", methodName); } @@ -725,7 +724,7 @@ public void testActiveAndInActiveConsumerEntryCacheBehavior() throws Exception { retryStrategically((test) -> entryCache.getSize() == 0, 5, 100); // Verify: EntryCache should be cleared - assertTrue(entryCache.getSize() == 0); + assertEquals(entryCache.getSize(), 0); subscriber1.close(); log.info("-- Exiting {} test --", methodName); } @@ -881,14 +880,14 @@ public void testSharedConsumerAckDifferentConsumer() throws Exception { consumerMsgSet2.add(msg); } - consumerMsgSet1.stream().forEach(m -> { + consumerMsgSet1.forEach(m -> { try { consumer2.acknowledge(m); } catch (PulsarClientException e) { fail(); } }); - consumerMsgSet2.stream().forEach(m -> { + consumerMsgSet2.forEach(m -> { try { consumer1.acknowledge(m); } catch (PulsarClientException e) { @@ -1106,8 +1105,6 @@ public void testConsumerBlockingWithUnAckedMessagesMultipleIteration() throws Ex /** * Verify: Consumer1 which doesn't send ack will not impact Consumer2 which sends ack for consumed message. * - * - * @param batchMessageDelayMs * @throws Exception */ @Test @@ -1433,8 +1430,6 @@ public void testUnackedBlockAtBatch(int batchMessageDelayMs) throws Exception { /** * Verify: Consumer2 sends ack of Consumer1 and consumer1 should be unblock if it is blocked due to unack-messages * - * - * @param batchMessageDelayMs * @throws Exception */ @Test diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/client/impl/BrokerClientIntegrationTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/client/impl/BrokerClientIntegrationTest.java index e0aec987abfb4..5f09992e4359d 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/client/impl/BrokerClientIntegrationTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/client/impl/BrokerClientIntegrationTest.java @@ -30,6 +30,7 @@ import static org.mockito.Mockito.verify; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; @@ -211,14 +212,14 @@ public void testDisconnectClientWithoutClosingConnection() throws Exception { Thread.sleep(200); // producer1 must not be able to connect again - assertTrue(prod1.getClientCnx() == null); - assertTrue(prod1.getState().equals(State.Connecting)); + assertNull(prod1.getClientCnx()); + assertEquals(State.Connecting, prod1.getState()); // consumer1 must not be able to connect again - assertTrue(cons1.getClientCnx() == null); - assertTrue(cons1.getState().equals(State.Connecting)); + assertNull(cons1.getClientCnx()); + assertEquals(State.Connecting, cons1.getState()); // producer2 must have live connection - assertTrue(prod2.getClientCnx() != null); - assertTrue(prod2.getState().equals(State.Ready)); + assertNotNull(prod2.getClientCnx()); + assertEquals(State.Ready, prod2.getState()); // unload ns-bundle2 as well pulsar.getNamespaceService().unloadNamespaceBundle((NamespaceBundle) bundle2); @@ -227,14 +228,14 @@ public void testDisconnectClientWithoutClosingConnection() throws Exception { verify(producer2, atLeastOnce()).connectionClosed(any()); // producer1 must not be able to connect again - assertTrue(prod1.getClientCnx() == null); - assertTrue(prod1.getState().equals(State.Connecting)); + assertNull(prod1.getClientCnx()); + assertEquals(State.Connecting, prod1.getState()); // consumer1 must not be able to connect again - assertTrue(cons1.getClientCnx() == null); - assertTrue(cons1.getState().equals(State.Connecting)); + assertNull(cons1.getClientCnx()); + assertEquals(State.Connecting, cons1.getState()); // producer2 must not be able to connect again - assertTrue(prod2.getClientCnx() == null); - assertTrue(prod2.getState().equals(State.Connecting)); + assertNull(prod2.getClientCnx()); + assertEquals(State.Connecting, prod2.getState()); producer1.close(); producer2.close(); @@ -278,14 +279,14 @@ public void testCloseBrokerService() throws Exception { && producer2.getClientCnx() == null), 5, 100); // [2] All clients must be disconnected and in connecting state // producer1 must not be able to connect again - assertTrue(producer1.getClientCnx() == null); - assertTrue(producer1.getState().equals(State.Connecting)); + assertNull(producer1.getClientCnx()); + assertEquals(State.Connecting, producer1.getState()); // consumer1 must not be able to connect again - assertTrue(consumer1.getClientCnx() == null); - assertTrue(consumer1.getState().equals(State.Connecting)); + assertNull(consumer1.getClientCnx()); + assertEquals(State.Connecting, consumer1.getState()); // producer2 must not be able to connect again - assertTrue(producer2.getClientCnx() == null); - assertTrue(producer2.getState().equals(State.Connecting)); + assertNull(producer2.getClientCnx()); + assertEquals(State.Connecting, producer2.getState()); producer1.close(); producer2.close(); @@ -417,7 +418,7 @@ public void testResetCursor(SubscriptionType subType) throws Exception { received.add(msg); } consumer.acknowledge(msg); - long publishTime = ((MessageImpl) msg).getPublishTime(); + long publishTime = msg.getPublishTime(); log.info(" publish time is " + publishTime + "," + msg.getMessageId()); TimestampEntryCount timestampEntryCount = publishTimeIdMap.computeIfAbsent(publishTime, (k) -> new TimestampEntryCount(publishTime)); @@ -433,7 +434,7 @@ public void testResetCursor(SubscriptionType subType) throws Exception { log.info("warm up started for " + topicName.toString()); // send warmup msgs byte[] msgBytes = new byte[1000]; - for (Integer i = 0; i < warmup; i++) { + for (int i = 0; i < warmup; i++) { producer.send(msgBytes); } log.info("warm up finished."); @@ -449,7 +450,7 @@ public void testResetCursor(SubscriptionType subType) throws Exception { // publish testSize num of msgs log.info("Sending more messages."); - for (Integer n = 0; n < testSize; n++) { + for (int n = 0; n < testSize; n++) { producer.send(msgBytes); Thread.sleep(1); } @@ -560,7 +561,7 @@ public void testCloseConnectionOnBrokerRejectedRequest() throws Exception { latch.await(10, TimeUnit.SECONDS); // connection must be closed - assertTrue(failed.get() == 1); + assertEquals(failed.get(), 1); try { pulsarClient.close(); pulsarClient2.close(); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/client/impl/MessageRedeliveryTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/client/impl/MessageRedeliveryTest.java index 819b0c1c372b7..2d313088e930f 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/client/impl/MessageRedeliveryTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/client/impl/MessageRedeliveryTest.java @@ -19,7 +19,6 @@ package org.apache.pulsar.client.impl; import static org.testng.Assert.assertNotEquals; -import static org.testng.Assert.assertTrue; import static org.testng.Assert.assertEquals; import java.util.Set; @@ -30,7 +29,6 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; -import org.apache.bookkeeper.mledger.Position; import org.apache.bookkeeper.mledger.impl.ManagedCursorImpl; import org.apache.bookkeeper.mledger.impl.ManagedLedgerImpl; import org.apache.pulsar.broker.service.persistent.PersistentTopic; diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/client/impl/PatternTopicsConsumerImplTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/client/impl/PatternTopicsConsumerImplTest.java index 4228fdb7176d7..1d3364179dd8c 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/client/impl/PatternTopicsConsumerImplTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/client/impl/PatternTopicsConsumerImplTest.java @@ -187,7 +187,7 @@ public void testBinaryProtoToGetTopicsOfNamespacePersistent() throws Exception { consumers.forEach(c -> log.debug("consumer: {}", c.getTopic())); IntStream.range(0, topics.size()).forEach(index -> - assertTrue(topics.get(index).equals(consumers.get(index).getTopic()))); + assertEquals(consumers.get(index).getTopic(), topics.get(index))); ((PatternMultiTopicsConsumerImpl) consumer).getTopics().forEach(topic -> log.debug("getTopics topic: {}", topic)); @@ -277,7 +277,7 @@ public void testBinaryProtoToGetTopicsOfNamespaceNonPersistent() throws Exceptio consumers.forEach(c -> log.debug("consumer: {}", c.getTopic())); IntStream.range(0, topics.size()).forEach(index -> - assertTrue(topics.get(index).equals(consumers.get(index).getTopic()))); + assertEquals(consumers.get(index).getTopic(), topics.get(index))); ((PatternMultiTopicsConsumerImpl) consumer).getTopics().forEach(topic -> log.debug("getTopics topic: {}", topic)); @@ -367,7 +367,7 @@ public void testBinaryProtoToGetTopicsOfNamespaceAll() throws Exception { consumers.forEach(c -> log.debug("consumer: {}", c.getTopic())); IntStream.range(0, topics.size()).forEach(index -> - assertTrue(topics.get(index).equals(consumers.get(index).getTopic()))); + assertEquals(consumers.get(index).getTopic(), topics.get(index))); ((PatternMultiTopicsConsumerImpl) consumer).getTopics().forEach(topic -> log.debug("getTopics topic: {}", topic)); @@ -452,7 +452,7 @@ public void testTopicsListMinus() throws Exception { // empty list minus: addedNames2.size = 2, addedNames3.size = 0 List addedNames4 = PatternMultiTopicsConsumerImpl.topicsListsMinus(addedNames2, addedNames3); - assertTrue(addedNames4.size() == addedNames2.size()); + assertEquals(addedNames2.size(), addedNames4.size()); addedNames4.forEach(name -> assertTrue(addedNames2.contains(name))); List addedNames5 = PatternMultiTopicsConsumerImpl.topicsListsMinus(addedNames3, addedNames2); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/client/impl/TopicsConsumerImplTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/client/impl/TopicsConsumerImplTest.java index 433544eb91ac2..0950bddc83327 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/client/impl/TopicsConsumerImplTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/client/impl/TopicsConsumerImplTest.java @@ -138,9 +138,9 @@ public void testGetConsumersAndGetTopics() throws Exception { consumers.forEach(c -> log.info("consumer: {}", c.getTopic())); IntStream.range(0, 6).forEach(index -> - assertTrue(topics.get(index).equals(consumers.get(index).getTopic()))); + assertEquals(consumers.get(index).getTopic(), topics.get(index))); - assertTrue(((MultiTopicsConsumerImpl) consumer).getTopics().size() == 3); + assertEquals(((MultiTopicsConsumerImpl) consumer).getTopics().size(), 3); consumer.unsubscribe(); consumer.close(); @@ -524,7 +524,7 @@ public void testSubscribeUnsubscribeSingleTopic() throws Exception { assertEquals(topics.size(), 3); assertEquals(consumers.size(), 3); - assertTrue(((MultiTopicsConsumerImpl) consumer).getTopics().size() == 2); + assertEquals(((MultiTopicsConsumerImpl) consumer).getTopics().size(), 2); // 8. re-subscribe topic3 CompletableFuture subFuture = ((MultiTopicsConsumerImpl)consumer).subscribeAsync(topicName3); @@ -555,7 +555,7 @@ public void testSubscribeUnsubscribeSingleTopic() throws Exception { assertEquals(topics.size(), 6); assertEquals(consumers.size(), 6); - assertTrue(((MultiTopicsConsumerImpl) consumer).getTopics().size() == 3); + assertEquals(((MultiTopicsConsumerImpl) consumer).getTopics().size(), 3); consumer.unsubscribe(); consumer.close(); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/client/impl/UnAcknowledgedMessagesTimeoutTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/client/impl/UnAcknowledgedMessagesTimeoutTest.java index 794ce31105386..4ee0b8f8caaf9 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/client/impl/UnAcknowledgedMessagesTimeoutTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/client/impl/UnAcknowledgedMessagesTimeoutTest.java @@ -20,6 +20,7 @@ import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import java.util.HashSet; @@ -148,18 +149,18 @@ public void testExclusiveCumulativeAckedNormalTopic() throws Exception { lastMessage = message; hSet.add(new String(message.getData())); log.info("Consumer received " + new String(message.getData())); - log.info("Message ID details " + ((MessageIdImpl) message.getMessageId()).toString()); + log.info("Message ID details " + message.getMessageId().toString()); message = consumer.receive(500, TimeUnit.MILLISECONDS); } long size = ((ConsumerImpl) consumer).getUnAckedMessageTracker().size(); assertEquals(size, totalMessages); log.info("Comulative Ack sent for " + new String(lastMessage.getData())); - log.info("Message ID details " + ((MessageIdImpl) lastMessage.getMessageId()).toString()); + log.info("Message ID details " + lastMessage.getMessageId().toString()); consumer.acknowledgeCumulative(lastMessage); size = ((ConsumerImpl) consumer).getUnAckedMessageTracker().size(); assertEquals(size, 0); message = consumer.receive((int) (2 * ackTimeOutMillis), TimeUnit.MILLISECONDS); - assertEquals(message, null); + assertNull(message); } @Test(timeOut = testTimeout) diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/common/naming/NamespaceBundleTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/common/naming/NamespaceBundleTest.java index e7a528cdeb633..5b84b7e564b1f 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/common/naming/NamespaceBundleTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/common/naming/NamespaceBundleTest.java @@ -23,17 +23,14 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import org.apache.pulsar.broker.PulsarService; import org.apache.pulsar.broker.cache.LocalZooKeeperCacheService; -import org.apache.pulsar.common.naming.TopicName; -import org.apache.pulsar.common.naming.NamespaceBundle; -import org.apache.pulsar.common.naming.NamespaceBundleFactory; -import org.apache.pulsar.common.naming.NamespaceBundles; -import org.apache.pulsar.common.naming.NamespaceName; import org.apache.pulsar.common.policies.data.LocalPolicies; import org.apache.pulsar.zookeeper.ZooKeeperDataCache; import org.testng.annotations.Test; @@ -111,9 +108,9 @@ public void testConstructor() { NamespaceBundle bundle = new NamespaceBundle(NamespaceName.get("pulsar/use/ns"), Range.range(0L, BoundType.CLOSED, 1L, BoundType.OPEN), factory); - assertTrue(bundle.getKeyRange().lowerEndpoint().equals(0L)); + assertEquals((long) bundle.getKeyRange().lowerEndpoint(), 0L); assertEquals(bundle.getKeyRange().lowerBoundType(), BoundType.CLOSED); - assertTrue(bundle.getKeyRange().upperEndpoint().equals(1L)); + assertEquals((long) bundle.getKeyRange().upperEndpoint(), 1L); assertEquals(bundle.getKeyRange().upperBoundType(), BoundType.OPEN); assertEquals(bundle.getNamespaceObject().toString(), "pulsar/use/ns"); } @@ -164,7 +161,7 @@ public void testCompareTo() throws Exception { NamespaceBundle bundle3 = factory.getBundle(NamespaceName.get("pulsar/use/ns1"), Range.range(0l, BoundType.CLOSED, 0x40000000L, BoundType.OPEN)); - assertTrue(bundle.compareTo(bundle3) == 0); + assertEquals(bundle.compareTo(bundle3), 0); NamespaceBundle otherBundle = factory.getBundle(NamespaceName.get("pulsar/use/ns2"), Range.range(0x10000000l, BoundType.CLOSED, 0x30000000L, BoundType.OPEN)); @@ -177,15 +174,15 @@ public void testEquals() throws Exception { Range.range(0l, BoundType.CLOSED, 0x40000000L, BoundType.OPEN)); NamespaceBundle bundle2 = factory.getBundle(NamespaceName.get("pulsar/use/ns1"), Range.range(0x20000000l, BoundType.CLOSED, 0x40000000L, BoundType.OPEN)); - assertTrue(!bundle.equals(bundle2)); + assertNotEquals(bundle2, bundle); NamespaceBundle bundle0 = factory.getBundle(NamespaceName.get("pulsar/use/ns1"), Range.range(0l, BoundType.CLOSED, 0x40000000L, BoundType.OPEN)); - assertTrue(bundle0.equals(bundle)); + assertEquals(bundle, bundle0); NamespaceBundle otherBundle = factory.getBundle(NamespaceName.get("pulsar/use/ns2"), Range.range(0l, BoundType.CLOSED, 0x40000000L, BoundType.OPEN)); - assertTrue(!otherBundle.equals(bundle)); + assertNotEquals(bundle, otherBundle); } @Test @@ -199,11 +196,11 @@ public void testIncludes() throws Exception { assertTrue(bundle.includes(topicName)); bundle = factory.getBundle(NamespaceName.get("pulsar/use/ns1"), Range.range(upper, BoundType.CLOSED, NamespaceBundles.FULL_UPPER_BOUND, BoundType.CLOSED)); - assertTrue(!bundle.includes(topicName)); + assertFalse(bundle.includes(topicName)); NamespaceBundle otherBundle = factory.getBundle(NamespaceName.get("pulsar/use/ns2"), Range.range(0l, BoundType.CLOSED, 0x40000000L, BoundType.OPEN)); - assertTrue(!otherBundle.includes(topicName)); + assertFalse(otherBundle.includes(topicName)); } @Test diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/common/naming/NamespaceBundlesTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/common/naming/NamespaceBundlesTest.java index 7ef0e325482fa..4093899bf811b 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/common/naming/NamespaceBundlesTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/common/naming/NamespaceBundlesTest.java @@ -112,7 +112,7 @@ public void testConstructor() throws Exception { // the same instance assertEquals(partitions.size(), partFld.length); NamespaceName nsFld = (NamespaceName) nsField.get(bundles); - assertTrue(nsFld.toString().equals("pulsar/use/ns2")); + assertEquals(nsFld.toString(), "pulsar/use/ns2"); ArrayList bundleList = (ArrayList) bundlesField.get(bundles); assertEquals(bundleList.size(), 3); assertEquals(bundleList.get(0), @@ -256,7 +256,7 @@ private void validateSplitBundlesRange(NamespaceBundle fullBundle, List bundles, int numBundles) { - assertTrue(bundles.size() == 2); + assertEquals(bundles.size(), 2); String[] range = bundle.getBundleRange().split("_"); long lower = Long.decode(range[0]); long upper = Long.decode(range[1]); @@ -296,8 +296,8 @@ private void assertBundleDivideInTwo(NamespaceBundle bundle, List [{},{}]", range[0], range[1], lRange, uRange); } diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/functions/worker/PulsarFunctionE2ESecurityTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/functions/worker/PulsarFunctionE2ESecurityTest.java index 2b88ad2b874fb..54f05d8125ff6 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/functions/worker/PulsarFunctionE2ESecurityTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/functions/worker/PulsarFunctionE2ESecurityTest.java @@ -37,7 +37,6 @@ import org.apache.pulsar.client.api.Message; import org.apache.pulsar.client.api.Producer; import org.apache.pulsar.client.api.PulsarClient; -import org.apache.pulsar.client.api.PulsarClientException; import org.apache.pulsar.client.api.Schema; import org.apache.pulsar.client.impl.auth.AuthenticationToken; import org.apache.pulsar.common.functions.FunctionConfig; @@ -47,7 +46,6 @@ import org.apache.pulsar.common.policies.data.SubscriptionStats; import org.apache.pulsar.common.policies.data.TenantInfo; import org.apache.pulsar.common.util.FutureUtil; -import org.apache.pulsar.functions.utils.functioncache.FunctionCacheEntry; import org.apache.pulsar.io.PulsarFunctionE2ETest; import org.apache.pulsar.zookeeper.LocalBookkeeperEnsemble; import org.slf4j.Logger; diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/functions/worker/PulsarFunctionLocalRunTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/functions/worker/PulsarFunctionLocalRunTest.java index ecf65677b6129..97cabc335c2b6 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/functions/worker/PulsarFunctionLocalRunTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/functions/worker/PulsarFunctionLocalRunTest.java @@ -64,7 +64,6 @@ import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; -import java.io.FilenameFilter; import java.io.OutputStream; import java.lang.reflect.Method; import java.net.InetSocketAddress; @@ -83,6 +82,7 @@ import static org.mockito.Mockito.spy; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotEquals; +import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; @@ -479,7 +479,7 @@ private void testE2EPulsarFunctionLocalRun(String jarFilePathUrl) throws Excepti }, 10, 150); try { - assertTrue(admin.topics().getStats(sinkTopic).publishers.size() == 0); + assertEquals(admin.topics().getStats(sinkTopic).publishers.size(), 0); } catch (PulsarAdminException e) { if (e.getStatusCode() != 404) { fail(); @@ -553,7 +553,7 @@ private void testPulsarSourceLocalRun(String jarFilePathUrl) throws Exception { TopicStats sourceStats = admin.topics().getStats(sinkTopic); assertEquals(sourceStats.publishers.size(), 1); - assertTrue(sourceStats.publishers.get(0).metadata != null); + assertNotNull(sourceStats.publishers.get(0).metadata); assertTrue(sourceStats.publishers.get(0).metadata.containsKey("id")); assertEquals(sourceStats.publishers.get(0).metadata.get("id"), String.format("%s/%s/%s", tenant, namespacePortion, sourceName)); @@ -573,15 +573,12 @@ private void testPulsarSourceLocalRun(String jarFilePathUrl) throws Exception { try { return (admin.topics().getStats(sinkTopic).publishers.size() == 0); } catch (PulsarAdminException e) { - if (e.getStatusCode() == 404) { - return true; - } - return false; + return e.getStatusCode() == 404; } }, 10, 150); try { - assertTrue(admin.topics().getStats(sinkTopic).publishers.size() == 0); + assertEquals(admin.topics().getStats(sinkTopic).publishers.size(), 0); } catch (PulsarAdminException e) { if (e.getStatusCode() != 404) { fail(); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/functions/worker/PulsarFunctionPublishTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/functions/worker/PulsarFunctionPublishTest.java index d8ecce3354e38..9c2b7b7688c5b 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/functions/worker/PulsarFunctionPublishTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/functions/worker/PulsarFunctionPublishTest.java @@ -40,7 +40,6 @@ import org.apache.pulsar.client.impl.auth.AuthenticationTls; import org.apache.pulsar.common.functions.FunctionConfig; import org.apache.pulsar.common.functions.Utils; -import org.apache.pulsar.common.naming.TopicName; import org.apache.pulsar.common.policies.data.ClusterData; import org.apache.pulsar.common.policies.data.FunctionStats; import org.apache.pulsar.common.policies.data.SubscriptionStats; @@ -56,7 +55,6 @@ import org.testng.annotations.Test; import java.io.File; -import java.io.FilenameFilter; import java.lang.reflect.Method; import java.net.URL; import java.util.Arrays; diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/functions/worker/PulsarFunctionStateTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/functions/worker/PulsarFunctionStateTest.java index e49b8e8b9f81a..809fca79c4634 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/functions/worker/PulsarFunctionStateTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/functions/worker/PulsarFunctionStateTest.java @@ -20,9 +20,6 @@ import com.google.common.collect.Lists; import com.google.common.collect.Sets; -import com.sun.net.httpserver.Headers; -import com.sun.net.httpserver.HttpServer; -import lombok.ToString; import org.apache.bookkeeper.test.PortManager; import org.apache.pulsar.broker.PulsarService; import org.apache.pulsar.broker.ServiceConfiguration; @@ -35,8 +32,6 @@ import org.apache.pulsar.client.admin.PulsarAdminException; import org.apache.pulsar.client.api.Authentication; import org.apache.pulsar.client.api.ClientBuilder; -import org.apache.pulsar.client.api.Consumer; -import org.apache.pulsar.client.api.Message; import org.apache.pulsar.client.api.Producer; import org.apache.pulsar.client.api.PulsarClient; import org.apache.pulsar.client.api.Schema; @@ -44,37 +39,22 @@ import org.apache.pulsar.common.functions.FunctionConfig; import org.apache.pulsar.common.functions.FunctionState; import org.apache.pulsar.common.functions.Utils; -import org.apache.pulsar.common.io.SinkConfig; -import org.apache.pulsar.common.io.SourceConfig; import org.apache.pulsar.common.policies.data.ClusterData; import org.apache.pulsar.common.policies.data.FunctionStats; -import org.apache.pulsar.common.policies.data.FunctionStatus; import org.apache.pulsar.common.policies.data.SubscriptionStats; import org.apache.pulsar.common.policies.data.TenantInfo; import org.apache.pulsar.common.util.FutureUtil; -import org.apache.pulsar.functions.instance.InstanceUtils; -import org.apache.pulsar.functions.utils.FunctionCommon; import org.apache.pulsar.zookeeper.LocalBookkeeperEnsemble; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import javax.ws.rs.core.Response; -import java.io.BufferedInputStream; -import java.io.BufferedReader; import java.io.File; -import java.io.FileInputStream; -import java.io.FilenameFilter; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStream; import java.lang.reflect.Method; -import java.net.HttpURLConnection; -import java.net.InetSocketAddress; import java.net.URL; import java.util.Arrays; import java.util.Collections; @@ -85,20 +65,14 @@ import java.util.Map; import java.util.Optional; import java.util.Set; -import java.util.TreeMap; -import java.util.concurrent.TimeUnit; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import static com.google.common.base.Preconditions.checkArgument; import static org.apache.commons.lang3.StringUtils.isNotBlank; import static org.apache.pulsar.broker.auth.MockedPulsarServiceBaseTest.retryStrategically; import static org.apache.pulsar.functions.utils.functioncache.FunctionCacheEntry.JAVA_INSTANCE_JAR_PROPERTY; import static org.mockito.Mockito.spy; import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotEquals; -import static org.testng.Assert.assertTrue; +import static org.testng.Assert.fail; /** * Test Pulsar function state @@ -364,27 +338,27 @@ public void testPulsarFunctionState() throws Exception { }, 5, 150); FunctionState state = admin.functions().getFunctionState(tenant, namespacePortion, functionName, "foo"); - Assert.assertEquals(state.getNumberValue().intValue(), 5); + assertEquals(state.getNumberValue().intValue(), 5); try { admin.functions().getFunctionState(tenant, namespacePortion, functionName, "bar"); - Assert.fail("Should have failed since key shouldn't exist"); + fail("Should have failed since key shouldn't exist"); } catch (PulsarAdminException e) { - Assert.assertEquals(e.getStatusCode(), Response.Status.NOT_FOUND.getStatusCode()); + assertEquals(e.getStatusCode(), Response.Status.NOT_FOUND.getStatusCode()); } FunctionState newState = new FunctionState("foobar", "foobarvalue", null, 0l, 0l); try { admin.functions().putFunctionState(tenant, namespacePortion, functionName + "bar", newState); - Assert.fail("Should have failed since function doesn't exist"); + fail("Should have failed since function doesn't exist"); } catch (PulsarAdminException e) { - Assert.assertEquals(e.getStatusCode(), Response.Status.NOT_FOUND.getStatusCode()); + assertEquals(e.getStatusCode(), Response.Status.NOT_FOUND.getStatusCode()); } // This succeeds because function name is correct admin.functions().putFunctionState(tenant, namespacePortion, functionName, newState); state = admin.functions().getFunctionState(tenant, namespacePortion, functionName, "foobar"); - Assert.assertTrue(state.getStringValue().equals("foobarvalue")); + assertEquals(state.getStringValue(), "foobarvalue"); // validate pulsar-sink consumer has consumed all messages and delivered to Pulsar sink but unacked messages // due to publish failure @@ -409,6 +383,6 @@ public void testPulsarFunctionState() throws Exception { File dir = new File(System.getProperty("java.io.tmpdir")); File[] foundFiles = dir.listFiles((dir1, name) -> name.startsWith("function")); - Assert.assertEquals(foundFiles.length, 0, "Temporary files left over: " + Arrays.asList(foundFiles)); + assertEquals(foundFiles.length, 0, "Temporary files left over: " + Arrays.asList(foundFiles)); } } \ No newline at end of file diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/io/PulsarFunctionAdminTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/io/PulsarFunctionAdminTest.java index a019e8b2105ec..ecfce1c738541 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/io/PulsarFunctionAdminTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/io/PulsarFunctionAdminTest.java @@ -25,7 +25,6 @@ import com.google.common.collect.Sets; import java.lang.reflect.Method; -import java.net.InetAddress; import java.net.URL; import java.util.HashMap; import java.util.HashSet; diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/io/PulsarFunctionE2ETest.java b/pulsar-broker/src/test/java/org/apache/pulsar/io/PulsarFunctionE2ETest.java index 9869f385dbd32..847958fc223b0 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/io/PulsarFunctionE2ETest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/io/PulsarFunctionE2ETest.java @@ -99,6 +99,7 @@ import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotEquals; +import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; /** @@ -435,7 +436,7 @@ private void testE2EPulsarFunction(String jarFilePathUrl) throws Exception { TopicStats topicStats = admin.topics().getStats(sinkTopic2); assertEquals(topicStats.publishers.size(), 2); - assertTrue(topicStats.publishers.get(0).metadata != null); + assertNotNull(topicStats.publishers.get(0).metadata); assertTrue(topicStats.publishers.get(0).metadata.containsKey("id")); assertEquals(topicStats.publishers.get(0).metadata.get("id"), String.format("%s/%s/%s", tenant, namespacePortion, functionName)); @@ -774,7 +775,7 @@ private void testPulsarSourceStats(String jarFilePathUrl) throws Exception { TopicStats sourceStats = admin.topics().getStats(sinkTopic2); assertEquals(sourceStats.publishers.size(), 1); - assertTrue(sourceStats.publishers.get(0).metadata != null); + assertNotNull(sourceStats.publishers.get(0).metadata); assertTrue(sourceStats.publishers.get(0).metadata.containsKey("id")); assertEquals(sourceStats.publishers.get(0).metadata.get("id"), String.format("%s/%s/%s", tenant, namespacePortion, sourceName)); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/websocket/proxy/ProxyAuthorizationTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/websocket/proxy/ProxyAuthorizationTest.java index 9df17c7175353..0a894ab9b8cc3 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/websocket/proxy/ProxyAuthorizationTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/websocket/proxy/ProxyAuthorizationTest.java @@ -20,7 +20,8 @@ import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; -import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertTrue; import java.util.EnumSet; import java.util.Optional; @@ -39,7 +40,6 @@ import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; -import com.google.common.collect.Lists; import com.google.common.collect.Sets; public class ProxyAuthorizationTest extends MockedPulsarServiceBaseTest { @@ -80,7 +80,7 @@ protected void cleanup() throws Exception { public void test() throws Exception { AuthorizationService auth = service.getAuthorizationService(); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "my-role", null), false); + assertFalse(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "my-role", null)); admin.clusters().createCluster(configClusterName, new ClusterData()); admin.tenants().createTenant("p1", new TenantInfo(Sets.newHashSet("role1"), Sets.newHashSet("c1"))); @@ -88,31 +88,31 @@ public void test() throws Exception { admin.namespaces().createNamespace("p1/c1/ns1"); waitForChange(); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "my-role", null), false); + assertFalse(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "my-role", null)); admin.namespaces().grantPermissionOnNamespace("p1/c1/ns1", "my-role", EnumSet.of(AuthAction.produce)); waitForChange(); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "my-role", null), true); - assertEquals(auth.canProduce(TopicName.get("persistent://p1/c1/ns1/ds1"), "my-role", null), true); + assertTrue(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "my-role", null)); + assertTrue(auth.canProduce(TopicName.get("persistent://p1/c1/ns1/ds1"), "my-role", null)); admin.topics().grantPermission("persistent://p1/c1/ns1/ds2", "other-role", EnumSet.of(AuthAction.consume)); waitForChange(); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds2"), "other-role", null), true); - assertEquals(auth.canProduce(TopicName.get("persistent://p1/c1/ns1/ds1"), "my-role", null), true); - assertEquals(auth.canProduce(TopicName.get("persistent://p1/c1/ns1/ds2"), "other-role", null), false); - assertEquals(auth.canConsume(TopicName.get("persistent://p1/c1/ns1/ds2"), "other-role", null, null), true); - assertEquals(auth.canConsume(TopicName.get("persistent://p1/c1/ns1/ds2"), "no-access-role", null, null), false); + assertTrue(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds2"), "other-role", null)); + assertTrue(auth.canProduce(TopicName.get("persistent://p1/c1/ns1/ds1"), "my-role", null)); + assertFalse(auth.canProduce(TopicName.get("persistent://p1/c1/ns1/ds2"), "other-role", null)); + assertTrue(auth.canConsume(TopicName.get("persistent://p1/c1/ns1/ds2"), "other-role", null, null)); + assertFalse(auth.canConsume(TopicName.get("persistent://p1/c1/ns1/ds2"), "no-access-role", null,null)); - assertEquals(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "no-access-role", null), false); + assertFalse(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "no-access-role", null)); admin.namespaces().grantPermissionOnNamespace("p1/c1/ns1", "my-role", EnumSet.allOf(AuthAction.class)); waitForChange(); - assertEquals(auth.canProduce(TopicName.get("persistent://p1/c1/ns1/ds1"), "my-role", null), true); - assertEquals(auth.canConsume(TopicName.get("persistent://p1/c1/ns1/ds1"), "my-role", null, null), true); + assertTrue(auth.canProduce(TopicName.get("persistent://p1/c1/ns1/ds1"), "my-role", null)); + assertTrue(auth.canConsume(TopicName.get("persistent://p1/c1/ns1/ds1"), "my-role", null, null)); admin.namespaces().deleteNamespace("p1/c1/ns1"); admin.tenants().deleteTenant("p1"); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/websocket/proxy/ProxyPublishConsumeTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/websocket/proxy/ProxyPublishConsumeTest.java index 2d5c9f2868d12..770790373c3b3 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/websocket/proxy/ProxyPublishConsumeTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/websocket/proxy/ProxyPublishConsumeTest.java @@ -21,6 +21,11 @@ import static java.util.concurrent.Executors.newFixedThreadPool; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; +import static org.testng.Assert.fail; import com.google.common.collect.Sets; import com.google.gson.Gson; @@ -62,7 +67,6 @@ import org.glassfish.jersey.logging.LoggingFeature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @@ -139,9 +143,9 @@ public void socketTest() throws Exception { log.info("Connecting to : {}", readUri); // let it connect - Assert.assertTrue(consumerFuture1.get().isOpen()); - Assert.assertTrue(consumerFuture2.get().isOpen()); - Assert.assertTrue(readerFuture.get().isOpen()); + assertTrue(consumerFuture1.get().isOpen()); + assertTrue(consumerFuture2.get().isOpen()); + assertTrue(readerFuture.get().isOpen()); // Also make sure subscriptions and reader are already created Thread.sleep(500); @@ -149,7 +153,7 @@ public void socketTest() throws Exception { ClientUpgradeRequest produceRequest = new ClientUpgradeRequest(); produceClient.start(); Future producerFuture = produceClient.connect(produceSocket, produceUri, produceRequest); - Assert.assertTrue(producerFuture.get().isOpen()); + assertTrue(producerFuture.get().isOpen()); int retry = 0; int maxRetry = 400; @@ -165,16 +169,16 @@ public void socketTest() throws Exception { } // if the subscription type is exclusive (default), either of the consumer sessions has already been closed - Assert.assertTrue(consumerFuture1.get().isOpen()); - Assert.assertTrue(consumerFuture2.get().isOpen()); - Assert.assertTrue(produceSocket.getBuffer().size() > 0); + assertTrue(consumerFuture1.get().isOpen()); + assertTrue(consumerFuture2.get().isOpen()); + assertTrue(produceSocket.getBuffer().size() > 0); if (consumeSocket1.getBuffer().size() > consumeSocket2.getBuffer().size()) { - Assert.assertEquals(produceSocket.getBuffer(), consumeSocket1.getBuffer()); + assertEquals(produceSocket.getBuffer(), consumeSocket1.getBuffer()); } else { - Assert.assertEquals(produceSocket.getBuffer(), consumeSocket2.getBuffer()); + assertEquals(produceSocket.getBuffer(), consumeSocket2.getBuffer()); } - Assert.assertEquals(produceSocket.getBuffer(), readSocket.getBuffer()); + assertEquals(produceSocket.getBuffer(), readSocket.getBuffer()); } finally { stopWebSocketClient(consumeClient1, consumeClient2, readClient, produceClient); } @@ -196,11 +200,11 @@ public void emptySubcriptionConsumerTest() throws Exception { ClientUpgradeRequest consumeRequest1 = new ClientUpgradeRequest(); Future consumerFuture1 = consumeClient1.connect(consumeSocket1, consumeUri, consumeRequest1); consumerFuture1.get(); - Assert.fail("should fail: empty subscription"); + fail("should fail: empty subscription"); } catch (Exception e) { // Expected - Assert.assertTrue(e.getCause() instanceof UpgradeException); - Assert.assertEquals(((UpgradeException) e.getCause()).getResponseStatusCode(), + assertTrue(e.getCause() instanceof UpgradeException); + assertEquals(((UpgradeException) e.getCause()).getResponseStatusCode(), HttpServletResponse.SC_BAD_REQUEST); } finally { stopWebSocketClient(consumeClient1); @@ -229,11 +233,11 @@ public void conflictingConsumerTest() throws Exception { ClientUpgradeRequest consumeRequest2 = new ClientUpgradeRequest(); Future consumerFuture2 = consumeClient2.connect(consumeSocket2, consumeUri, consumeRequest2); consumerFuture2.get(); - Assert.fail("should fail: conflicting subscription name"); + fail("should fail: conflicting subscription name"); } catch (Exception e) { // Expected - Assert.assertTrue(e.getCause() instanceof UpgradeException); - Assert.assertEquals(((UpgradeException) e.getCause()).getResponseStatusCode(), + assertTrue(e.getCause() instanceof UpgradeException); + assertEquals(((UpgradeException) e.getCause()).getResponseStatusCode(), HttpServletResponse.SC_CONFLICT); } finally { stopWebSocketClient(consumeClient2); @@ -265,11 +269,11 @@ public void conflictingProducerTest() throws Exception { ClientUpgradeRequest produceRequest2 = new ClientUpgradeRequest(); Future producerFuture2 = produceClient2.connect(produceSocket2, produceUri, produceRequest2); producerFuture2.get(); - Assert.fail("should fail: conflicting producer name"); + fail("should fail: conflicting producer name"); } catch (Exception e) { // Expected - Assert.assertTrue(e.getCause() instanceof UpgradeException); - Assert.assertEquals(((UpgradeException) e.getCause()).getResponseStatusCode(), + assertTrue(e.getCause() instanceof UpgradeException); + assertEquals(((UpgradeException) e.getCause()).getResponseStatusCode(), HttpServletResponse.SC_CONFLICT); } finally { stopWebSocketClient(produceClient2); @@ -332,11 +336,11 @@ public void producerBacklogQuotaExceededTest() throws Exception { ClientUpgradeRequest produceRequest = new ClientUpgradeRequest(); Future producerFuture = produceClient2.connect(produceSocket2, produceUri, produceRequest); producerFuture.get(); - Assert.fail("should fail: backlog quota exceeded"); + fail("should fail: backlog quota exceeded"); } catch (Exception e) { // Expected - Assert.assertTrue(e.getCause() instanceof UpgradeException); - Assert.assertEquals(((UpgradeException) e.getCause()).getResponseStatusCode(), + assertTrue(e.getCause() instanceof UpgradeException); + assertEquals(((UpgradeException) e.getCause()).getResponseStatusCode(), HttpServletResponse.SC_SERVICE_UNAVAILABLE); } finally { stopWebSocketClient(produceClient2); @@ -382,8 +386,8 @@ public void testProxyStats() throws Exception { Future readerFuture = readClient.connect(readSocket, readUri, readRequest); log.info("Connecting to : {}", readUri); - Assert.assertTrue(consumerFuture1.get().isOpen()); - Assert.assertTrue(readerFuture.get().isOpen()); + assertTrue(consumerFuture1.get().isOpen()); + assertTrue(readerFuture.get().isOpen()); Thread.sleep(500); @@ -392,7 +396,7 @@ public void testProxyStats() throws Exception { Future producerFuture = produceClient.connect(produceSocket, produceUri, produceRequest); // let it connect - Assert.assertTrue(producerFuture.get().isOpen()); + assertTrue(producerFuture.get().isOpen()); // sleep so, proxy can deliver few messages to consumers for stats int retry = 0; @@ -496,20 +500,20 @@ public void socketPullModeTest() throws Exception { log.info("Connecting to : {}", consumeUri); // let it connect - Assert.assertTrue(consumerFuture1.get().isOpen()); - Assert.assertTrue(consumerFuture2.get().isOpen()); + assertTrue(consumerFuture1.get().isOpen()); + assertTrue(consumerFuture2.get().isOpen()); ClientUpgradeRequest produceRequest = new ClientUpgradeRequest(); produceClient.start(); Future producerFuture = produceClient.connect(produceSocket, produceUri, produceRequest); - Assert.assertTrue(producerFuture.get().isOpen()); + assertTrue(producerFuture.get().isOpen()); produceSocket.sendMessage(100); Thread.sleep(500); // Verify no messages received despite production - Assert.assertEquals(consumeSocket1.getReceivedMessagesCount(), 0); - Assert.assertEquals(consumeSocket2.getReceivedMessagesCount(), 0); + assertEquals(consumeSocket1.getReceivedMessagesCount(), 0); + assertEquals(consumeSocket2.getReceivedMessagesCount(), 0); consumeSocket1.sendPermits(3); consumeSocket2.sendPermits(2); @@ -518,8 +522,8 @@ public void socketPullModeTest() throws Exception { Thread.sleep(500); - Assert.assertEquals(consumeSocket1.getReceivedMessagesCount(), 3); - Assert.assertEquals(consumeSocket2.getReceivedMessagesCount(), 6); + assertEquals(consumeSocket1.getReceivedMessagesCount(), 3); + assertEquals(consumeSocket2.getReceivedMessagesCount(), 6); } finally { stopWebSocketClient(consumeClient1, consumeClient2, produceClient); @@ -534,8 +538,8 @@ private void verifyTopicStat(Client client, String baseUrl, String topic) { String responseStr = response.readEntity(String.class); final Gson gson = new Gson(); final ProxyTopicStat data = gson.fromJson(responseStr, ProxyTopicStat.class); - Assert.assertFalse(data.producerStats.isEmpty()); - Assert.assertFalse(data.consumerStats.isEmpty()); + assertFalse(data.producerStats.isEmpty()); + assertFalse(data.consumerStats.isEmpty()); } private void verifyProxyMetrics(Client client, String baseUrl) { @@ -550,7 +554,7 @@ private void verifyProxyMetrics(Client client, String baseUrl) { final Gson gson = new Gson(); List data = gson.fromJson(responseStr, new TypeToken>() { }.getType()); - Assert.assertFalse(data.isEmpty()); + assertFalse(data.isEmpty()); // re-generate metrics service.getProxyStats().generate(); invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON); @@ -558,7 +562,7 @@ private void verifyProxyMetrics(Client client, String baseUrl) { responseStr = response.readEntity(String.class); data = gson.fromJson(responseStr, new TypeToken>() { }.getType()); - Assert.assertFalse(data.isEmpty()); + assertFalse(data.isEmpty()); } private void verifyProxyStats(Client client, String baseUrl, String topic) { @@ -573,21 +577,21 @@ private void verifyProxyStats(Client client, String baseUrl, String topic) { new TypeToken>() { }.getType()); // number of topic is loaded = 1 - Assert.assertEquals(data.size(), 1); + assertEquals(data.size(), 1); Entry entry = data.entrySet().iterator().next(); - Assert.assertEquals(entry.getKey(), "persistent://" + topic); + assertEquals(entry.getKey(), "persistent://" + topic); ProxyTopicStat stats = entry.getValue(); // number of consumers are connected = 2 (one is reader) - Assert.assertEquals(stats.consumerStats.size(), 2); + assertEquals(stats.consumerStats.size(), 2); ConsumerStats consumerStats = stats.consumerStats.iterator().next(); // Assert.assertTrue(consumerStats.numberOfMsgDelivered > 0); - Assert.assertNotNull(consumerStats.remoteConnection); + assertNotNull(consumerStats.remoteConnection); // number of producers are connected = 1 - Assert.assertEquals(stats.producerStats.size(), 1); + assertEquals(stats.producerStats.size(), 1); ProducerStats producerStats = stats.producerStats.iterator().next(); // Assert.assertTrue(producerStats.numberOfMsgPublished > 0); - Assert.assertNotNull(producerStats.remoteConnection); + assertNotNull(producerStats.remoteConnection); } private void stopWebSocketClient(WebSocketClient... clients) { diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/websocket/proxy/ProxyPublishConsumeTlsTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/websocket/proxy/ProxyPublishConsumeTlsTest.java index 86e27ab8dcc23..ed9d25b6d2249 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/websocket/proxy/ProxyPublishConsumeTlsTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/websocket/proxy/ProxyPublishConsumeTlsTest.java @@ -24,8 +24,6 @@ import java.net.URI; import java.security.GeneralSecurityException; -import java.util.HashMap; -import java.util.Map; import java.util.Optional; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; diff --git a/pulsar-client-auth-athenz/src/test/java/org/apache/pulsar/client/impl/auth/AuthenticationAthenzTest.java b/pulsar-client-auth-athenz/src/test/java/org/apache/pulsar/client/impl/auth/AuthenticationAthenzTest.java index 4419c1bc6641e..f6f696832ab86 100644 --- a/pulsar-client-auth-athenz/src/test/java/org/apache/pulsar/client/impl/auth/AuthenticationAthenzTest.java +++ b/pulsar-client-auth-athenz/src/test/java/org/apache/pulsar/client/impl/auth/AuthenticationAthenzTest.java @@ -22,7 +22,6 @@ import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import org.testng.annotations.Test; -import org.apache.pulsar.client.impl.auth.AuthenticationAthenz; import org.apache.pulsar.common.util.ObjectMapperFactory; import static org.apache.pulsar.common.util.Codec.encode; import org.testng.Assert; @@ -140,7 +139,7 @@ public void testLoadPrivateKeyBase64() throws Exception { Field field = authBase64.getClass().getDeclaredField("privateKey"); field.setAccessible(true); PrivateKey key = (PrivateKey) field.get(authBase64); - assertTrue(privateKey.equals(key)); + assertEquals(key, privateKey); } catch (Exception e) { Assert.fail(); } @@ -158,7 +157,7 @@ public void testLoadPrivateKeyUrlEncode() throws Exception { }); String privateKeyContents = new String(Files.readAllBytes(Paths.get(authParamsMap.get("privateKey")))); authParamsMap.put("privateKey", - "data:application/x-pem-file," + new String(encode(privateKeyContents).replace("+", "%20"))); + "data:application/x-pem-file," + encode(privateKeyContents).replace("+", "%20")); AuthenticationAthenz authEncode = new AuthenticationAthenz(); authEncode.configure(jsonMapper.writeValueAsString(authParamsMap)); @@ -167,7 +166,7 @@ public void testLoadPrivateKeyUrlEncode() throws Exception { Field field = authEncode.getClass().getDeclaredField("privateKey"); field.setAccessible(true); PrivateKey key = (PrivateKey) field.get(authEncode); - assertTrue(privateKey.equals(key)); + assertEquals(key, privateKey); } catch (Exception e) { Assert.fail(); } diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/api/ConsumerIdTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/api/ConsumerIdTest.java index 1a1301b85a8db..7ecf85abbe187 100644 --- a/pulsar-client/src/test/java/org/apache/pulsar/client/api/ConsumerIdTest.java +++ b/pulsar-client/src/test/java/org/apache/pulsar/client/api/ConsumerIdTest.java @@ -18,12 +18,14 @@ */ package org.apache.pulsar.client.api; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotEquals; + import org.testng.annotations.Test; import com.google.common.base.Objects; import org.apache.pulsar.client.impl.ConsumerId; -import org.testng.Assert; public class ConsumerIdTest { private static final String TOPIC_TEST = "my-topic-1"; @@ -33,19 +35,19 @@ public class ConsumerIdTest { @Test public void getTopicTest() { ConsumerId testConsumerId = new ConsumerId(TOPIC_TEST, SUBCRIBTION_TEST); - Assert.assertEquals(TOPIC_TEST, testConsumerId.getTopic()); + assertEquals(TOPIC_TEST, testConsumerId.getTopic()); } @Test public void getSubscribtionTest() { ConsumerId testConsumerId = new ConsumerId(TOPIC_TEST, SUBCRIBTION_TEST); - Assert.assertEquals(SUBCRIBTION_TEST, testConsumerId.getSubscription()); + assertEquals(SUBCRIBTION_TEST, testConsumerId.getSubscription()); } @Test public void hashCodeTest() { ConsumerId testConsumerId = new ConsumerId(TOPIC_TEST, SUBCRIBTION_TEST); - Assert.assertEquals(Objects.hashCode(TOPIC_TEST, SUBCRIBTION_TEST), testConsumerId.hashCode()); + assertEquals(Objects.hashCode(TOPIC_TEST, SUBCRIBTION_TEST), testConsumerId.hashCode()); } @Test @@ -54,11 +56,11 @@ public void equalTest() { ConsumerId testConsumerId2 = new ConsumerId(TOPIC_TEST, SUBCRIBTION_TEST); ConsumerId testConsumerId3 = new ConsumerId(TOPIC_TEST_2, SUBCRIBTION_TEST); - Assert.assertTrue(testConsumerId1.equals(testConsumerId2)); + assertEquals(testConsumerId2, testConsumerId1); - Assert.assertTrue(!testConsumerId1.equals(testConsumerId3)); + assertNotEquals(testConsumerId3, testConsumerId1); - Assert.assertTrue(!testConsumerId1.equals(new String())); + assertNotEquals("", testConsumerId1); } @Test @@ -67,8 +69,8 @@ public void compareToTest() { ConsumerId testConsumerId2 = new ConsumerId(TOPIC_TEST, SUBCRIBTION_TEST); ConsumerId testConsumerId3 = new ConsumerId(TOPIC_TEST_2, SUBCRIBTION_TEST); - Assert.assertEquals(0, testConsumerId1.compareTo(testConsumerId2)); - Assert.assertEquals(-1, testConsumerId1.compareTo(testConsumerId3)); + assertEquals(0, testConsumerId1.compareTo(testConsumerId2)); + assertEquals(-1, testConsumerId1.compareTo(testConsumerId3)); } } diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/BackoffTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/BackoffTest.java index 6bdb2136bc276..e8e353932e26d 100644 --- a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/BackoffTest.java +++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/BackoffTest.java @@ -42,7 +42,7 @@ boolean checkExactAndDecrementTimer(Backoff backoff, long t2) { @Test public void shouldBackoffTest() { // gives false - assertTrue(!Backoff.shouldBackoff(0L, TimeUnit.NANOSECONDS, 0)); + assertFalse(Backoff.shouldBackoff(0L, TimeUnit.NANOSECONDS, 0)); long currentTimestamp = System.nanoTime(); // gives true assertTrue(Backoff.shouldBackoff(currentTimestamp, TimeUnit.NANOSECONDS, 100)); @@ -78,7 +78,7 @@ public void firstBackoffTimerTest() { backoff.reset(); assertEquals(backoff.next(), 100); long diffBackOffTime = backoff.getFirstBackoffTimeInMillis() - firstBackOffTime; - assertTrue(diffBackOffTime == 300); + assertEquals(diffBackOffTime, 300); } @Test diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/BatchMessageIdImplTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/BatchMessageIdImplTest.java index af21fcfde6ec2..9e76a66b4d39a 100644 --- a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/BatchMessageIdImplTest.java +++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/BatchMessageIdImplTest.java @@ -18,8 +18,10 @@ */ package org.apache.pulsar.client.impl; -import org.apache.pulsar.client.impl.BatchMessageIdImpl; -import org.testng.Assert; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotEquals; +import static org.testng.Assert.assertTrue; + import org.testng.annotations.Test; public class BatchMessageIdImplTest { @@ -29,10 +31,9 @@ public void compareToTest() { BatchMessageIdImpl batchMsgId1 = new BatchMessageIdImpl(0, 0, 0, 0); BatchMessageIdImpl batchMsgId2 = new BatchMessageIdImpl(1, 1, 1, 1); - Assert.assertEquals(batchMsgId1.compareTo(batchMsgId2), -1); - Assert.assertEquals(batchMsgId2.compareTo(batchMsgId1), 1); - Assert.assertEquals(batchMsgId2.compareTo(batchMsgId2), 0); - + assertEquals(batchMsgId1.compareTo(batchMsgId2), -1); + assertEquals(batchMsgId2.compareTo(batchMsgId1), 1); + assertEquals(batchMsgId2.compareTo(batchMsgId2), 0); } @Test @@ -40,9 +41,8 @@ public void hashCodeTest() { BatchMessageIdImpl batchMsgId1 = new BatchMessageIdImpl(0, 0, 0, 0); BatchMessageIdImpl batchMsgId2 = new BatchMessageIdImpl(1, 1, 1, 1); - Assert.assertEquals(batchMsgId1.hashCode(), batchMsgId1.hashCode()); - Assert.assertTrue(batchMsgId1.hashCode() != batchMsgId2.hashCode()); - + assertEquals(batchMsgId1.hashCode(), batchMsgId1.hashCode()); + assertTrue(batchMsgId1.hashCode() != batchMsgId2.hashCode()); } @Test @@ -53,19 +53,19 @@ public void equalsTest() { BatchMessageIdImpl batchMsgId4 = new BatchMessageIdImpl(0, 0, 0, -1); MessageIdImpl msgId = new MessageIdImpl(0, 0, 0); - Assert.assertTrue(batchMsgId1.equals(batchMsgId1)); - Assert.assertFalse(batchMsgId1.equals(batchMsgId2)); - Assert.assertFalse(batchMsgId1.equals(batchMsgId3)); - Assert.assertFalse(batchMsgId1.equals(batchMsgId4)); - Assert.assertFalse(batchMsgId1.equals(msgId)); + assertEquals(batchMsgId1, batchMsgId1); + assertNotEquals(batchMsgId2, batchMsgId1); + assertNotEquals(batchMsgId3, batchMsgId1); + assertNotEquals(batchMsgId4, batchMsgId1); + assertNotEquals(msgId, batchMsgId1); - Assert.assertTrue(msgId.equals(msgId)); - Assert.assertFalse(msgId.equals(batchMsgId1)); - Assert.assertFalse(msgId.equals(batchMsgId2)); - Assert.assertFalse(msgId.equals(batchMsgId3)); - Assert.assertTrue(msgId.equals(batchMsgId4)); + assertEquals(msgId, msgId); + assertNotEquals(batchMsgId1, msgId); + assertNotEquals(batchMsgId2, msgId); + assertNotEquals(batchMsgId3, msgId); + assertEquals(batchMsgId4, msgId); - Assert.assertTrue(batchMsgId4.equals(msgId)); + assertEquals(msgId, batchMsgId4); } } diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/BuildersTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/BuildersTest.java index 0bb68c0ea44f3..2560d674a600f 100644 --- a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/BuildersTest.java +++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/BuildersTest.java @@ -19,6 +19,8 @@ package org.apache.pulsar.client.impl; import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotSame; import static org.testng.Assert.assertTrue; import java.lang.reflect.Field; @@ -36,11 +38,11 @@ public void clientBuilderTest() { ClientBuilderImpl clientBuilder = (ClientBuilderImpl) PulsarClient.builder().ioThreads(10) .maxNumberOfRejectedRequestPerConnection(200).serviceUrl("pulsar://service:6650"); - assertEquals(clientBuilder.conf.isUseTls(), false); + assertFalse(clientBuilder.conf.isUseTls()); assertEquals(clientBuilder.conf.getServiceUrl(), "pulsar://service:6650"); ClientBuilderImpl b2 = (ClientBuilderImpl) clientBuilder.clone(); - assertTrue(b2 != clientBuilder); + assertNotSame(b2, clientBuilder); b2.serviceUrl("pulsar://other-broker:6650"); @@ -51,27 +53,27 @@ public void clientBuilderTest() { @Test public void enableTlsTest() { ClientBuilderImpl builder = (ClientBuilderImpl)PulsarClient.builder().serviceUrl("pulsar://service:6650"); - assertEquals(builder.conf.isUseTls(), false); + assertFalse(builder.conf.isUseTls()); assertEquals(builder.conf.getServiceUrl(), "pulsar://service:6650"); builder = (ClientBuilderImpl)PulsarClient.builder().serviceUrl("http://service:6650"); - assertEquals(builder.conf.isUseTls(), false); + assertFalse(builder.conf.isUseTls()); assertEquals(builder.conf.getServiceUrl(), "http://service:6650"); builder = (ClientBuilderImpl)PulsarClient.builder().serviceUrl("pulsar+ssl://service:6650"); - assertEquals(builder.conf.isUseTls(), true); + assertTrue(builder.conf.isUseTls()); assertEquals(builder.conf.getServiceUrl(), "pulsar+ssl://service:6650"); builder = (ClientBuilderImpl)PulsarClient.builder().serviceUrl("https://service:6650"); - assertEquals(builder.conf.isUseTls(), true); + assertTrue(builder.conf.isUseTls()); assertEquals(builder.conf.getServiceUrl(), "https://service:6650"); builder = (ClientBuilderImpl)PulsarClient.builder().serviceUrl("pulsar://service:6650").enableTls(true); - assertEquals(builder.conf.isUseTls(), true); + assertTrue(builder.conf.isUseTls()); assertEquals(builder.conf.getServiceUrl(), "pulsar://service:6650"); builder = (ClientBuilderImpl)PulsarClient.builder().serviceUrl("pulsar+ssl://service:6650").enableTls(false); - assertEquals(builder.conf.isUseTls(), true); + assertTrue(builder.conf.isUseTls()); assertEquals(builder.conf.getServiceUrl(), "pulsar+ssl://service:6650"); } @@ -92,9 +94,7 @@ public void readerBuilderLoadConfTest() throws Exception { conf.setAccessible(true); Object obj = conf.get(builder); assertTrue(obj instanceof ReaderConfigurationData); - if (obj instanceof ReaderConfigurationData) { - assertEquals(((ReaderConfigurationData) obj).getTopicName(), topicName); - assertEquals(((ReaderConfigurationData) obj).getStartMessageId(), messageId); - } + assertEquals(((ReaderConfigurationData) obj).getTopicName(), topicName); + assertEquals(((ReaderConfigurationData) obj).getStartMessageId(), messageId); } } diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/ClientInitializationTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/ClientInitializationTest.java index 016929642139d..c99bdcb1b0b15 100644 --- a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/ClientInitializationTest.java +++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/ClientInitializationTest.java @@ -19,7 +19,8 @@ package org.apache.pulsar.client.impl; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; import org.apache.pulsar.client.api.Authentication; import org.apache.pulsar.client.api.PulsarClient; diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/ConnectionTimeoutTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/ConnectionTimeoutTest.java index f81ada0bc3c58..eac23c5211107 100644 --- a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/ConnectionTimeoutTest.java +++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/ConnectionTimeoutTest.java @@ -23,9 +23,7 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; -import org.apache.pulsar.client.api.Producer; import org.apache.pulsar.client.api.PulsarClient; -import org.apache.pulsar.client.api.PulsarClientException; import org.testng.Assert; import org.testng.annotations.Test; diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/MessageIdCompareToTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/MessageIdCompareToTest.java index d032c230041cb..86869172c64da 100644 --- a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/MessageIdCompareToTest.java +++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/MessageIdCompareToTest.java @@ -18,6 +18,7 @@ */ package org.apache.pulsar.client.impl; +import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import org.testng.annotations.Test; @@ -35,8 +36,8 @@ public void testEqual() { BatchMessageIdImpl batchMessageId1 = new BatchMessageIdImpl(234L, 345L, 456, 567); BatchMessageIdImpl batchMessageId2 = new BatchMessageIdImpl(234L, 345L, 456, 567); - assertTrue(messageIdImpl1.compareTo(messageIdImpl2) == 0, "Expected to be equal"); - assertTrue(batchMessageId1.compareTo(batchMessageId2) == 0, "Expected to be equal"); + assertEquals(messageIdImpl1.compareTo(messageIdImpl2), 0, "Expected to be equal"); + assertEquals(batchMessageId1.compareTo(batchMessageId2), 0, "Expected to be equal"); } @Test @@ -110,11 +111,11 @@ public void testCompareDifferentType() { BatchMessageIdImpl batchMessageId2 = new BatchMessageIdImpl(123L, 345L, 567, 789); BatchMessageIdImpl batchMessageId3 = new BatchMessageIdImpl(messageIdImpl); assertTrue(messageIdImpl.compareTo(batchMessageId1) > 0, "Expected to be greater than"); - assertTrue(messageIdImpl.compareTo(batchMessageId2) == 0, "Expected to be equal"); - assertTrue(messageIdImpl.compareTo(batchMessageId3) == 0, "Expected to be equal"); + assertEquals(messageIdImpl.compareTo(batchMessageId2), 0, "Expected to be equal"); + assertEquals(messageIdImpl.compareTo(batchMessageId3), 0, "Expected to be equal"); assertTrue(batchMessageId1.compareTo(messageIdImpl) < 0, "Expected to be less than"); assertTrue(batchMessageId2.compareTo(messageIdImpl) > 0, "Expected to be greater than"); - assertTrue(batchMessageId3.compareTo(messageIdImpl) == 0, "Expected to be equal"); + assertEquals(batchMessageId3.compareTo(messageIdImpl), 0, "Expected to be equal"); } @Test @@ -133,11 +134,11 @@ public void testMessageIdImplCompareToTopicMessageId() { "test-topic", new BatchMessageIdImpl(messageIdImpl)); assertTrue(messageIdImpl.compareTo(topicMessageId1) > 0, "Expected to be greater than"); - assertTrue(messageIdImpl.compareTo(topicMessageId2) == 0, "Expected to be equal"); - assertTrue(messageIdImpl.compareTo(topicMessageId3) == 0, "Expected to be equal"); + assertEquals(messageIdImpl.compareTo(topicMessageId2), 0, "Expected to be equal"); + assertEquals(messageIdImpl.compareTo(topicMessageId3), 0, "Expected to be equal"); assertTrue(topicMessageId1.compareTo(messageIdImpl) < 0, "Expected to be less than"); assertTrue(topicMessageId2.compareTo(messageIdImpl) > 0, "Expected to be greater than"); - assertTrue(topicMessageId3.compareTo(messageIdImpl) == 0, "Expected to be equal"); + assertEquals(topicMessageId3.compareTo(messageIdImpl), 0, "Expected to be equal"); } @Test @@ -156,11 +157,11 @@ public void testBatchMessageIdImplCompareToTopicMessageId() { assertTrue(messageIdImpl1.compareTo(topicMessageId1) > 0, "Expected to be greater than"); assertTrue(messageIdImpl1.compareTo(topicMessageId2) > 0, "Expected to be greater than"); assertTrue(messageIdImpl2.compareTo(topicMessageId2) > 0, "Expected to be greater than"); - assertTrue(messageIdImpl3.compareTo(topicMessageId2) == 0, "Expected to be equal"); + assertEquals(messageIdImpl3.compareTo(topicMessageId2), 0, "Expected to be equal"); assertTrue(topicMessageId1.compareTo(messageIdImpl1) < 0, "Expected to be less than"); - assertTrue(topicMessageId2.compareTo(messageIdImpl1) == 0, "Expected to be equal"); - assertTrue(topicMessageId2.compareTo(messageIdImpl2) == 0, "Expected to be equal"); - assertTrue(topicMessageId2.compareTo(messageIdImpl2) == 0, "Expected to be equal"); + assertEquals(topicMessageId2.compareTo(messageIdImpl1), 0, "Expected to be equal"); + assertEquals(topicMessageId2.compareTo(messageIdImpl2), 0, "Expected to be equal"); + assertEquals(topicMessageId2.compareTo(messageIdImpl2), 0, "Expected to be equal"); } } diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/TypedMessageBuilderImplTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/TypedMessageBuilderImplTest.java index 09fde0527fb3c..34d212f35aa7e 100644 --- a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/TypedMessageBuilderImplTest.java +++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/TypedMessageBuilderImplTest.java @@ -69,7 +69,7 @@ public void testDefaultValue() { KeyValue decodeKeyValue = keyValueSchema.decode(contentByte); assertEquals(decodeKeyValue.getKey(), foo); assertEquals(decodeKeyValue.getValue(), bar); - assertEquals(typedMessageBuilderImpl.hasKey(), false); + assertFalse(typedMessageBuilderImpl.hasKey()); } @Test @@ -97,7 +97,7 @@ public void testInlineValue() { KeyValue decodeKeyValue = keyValueSchema.decode(contentByte); assertEquals(decodeKeyValue.getKey(), foo); assertEquals(decodeKeyValue.getValue(), bar); - assertEquals(typedMessageBuilderImpl.hasKey(), false); + assertFalse(typedMessageBuilderImpl.hasKey()); } @Test @@ -122,7 +122,7 @@ public void testSeparatedValue() { ByteBuffer content = typedMessageBuilder.getContent(); byte[] contentByte = new byte[content.remaining()]; content.get(contentByte); - assertEquals(typedMessageBuilderImpl.hasKey(), true); + assertTrue(typedMessageBuilderImpl.hasKey()); assertEquals(typedMessageBuilderImpl.getKey(), Base64.getEncoder().encodeToString(fooSchema.encode(foo))); assertEquals(barSchema.decode(contentByte), bar); } diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/conf/ConfigurationDataUtilsTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/conf/ConfigurationDataUtilsTest.java index 3dcff77f7fd6c..b144f71e243a8 100644 --- a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/conf/ConfigurationDataUtilsTest.java +++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/conf/ConfigurationDataUtilsTest.java @@ -19,6 +19,8 @@ package org.apache.pulsar.client.impl.conf; import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; @@ -63,7 +65,7 @@ public void testLoadProducerConfigurationData() { confData.setBatcherBuilder(BatcherBuilder.DEFAULT); confData = ConfigurationDataUtils.loadData(config, confData, ProducerConfigurationData.class); assertEquals("test-producer", confData.getProducerName()); - assertEquals(false, confData.isBatchingEnabled()); + assertFalse(confData.isBatchingEnabled()); assertEquals(1234, confData.getBatchingMaxMessages()); } @@ -121,9 +123,9 @@ public void testConfigBuilder() throws PulsarClientException { clientConfig.setStatsIntervalSeconds(80); PulsarClientImpl pulsarClient = new PulsarClientImpl(clientConfig); - assertTrue(pulsarClient != null, "Pulsar client built using config should not be null"); + assertNotNull(pulsarClient, "Pulsar client built using config should not be null"); - assertTrue(pulsarClient.getConfiguration().getServiceUrl().equals("pulsar://unknown:6650")); + assertEquals(pulsarClient.getConfiguration().getServiceUrl(), "pulsar://unknown:6650"); assertEquals(pulsarClient.getConfiguration().getNumListenerThreads(), 1, "builder default not set properly"); assertEquals(pulsarClient.getConfiguration().getStatsIntervalSeconds(), 80, "builder default should overrite if set explicitly"); diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/DefaultSchemasTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/DefaultSchemasTest.java index 46516f0cdbb5e..84ad448f339d6 100644 --- a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/DefaultSchemasTest.java +++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/DefaultSchemasTest.java @@ -70,12 +70,12 @@ public void testStringSchema() throws Exception { String testString = "hello world"; byte[] testBytes = testString.getBytes(StandardCharsets.UTF_8); StringSchema stringSchema = new StringSchema(); - Assert.assertTrue(stringSchema.decode(testBytes).equals(testString)); + assertEquals(testString, stringSchema.decode(testBytes)); assertEquals(stringSchema.encode(testString), testBytes); byte[] bytes2 = testString.getBytes(StandardCharsets.UTF_16); StringSchema stringSchemaUtf16 = new StringSchema(StandardCharsets.UTF_16); - Assert.assertTrue(stringSchemaUtf16.decode(bytes2).equals(testString)); + assertEquals(testString, stringSchemaUtf16.decode(bytes2)); assertEquals(stringSchemaUtf16.encode(testString), bytes2); } diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/DoubleSchemaTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/DoubleSchemaTest.java index 0fbbca0929fbc..f5a1ab3928ea6 100644 --- a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/DoubleSchemaTest.java +++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/DoubleSchemaTest.java @@ -21,8 +21,6 @@ import org.testng.Assert; import org.testng.annotations.Test; -import java.util.Date; - public class DoubleSchemaTest { @Test diff --git a/pulsar-common/src/test/java/org/apache/pulsar/common/compression/CompressorCodecTest.java b/pulsar-common/src/test/java/org/apache/pulsar/common/compression/CompressorCodecTest.java index 515bb3c033942..540701a9fafaa 100644 --- a/pulsar-common/src/test/java/org/apache/pulsar/common/compression/CompressorCodecTest.java +++ b/pulsar-common/src/test/java/org/apache/pulsar/common/compression/CompressorCodecTest.java @@ -19,7 +19,7 @@ package org.apache.pulsar.common.compression; import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; +import static org.testng.Assert.assertSame; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; @@ -111,6 +111,6 @@ void testCodecProvider(CompressionType type) throws IOException { CompressionCodec codec2 = CompressionCodecProvider.getCompressionCodec(type); // A single provider instance must return the same codec instance every time - assertTrue(codec1 == codec2); + assertSame(codec1, codec2); } } diff --git a/pulsar-common/src/test/java/org/apache/pulsar/common/naming/NamespaceNameTest.java b/pulsar-common/src/test/java/org/apache/pulsar/common/naming/NamespaceNameTest.java index b91ee561a0720..32414bdd4b525 100644 --- a/pulsar-common/src/test/java/org/apache/pulsar/common/naming/NamespaceNameTest.java +++ b/pulsar-common/src/test/java/org/apache/pulsar/common/naming/NamespaceNameTest.java @@ -19,11 +19,11 @@ package org.apache.pulsar.common.naming; import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotEquals; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; -import org.apache.pulsar.common.naming.TopicDomain; -import org.apache.pulsar.common.naming.NamespaceName; import org.testng.annotations.Test; @Test @@ -92,7 +92,7 @@ void namespace() { "persistent://prop/cluster/ns/ds"); assertEquals(NamespaceName.get("prop/cluster/ns"), NamespaceName.get("prop/cluster/ns")); assertEquals(NamespaceName.get("prop/cluster/ns").toString(), "prop/cluster/ns"); - assertFalse(NamespaceName.get("prop/cluster/ns").equals("prop/cluster/ns")); + assertNotEquals(NamespaceName.get("prop/cluster/ns"), "prop/cluster/ns"); assertEquals(NamespaceName.get("prop", "cluster", "ns"), NamespaceName.get("prop/cluster/ns")); assertEquals(NamespaceName.get("prop/cluster/ns").getTenant(), "prop"); @@ -187,8 +187,8 @@ void testNewScheme() { NamespaceName ns = NamespaceName.get("my-tenant/my-namespace"); assertEquals(ns.getTenant(), "my-tenant"); assertEquals(ns.getLocalName(), "my-namespace"); - assertEquals(ns.isGlobal(), true); - assertEquals(ns.getCluster(), null); + assertTrue(ns.isGlobal()); + assertNull(ns.getCluster()); assertEquals(ns.getPersistentTopicName("my-topic"), "persistent://my-tenant/my-namespace/my-topic"); } } diff --git a/pulsar-common/src/test/java/org/apache/pulsar/common/naming/TopicNameTest.java b/pulsar-common/src/test/java/org/apache/pulsar/common/naming/TopicNameTest.java index f458c5dccdd25..f96b5954460c0 100644 --- a/pulsar-common/src/test/java/org/apache/pulsar/common/naming/TopicNameTest.java +++ b/pulsar-common/src/test/java/org/apache/pulsar/common/naming/TopicNameTest.java @@ -19,7 +19,8 @@ package org.apache.pulsar.common.naming; import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotEquals; +import static org.testng.Assert.assertNull; import static org.testng.Assert.fail; import org.apache.pulsar.common.util.Codec; @@ -52,8 +53,8 @@ void topic() { assertEquals(TopicName.get("persistent://tenant/cluster/namespace/topic").toString(), "persistent://tenant/cluster/namespace/topic"); - assertFalse(TopicName.get("persistent://tenant/cluster/namespace/topic") - .equals("persistent://tenant/cluster/namespace/topic")); + assertNotEquals(TopicName.get("persistent://tenant/cluster/namespace/topic"), + "persistent://tenant/cluster/namespace/topic"); assertEquals(TopicName.get("persistent://tenant/cluster/namespace/topic").getDomain(), TopicDomain.persistent); @@ -231,7 +232,7 @@ public void testTopicNameWithoutCluster() throws Exception { assertEquals(topicName.toString(), "persistent://tenant/namespace/topic"); assertEquals(topicName.getDomain(), TopicDomain.persistent); assertEquals(topicName.getTenant(), "tenant"); - assertEquals(topicName.getCluster(), null); + assertNull(topicName.getCluster()); assertEquals(topicName.getNamespacePortion(), "namespace"); assertEquals(topicName.getNamespace(), "tenant/namespace"); assertEquals(topicName.getLocalName(), "topic"); diff --git a/pulsar-common/src/test/java/org/apache/pulsar/common/policies/data/AutoFailoverPolicyDataTest.java b/pulsar-common/src/test/java/org/apache/pulsar/common/policies/data/AutoFailoverPolicyDataTest.java index 1bdd24968b094..91d54e315e5da 100644 --- a/pulsar-common/src/test/java/org/apache/pulsar/common/policies/data/AutoFailoverPolicyDataTest.java +++ b/pulsar-common/src/test/java/org/apache/pulsar/common/policies/data/AutoFailoverPolicyDataTest.java @@ -18,14 +18,12 @@ */ package org.apache.pulsar.common.policies.data; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotEquals; import static org.testng.Assert.fail; import java.util.HashMap; -import org.apache.pulsar.common.policies.data.AutoFailoverPolicyData; -import org.apache.pulsar.common.policies.data.AutoFailoverPolicyType; import org.testng.annotations.Test; public class AutoFailoverPolicyDataTest { @@ -48,9 +46,9 @@ public void testAutoFailoverPolicyData() { } catch (Exception e) { fail("Should not happen"); } - assertTrue(policy0.equals(policy1)); + assertEquals(policy1, policy0); policy1.parameters.put("min_limit", "5"); - assertFalse(policy0.equals(policy1)); - assertFalse(policy1.equals(new OldPolicies())); + assertNotEquals(policy1, policy0); + assertNotEquals(new OldPolicies(), policy1); } } diff --git a/pulsar-common/src/test/java/org/apache/pulsar/common/policies/data/ClusterDataTest.java b/pulsar-common/src/test/java/org/apache/pulsar/common/policies/data/ClusterDataTest.java index eb8c831c9a197..236d58823703c 100644 --- a/pulsar-common/src/test/java/org/apache/pulsar/common/policies/data/ClusterDataTest.java +++ b/pulsar-common/src/test/java/org/apache/pulsar/common/policies/data/ClusterDataTest.java @@ -19,9 +19,8 @@ package org.apache.pulsar.common.policies.data; import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotEquals; -import org.apache.pulsar.common.policies.data.ClusterData; import org.testng.annotations.Test; @Test @@ -40,26 +39,26 @@ void simple() { assertEquals(new ClusterData(s1), new ClusterData(s1)); assertEquals(new ClusterData(s1).getServiceUrl(), s1); - assertFalse(new ClusterData(s1).equals(new ClusterData())); - assertFalse(new ClusterData(s1).equals(new ClusterData(s2))); - assertFalse(new ClusterData(s1).equals(s1)); + assertNotEquals(new ClusterData(), new ClusterData(s1)); + assertNotEquals(new ClusterData(s2), new ClusterData(s1)); + assertNotEquals(s1, new ClusterData(s1)); assertEquals(new ClusterData(s1).hashCode(), new ClusterData(s1).hashCode()); - assertFalse(new ClusterData(s1).hashCode() == new ClusterData(s2).hashCode()); + assertNotEquals(new ClusterData(s2).hashCode(), new ClusterData(s1).hashCode()); - assertFalse(new ClusterData(s1).hashCode() == c.hashCode()); + assertNotEquals(c.hashCode(), new ClusterData(s1).hashCode()); assertEquals(new ClusterData(s1, s3), new ClusterData(s1, s3)); assertEquals(new ClusterData(s1, s3).getServiceUrl(), s1); assertEquals(new ClusterData(s1, s3).getServiceUrlTls(), s3); - assertFalse(new ClusterData(s1, s3).equals(new ClusterData())); - assertFalse(new ClusterData(s1, s3).equals(new ClusterData(s2, s4))); + assertNotEquals(new ClusterData(), new ClusterData(s1, s3)); + assertNotEquals(new ClusterData(s2, s4), new ClusterData(s1, s3)); assertEquals(new ClusterData(s1, s3).hashCode(), new ClusterData(s1, s3).hashCode()); - assertFalse(new ClusterData(s1, s3).hashCode() == new ClusterData(s2, s4).hashCode()); - assertFalse(new ClusterData(s1, s3).hashCode() == new ClusterData(s1, s4).hashCode()); + assertNotEquals(new ClusterData(s2, s4).hashCode(), new ClusterData(s1, s3).hashCode()); + assertNotEquals(new ClusterData(s1, s4).hashCode(), new ClusterData(s1, s3).hashCode()); } } diff --git a/pulsar-common/src/test/java/org/apache/pulsar/common/policies/data/ConsumerStatsTest.java b/pulsar-common/src/test/java/org/apache/pulsar/common/policies/data/ConsumerStatsTest.java index 731f52e75e96f..853597d21247d 100644 --- a/pulsar-common/src/test/java/org/apache/pulsar/common/policies/data/ConsumerStatsTest.java +++ b/pulsar-common/src/test/java/org/apache/pulsar/common/policies/data/ConsumerStatsTest.java @@ -18,7 +18,9 @@ */ package org.apache.pulsar.common.policies.data; -import org.testng.Assert; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNull; + import org.testng.annotations.Test; public class ConsumerStatsTest { @@ -26,40 +28,40 @@ public class ConsumerStatsTest { @Test public void testConsumerStats() { ConsumerStats stats = new ConsumerStats(); - Assert.assertNull(stats.getAddress()); - Assert.assertNull(stats.getClientVersion()); - Assert.assertNull(stats.getConnectedSince()); + assertNull(stats.getAddress()); + assertNull(stats.getClientVersion()); + assertNull(stats.getConnectedSince()); stats.setAddress("address"); - Assert.assertEquals(stats.getAddress(), "address"); + assertEquals(stats.getAddress(), "address"); stats.setAddress("address1"); - Assert.assertEquals(stats.getAddress(), "address1"); + assertEquals(stats.getAddress(), "address1"); stats.setClientVersion("version"); - Assert.assertEquals(stats.getClientVersion(), "version"); - Assert.assertEquals(stats.getAddress(), "address1"); + assertEquals(stats.getClientVersion(), "version"); + assertEquals(stats.getAddress(), "address1"); stats.setConnectedSince("connected"); - Assert.assertEquals(stats.getConnectedSince(), "connected"); - Assert.assertEquals(stats.getAddress(), "address1"); - Assert.assertEquals(stats.getClientVersion(), "version"); + assertEquals(stats.getConnectedSince(), "connected"); + assertEquals(stats.getAddress(), "address1"); + assertEquals(stats.getClientVersion(), "version"); stats.setAddress(null); - Assert.assertEquals(stats.getAddress(), null); + assertNull(stats.getAddress()); stats.setConnectedSince(""); - Assert.assertEquals(stats.getConnectedSince(), ""); + assertEquals(stats.getConnectedSince(), ""); stats.setClientVersion("version2"); - Assert.assertEquals(stats.getClientVersion(), "version2"); - - Assert.assertEquals(stats.getAddress(), null); + assertEquals(stats.getClientVersion(), "version2"); + + assertNull(stats.getAddress()); - Assert.assertEquals(stats.getClientVersion(), "version2"); + assertEquals(stats.getClientVersion(), "version2"); stats.setConnectedSince(null); stats.setClientVersion(null); - Assert.assertNull(stats.getConnectedSince()); - Assert.assertNull(stats.getClientVersion()); + assertNull(stats.getConnectedSince()); + assertNull(stats.getClientVersion()); } } diff --git a/pulsar-common/src/test/java/org/apache/pulsar/common/policies/data/LocalPolicesTest.java b/pulsar-common/src/test/java/org/apache/pulsar/common/policies/data/LocalPolicesTest.java index 6cba8cb0f6bf8..7b74b546c6699 100644 --- a/pulsar-common/src/test/java/org/apache/pulsar/common/policies/data/LocalPolicesTest.java +++ b/pulsar-common/src/test/java/org/apache/pulsar/common/policies/data/LocalPolicesTest.java @@ -18,13 +18,12 @@ */ package org.apache.pulsar.common.policies.data; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotEquals; import java.util.ArrayList; import java.util.List; -import org.apache.pulsar.common.policies.data.LocalPolicies; import org.testng.annotations.Test; public class LocalPolicesTest { @@ -44,10 +43,10 @@ public void testLocalPolices() { localPolicy0.bundles.setNumBundles(boundaries0.size() - 1); localPolicy1.bundles.setBoundaries(boundaries1); localPolicy1.bundles.setNumBundles(boundaries1.size() - 1); - assertFalse(localPolicy0.equals(localPolicy1)); - assertFalse(localPolicy0.equals(new OldPolicies())); + assertNotEquals(localPolicy1, localPolicy0); + assertNotEquals(new OldPolicies(), localPolicy0); localPolicy1.bundles.setBoundaries(boundaries0); localPolicy1.bundles.setNumBundles(boundaries0.size() - 1); - assertTrue(localPolicy0.equals(localPolicy1)); + assertEquals(localPolicy1, localPolicy0); } } diff --git a/pulsar-common/src/test/java/org/apache/pulsar/common/policies/data/NamespaceIsolationDataTest.java b/pulsar-common/src/test/java/org/apache/pulsar/common/policies/data/NamespaceIsolationDataTest.java index f9da92d391de4..8820d6dec878e 100644 --- a/pulsar-common/src/test/java/org/apache/pulsar/common/policies/data/NamespaceIsolationDataTest.java +++ b/pulsar-common/src/test/java/org/apache/pulsar/common/policies/data/NamespaceIsolationDataTest.java @@ -18,16 +18,13 @@ */ package org.apache.pulsar.common.policies.data; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotEquals; import static org.testng.Assert.fail; import java.util.ArrayList; import java.util.HashMap; -import org.apache.pulsar.common.policies.data.AutoFailoverPolicyData; -import org.apache.pulsar.common.policies.data.AutoFailoverPolicyType; -import org.apache.pulsar.common.policies.data.NamespaceIsolationData; import org.testng.annotations.Test; public class NamespaceIsolationDataTest { @@ -36,7 +33,7 @@ public class NamespaceIsolationDataTest { public void testNamespaceIsolationData() { NamespaceIsolationData n0 = new NamespaceIsolationData(); NamespaceIsolationData n1 = new NamespaceIsolationData(); - assertFalse(n0.equals(new OldPolicies())); + assertNotEquals(new OldPolicies(), n0); n0.namespaces = new ArrayList<>(); n0.primary = new ArrayList<>(); n0.secondary = new ArrayList<>(); @@ -47,12 +44,12 @@ public void testNamespaceIsolationData() { n0.secondary.add(String.format("s%d", i)); } - assertFalse(n0.equals(new NamespaceIsolationData())); + assertNotEquals(new NamespaceIsolationData(), n0); n1.namespaces = n0.namespaces; n1.primary = n0.primary; n1.secondary = n0.secondary; - assertTrue(n0.equals(n1)); + assertEquals(n1, n0); try { n0.validate(); diff --git a/pulsar-common/src/test/java/org/apache/pulsar/common/policies/data/PersistencePoliciesTest.java b/pulsar-common/src/test/java/org/apache/pulsar/common/policies/data/PersistencePoliciesTest.java index f487d6a7ca7cc..8755303da71c7 100644 --- a/pulsar-common/src/test/java/org/apache/pulsar/common/policies/data/PersistencePoliciesTest.java +++ b/pulsar-common/src/test/java/org/apache/pulsar/common/policies/data/PersistencePoliciesTest.java @@ -18,10 +18,9 @@ */ package org.apache.pulsar.common.policies.data; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotEquals; -import org.apache.pulsar.common.policies.data.PersistencePolicies; import org.testng.annotations.Test; public class PersistencePoliciesTest { @@ -30,7 +29,7 @@ public class PersistencePoliciesTest { public void testPersistencePolicies() { PersistencePolicies policy0 = new PersistencePolicies(); PersistencePolicies policy1 = new PersistencePolicies(); - assertTrue(policy0.equals(policy1)); - assertFalse(policy0.equals(new OldPolicies())); + assertEquals(policy1, policy0); + assertNotEquals(new OldPolicies(), policy0); } } diff --git a/pulsar-common/src/test/java/org/apache/pulsar/common/policies/data/PoliciesDataTest.java b/pulsar-common/src/test/java/org/apache/pulsar/common/policies/data/PoliciesDataTest.java index f88fd9e0f7754..9be66d66d9476 100644 --- a/pulsar-common/src/test/java/org/apache/pulsar/common/policies/data/PoliciesDataTest.java +++ b/pulsar-common/src/test/java/org/apache/pulsar/common/policies/data/PoliciesDataTest.java @@ -19,7 +19,7 @@ package org.apache.pulsar.common.policies.data; import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; +import static org.testng.Assert.assertNotEquals; import java.io.IOException; import java.util.EnumSet; @@ -49,15 +49,15 @@ void policies() { policies.auth_policies.namespace_auth.put("my-role", EnumSet.of(AuthAction.consume)); - assertTrue(!policies.equals(new Policies())); - assertTrue(!policies.equals(new Object())); + assertNotEquals(new Policies(), policies); + assertNotEquals(new Object(), policies); policies.auth_policies.namespace_auth.clear(); Map> permissions = Maps.newTreeMap(); permissions.put("my-role", EnumSet.of(AuthAction.consume)); policies.auth_policies.destination_auth.put("persistent://my-dest", permissions); - assertTrue(!policies.equals(new Policies())); + assertNotEquals(new Policies(), policies); } @Test @@ -67,9 +67,9 @@ void propertyAdmin() { pa1.setAllowedClusters(Sets.newHashSet("use", "usw")); assertEquals(pa1, new TenantInfo(Sets.newHashSet("role1", "role2"), Sets.newHashSet("use", "usw"))); - assertTrue(!pa1.equals(new Object())); - assertTrue(!pa1.equals(new TenantInfo())); - assertTrue(!pa1.equals(new TenantInfo(Sets.newHashSet("role1", "role3"), Sets.newHashSet("usc")))); + assertNotEquals(new Object(), pa1); + assertNotEquals(new TenantInfo(), pa1); + assertNotEquals(new TenantInfo(Sets.newHashSet("role1", "role3"), Sets.newHashSet("usc")), pa1); assertEquals(pa1.getAdminRoles(), Lists.newArrayList("role1", "role2")); } diff --git a/pulsar-common/src/test/java/org/apache/pulsar/common/policies/data/PublisherStatsTest.java b/pulsar-common/src/test/java/org/apache/pulsar/common/policies/data/PublisherStatsTest.java index 2ab08d4ce018a..2bc4dd75ca4fd 100644 --- a/pulsar-common/src/test/java/org/apache/pulsar/common/policies/data/PublisherStatsTest.java +++ b/pulsar-common/src/test/java/org/apache/pulsar/common/policies/data/PublisherStatsTest.java @@ -18,7 +18,9 @@ */ package org.apache.pulsar.common.policies.data; -import org.testng.Assert; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNull; + import org.testng.annotations.Test; public class PublisherStatsTest { @@ -26,51 +28,51 @@ public class PublisherStatsTest { @Test public void testPublisherStats() { PublisherStats stats = new PublisherStats(); - Assert.assertNull(stats.getAddress()); - Assert.assertNull(stats.getClientVersion()); - Assert.assertNull(stats.getConnectedSince()); - Assert.assertNull(stats.getProducerName()); + assertNull(stats.getAddress()); + assertNull(stats.getClientVersion()); + assertNull(stats.getConnectedSince()); + assertNull(stats.getProducerName()); stats.setAddress("address"); - Assert.assertEquals(stats.getAddress(), "address"); + assertEquals(stats.getAddress(), "address"); stats.setAddress("address1"); - Assert.assertEquals(stats.getAddress(), "address1"); + assertEquals(stats.getAddress(), "address1"); stats.setClientVersion("version"); - Assert.assertEquals(stats.getClientVersion(), "version"); - Assert.assertEquals(stats.getAddress(), "address1"); + assertEquals(stats.getClientVersion(), "version"); + assertEquals(stats.getAddress(), "address1"); stats.setConnectedSince("connected"); - Assert.assertEquals(stats.getConnectedSince(), "connected"); - Assert.assertEquals(stats.getAddress(), "address1"); - Assert.assertEquals(stats.getClientVersion(), "version"); + assertEquals(stats.getConnectedSince(), "connected"); + assertEquals(stats.getAddress(), "address1"); + assertEquals(stats.getClientVersion(), "version"); stats.setProducerName("producer"); - Assert.assertEquals(stats.getProducerName(), "producer"); - Assert.assertEquals(stats.getConnectedSince(), "connected"); - Assert.assertEquals(stats.getAddress(), "address1"); - Assert.assertEquals(stats.getClientVersion(), "version"); + assertEquals(stats.getProducerName(), "producer"); + assertEquals(stats.getConnectedSince(), "connected"); + assertEquals(stats.getAddress(), "address1"); + assertEquals(stats.getClientVersion(), "version"); stats.setAddress(null); - Assert.assertEquals(stats.getAddress(), null); + assertNull(stats.getAddress()); stats.setConnectedSince(""); - Assert.assertEquals(stats.getConnectedSince(), ""); + assertEquals(stats.getConnectedSince(), ""); stats.setClientVersion("version2"); - Assert.assertEquals(stats.getClientVersion(), "version2"); + assertEquals(stats.getClientVersion(), "version2"); stats.setProducerName(null); - Assert.assertEquals(stats.getProducerName(), null); - - Assert.assertEquals(stats.getAddress(), null); + assertNull(stats.getProducerName()); + + assertNull(stats.getAddress()); - Assert.assertEquals(stats.getClientVersion(), "version2"); + assertEquals(stats.getClientVersion(), "version2"); stats.setConnectedSince(null); stats.setClientVersion(null); - Assert.assertNull(stats.getConnectedSince()); - Assert.assertNull(stats.getClientVersion()); + assertNull(stats.getConnectedSince()); + assertNull(stats.getClientVersion()); } @Test @@ -89,9 +91,9 @@ public void testPublisherStatsAggregation() { target.add(stats1); target.add(stats2); - Assert.assertEquals(target.msgRateIn, 2.0); - Assert.assertEquals(target.msgThroughputIn, 3.0); - Assert.assertEquals(target.averageMsgSize, 2.0); + assertEquals(target.msgRateIn, 2.0); + assertEquals(target.msgThroughputIn, 3.0); + assertEquals(target.averageMsgSize, 2.0); } } diff --git a/pulsar-common/src/test/java/org/apache/pulsar/common/policies/data/RetentionPolicesTest.java b/pulsar-common/src/test/java/org/apache/pulsar/common/policies/data/RetentionPolicesTest.java index a22ca2182b1e6..8ad34352f60f0 100644 --- a/pulsar-common/src/test/java/org/apache/pulsar/common/policies/data/RetentionPolicesTest.java +++ b/pulsar-common/src/test/java/org/apache/pulsar/common/policies/data/RetentionPolicesTest.java @@ -18,8 +18,9 @@ */ package org.apache.pulsar.common.policies.data; -import org.apache.pulsar.common.policies.data.RetentionPolicies; -import org.testng.Assert; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotEquals; + import org.testng.annotations.Test; public class RetentionPolicesTest { @@ -28,9 +29,9 @@ public class RetentionPolicesTest { public void testRetentionPolices() { RetentionPolicies retentionPolicy0 = new RetentionPolicies(); RetentionPolicies retentionPolicy1 = new RetentionPolicies(1, 100); - Assert.assertFalse(retentionPolicy0.equals(null)); - Assert.assertTrue(retentionPolicy0.equals(retentionPolicy0)); - Assert.assertFalse(retentionPolicy0.hashCode() == retentionPolicy1.hashCode()); - Assert.assertFalse(retentionPolicy0.toString().equals(retentionPolicy1.toString())); + assertNotEquals(retentionPolicy0, null); + assertEquals(retentionPolicy0, retentionPolicy0); + assertNotEquals(retentionPolicy1.hashCode(), retentionPolicy0.hashCode()); + assertNotEquals(retentionPolicy1.toString(), retentionPolicy0.toString()); } } diff --git a/pulsar-common/src/test/java/org/apache/pulsar/common/policies/impl/MinAvailablePolicyTest.java b/pulsar-common/src/test/java/org/apache/pulsar/common/policies/impl/MinAvailablePolicyTest.java index c2122ddedb4af..de7370bb8c690 100644 --- a/pulsar-common/src/test/java/org/apache/pulsar/common/policies/impl/MinAvailablePolicyTest.java +++ b/pulsar-common/src/test/java/org/apache/pulsar/common/policies/impl/MinAvailablePolicyTest.java @@ -18,9 +18,11 @@ */ package org.apache.pulsar.common.policies.impl; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotEquals; +import static org.testng.Assert.assertTrue; + import org.apache.pulsar.common.policies.data.OldPolicies; -import org.apache.pulsar.common.policies.impl.MinAvailablePolicy; -import org.testng.Assert; import org.testng.annotations.Test; public class MinAvailablePolicyTest { @@ -28,8 +30,8 @@ public class MinAvailablePolicyTest { @Test public void testMinAvailablePolicty() { MinAvailablePolicy m = new MinAvailablePolicy(3, 10); - Assert.assertFalse(m.equals(new OldPolicies())); - Assert.assertFalse(m.shouldFailoverToSecondary(15)); - Assert.assertTrue(m.shouldFailoverToSecondary(2)); + assertNotEquals(new OldPolicies(), m); + assertFalse(m.shouldFailoverToSecondary(15)); + assertTrue(m.shouldFailoverToSecondary(2)); } } diff --git a/pulsar-common/src/test/java/org/apache/pulsar/common/policies/impl/NamespaceIsolationPoliciesTest.java b/pulsar-common/src/test/java/org/apache/pulsar/common/policies/impl/NamespaceIsolationPoliciesTest.java index a8cbd7bff76aa..aa11caaa08364 100644 --- a/pulsar-common/src/test/java/org/apache/pulsar/common/policies/impl/NamespaceIsolationPoliciesTest.java +++ b/pulsar-common/src/test/java/org/apache/pulsar/common/policies/impl/NamespaceIsolationPoliciesTest.java @@ -19,7 +19,10 @@ package org.apache.pulsar.common.policies.impl; import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotEquals; import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import java.util.ArrayList; @@ -38,8 +41,6 @@ import org.apache.pulsar.common.policies.data.AutoFailoverPolicyType; import org.apache.pulsar.common.policies.data.BrokerStatus; import org.apache.pulsar.common.policies.data.NamespaceIsolationData; -import org.apache.pulsar.common.policies.impl.NamespaceIsolationPolicies; -import org.apache.pulsar.common.policies.impl.NamespaceIsolationPolicyImpl; import org.apache.pulsar.common.util.ObjectMapperFactory; import org.testng.annotations.Test; @@ -68,15 +69,15 @@ public void testJsonSerialization() throws Exception { assertEquals(new String(outJson), this.defaultJson); NamespaceIsolationData nsPolicyData = new NamespaceIsolationData(); - nsPolicyData.namespaces = new ArrayList(); + nsPolicyData.namespaces = new ArrayList<>(); nsPolicyData.namespaces.add("other/use/other.*"); - nsPolicyData.primary = new ArrayList(); + nsPolicyData.primary = new ArrayList<>(); nsPolicyData.primary.add("prod1-broker[4-6].messaging.use.example.com"); - nsPolicyData.secondary = new ArrayList(); + nsPolicyData.secondary = new ArrayList<>(); nsPolicyData.secondary.add("prod1-broker.*.messaging.use.example.com"); nsPolicyData.auto_failover_policy = new AutoFailoverPolicyData(); nsPolicyData.auto_failover_policy.policy_type = AutoFailoverPolicyType.min_available; - nsPolicyData.auto_failover_policy.parameters = new HashMap(); + nsPolicyData.auto_failover_policy.parameters = new HashMap<>(); nsPolicyData.auto_failover_policy.parameters.put("min_limit", "1"); nsPolicyData.auto_failover_policy.parameters.put("usage_threshold", "100"); policies.setPolicy("otherPolicy", nsPolicyData); @@ -101,7 +102,7 @@ public void testDefaultConstructor() throws Exception { public void testDeletePolicy() throws Exception { NamespaceIsolationPolicies policies = this.getDefaultTestPolicies(); policies.deletePolicy("non-existing-policy"); - assertTrue(!policies.getPolicies().isEmpty()); + assertFalse(policies.getPolicies().isEmpty()); policies.deletePolicy("policy1"); assertTrue(policies.getPolicies().isEmpty()); @@ -111,7 +112,7 @@ public void testDeletePolicy() throws Exception { public void testGetNamespaceIsolationPolicyByName() throws Exception { NamespaceIsolationPolicies policies = this.getDefaultTestPolicies(); NamespaceIsolationPolicy nsPolicy = policies.getPolicyByName("non-existing-policy"); - assertTrue(nsPolicy == null); + assertNull(nsPolicy); nsPolicy = policies.getPolicyByName("policy1"); assertNotNull(nsPolicy); assertEquals(new NamespaceIsolationPolicyImpl(policies.getPolicies().get("policy1")), nsPolicy); @@ -121,7 +122,7 @@ public void testGetNamespaceIsolationPolicyByName() throws Exception { public void testGetNamespaceIsolationPolicyByNamespace() throws Exception { NamespaceIsolationPolicies policies = this.getDefaultTestPolicies(); NamespaceIsolationPolicy nsPolicy = policies.getPolicyByNamespace(NamespaceName.get("no/such/namespace")); - assertTrue(nsPolicy == null); + assertNull(nsPolicy); nsPolicy = policies.getPolicyByNamespace(NamespaceName.get("pulsar/use/testns-1")); assertNotNull(nsPolicy); assertEquals(new NamespaceIsolationPolicyImpl(policies.getPolicies().get("policy1")), nsPolicy); @@ -140,7 +141,7 @@ public void testSetPolicy() throws Exception { assertEquals(policies.getPolicies().size(), 2); assertEquals(policies.getPolicyByName(newPolicyName), new NamespaceIsolationPolicyImpl(nsPolicyData)); - assertTrue(!policies.getPolicyByName(newPolicyName).equals(policies.getPolicyByName("policy1"))); + assertNotEquals(policies.getPolicyByName("policy1"), policies.getPolicyByName(newPolicyName)); assertEquals(policies.getPolicyByNamespace(NamespaceName.get("pulsar/use/TESTNS.1")), new NamespaceIsolationPolicyImpl(nsPolicyData)); } @@ -148,7 +149,7 @@ public void testSetPolicy() throws Exception { @SuppressWarnings("unchecked") private NamespaceIsolationPolicies getDefaultTestPolicies() throws Exception { ObjectMapper jsonMapper = ObjectMapperFactory.create(); - return new NamespaceIsolationPolicies((Map) jsonMapper + return new NamespaceIsolationPolicies(jsonMapper .readValue(this.defaultJson.getBytes(), new TypeReference>() { })); } @@ -167,17 +168,17 @@ public void testBrokerAssignment() throws Exception { assertEquals(primaryCandidates.size(), 1); assertEquals(secondaryCandidates.size(), 0); assertEquals(sharedCandidates.size(), 0); - assertTrue(primaryCandidates.first().equals(primary)); + assertEquals(primary, primaryCandidates.first()); policies.assignBroker(ns, secondary, primaryCandidates, secondaryCandidates, sharedCandidates); assertEquals(primaryCandidates.size(), 1); assertEquals(secondaryCandidates.size(), 1); assertEquals(sharedCandidates.size(), 0); - assertTrue(secondaryCandidates.first().equals(secondary)); + assertEquals(secondary, secondaryCandidates.first()); policies.assignBroker(NamespaceName.get("pulsar/use1/testns-1"), shared, primaryCandidates, secondaryCandidates, sharedCandidates); assertEquals(primaryCandidates.size(), 1); assertEquals(secondaryCandidates.size(), 1); assertEquals(sharedCandidates.size(), 1); - assertTrue(sharedCandidates.first().equals(shared)); + assertEquals(shared, sharedCandidates.first()); } } diff --git a/pulsar-common/src/test/java/org/apache/pulsar/common/policies/impl/NamespaceIsolationPolicyImplTest.java b/pulsar-common/src/test/java/org/apache/pulsar/common/policies/impl/NamespaceIsolationPolicyImplTest.java index 1aee82f016962..986fd8f35f193 100644 --- a/pulsar-common/src/test/java/org/apache/pulsar/common/policies/impl/NamespaceIsolationPolicyImplTest.java +++ b/pulsar-common/src/test/java/org/apache/pulsar/common/policies/impl/NamespaceIsolationPolicyImplTest.java @@ -19,6 +19,8 @@ package org.apache.pulsar.common.policies.impl; import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotEquals; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; @@ -37,7 +39,6 @@ import org.apache.pulsar.common.policies.data.BrokerStatus; import org.apache.pulsar.common.policies.data.NamespaceIsolationData; import org.apache.pulsar.common.policies.data.OldPolicies; -import org.apache.pulsar.common.policies.impl.NamespaceIsolationPolicyImpl; import org.apache.pulsar.common.util.ObjectMapperFactory; import org.testng.annotations.Test; @@ -55,23 +56,23 @@ private NamespaceIsolationPolicyImpl getDefaultPolicy() throws Exception { public void testConstructor() throws Exception { NamespaceIsolationPolicyImpl defaultPolicy = this.getDefaultPolicy(); NamespaceIsolationData policyData = new NamespaceIsolationData(); - policyData.namespaces = new ArrayList(); + policyData.namespaces = new ArrayList<>(); policyData.namespaces.add("pulsar/use/test.*"); - policyData.primary = new ArrayList(); + policyData.primary = new ArrayList<>(); policyData.primary.add("prod1-broker[1-3].messaging.use.example.com"); - policyData.secondary = new ArrayList(); + policyData.secondary = new ArrayList<>(); policyData.secondary.add("prod1-broker.*.use.example.com"); policyData.auto_failover_policy = new AutoFailoverPolicyData(); policyData.auto_failover_policy.policy_type = AutoFailoverPolicyType.min_available; - policyData.auto_failover_policy.parameters = new HashMap(); + policyData.auto_failover_policy.parameters = new HashMap<>(); policyData.auto_failover_policy.parameters.put("min_limit", "3"); policyData.auto_failover_policy.parameters.put("usage_threshold", "90"); NamespaceIsolationPolicyImpl newPolicy = new NamespaceIsolationPolicyImpl(policyData); - assertTrue(defaultPolicy.equals(newPolicy)); + assertEquals(newPolicy, defaultPolicy); policyData.auto_failover_policy.parameters.put("usage_threshold", "80"); newPolicy = new NamespaceIsolationPolicyImpl(policyData); - assertTrue(!defaultPolicy.equals(newPolicy)); - assertTrue(!newPolicy.equals(new OldPolicies())); + assertNotEquals(newPolicy, defaultPolicy); + assertNotEquals(new OldPolicies(), newPolicy); } @Test @@ -92,9 +93,9 @@ public void testGetSecondaryBrokers() throws Exception { public void testIsPrimaryOrSecondaryBroker() throws Exception { NamespaceIsolationPolicyImpl defaultPolicy = this.getDefaultPolicy(); assertTrue(defaultPolicy.isPrimaryBroker("prod1-broker2.messaging.use.example.com")); - assertTrue(!defaultPolicy.isPrimaryBroker("prod1-broker5.messaging.use.example.com")); + assertFalse(defaultPolicy.isPrimaryBroker("prod1-broker5.messaging.use.example.com")); assertTrue(defaultPolicy.isSecondaryBroker("prod1-broker5.messaging.use.example.com")); - assertTrue(!defaultPolicy.isSecondaryBroker("broker-X.messaging.use.example.com")); + assertFalse(defaultPolicy.isSecondaryBroker("broker-X.messaging.use.example.com")); } @Test @@ -140,24 +141,23 @@ public void testFindBrokers() throws Exception { @Test public void testShouldFailover() throws Exception { NamespaceIsolationPolicyImpl defaultPolicy = this.getDefaultPolicy(); - SortedSet brokerStatus = new TreeSet(); + SortedSet brokerStatus = new TreeSet<>(); for (int i = 0; i < 10; i++) { BrokerStatus status = new BrokerStatus(String.format("broker-%d", i), true, i * 10); brokerStatus.add(status); } - assertEquals(defaultPolicy.shouldFailover(brokerStatus), false); - List objList = new ArrayList(); - objList.addAll(brokerStatus); + assertFalse(defaultPolicy.shouldFailover(brokerStatus)); + List objList = new ArrayList<>(brokerStatus); for (int i = 0; i < 8; i++) { objList.get(i).setActive(false); } - assertEquals(defaultPolicy.shouldFailover(brokerStatus), true); + assertTrue(defaultPolicy.shouldFailover(brokerStatus)); objList.get(7).setActive(true); - assertEquals(defaultPolicy.shouldFailover(brokerStatus), true); + assertTrue(defaultPolicy.shouldFailover(brokerStatus)); objList.get(9).setLoadFactor(80); - assertEquals(defaultPolicy.shouldFailover(brokerStatus), false); + assertFalse(defaultPolicy.shouldFailover(brokerStatus)); - brokerStatus = new TreeSet(); + brokerStatus = new TreeSet<>(); for (int i = 0; i < 5; i++) { BrokerStatus status = new BrokerStatus(String.format("broker-%d", 2 * i), true, i * 20); brokerStatus.add(status); @@ -170,8 +170,8 @@ public void testShouldFailover() throws Exception { @Test public void testGetAvailablePrimaryBrokers() throws Exception { NamespaceIsolationPolicyImpl defaultPolicy = this.getDefaultPolicy(); - SortedSet brokerStatus = new TreeSet(); - SortedSet expectedAvailablePrimaries = new TreeSet(); + SortedSet brokerStatus = new TreeSet<>(); + SortedSet expectedAvailablePrimaries = new TreeSet<>(); for (int i = 0; i < 10; i++) { BrokerStatus status = new BrokerStatus(String.format("prod1-broker%d.messaging.use.example.com", i), i % 2 == 0, i * 10); diff --git a/pulsar-common/src/test/java/org/apache/pulsar/common/util/RateLimiterTest.java b/pulsar-common/src/test/java/org/apache/pulsar/common/util/RateLimiterTest.java index dc36d793b5250..b6fe780688f54 100644 --- a/pulsar-common/src/test/java/org/apache/pulsar/common/util/RateLimiterTest.java +++ b/pulsar-common/src/test/java/org/apache/pulsar/common/util/RateLimiterTest.java @@ -65,7 +65,7 @@ public void testAcquireBlock() throws Exception { final long rateTimeMSec = 1000; RateLimiter rate = new RateLimiter(1, rateTimeMSec, TimeUnit.MILLISECONDS); rate.acquire(); - assertTrue(rate.getAvailablePermits() == 0); + assertEquals(rate.getAvailablePermits(), 0); long start = System.currentTimeMillis(); rate.acquire(); long end = System.currentTimeMillis(); @@ -85,7 +85,7 @@ public void testAcquire() throws Exception { } long end = System.currentTimeMillis(); assertTrue((end - start) < rateTimeMSec); - assertTrue(rate.getAvailablePermits() == 0); + assertEquals(rate.getAvailablePermits(), 0); rate.close(); } @@ -101,7 +101,7 @@ public void testMultipleAcquire() throws Exception { } long end = System.currentTimeMillis(); assertTrue((end - start) < rateTimeMSec); - assertTrue(rate.getAvailablePermits() == 0); + assertEquals(rate.getAvailablePermits(), 0); rate.close(); } @@ -111,7 +111,7 @@ public void testTryAcquireNoPermits() throws Exception { RateLimiter rate = new RateLimiter(1, rateTimeMSec, TimeUnit.MILLISECONDS); assertTrue(rate.tryAcquire()); assertFalse(rate.tryAcquire()); - assertTrue(rate.getAvailablePermits() == 0); + assertEquals(rate.getAvailablePermits(), 0); rate.close(); } @@ -123,7 +123,7 @@ public void testTryAcquire() throws Exception { for (int i = 0; i < permits; i++) { rate.tryAcquire(); } - assertTrue(rate.getAvailablePermits() == 0); + assertEquals(rate.getAvailablePermits(), 0); rate.close(); } @@ -136,7 +136,7 @@ public void testMultipleTryAcquire() throws Exception { for (int i = 0; i < permits / acquirePermist; i++) { rate.tryAcquire(acquirePermist); } - assertTrue(rate.getAvailablePermits() == 0); + assertEquals(rate.getAvailablePermits(), 0); rate.close(); } diff --git a/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/ConcurrentLongHashMapTest.java b/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/ConcurrentLongHashMapTest.java index 5a9f49be38a9f..cac262607d844 100644 --- a/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/ConcurrentLongHashMapTest.java +++ b/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/ConcurrentLongHashMapTest.java @@ -86,8 +86,8 @@ public void simpleInsertions() { assertEquals(map.remove(1), "one"); assertEquals(map.size(), 2); - assertEquals(map.get(1), null); - assertEquals(map.get(5), null); + assertNull(map.get(1)); + assertNull(map.get(5)); assertEquals(map.size(), 2); assertNull(map.put(1, "one")); @@ -341,14 +341,14 @@ public void testHashConflictWithDeletion() { int bucket2 = ConcurrentLongHashMap.signSafeMod(ConcurrentLongHashMap.hash(key2), Buckets); assertEquals(bucket1, bucket2); - assertEquals(map.put(key1, "value-1"), null); - assertEquals(map.put(key2, "value-2"), null); + assertNull(map.put(key1, "value-1")); + assertNull(map.put(key2, "value-2")); assertEquals(map.size(), 2); assertEquals(map.remove(key1), "value-1"); assertEquals(map.size(), 1); - assertEquals(map.put(key1, "value-1-overwrite"), null); + assertNull(map.put(key1, "value-1-overwrite")); assertEquals(map.size(), 2); assertEquals(map.remove(key1), "value-1-overwrite"); @@ -365,7 +365,7 @@ public void testHashConflictWithDeletion() { @Test public void testPutIfAbsent() { ConcurrentLongHashMap map = new ConcurrentLongHashMap<>(); - assertEquals(map.putIfAbsent(1, "one"), null); + assertNull(map.putIfAbsent(1, "one")); assertEquals(map.get(1), "one"); assertEquals(map.putIfAbsent(1, "uno"), "one"); diff --git a/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/ConcurrentLongPairSetTest.java b/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/ConcurrentLongPairSetTest.java index 20d3d0d8d6e04..c51616aa857b9 100644 --- a/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/ConcurrentLongPairSetTest.java +++ b/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/ConcurrentLongPairSetTest.java @@ -20,6 +20,7 @@ import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotEquals; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; @@ -33,7 +34,6 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; -import org.apache.pulsar.common.util.collections.ConcurrentLongPairSet; import org.apache.pulsar.common.util.collections.ConcurrentLongPairSet.LongPair; import org.testng.annotations.Test; @@ -250,7 +250,7 @@ public void testIteration() { set.add(0l, 0l); - assertTrue(set.items().iterator().next().equals(new LongPair(0l, 0l))); + assertEquals(new LongPair(0l, 0l), set.items().iterator().next()); set.remove(0l, 0l); @@ -382,8 +382,8 @@ public void testEqualsObjects() { long t2 = 2; long t1_b = 1; assertEquals(t1, t1_b); - assertFalse(t1 == t2); - assertFalse(t1_b == t2); + assertNotEquals(t2, t1); + assertNotEquals(t2, t1_b); set.add(t1, t1); assertTrue(set.contains(t1, t1)); diff --git a/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/ConcurrentOpenHashMapTest.java b/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/ConcurrentOpenHashMapTest.java index 3ca8e9e1af1ef..4bac2dbeb5b38 100644 --- a/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/ConcurrentOpenHashMapTest.java +++ b/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/ConcurrentOpenHashMapTest.java @@ -20,6 +20,7 @@ import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotEquals; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; @@ -37,7 +38,6 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; -import org.apache.pulsar.common.util.collections.ConcurrentOpenHashMap; import org.testng.annotations.Test; import com.google.common.collect.Lists; @@ -86,8 +86,8 @@ public void simpleInsertions() { assertEquals(map.remove("1"), "one"); assertEquals(map.size(), 2); - assertEquals(map.get("1"), null); - assertEquals(map.get("5"), null); + assertNull(map.get("1")); + assertNull(map.get("5")); assertEquals(map.size(), 2); assertNull(map.put("1", "one")); @@ -276,14 +276,14 @@ public void testHashConflictWithDeletion() { int bucket2 = ConcurrentOpenHashMap.signSafeMod(ConcurrentOpenHashMap.hash(key2), Buckets); assertEquals(bucket1, bucket2); - assertEquals(map.put(key1, "value-1"), null); - assertEquals(map.put(key2, "value-2"), null); + assertNull(map.put(key1, "value-1")); + assertNull(map.put(key2, "value-2")); assertEquals(map.size(), 2); assertEquals(map.remove(key1), "value-1"); assertEquals(map.size(), 1); - assertEquals(map.put(key1, "value-1-overwrite"), null); + assertNull(map.put(key1, "value-1-overwrite")); assertEquals(map.size(), 2); assertEquals(map.remove(key1), "value-1-overwrite"); @@ -300,7 +300,7 @@ public void testHashConflictWithDeletion() { @Test public void testPutIfAbsent() { ConcurrentOpenHashMap map = new ConcurrentOpenHashMap<>(); - assertEquals(map.putIfAbsent(1l, "one"), null); + assertNull(map.putIfAbsent(1l, "one")); assertEquals(map.get(1l), "one"); assertEquals(map.putIfAbsent(1l, "uno"), "one"); @@ -357,8 +357,8 @@ public boolean equals(Object obj) { T t2 = new T(2); assertEquals(t1, t1_b); - assertFalse(t1.equals(t2)); - assertFalse(t1_b.equals(t2)); + assertNotEquals(t2, t1); + assertNotEquals(t2, t1_b); assertNull(map.put(t1, "t1")); assertEquals(map.get(t1), "t1"); diff --git a/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/ConcurrentOpenHashSetTest.java b/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/ConcurrentOpenHashSetTest.java index 593fbb6f96dc9..eec176bea2968 100644 --- a/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/ConcurrentOpenHashSetTest.java +++ b/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/ConcurrentOpenHashSetTest.java @@ -20,6 +20,7 @@ import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotEquals; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; @@ -31,7 +32,6 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; -import org.apache.pulsar.common.util.collections.ConcurrentOpenHashSet; import org.testng.annotations.Test; import com.google.common.collect.Lists; @@ -323,8 +323,8 @@ public boolean equals(Object obj) { T t2 = new T(2); assertEquals(t1, t1_b); - assertFalse(t1.equals(t2)); - assertFalse(t1_b.equals(t2)); + assertNotEquals(t2, t1); + assertNotEquals(t2, t1_b); set.add(t1); assertTrue(set.contains(t1)); diff --git a/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/ConcurrentOpenLongPairRangeSetTest.java b/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/ConcurrentOpenLongPairRangeSetTest.java index 54bcecc6e6fb6..343c5e1a98a2b 100644 --- a/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/ConcurrentOpenLongPairRangeSetTest.java +++ b/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/ConcurrentOpenLongPairRangeSetTest.java @@ -19,6 +19,7 @@ package org.apache.pulsar.common.util.collections; import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNull; import java.util.List; import java.util.Set; @@ -335,7 +336,7 @@ public void testRangeContaining() { assertEquals(set.rangeContaining(position.getKey(), position.getValue()), gSet.rangeContaining(position)); position = new LongPair(2, 30); - assertEquals(set.rangeContaining(position.getKey(), position.getValue()), null); + assertNull(set.rangeContaining(position.getKey(), position.getValue())); assertEquals(set.rangeContaining(position.getKey(), position.getValue()), gSet.rangeContaining(position)); position = new LongPair(3, 13); @@ -344,7 +345,7 @@ public void testRangeContaining() { assertEquals(set.rangeContaining(position.getKey(), position.getValue()), gSet.rangeContaining(position)); position = new LongPair(3, 22); - assertEquals(set.rangeContaining(position.getKey(), position.getValue()), null); + assertNull(set.rangeContaining(position.getKey(), position.getValue())); assertEquals(set.rangeContaining(position.getKey(), position.getValue()), gSet.rangeContaining(position)); } diff --git a/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/ConcurrentSortedLongPairSetTest.java b/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/ConcurrentSortedLongPairSetTest.java index 65b26c4f384fb..8f155c3fdc8ae 100644 --- a/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/ConcurrentSortedLongPairSetTest.java +++ b/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/ConcurrentSortedLongPairSetTest.java @@ -20,6 +20,7 @@ import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotEquals; import static org.testng.Assert.assertTrue; import java.util.ArrayList; @@ -31,7 +32,6 @@ import java.util.concurrent.Future; import org.apache.pulsar.common.util.collections.ConcurrentLongPairSet.LongPair; -import org.apache.pulsar.common.util.collections.LongPairSet.LongPairPredicate; import org.testng.annotations.Test; import com.google.common.collect.Lists; @@ -215,8 +215,8 @@ public void testEqualsObjects() { long t2 = 2; long t1_b = 1; assertEquals(t1, t1_b); - assertFalse(t1 == t2); - assertFalse(t1_b == t2); + assertNotEquals(t2, t1); + assertNotEquals(t2, t1_b); set.add(t1, t1); assertTrue(set.contains(t1, t1)); diff --git a/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/GrowableArrayBlockingQueueTest.java b/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/GrowableArrayBlockingQueueTest.java index 25aec3afc3589..860fab54cf272 100644 --- a/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/GrowableArrayBlockingQueueTest.java +++ b/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/GrowableArrayBlockingQueueTest.java @@ -20,6 +20,7 @@ import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; @@ -31,7 +32,6 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; -import org.apache.pulsar.common.util.collections.GrowableArrayBlockingQueue; import org.testng.annotations.Test; import com.google.common.collect.Lists; @@ -42,7 +42,7 @@ public class GrowableArrayBlockingQueueTest { public void simple() throws Exception { BlockingQueue queue = new GrowableArrayBlockingQueue<>(4); - assertEquals(queue.poll(), null); + assertNull(queue.poll()); assertEquals(queue.remainingCapacity(), Integer.MAX_VALUE); assertEquals(queue.toString(), "[]"); @@ -145,7 +145,7 @@ public void blockingTake() throws Exception { public void growArray() throws Exception { BlockingQueue queue = new GrowableArrayBlockingQueue<>(4); - assertEquals(queue.poll(), null); + assertNull(queue.poll()); assertTrue(queue.offer(1)); assertTrue(queue.offer(2)); @@ -174,13 +174,13 @@ public void growArray() throws Exception { public void pollTimeout() throws Exception { BlockingQueue queue = new GrowableArrayBlockingQueue<>(4); - assertEquals(queue.poll(1, TimeUnit.MILLISECONDS), null); + assertNull(queue.poll(1, TimeUnit.MILLISECONDS)); queue.put(1); assertEquals(queue.poll(1, TimeUnit.MILLISECONDS).intValue(), 1); // 0 timeout should not block - assertEquals(queue.poll(0, TimeUnit.HOURS), null); + assertNull(queue.poll(0, TimeUnit.HOURS)); queue.put(2); queue.put(3); @@ -215,7 +215,7 @@ public void pollTimeout2() throws Exception { public void removeTest() throws Exception { BlockingQueue queue = new GrowableArrayBlockingQueue<>(4); - assertEquals(queue.poll(), null); + assertNull(queue.poll()); assertTrue(queue.offer(1)); assertTrue(queue.offer(2)); diff --git a/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/GrowablePriorityLongPairQueueTest.java b/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/GrowablePriorityLongPairQueueTest.java index cab0a56678f4a..3adfd418f56f5 100644 --- a/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/GrowablePriorityLongPairQueueTest.java +++ b/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/GrowablePriorityLongPairQueueTest.java @@ -20,6 +20,7 @@ import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotEquals; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; @@ -234,7 +235,7 @@ public void testIteration() { queue.add(0l, 0l); - assertTrue(queue.items().iterator().next().equals(new LongPair(0l, 0l))); + assertEquals(new LongPair(0l, 0l), queue.items().iterator().next()); queue.remove(0l, 0l); @@ -334,8 +335,8 @@ public void testEqualsObjects() { long t2 = 2; long t1_b = 1; assertEquals(t1, t1_b); - assertFalse(t1 == t2); - assertFalse(t1_b == t2); + assertNotEquals(t2, t1); + assertNotEquals(t2, t1_b); queue.add(t1, t1); assertTrue(queue.remove(t1_b, t1_b)); } diff --git a/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/TripleLongPriorityQueueTest.java b/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/TripleLongPriorityQueueTest.java index ea04a6d372f7a..241b4f23f5dae 100644 --- a/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/TripleLongPriorityQueueTest.java +++ b/pulsar-common/src/test/java/org/apache/pulsar/common/util/collections/TripleLongPriorityQueueTest.java @@ -20,6 +20,7 @@ import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import org.testng.annotations.Test; @@ -57,7 +58,7 @@ public void testQueue() { public void testCheckForEmpty() { TripleLongPriorityQueue pq = new TripleLongPriorityQueue(); assertEquals(pq.size(), 0); - assertEquals(pq.isEmpty(), true); + assertTrue(pq.isEmpty()); try { pq.peekN1(); @@ -94,7 +95,7 @@ public void testCheckForEmpty() { public void testCompareWithSamePrefix() { TripleLongPriorityQueue pq = new TripleLongPriorityQueue(); assertEquals(pq.size(), 0); - assertEquals(pq.isEmpty(), true); + assertTrue(pq.isEmpty()); pq.add(10, 20, 30); pq.add(20, 10, 10); @@ -130,7 +131,7 @@ public void testCompareWithSamePrefix() { pq.pop(); assertEquals(pq.size(), 0); - assertEquals(pq.isEmpty(), true); + assertTrue(pq.isEmpty()); pq.close(); } diff --git a/pulsar-discovery-service/src/test/java/org/apache/pulsar/discovery/service/web/ZookeeperCacheLoaderTest.java b/pulsar-discovery-service/src/test/java/org/apache/pulsar/discovery/service/web/ZookeeperCacheLoaderTest.java index 84e0f8fc37a8c..0c435337d0479 100644 --- a/pulsar-discovery-service/src/test/java/org/apache/pulsar/discovery/service/web/ZookeeperCacheLoaderTest.java +++ b/pulsar-discovery-service/src/test/java/org/apache/pulsar/discovery/service/web/ZookeeperCacheLoaderTest.java @@ -39,7 +39,6 @@ import org.testng.annotations.Test; import com.google.common.collect.Lists; -import com.google.common.collect.Sets; public class ZookeeperCacheLoaderTest extends BaseZKStarterTest { diff --git a/pulsar-flink/src/test/java/org/apache/flink/batch/connectors/pulsar/serialization/AvroSerializationSchemaTest.java b/pulsar-flink/src/test/java/org/apache/flink/batch/connectors/pulsar/serialization/AvroSerializationSchemaTest.java index 48d043539fedb..c283d2fe03b49 100644 --- a/pulsar-flink/src/test/java/org/apache/flink/batch/connectors/pulsar/serialization/AvroSerializationSchemaTest.java +++ b/pulsar-flink/src/test/java/org/apache/flink/batch/connectors/pulsar/serialization/AvroSerializationSchemaTest.java @@ -26,6 +26,7 @@ import java.io.IOException; import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNull; /** * Tests for Avro Serialization Schema @@ -58,8 +59,8 @@ public void testAvroSerializationSchemaWithEmptyRecord() throws IOException { assertEquals(nasaMission.getId(), genericRecord.get("id")); assertEquals(nasaMission.getName(), genericRecord.get("name").toString()); - assertEquals(null, genericRecord.get("start_year")); - assertEquals(null, genericRecord.get("end_year")); + assertNull(genericRecord.get("start_year")); + assertNull(genericRecord.get("end_year")); } } diff --git a/pulsar-flink/src/test/java/org/apache/flink/streaming/connectors/pulsar/PulsarConsumerSourceTests.java b/pulsar-flink/src/test/java/org/apache/flink/streaming/connectors/pulsar/PulsarConsumerSourceTests.java index 82d831b490f40..a666bb02dc16a 100644 --- a/pulsar-flink/src/test/java/org/apache/flink/streaming/connectors/pulsar/PulsarConsumerSourceTests.java +++ b/pulsar-flink/src/test/java/org/apache/flink/streaming/connectors/pulsar/PulsarConsumerSourceTests.java @@ -38,9 +38,6 @@ import org.apache.pulsar.client.api.PulsarClientException; import org.apache.pulsar.client.api.Schema; import org.apache.pulsar.client.impl.MessageImpl; -import io.netty.buffer.Unpooled; -import org.mockito.Mockito; -import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @@ -58,6 +55,10 @@ import java.util.concurrent.atomic.AtomicInteger; import static org.mockito.Mockito.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertTrue; /** * Tests for the PulsarConsumerSource. The source supports two operation modes. @@ -133,7 +134,7 @@ public void testCheckpointing() throws Exception { } final TestPulsarConsumerSource sourceCopy = - createSource(Mockito.mock(Consumer.class), 1, true); + createSource(mock(Consumer.class), 1, true); final StreamSource srcCopy = new StreamSource<>(sourceCopy); final AbstractStreamOperatorTestHarness testHarnessCopy = new AbstractStreamOperatorTestHarness<>(srcCopy, 1, 1, 0); @@ -147,14 +148,14 @@ public void testCheckpointing() throws Exception { final int start = consumer.currentMessage.get() - numMessages; for (int mi = start; mi < (start + numMessages); ++mi) { - Assert.assertTrue(messageIds.contains(consumer.messages.get(mi).getMessageId())); + assertTrue(messageIds.contains(consumer.messages.get(mi).getMessageId())); } // check if the messages are being acknowledged synchronized (context.getCheckpointLock()) { source.notifyCheckpointComplete(snapshotId); - Assert.assertEquals(consumer.acknowledgedIds.keySet(), messageIds); + assertEquals(consumer.acknowledgedIds.keySet(), messageIds); // clear acknowledgements for the next snapshot comparison consumer.acknowledgedIds.clear(); } @@ -175,14 +176,14 @@ public void testCheckpointingDuplicatedIds() throws Exception { receiveMessages(); - Assert.assertEquals(5, context.elements.size()); + assertEquals(5, context.elements.size()); // try to reprocess the messages we should not collect any more elements consumer.reset(); receiveMessages(); - Assert.assertEquals(5, context.elements.size()); + assertEquals(5, context.elements.size()); } @Test @@ -197,7 +198,7 @@ public void testCheckpointingDisabledMessagesEqualBatchSize() throws Exception { receiveMessages(); - Assert.assertEquals(1, consumer.acknowledgedIds.size()); + assertEquals(1, consumer.acknowledgedIds.size()); } @Test @@ -212,7 +213,7 @@ public void testCheckpointingDisabledMoreMessagesThanBatchSize() throws Exceptio receiveMessages(); - Assert.assertEquals(1, consumer.acknowledgedIds.size()); + assertEquals(1, consumer.acknowledgedIds.size()); } @Test @@ -227,7 +228,7 @@ public void testCheckpointingDisabledLessMessagesThanBatchSize() throws Exceptio receiveMessages(); - Assert.assertEquals(0, consumer.acknowledgedIds.size()); + assertEquals(0, consumer.acknowledgedIds.size()); } @Test @@ -242,7 +243,7 @@ public void testCheckpointingDisabledMessages2XBatchSize() throws Exception { receiveMessages(); - Assert.assertEquals(2, consumer.acknowledgedIds.size()); + assertEquals(2, consumer.acknowledgedIds.size()); } private void receiveMessages() throws InterruptedException { @@ -258,10 +259,10 @@ private TestPulsarConsumerSource createSource(Consumer testConsumer, .acknowledgementBatchSize(batchSize); TestPulsarConsumerSource source = new TestPulsarConsumerSource(builder, testConsumer, isCheckpointingEnabled); - OperatorStateStore mockStore = Mockito.mock(OperatorStateStore.class); - FunctionInitializationContext mockContext = Mockito.mock(FunctionInitializationContext.class); - Mockito.when(mockContext.getOperatorStateStore()).thenReturn(mockStore); - Mockito.when(mockStore.getSerializableListState(any(String.class))).thenReturn(null); + OperatorStateStore mockStore = mock(OperatorStateStore.class); + FunctionInitializationContext mockContext = mock(FunctionInitializationContext.class); + when(mockContext.getOperatorStateStore()).thenReturn(mockStore); + when(mockStore.getSerializableListState(any(String.class))).thenReturn(null); source.initializeState(mockContext); @@ -284,14 +285,14 @@ private static class TestPulsarConsumerSource extends PulsarConsumerSource>> getRestoredState() { @Override PulsarClient createClient() { - return Mockito.mock(PulsarClient.class); + return mock(PulsarClient.class); } @Override diff --git a/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/sink/PulsarSinkTest.java b/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/sink/PulsarSinkTest.java index fcea8a23bf5a5..ed64f801d0fb5 100644 --- a/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/sink/PulsarSinkTest.java +++ b/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/sink/PulsarSinkTest.java @@ -29,7 +29,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; @@ -170,11 +170,11 @@ public void testVoidOutputClasses() throws Exception { try { Schema schema = pulsarSink.initializeSchema(); - assertEquals(schema, (Schema)null); + assertNull(schema); } catch (Exception ex) { ex.printStackTrace(); - assertEquals(ex, null); - assertTrue(false); + assertNull(ex); + fail(); } } @@ -193,7 +193,7 @@ public void testInconsistentOutputType() throws IOException { assertTrue(ex.getMessage().startsWith("Inconsistent types found between function input type and serde type:")); } catch (Exception ex) { log.error("Exception: {}", ex, ex); - assertTrue(false); + fail(); } } diff --git a/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/source/PulsarSourceTest.java b/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/source/PulsarSourceTest.java index 99e9d913d6e1b..409db45937ae3 100644 --- a/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/source/PulsarSourceTest.java +++ b/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/source/PulsarSourceTest.java @@ -26,7 +26,6 @@ import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import static org.testng.AssertJUnit.fail; @@ -131,13 +130,13 @@ public void testVoidInputClasses() throws Exception { try { pulsarSource.open(new HashMap<>(), mock(SourceContext.class)); - assertFalse(true); + fail(); } catch (RuntimeException ex) { log.error("RuntimeException: {}", ex, ex); assertEquals(ex.getMessage(), "Input type of Pulsar Function cannot be Void"); } catch (Exception ex) { log.error("Exception: {}", ex, ex); - assertFalse(true); + fail(); } } @@ -164,7 +163,7 @@ public void testInconsistentInputType() throws Exception { assertTrue(ex.getMessage().startsWith("Inconsistent types found between function input type and serde type:")); } catch (Exception ex) { log.error("Exception: {}", ex, ex); - assertTrue(false); + fail(); } } diff --git a/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/windowing/WindowFunctionExecutorTest.java b/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/windowing/WindowFunctionExecutorTest.java index 67e9ccc021d40..c60b15221d9f7 100644 --- a/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/windowing/WindowFunctionExecutorTest.java +++ b/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/windowing/WindowFunctionExecutorTest.java @@ -19,7 +19,6 @@ package org.apache.pulsar.functions.windowing; import com.google.gson.Gson; -import lombok.extern.slf4j.Slf4j; import org.apache.pulsar.client.api.TypedMessageBuilder; import org.apache.pulsar.functions.api.Context; import org.apache.pulsar.functions.api.Record; diff --git a/pulsar-functions/runtime/src/test/java/org/apache/pulsar/functions/runtime/KubernetesRuntimeFactoryTest.java b/pulsar-functions/runtime/src/test/java/org/apache/pulsar/functions/runtime/KubernetesRuntimeFactoryTest.java index 5ea75fa296fe1..fc7d353bd8681 100644 --- a/pulsar-functions/runtime/src/test/java/org/apache/pulsar/functions/runtime/KubernetesRuntimeFactoryTest.java +++ b/pulsar-functions/runtime/src/test/java/org/apache/pulsar/functions/runtime/KubernetesRuntimeFactoryTest.java @@ -35,8 +35,6 @@ import java.util.HashMap; import java.util.Map; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; import static org.powermock.api.mockito.PowerMockito.doNothing; import static org.powermock.api.mockito.PowerMockito.spy; import static org.testng.Assert.assertEquals; diff --git a/pulsar-functions/secrets/src/test/java/org/apache/pulsar/functions/secretsprovider/ClearTextSecretsProviderTest.java b/pulsar-functions/secrets/src/test/java/org/apache/pulsar/functions/secretsprovider/ClearTextSecretsProviderTest.java index d6f01395a3166..5f579f8a78c18 100644 --- a/pulsar-functions/secrets/src/test/java/org/apache/pulsar/functions/secretsprovider/ClearTextSecretsProviderTest.java +++ b/pulsar-functions/secrets/src/test/java/org/apache/pulsar/functions/secretsprovider/ClearTextSecretsProviderTest.java @@ -19,19 +19,18 @@ package org.apache.pulsar.functions.secretsprovider; -import org.testng.Assert; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNull; + import org.testng.annotations.Test; -/** - * Unit test of {@link Exceptions}. - */ public class ClearTextSecretsProviderTest { @Test public void testConfigValidation() throws Exception { ClearTextSecretsProvider provider = new ClearTextSecretsProvider(); - Assert.assertEquals(provider.provideSecret("SecretName", "SecretValue"), "SecretValue"); - Assert.assertEquals(provider.provideSecret("SecretName", ""), ""); - Assert.assertEquals(provider.provideSecret("SecretName", null), null); + assertEquals(provider.provideSecret("SecretName", "SecretValue"), "SecretValue"); + assertEquals(provider.provideSecret("SecretName", ""), ""); + assertNull(provider.provideSecret("SecretName", null)); } } diff --git a/pulsar-functions/secrets/src/test/java/org/apache/pulsar/functions/secretsprovider/EnvironmentBasedSecretsProviderTest.java b/pulsar-functions/secrets/src/test/java/org/apache/pulsar/functions/secretsprovider/EnvironmentBasedSecretsProviderTest.java index 3ebb52674e084..1fc76b337a5fd 100644 --- a/pulsar-functions/secrets/src/test/java/org/apache/pulsar/functions/secretsprovider/EnvironmentBasedSecretsProviderTest.java +++ b/pulsar-functions/secrets/src/test/java/org/apache/pulsar/functions/secretsprovider/EnvironmentBasedSecretsProviderTest.java @@ -19,22 +19,21 @@ package org.apache.pulsar.functions.secretsprovider; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNull; + import java.lang.reflect.Field; import java.util.Map; -import org.testng.Assert; import org.testng.annotations.Test; -/** - * Unit test of {@link Exceptions}. - */ public class EnvironmentBasedSecretsProviderTest { @Test public void testConfigValidation() throws Exception { EnvironmentBasedSecretsProvider provider = new EnvironmentBasedSecretsProvider(); - Assert.assertEquals(provider.provideSecret("mySecretName", "Ignored"), null); + assertNull(provider.provideSecret("mySecretName", "Ignored")); injectEnvironmentVariable("mySecretName", "SecretValue"); - Assert.assertEquals(provider.provideSecret("mySecretName", "Ignored"), "SecretValue"); + assertEquals(provider.provideSecret("mySecretName", "Ignored"), "SecretValue"); } private static void injectEnvironmentVariable(String key, String value) diff --git a/pulsar-functions/utils/src/test/java/org/apache/pulsar/functions/utils/ReflectionsTest.java b/pulsar-functions/utils/src/test/java/org/apache/pulsar/functions/utils/ReflectionsTest.java index b0fa14c052f04..da2a5402f461b 100644 --- a/pulsar-functions/utils/src/test/java/org/apache/pulsar/functions/utils/ReflectionsTest.java +++ b/pulsar-functions/utils/src/test/java/org/apache/pulsar/functions/utils/ReflectionsTest.java @@ -20,6 +20,7 @@ import static org.apache.pulsar.functions.utils.Reflections.createInstance; import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import static org.testng.AssertJUnit.fail; @@ -156,13 +157,13 @@ public void testCreateTypedInstanceUnassignableClass() { @Test public void testClassInJarImplementsIface() { assertTrue(Reflections.classImplementsIface(aImplementation.class.getName(), aInterface.class)); - assertTrue(!Reflections.classImplementsIface(aImplementation.class.getName(), bInterface.class)); + assertFalse(Reflections.classImplementsIface(aImplementation.class.getName(), bInterface.class)); } @Test public void testClassExists() { assertTrue(Reflections.classExists(String.class.getName())); - assertTrue(!Reflections.classExists("com.fake.class")); + assertFalse(Reflections.classExists("com.fake.class")); } @Test diff --git a/pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/FunctionActionerTest.java b/pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/FunctionActionerTest.java index ca21c8b623f89..bd44741559349 100644 --- a/pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/FunctionActionerTest.java +++ b/pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/FunctionActionerTest.java @@ -38,8 +38,9 @@ import org.apache.pulsar.functions.runtime.ThreadRuntimeFactory; import org.testng.annotations.Test; import static org.apache.pulsar.common.functions.Utils.FILE; -import static org.testng.Assert.*; -import static org.testng.AssertJUnit.assertFalse; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNull; +import static org.testng.AssertJUnit.fail; /** * Unit test of {@link FunctionActioner}. @@ -84,7 +85,7 @@ public void testStartFunctionWithDLNamespace() throws Exception { // actioner should try to download file from bk-dlogNamespace and fails with exception try { actioner.startFunction(functionRuntimeInfo); - assertFalse(true); + fail(); } catch (IllegalStateException ex) { assertEquals(ex.getMessage(), "StartupException"); } @@ -144,7 +145,7 @@ public void testStartFunctionWithPkgUrl() throws Exception { try { actioner.startFunction(functionRuntimeInfo); - assertFalse(true); + fail(); } catch (IllegalStateException ex) { assertEquals(ex.getMessage(), "StartupException"); } @@ -186,7 +187,7 @@ public void testFunctionAuthDisabled() throws Exception { RuntimeSpawner runtimeSpawner = spy(actioner.getRuntimeSpawner(instance, "foo")); - assertTrue(runtimeSpawner.getInstanceConfig().getFunctionAuthenticationSpec() == null); + assertNull(runtimeSpawner.getInstanceConfig().getFunctionAuthenticationSpec()); FunctionRuntimeInfo functionRuntimeInfo = mock(FunctionRuntimeInfo.class); diff --git a/pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/FunctionRuntimeManagerTest.java b/pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/FunctionRuntimeManagerTest.java index 399b3554ddc75..ac3a3956dd2be 100644 --- a/pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/FunctionRuntimeManagerTest.java +++ b/pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/FunctionRuntimeManagerTest.java @@ -32,10 +32,8 @@ import org.apache.pulsar.functions.runtime.KubernetesRuntime; import org.apache.pulsar.functions.runtime.KubernetesRuntimeFactory; import org.apache.pulsar.functions.utils.FunctionCommon; -import org.mockito.ArgumentMatcher; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import org.testng.Assert; import org.testng.annotations.Test; import java.util.HashMap; @@ -56,6 +54,10 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; @Slf4j public class FunctionRuntimeManagerTest { @@ -123,25 +125,18 @@ public void testProcessAssignmentUpdateAddFunctions() throws Exception { verify(functionRuntimeManager, times(2)).setAssignment(any(Function.Assignment.class)); verify(functionRuntimeManager, times(0)).deleteAssignment(any(Function.Assignment.class)); - Assert.assertEquals(functionRuntimeManager.workerIdToAssignments.size(), 2); - Assert.assertEquals(functionRuntimeManager.workerIdToAssignments + assertEquals(functionRuntimeManager.workerIdToAssignments.size(), 2); + assertEquals(functionRuntimeManager.workerIdToAssignments .get("worker-1").get("test-tenant/test-namespace/func-1:0"), assignment1); - Assert.assertEquals(functionRuntimeManager.workerIdToAssignments.get("worker-2") + assertEquals(functionRuntimeManager.workerIdToAssignments.get("worker-2") .get("test-tenant/test-namespace/func-2:0"), assignment2); verify(functionActioner, times(1)).startFunction(any(FunctionRuntimeInfo.class)); - verify(functionActioner).startFunction(argThat(new ArgumentMatcher() { - @Override - public boolean matches(FunctionRuntimeInfo functionRuntimeInfo) { - if (!functionRuntimeInfo.getFunctionInstance().getFunctionMetaData().equals(function1)) { - return false; - } - return true; - } - })); + verify(functionActioner).startFunction(argThat( + functionRuntimeInfo -> functionRuntimeInfo.getFunctionInstance().getFunctionMetaData().equals(function1))); verify(functionActioner, times(0)).stopFunction(any(FunctionRuntimeInfo.class)); - Assert.assertEquals(functionRuntimeManager.functionRuntimeInfoMap.size(), 1); - Assert.assertEquals(functionRuntimeManager.functionRuntimeInfoMap.get("test-tenant/test-namespace/func-1:0"), + assertEquals(functionRuntimeManager.functionRuntimeInfoMap.size(), 1); + assertEquals(functionRuntimeManager.functionRuntimeInfoMap.get("test-tenant/test-namespace/func-1:0"), new FunctionRuntimeInfo().setFunctionInstance( Function.Instance.newBuilder().setFunctionMetaData(function1).setInstanceId(0) .build())); @@ -218,23 +213,16 @@ public void testProcessAssignmentUpdateDeleteFunctions() throws Exception { verify(functionRuntimeManager, times(0)).setAssignment(any(Function.Assignment.class)); verify(functionRuntimeManager, times(1)).deleteAssignment(any(String.class)); - Assert.assertEquals(functionRuntimeManager.workerIdToAssignments.size(), 1); - Assert.assertEquals(functionRuntimeManager.workerIdToAssignments + assertEquals(functionRuntimeManager.workerIdToAssignments.size(), 1); + assertEquals(functionRuntimeManager.workerIdToAssignments .get("worker-2").get("test-tenant/test-namespace/func-2:0"), assignment2); verify(functionActioner, times(0)).startFunction(any(FunctionRuntimeInfo.class)); verify(functionActioner, times(1)).terminateFunction(any(FunctionRuntimeInfo.class)); - verify(functionActioner).terminateFunction(argThat(new ArgumentMatcher() { - @Override - public boolean matches(FunctionRuntimeInfo functionRuntimeInfo) { - if (!functionRuntimeInfo.getFunctionInstance().getFunctionMetaData().equals(function1)) { - return false; - } - return true; - } - })); + verify(functionActioner).terminateFunction(argThat( + functionRuntimeInfo -> functionRuntimeInfo.getFunctionInstance().getFunctionMetaData().equals(function1))); - Assert.assertEquals(functionRuntimeManager.functionRuntimeInfoMap.size(), 0); + assertEquals(functionRuntimeManager.functionRuntimeInfoMap.size(), 0); } @Test @@ -317,32 +305,18 @@ public void testProcessAssignmentUpdateModifyFunctions() throws Exception { // make sure terminate is not called since this is a update operation verify(functionActioner, times(0)).terminateFunction(any(FunctionRuntimeInfo.class)); - verify(functionActioner).stopFunction(argThat(new ArgumentMatcher() { - @Override - public boolean matches(FunctionRuntimeInfo functionRuntimeInfo) { - if (!functionRuntimeInfo.getFunctionInstance().getFunctionMetaData().equals(function2)) { - return false; - } - return true; - } - })); + verify(functionActioner).stopFunction(argThat( + functionRuntimeInfo -> functionRuntimeInfo.getFunctionInstance().getFunctionMetaData().equals(function2))); verify(functionActioner, times(1)).startFunction(any(FunctionRuntimeInfo.class)); - verify(functionActioner).startFunction(argThat(new ArgumentMatcher() { - @Override - public boolean matches(FunctionRuntimeInfo functionRuntimeInfo) { - if (!functionRuntimeInfo.getFunctionInstance().getFunctionMetaData().equals(function2)) { - return false; - } - return true; - } - })); + verify(functionActioner).startFunction(argThat( + functionRuntimeInfo -> functionRuntimeInfo.getFunctionInstance().getFunctionMetaData().equals(function2))); - Assert.assertEquals(functionRuntimeManager.functionRuntimeInfoMap.size(), 2); - Assert.assertEquals(functionRuntimeManager.workerIdToAssignments.size(), 1); - Assert.assertEquals(functionRuntimeManager.workerIdToAssignments + assertEquals(functionRuntimeManager.functionRuntimeInfoMap.size(), 2); + assertEquals(functionRuntimeManager.workerIdToAssignments.size(), 1); + assertEquals(functionRuntimeManager.workerIdToAssignments .get("worker-1").get("test-tenant/test-namespace/func-1:0"), assignment1); - Assert.assertEquals(functionRuntimeManager.workerIdToAssignments + assertEquals(functionRuntimeManager.workerIdToAssignments .get("worker-1").get("test-tenant/test-namespace/func-2:0"), assignment3); reset(functionRuntimeManager); @@ -365,20 +339,16 @@ public boolean matches(FunctionRuntimeInfo functionRuntimeInfo) { // make sure terminate is not called since this is a update operation verify(functionActioner, times(0)).terminateFunction(any(FunctionRuntimeInfo.class)); - verify(functionActioner).stopFunction(argThat(functionRuntimeInfo -> { - if (!functionRuntimeInfo.getFunctionInstance().getFunctionMetaData().equals(function2)) { - return false; - } - return true; - })); + verify(functionActioner).stopFunction(argThat(functionRuntimeInfo -> + functionRuntimeInfo.getFunctionInstance().getFunctionMetaData().equals(function2))); verify(functionActioner, times(0)).startFunction(any(FunctionRuntimeInfo.class)); - Assert.assertEquals(functionRuntimeManager.functionRuntimeInfoMap.size(), 2); - Assert.assertEquals(functionRuntimeManager.workerIdToAssignments.size(), 1); - Assert.assertEquals(functionRuntimeManager.workerIdToAssignments + assertEquals(functionRuntimeManager.functionRuntimeInfoMap.size(), 2); + assertEquals(functionRuntimeManager.workerIdToAssignments.size(), 1); + assertEquals(functionRuntimeManager.workerIdToAssignments .get("worker-1").get("test-tenant/test-namespace/func-1:0"), assignment1); - Assert.assertEquals(functionRuntimeManager.workerIdToAssignments + assertEquals(functionRuntimeManager.workerIdToAssignments .get("worker-1").get("test-tenant/test-namespace/func-2:0"), assignment4); } @@ -452,10 +422,10 @@ public void testReassignment() throws Exception { verify(functionActioner, times(0)).terminateFunction(any(FunctionRuntimeInfo.class)); verify(functionActioner, times(1)).stopFunction(any(FunctionRuntimeInfo.class)); - Assert.assertEquals(functionRuntimeManager.workerIdToAssignments + assertEquals(functionRuntimeManager.workerIdToAssignments .get("worker-2").get("test-tenant/test-namespace/func-1:0"), assignment2); - Assert.assertEquals(functionRuntimeManager.functionRuntimeInfoMap.size(), 0); - Assert.assertEquals(functionRuntimeManager.functionRuntimeInfoMap.get("test-tenant/test-namespace/func-1:0"), null); + assertEquals(functionRuntimeManager.functionRuntimeInfoMap.size(), 0); + assertNull(functionRuntimeManager.functionRuntimeInfoMap.get("test-tenant/test-namespace/func-1:0")); /** Test transfer from other worker to me **/ reset(functionRuntimeManager); @@ -477,13 +447,13 @@ public void testReassignment() throws Exception { verify(functionActioner, times(0)).terminateFunction(any(FunctionRuntimeInfo.class)); verify(functionActioner, times(0)).stopFunction(any(FunctionRuntimeInfo.class)); - Assert.assertEquals(functionRuntimeManager.workerIdToAssignments + assertEquals(functionRuntimeManager.workerIdToAssignments .get("worker-1").get("test-tenant/test-namespace/func-1:0"), assignment3); - Assert.assertEquals(functionRuntimeManager.workerIdToAssignments - .get("worker-2"), null); + assertNull(functionRuntimeManager.workerIdToAssignments + .get("worker-2")); - Assert.assertEquals(functionRuntimeManager.functionRuntimeInfoMap.size(), 1); - Assert.assertEquals(functionRuntimeManager.functionRuntimeInfoMap.get("test-tenant/test-namespace/func-1:0"), functionRuntimeInfo); + assertEquals(functionRuntimeManager.functionRuntimeInfoMap.size(), 1); + assertEquals(functionRuntimeManager.functionRuntimeInfoMap.get("test-tenant/test-namespace/func-1:0"), functionRuntimeInfo); } @Test @@ -595,28 +565,18 @@ public Boolean answer(InvocationOnMock invocationOnMock) throws Throwable { functionRuntimeManager.initialize(); - Assert.assertEquals(functionRuntimeManager.workerIdToAssignments.size(), 1); + assertEquals(functionRuntimeManager.workerIdToAssignments.size(), 1); verify(functionActioner, times(1)).startFunction(any(FunctionRuntimeInfo.class)); // Ideally this should be zero, but it will nevertheless be called with null runtimespawner which essentially // results in it being noop. We ensure that in the check below. verify(functionActioner, times(1)).stopFunction(any(FunctionRuntimeInfo.class)); verify(functionActioner, times(0)).terminateFunction(any(FunctionRuntimeInfo.class)); - verify(functionActioner).startFunction(argThat(functionRuntimeInfo -> { - if (!functionRuntimeInfo.getFunctionInstance().equals(assignment1.getInstance())) { - return false; - } - return true; - })); - verify(functionActioner).stopFunction(argThat(functionRuntimeInfo -> { - if (functionRuntimeInfo.getRuntimeSpawner() != null) { - return false; - } - return true; - })); - - Assert.assertEquals(functionRuntimeManager.functionRuntimeInfoMap.size(), 1); - Assert.assertEquals(functionRuntimeManager.functionRuntimeInfoMap.get("test-tenant/test-namespace/func-1:0"), + verify(functionActioner).startFunction(argThat(functionRuntimeInfo -> functionRuntimeInfo.getFunctionInstance().equals(assignment1.getInstance()))); + verify(functionActioner).stopFunction(argThat(functionRuntimeInfo -> functionRuntimeInfo.getRuntimeSpawner() == null)); + + assertEquals(functionRuntimeManager.functionRuntimeInfoMap.size(), 1); + assertEquals(functionRuntimeManager.functionRuntimeInfoMap.get("test-tenant/test-namespace/func-1:0"), new FunctionRuntimeInfo().setFunctionInstance( Function.Instance.newBuilder().setFunctionMetaData(function1).setInstanceId(0) .build())); @@ -705,9 +665,9 @@ public void testExternallyManagedRuntimeUpdate() throws Exception { verify(functionActioner, times(0)).terminateFunction(any(FunctionRuntimeInfo.class)); verify(functionActioner, times(0)).stopFunction(any(FunctionRuntimeInfo.class)); - Assert.assertEquals(functionRuntimeManager.workerIdToAssignments + assertEquals(functionRuntimeManager.workerIdToAssignments .get("worker-2").get("test-tenant/test-namespace/func-1:0"), assignment2); - Assert.assertEquals(functionRuntimeManager.functionRuntimeInfoMap.get("test-tenant/test-namespace/func-1:0"), null); + assertNull(functionRuntimeManager.functionRuntimeInfoMap.get("test-tenant/test-namespace/func-1:0")); /** Test transfer from other worker to me **/ @@ -724,26 +684,26 @@ public void testExternallyManagedRuntimeUpdate() throws Exception { verify(functionActioner, times(0)).terminateFunction(any(FunctionRuntimeInfo.class)); verify(functionActioner, times(0)).stopFunction(any(FunctionRuntimeInfo.class)); - Assert.assertEquals(functionRuntimeManager.workerIdToAssignments + assertEquals(functionRuntimeManager.workerIdToAssignments .get("worker-1").get("test-tenant/test-namespace/func-1:0"), assignment3); - Assert.assertEquals(functionRuntimeManager.workerIdToAssignments - .get("worker-2"), null); + assertNull(functionRuntimeManager.workerIdToAssignments + .get("worker-2")); - Assert.assertEquals( + assertEquals( functionRuntimeManager.functionRuntimeInfoMap.get("test-tenant/test-namespace/func-1:0").getFunctionInstance(), functionRuntimeInfo.getFunctionInstance()); - Assert.assertTrue( - functionRuntimeManager.functionRuntimeInfoMap.get("test-tenant/test-namespace/func-1:0").getRuntimeSpawner() != null); + assertNotNull( + functionRuntimeManager.functionRuntimeInfoMap.get("test-tenant/test-namespace/func-1:0").getRuntimeSpawner()); - Assert.assertEquals( + assertEquals( functionRuntimeManager.functionRuntimeInfoMap.get("test-tenant/test-namespace/func-1:0").getRuntimeSpawner().getInstanceConfig().getFunctionDetails(), function1.getFunctionDetails()); - Assert.assertEquals( + assertEquals( functionRuntimeManager.functionRuntimeInfoMap.get("test-tenant/test-namespace/func-1:0").getRuntimeSpawner().getInstanceConfig().getInstanceId(), instance.getInstanceId()); - Assert.assertTrue( + assertTrue( functionRuntimeManager.functionRuntimeInfoMap.get("test-tenant/test-namespace/func-1:0").getRuntimeSpawner().getRuntimeFactory() instanceof KubernetesRuntimeFactory); - Assert.assertTrue( - functionRuntimeManager.functionRuntimeInfoMap.get("test-tenant/test-namespace/func-1:0").getRuntimeSpawner().getRuntime() != null); + assertNotNull( + functionRuntimeManager.functionRuntimeInfoMap.get("test-tenant/test-namespace/func-1:0").getRuntimeSpawner().getRuntime()); } } diff --git a/pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/MembershipManagerTest.java b/pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/MembershipManagerTest.java index 494c93e9c455e..57eed32ad2d69 100644 --- a/pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/MembershipManagerTest.java +++ b/pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/MembershipManagerTest.java @@ -27,7 +27,9 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import java.util.LinkedList; @@ -48,7 +50,6 @@ import org.apache.pulsar.common.functions.WorkerInfo; import org.apache.pulsar.functions.proto.Function; import org.mockito.Mockito; -import org.testng.Assert; import org.testng.annotations.Test; public class MembershipManagerTest { @@ -191,7 +192,7 @@ public void testCheckFailuresNoFailures() throws Exception { verify(schedulerManager, times(0)).schedule(); verify(functionRuntimeManager, times(0)).removeAssignments(any()); - Assert.assertEquals(membershipManager.unsignedFunctionDurations.size(), 0); + assertEquals(membershipManager.unsignedFunctionDurations.size(), 0); } @Test @@ -258,9 +259,9 @@ public void testCheckFailuresSomeFailures() throws Exception { verify(schedulerManager, times(0)).schedule(); verify(functionRuntimeManager, times(0)).removeAssignments(any()); - Assert.assertEquals(membershipManager.unsignedFunctionDurations.size(), 1); + assertEquals(membershipManager.unsignedFunctionDurations.size(), 1); Function.Instance instance = Function.Instance.newBuilder().setFunctionMetaData(function2).setInstanceId(0).build(); - Assert.assertTrue(membershipManager.unsignedFunctionDurations.get(instance) != null); + assertNotNull(membershipManager.unsignedFunctionDurations.get(instance)); membershipManager.unsignedFunctionDurations.put(instance, membershipManager.unsignedFunctionDurations.get(instance) - 30001); @@ -336,9 +337,9 @@ public void testCheckFailuresSomeUnassigned() throws Exception { verify(schedulerManager, times(0)).schedule(); verify(functionRuntimeManager, times(0)).removeAssignments(any()); - Assert.assertEquals(membershipManager.unsignedFunctionDurations.size(), 1); + assertEquals(membershipManager.unsignedFunctionDurations.size(), 1); Function.Instance instance = Function.Instance.newBuilder().setFunctionMetaData(function2).setInstanceId(0).build(); - Assert.assertTrue(membershipManager.unsignedFunctionDurations.get(instance) != null); + assertNotNull(membershipManager.unsignedFunctionDurations.get(instance)); membershipManager.unsignedFunctionDurations.put(instance, membershipManager.unsignedFunctionDurations.get(instance) - 30001); @@ -420,7 +421,7 @@ public void testHeartBeatFunctionWorkerDown() throws Exception { verify(schedulerManager, times(0)).schedule(); verify(functionRuntimeManager, times(0)).removeAssignments(any()); - Assert.assertEquals(membershipManager.unsignedFunctionDurations.size(), 0); + assertEquals(membershipManager.unsignedFunctionDurations.size(), 0); } } diff --git a/pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/rest/api/FunctionsImplTest.java b/pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/rest/api/FunctionsImplTest.java index 4e0c5fbfce0c7..258c123797745 100644 --- a/pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/rest/api/FunctionsImplTest.java +++ b/pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/rest/api/FunctionsImplTest.java @@ -48,7 +48,6 @@ import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; -import org.testng.Assert; import org.testng.IObjectFactory; import org.testng.annotations.BeforeMethod; import org.testng.annotations.ObjectFactory; @@ -70,6 +69,9 @@ import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.doReturn; import static org.powermock.api.mockito.PowerMockito.mockStatic; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; @PrepareForTest({WorkerUtils.class, InstanceUtils.class}) @PowerMockIgnore({ "javax.management.*", "javax.ws.*", "org.apache.logging.log4j.*" }) @@ -193,7 +195,7 @@ public void setup() throws Exception { @Test public void testStatusEmpty() { - Assert.assertTrue(this.resource.getFunctionInstanceStatus(tenant, namespace, function, "0", null, null, null) !=null); + assertNotNull(this.resource.getFunctionInstanceStatus(tenant, namespace, function, "0", null, null, null)); } @Test @@ -224,7 +226,7 @@ public void testMetricsEmpty() { functionStats.addInstance(instanceStats1); functionStats.addInstance(instanceStats2); - Assert.assertTrue(functionStats.calculateOverall() != null); + assertNotNull(functionStats.calculateOverall()); } @Test @@ -239,7 +241,7 @@ public void testIsAuthorizedRole() throws PulsarAdminException { // test super user AuthenticationDataSource authenticationDataSource = mock(AuthenticationDataSource.class); - Assert.assertTrue(functionImpl.isAuthorizedRole("test-tenant", "test-ns", superUser, authenticationDataSource)); + assertTrue(functionImpl.isAuthorizedRole("test-tenant", "test-ns", superUser, authenticationDataSource)); // test normal user functionImpl = spy(new FunctionsImpl(() -> mockedWorkerService)); @@ -249,7 +251,7 @@ public void testIsAuthorizedRole() throws PulsarAdminException { PulsarAdmin admin = mock(PulsarAdmin.class); when(admin.tenants()).thenReturn(tenants); when(this.mockedWorkerService.getBrokerAdmin()).thenReturn(admin); - Assert.assertFalse(functionImpl.isAuthorizedRole("test-tenant", "test-ns", "test-user", authenticationDataSource)); + assertFalse(functionImpl.isAuthorizedRole("test-tenant", "test-ns", "test-user", authenticationDataSource)); // if user is tenant admin functionImpl = spy(new FunctionsImpl(() -> mockedWorkerService)); @@ -262,7 +264,7 @@ public void testIsAuthorizedRole() throws PulsarAdminException { admin = mock(PulsarAdmin.class); when(admin.tenants()).thenReturn(tenants); when(this.mockedWorkerService.getBrokerAdmin()).thenReturn(admin); - Assert.assertTrue(functionImpl.isAuthorizedRole("test-tenant", "test-ns", "test-user", authenticationDataSource)); + assertTrue(functionImpl.isAuthorizedRole("test-tenant", "test-ns", "test-user", authenticationDataSource)); // test user allow function action functionImpl = spy(new FunctionsImpl(() -> mockedWorkerService)); @@ -273,7 +275,7 @@ public void testIsAuthorizedRole() throws PulsarAdminException { admin = mock(PulsarAdmin.class); when(admin.tenants()).thenReturn(tenants); when(this.mockedWorkerService.getBrokerAdmin()).thenReturn(admin); - Assert.assertTrue(functionImpl.isAuthorizedRole("test-tenant", "test-ns", "test-user", authenticationDataSource)); + assertTrue(functionImpl.isAuthorizedRole("test-tenant", "test-ns", "test-user", authenticationDataSource)); // test role is null functionImpl = spy(new FunctionsImpl(() -> mockedWorkerService)); @@ -284,7 +286,7 @@ public void testIsAuthorizedRole() throws PulsarAdminException { admin = mock(PulsarAdmin.class); when(admin.tenants()).thenReturn(tenants); when(this.mockedWorkerService.getBrokerAdmin()).thenReturn(admin); - Assert.assertFalse(functionImpl.isAuthorizedRole("test-tenant", "test-ns", null, authenticationDataSource)); + assertFalse(functionImpl.isAuthorizedRole("test-tenant", "test-ns", null, authenticationDataSource)); } @Test @@ -297,10 +299,10 @@ public void testIsSuperUser() throws PulsarAdminException { doReturn(workerConfig).when(mockedWorkerService).getWorkerConfig(); AuthenticationDataSource authenticationDataSource = mock(AuthenticationDataSource.class); - Assert.assertTrue(functionImpl.isSuperUser(superUser)); + assertTrue(functionImpl.isSuperUser(superUser)); - Assert.assertFalse(functionImpl.isSuperUser("normal-user")); - Assert.assertFalse(functionImpl.isSuperUser( null)); + assertFalse(functionImpl.isSuperUser("normal-user")); + assertFalse(functionImpl.isSuperUser( null)); // test super roles is null @@ -309,7 +311,7 @@ public void testIsSuperUser() throws PulsarAdminException { workerConfig.setAuthorizationEnabled(true); doReturn(workerConfig).when(mockedWorkerService).getWorkerConfig(); - Assert.assertFalse(functionImpl.isSuperUser(superUser)); + assertFalse(functionImpl.isSuperUser(superUser)); } public static FunctionConfig createDefaultFunctionConfig() { diff --git a/pulsar-io/common/src/test/java/org/apache/pulsar/io/common/IOConfigUtilsTest.java b/pulsar-io/common/src/test/java/org/apache/pulsar/io/common/IOConfigUtilsTest.java index df263dec0fa9d..51f4e6ebf3f98 100644 --- a/pulsar-io/common/src/test/java/org/apache/pulsar/io/common/IOConfigUtilsTest.java +++ b/pulsar-io/common/src/test/java/org/apache/pulsar/io/common/IOConfigUtilsTest.java @@ -19,7 +19,6 @@ package org.apache.pulsar.io.common; import lombok.Data; -import lombok.ToString; import lombok.extern.slf4j.Slf4j; import org.apache.pulsar.io.core.SinkContext; import org.apache.pulsar.io.core.SourceContext; diff --git a/pulsar-io/flume/src/test/java/org/apache/pulsar/io/flume/node/TestAbstractConfigurationProvider.java b/pulsar-io/flume/src/test/java/org/apache/pulsar/io/flume/node/TestAbstractConfigurationProvider.java index ed2cf3f2e2212..492fdca7ab934 100644 --- a/pulsar-io/flume/src/test/java/org/apache/pulsar/io/flume/node/TestAbstractConfigurationProvider.java +++ b/pulsar-io/flume/src/test/java/org/apache/pulsar/io/flume/node/TestAbstractConfigurationProvider.java @@ -18,8 +18,13 @@ */ package org.apache.pulsar.io.flume.node; +import static junit.framework.Assert.assertEquals; +import static junit.framework.Assert.assertNotSame; +import static junit.framework.Assert.assertSame; +import static junit.framework.Assert.assertTrue; + import com.google.common.collect.Maps; -import junit.framework.Assert; +import java.util.Map; import org.apache.flume.Channel; import org.apache.flume.ChannelException; import org.apache.flume.Context; @@ -35,8 +40,6 @@ import org.apache.flume.source.AbstractSource; import org.junit.Test; -import java.util.Map; - public class TestAbstractConfigurationProvider { @Test @@ -48,11 +51,11 @@ public void testDispoableChannel() throws Exception { new MemoryConfigurationProvider(agentName, properties); MaterializedConfiguration config1 = provider.getConfiguration(); Channel channel1 = config1.getChannels().values().iterator().next(); - Assert.assertTrue(channel1 instanceof DisposableChannel); + assertTrue(channel1 instanceof DisposableChannel); MaterializedConfiguration config2 = provider.getConfiguration(); Channel channel2 = config2.getChannels().values().iterator().next(); - Assert.assertTrue(channel2 instanceof DisposableChannel); - Assert.assertNotSame(channel1, channel2); + assertTrue(channel2 instanceof DisposableChannel); + assertNotSame(channel1, channel2); } @Test @@ -65,13 +68,13 @@ public void testReusableChannel() throws Exception { MaterializedConfiguration config1 = provider.getConfiguration(); Channel channel1 = config1.getChannels().values().iterator().next(); - Assert.assertTrue(channel1 instanceof RecyclableChannel); + assertTrue(channel1 instanceof RecyclableChannel); MaterializedConfiguration config2 = provider.getConfiguration(); Channel channel2 = config2.getChannels().values().iterator().next(); - Assert.assertTrue(channel2 instanceof RecyclableChannel); + assertTrue(channel2 instanceof RecyclableChannel); - Assert.assertSame(channel1, channel2); + assertSame(channel1, channel2); } @Test @@ -84,13 +87,13 @@ public void testUnspecifiedChannel() throws Exception { MaterializedConfiguration config1 = provider.getConfiguration(); Channel channel1 = config1.getChannels().values().iterator().next(); - Assert.assertTrue(channel1 instanceof UnspecifiedChannel); + assertTrue(channel1 instanceof UnspecifiedChannel); MaterializedConfiguration config2 = provider.getConfiguration(); Channel channel2 = config2.getChannels().values().iterator().next(); - Assert.assertTrue(channel2 instanceof UnspecifiedChannel); + assertTrue(channel2 instanceof UnspecifiedChannel); - Assert.assertSame(channel1, channel2); + assertSame(channel1, channel2); } @Test @@ -106,19 +109,19 @@ public void testReusableChannelNotReusedLater() throws Exception { new MemoryConfigurationProvider(agentName, propertiesReusable); MaterializedConfiguration config1 = provider.getConfiguration(); Channel channel1 = config1.getChannels().values().iterator().next(); - Assert.assertTrue(channel1 instanceof RecyclableChannel); + assertTrue(channel1 instanceof RecyclableChannel); provider.setProperties(propertiesDispoable); MaterializedConfiguration config2 = provider.getConfiguration(); Channel channel2 = config2.getChannels().values().iterator().next(); - Assert.assertTrue(channel2 instanceof DisposableChannel); + assertTrue(channel2 instanceof DisposableChannel); provider.setProperties(propertiesReusable); MaterializedConfiguration config3 = provider.getConfiguration(); Channel channel3 = config3.getChannels().values().iterator().next(); - Assert.assertTrue(channel3 instanceof RecyclableChannel); + assertTrue(channel3 instanceof RecyclableChannel); - Assert.assertNotSame(channel1, channel3); + assertNotSame(channel1, channel3); } @Test @@ -132,9 +135,9 @@ public void testSourceThrowsExceptionDuringConfiguration() throws Exception { MemoryConfigurationProvider provider = new MemoryConfigurationProvider(agentName, properties); MaterializedConfiguration config = provider.getConfiguration(); - Assert.assertTrue(config.getSourceRunners().size() == 0); - Assert.assertTrue(config.getChannels().size() == 1); - Assert.assertTrue(config.getSinkRunners().size() == 1); + assertEquals(0, config.getSourceRunners().size()); + assertEquals(1, config.getChannels().size()); + assertEquals(1, config.getSinkRunners().size()); } @Test @@ -148,9 +151,9 @@ public void testChannelThrowsExceptionDuringConfiguration() throws Exception { MemoryConfigurationProvider provider = new MemoryConfigurationProvider(agentName, properties); MaterializedConfiguration config = provider.getConfiguration(); - Assert.assertTrue(config.getSourceRunners().size() == 0); - Assert.assertTrue(config.getChannels().size() == 0); - Assert.assertTrue(config.getSinkRunners().size() == 0); + assertEquals(0, config.getSourceRunners().size()); + assertEquals(0, config.getChannels().size()); + assertEquals(0, config.getSinkRunners().size()); } @Test @@ -164,9 +167,9 @@ public void testSinkThrowsExceptionDuringConfiguration() throws Exception { MemoryConfigurationProvider provider = new MemoryConfigurationProvider(agentName, properties); MaterializedConfiguration config = provider.getConfiguration(); - Assert.assertTrue(config.getSourceRunners().size() == 1); - Assert.assertTrue(config.getChannels().size() == 1); - Assert.assertTrue(config.getSinkRunners().size() == 0); + assertEquals(1, config.getSourceRunners().size()); + assertEquals(1, config.getChannels().size()); + assertEquals(0, config.getSinkRunners().size()); } @Test @@ -181,9 +184,9 @@ public void testSourceAndSinkThrowExceptionDuringConfiguration() MemoryConfigurationProvider provider = new MemoryConfigurationProvider(agentName, properties); MaterializedConfiguration config = provider.getConfiguration(); - Assert.assertTrue(config.getSourceRunners().size() == 0); - Assert.assertTrue(config.getChannels().size() == 0); - Assert.assertTrue(config.getSinkRunners().size() == 0); + assertEquals(0, config.getSourceRunners().size()); + assertEquals(0, config.getChannels().size()); + assertEquals(0, config.getSinkRunners().size()); } @Test @@ -204,36 +207,36 @@ public void testSinkSourceMismatchDuringConfiguration() throws Exception { MemoryConfigurationProvider provider = new MemoryConfigurationProvider(agentName, properties); MaterializedConfiguration config = provider.getConfiguration(); - Assert.assertTrue(config.getSourceRunners().size() == 1); - Assert.assertTrue(config.getChannels().size() == 1); - Assert.assertTrue(config.getSinkRunners().size() == 1); + assertEquals(1, config.getSourceRunners().size()); + assertEquals(1, config.getChannels().size()); + assertEquals(1, config.getSinkRunners().size()); properties.put(agentName + ".sources.source1.batchSize", "1001"); properties.put(agentName + ".sinks.sink1.batch-size", "1000"); provider = new MemoryConfigurationProvider(agentName, properties); config = provider.getConfiguration(); - Assert.assertTrue(config.getSourceRunners().size() == 0); - Assert.assertTrue(config.getChannels().size() == 1); - Assert.assertTrue(config.getSinkRunners().size() == 1); + assertEquals(0, config.getSourceRunners().size()); + assertEquals(1, config.getChannels().size()); + assertEquals(1, config.getSinkRunners().size()); properties.put(agentName + ".sources.source1.batchSize", "1000"); properties.put(agentName + ".sinks.sink1.batch-size", "1001"); provider = new MemoryConfigurationProvider(agentName, properties); config = provider.getConfiguration(); - Assert.assertTrue(config.getSourceRunners().size() == 1); - Assert.assertTrue(config.getChannels().size() == 1); - Assert.assertTrue(config.getSinkRunners().size() == 0); + assertEquals(1, config.getSourceRunners().size()); + assertEquals(1, config.getChannels().size()); + assertEquals(0, config.getSinkRunners().size()); properties.put(agentName + ".sources.source1.batchSize", "1001"); properties.put(agentName + ".sinks.sink1.batch-size", "1001"); provider = new MemoryConfigurationProvider(agentName, properties); config = provider.getConfiguration(); - Assert.assertTrue(config.getSourceRunners().size() == 0); - Assert.assertTrue(config.getChannels().size() == 0); - Assert.assertTrue(config.getSinkRunners().size() == 0); + assertEquals(0, config.getSourceRunners().size()); + assertEquals(0, config.getChannels().size()); + assertEquals(0, config.getSinkRunners().size()); } private Map getProperties(String agentName, diff --git a/pulsar-io/jdbc/src/main/java/org/apache/pulsar/io/jdbc/JdbcAbstractSink.java b/pulsar-io/jdbc/src/main/java/org/apache/pulsar/io/jdbc/JdbcAbstractSink.java index 40e2c23fc1159..f0ccec3c88668 100644 --- a/pulsar-io/jdbc/src/main/java/org/apache/pulsar/io/jdbc/JdbcAbstractSink.java +++ b/pulsar-io/jdbc/src/main/java/org/apache/pulsar/io/jdbc/JdbcAbstractSink.java @@ -22,7 +22,6 @@ import com.google.common.collect.Lists; import java.sql.Connection; import java.sql.PreparedStatement; -import java.sql.Statement; import java.util.Arrays; import java.util.List; import java.util.Map; diff --git a/pulsar-io/kafka-connect-adaptor/src/test/java/org/apache/pulsar/io/kafka/connect/KafkaConnectSourceTest.java b/pulsar-io/kafka-connect-adaptor/src/test/java/org/apache/pulsar/io/kafka/connect/KafkaConnectSourceTest.java index 4e4bf8162afa8..d2c38631739fd 100644 --- a/pulsar-io/kafka-connect-adaptor/src/test/java/org/apache/pulsar/io/kafka/connect/KafkaConnectSourceTest.java +++ b/pulsar-io/kafka-connect-adaptor/src/test/java/org/apache/pulsar/io/kafka/connect/KafkaConnectSourceTest.java @@ -18,7 +18,7 @@ */ package org.apache.pulsar.io.kafka.connect; -import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import java.io.File; @@ -108,14 +108,14 @@ public void testOpenAndRead() throws Exception { Record> record = kafkaConnectSource.read(); String readBack1 = new String(record.getValue().getValue()); assertTrue(line1.contains(readBack1)); - assertEquals(record.getValue().getKey(), null); + assertNull(record.getValue().getKey()); log.info("read line1: {}", readBack1); record.ack(); record = kafkaConnectSource.read(); String readBack2 = new String(record.getValue().getValue()); assertTrue(line2.contains(readBack2)); - assertEquals(record.getValue().getKey(), null); + assertNull(record.getValue().getKey()); log.info("read line2: {}", readBack2); record.ack(); @@ -126,7 +126,7 @@ record = kafkaConnectSource.read(); record = kafkaConnectSource.read(); String readBack3 = new String(record.getValue().getValue()); assertTrue(line3.contains(readBack3)); - assertEquals(record.getValue().getKey(), null); + assertNull(record.getValue().getKey()); log.info("read line3: {}", readBack3); record.ack(); } diff --git a/pulsar-io/kinesis/src/test/java/org/apache/pulsar/io/kinesis/UtilsTest.java b/pulsar-io/kinesis/src/test/java/org/apache/pulsar/io/kinesis/UtilsTest.java index f7e66822e1e7f..a8be9c87353b2 100644 --- a/pulsar-io/kinesis/src/test/java/org/apache/pulsar/io/kinesis/UtilsTest.java +++ b/pulsar-io/kinesis/src/test/java/org/apache/pulsar/io/kinesis/UtilsTest.java @@ -19,6 +19,8 @@ package org.apache.pulsar.io.kinesis; import static java.util.Base64.getDecoder; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertTrue; import com.google.gson.Gson; @@ -39,7 +41,6 @@ import org.apache.pulsar.functions.source.RecordWithEncryptionContext; import org.apache.pulsar.io.kinesis.fbs.KeyValue; import org.apache.pulsar.io.kinesis.fbs.Message; -import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.testng.collections.Maps; @@ -82,17 +83,17 @@ public void testJsonSerialization() throws Exception { // deserialize from json and assert KinesisMessageResponse kinesisJsonResponse = deSerializeRecordFromJson(json); - Assert.assertEquals(data, getDecoder().decode(kinesisJsonResponse.getPayloadBase64())); + assertEquals(data, getDecoder().decode(kinesisJsonResponse.getPayloadBase64())); EncryptionCtx encryptionCtxDeser = kinesisJsonResponse.getEncryptionCtx(); - Assert.assertEquals(key1Value.getBytes(), + assertEquals(key1Value.getBytes(), getDecoder().decode(encryptionCtxDeser.getKeysMapBase64().get(keyNames[0]))); - Assert.assertEquals(key2Value.getBytes(), + assertEquals(key2Value.getBytes(), getDecoder().decode(encryptionCtxDeser.getKeysMapBase64().get(keyNames[1]))); - Assert.assertEquals(param.getBytes(), getDecoder().decode(encryptionCtxDeser.getEncParamBase64())); - Assert.assertEquals(algo, encryptionCtxDeser.getAlgorithm()); - Assert.assertEquals(metadata1, encryptionCtxDeser.getKeysMetadataMap().get(keyNames[0])); - Assert.assertEquals(metadata2, encryptionCtxDeser.getKeysMetadataMap().get(keyNames[1])); - Assert.assertEquals(properties, kinesisJsonResponse.getProperties()); + assertEquals(param.getBytes(), getDecoder().decode(encryptionCtxDeser.getEncParamBase64())); + assertEquals(algo, encryptionCtxDeser.getAlgorithm()); + assertEquals(metadata1, encryptionCtxDeser.getKeysMetadataMap().get(keyNames[0])); + assertEquals(metadata2, encryptionCtxDeser.getKeysMetadataMap().get(keyNames[1])); + assertEquals(properties, kinesisJsonResponse.getProperties()); } @@ -126,7 +127,7 @@ public void testFbSerialization(boolean isEncryption) throws Exception { Message kinesisJsonResponse = Message.getRootAsMessage(flatBuffer); byte[] fbPayloadBytes = new byte[kinesisJsonResponse.payloadLength()]; kinesisJsonResponse.payloadAsByteBuffer().get(fbPayloadBytes); - Assert.assertEquals(data, fbPayloadBytes); + assertEquals(data, fbPayloadBytes); if(isEncryption) { org.apache.pulsar.io.kinesis.fbs.EncryptionCtx encryptionCtxDeser = kinesisJsonResponse.encryptionCtx(); @@ -153,17 +154,17 @@ public void testFbSerialization(boolean isEncryption) throws Exception { byte[] paramBytes = new byte[encryptionCtxDeser.paramLength()]; encryptionCtxDeser.paramAsByteBuffer().get(paramBytes); - Assert.assertEquals(totalKeys, 2); - Assert.assertEquals(batchSize, fbBatchSize); - Assert.assertEquals(isBathcMessage, true); - Assert.assertEquals(compressionMsgSize, fbCompressionMsgSize); - Assert.assertEquals(keyValues[0], fbKeyValueResult.get(keyNames[0])); - Assert.assertEquals(keyValues[1], fbKeyValueResult.get(keyNames[1])); - Assert.assertEquals(metadata1, fbKeyMetadataResult.get(keyNames[0])); - Assert.assertEquals(metadata2, fbKeyMetadataResult.get(keyNames[1])); - Assert.assertEquals(compressionType, org.apache.pulsar.io.kinesis.fbs.CompressionType.LZ4); - Assert.assertEquals(param.getBytes(), paramBytes); - Assert.assertEquals(algo, encryptionCtxDeser.algo()); + assertEquals(totalKeys, 2); + assertEquals(batchSize, fbBatchSize); + assertTrue(isBathcMessage); + assertEquals(compressionMsgSize, fbCompressionMsgSize); + assertEquals(keyValues[0], fbKeyValueResult.get(keyNames[0])); + assertEquals(keyValues[1], fbKeyValueResult.get(keyNames[1])); + assertEquals(metadata1, fbKeyMetadataResult.get(keyNames[0])); + assertEquals(metadata2, fbKeyMetadataResult.get(keyNames[1])); + assertEquals(compressionType, org.apache.pulsar.io.kinesis.fbs.CompressionType.LZ4); + assertEquals(param.getBytes(), paramBytes); + assertEquals(algo, encryptionCtxDeser.algo()); } Map fbproperties = Maps.newHashMap(); @@ -171,7 +172,7 @@ public void testFbSerialization(boolean isEncryption) throws Exception { KeyValue property = kinesisJsonResponse.properties(i); fbproperties.put(property.key(), property.value()); } - Assert.assertEquals(properties, fbproperties); + assertEquals(properties, fbproperties); } } diff --git a/pulsar-proxy/src/test/java/org/apache/pulsar/proxy/server/ProxyTest.java b/pulsar-proxy/src/test/java/org/apache/pulsar/proxy/server/ProxyTest.java index 42a990e5824ff..947561140bd59 100644 --- a/pulsar-proxy/src/test/java/org/apache/pulsar/proxy/server/ProxyTest.java +++ b/pulsar-proxy/src/test/java/org/apache/pulsar/proxy/server/ProxyTest.java @@ -24,7 +24,6 @@ import static org.mockito.Mockito.doReturn; import static org.testng.Assert.assertEquals; -import java.util.concurrent.ExecutionException; import java.util.Optional; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; diff --git a/pulsar-sql/presto-pulsar/src/main/java/org/apache/pulsar/sql/presto/PulsarRecordCursor.java b/pulsar-sql/presto-pulsar/src/main/java/org/apache/pulsar/sql/presto/PulsarRecordCursor.java index b2e8af5edef66..9afc2cd6b0e97 100644 --- a/pulsar-sql/presto-pulsar/src/main/java/org/apache/pulsar/sql/presto/PulsarRecordCursor.java +++ b/pulsar-sql/presto-pulsar/src/main/java/org/apache/pulsar/sql/presto/PulsarRecordCursor.java @@ -47,7 +47,6 @@ import java.util.Map; import java.util.concurrent.atomic.AtomicLong; -import org.apache.avro.Schema; import org.apache.bookkeeper.mledger.AsyncCallbacks; import org.apache.bookkeeper.mledger.Entry; import org.apache.bookkeeper.mledger.ManagedLedgerConfig; @@ -61,7 +60,6 @@ import org.apache.pulsar.common.api.raw.RawMessage; import org.apache.pulsar.common.naming.NamespaceName; import org.apache.pulsar.common.naming.TopicName; -import org.apache.pulsar.common.schema.SchemaType; import org.jctools.queues.MessagePassingQueue; import org.jctools.queues.SpscArrayQueue; diff --git a/pulsar-zookeeper-utils/src/test/java/org/apache/pulsar/zookeeper/LocalZooKeeperConnectionServiceTest.java b/pulsar-zookeeper-utils/src/test/java/org/apache/pulsar/zookeeper/LocalZooKeeperConnectionServiceTest.java index d05909e3ca928..3ed1d175f091c 100644 --- a/pulsar-zookeeper-utils/src/test/java/org/apache/pulsar/zookeeper/LocalZooKeeperConnectionServiceTest.java +++ b/pulsar-zookeeper-utils/src/test/java/org/apache/pulsar/zookeeper/LocalZooKeeperConnectionServiceTest.java @@ -19,12 +19,11 @@ package org.apache.pulsar.zookeeper; import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; -import org.apache.pulsar.zookeeper.LocalZooKeeperConnectionService; -import org.apache.pulsar.zookeeper.ZooKeeperClientFactory; -import org.apache.pulsar.zookeeper.ZookeeperClientFactoryImpl; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.MockZooKeeper; import org.testng.annotations.AfterMethod; @@ -60,7 +59,7 @@ void testSimpleZooKeeperConnection() throws Exception { // Create persistent node LocalZooKeeperConnectionService.checkAndCreatePersistNode(zk, "/path1"); - assertTrue(zk.exists("/path1", false) != null); + assertNotNull(zk.exists("/path1", false)); // Delete and re-create existing node zk.setSessionId(-1L); // The sessionId must be set to except 0L in order to re-create. @@ -69,32 +68,32 @@ void testSimpleZooKeeperConnection() throws Exception { // Try to create existing node (nothing should happen) LocalZooKeeperConnectionService.checkAndCreatePersistNode(zk, "/path1"); - assertTrue(zk.exists("/path1", false) != null); + assertNotNull(zk.exists("/path1", false)); // Create new node (data is given as String) LocalZooKeeperConnectionService.createIfAbsent(zk, "/path2", "data2", CreateMode.EPHEMERAL); - assertTrue(zk.exists("/path2", false) != null); + assertNotNull(zk.exists("/path2", false)); assertEquals(zk.getData("/path2", null, null), "data2".getBytes()); // Create new node (data is given as bytes) LocalZooKeeperConnectionService.createIfAbsent(zk, "/path3", "data3".getBytes(), CreateMode.EPHEMERAL); - assertTrue(zk.exists("/path3", false) != null); + assertNotNull(zk.exists("/path3", false)); assertEquals(zk.getData("/path3", null, null), "data3".getBytes()); // delete nodes LocalZooKeeperConnectionService.deleteIfExists(zk, "/path1", -1); - assertTrue(zk.exists("/path1", false) == null); + assertNull(zk.exists("/path1", false)); LocalZooKeeperConnectionService.deleteIfExists(zk, "/path2", -1); - assertTrue(zk.exists("/path2", false) == null); + assertNull(zk.exists("/path2", false)); LocalZooKeeperConnectionService.deleteIfExists(zk, "/path3", -1); - assertTrue(zk.exists("/path3", false) == null); + assertNull(zk.exists("/path3", false)); // delete not existing node LocalZooKeeperConnectionService.deleteIfExists(zk, "/not_exist", -1); // Try to create invalid node (nothing should happen) LocalZooKeeperConnectionService.checkAndCreatePersistNode(zk, "/////"); - assertTrue(zk.exists("//////", false) == null); + assertNull(zk.exists("//////", false)); localZkConnectionService.close(); } diff --git a/pulsar-zookeeper-utils/src/test/java/org/apache/pulsar/zookeeper/ZkIsolatedBookieEnsemblePlacementPolicyTest.java b/pulsar-zookeeper-utils/src/test/java/org/apache/pulsar/zookeeper/ZkIsolatedBookieEnsemblePlacementPolicyTest.java index 6187f1f50ebe4..192b0a1d55681 100644 --- a/pulsar-zookeeper-utils/src/test/java/org/apache/pulsar/zookeeper/ZkIsolatedBookieEnsemblePlacementPolicyTest.java +++ b/pulsar-zookeeper-utils/src/test/java/org/apache/pulsar/zookeeper/ZkIsolatedBookieEnsemblePlacementPolicyTest.java @@ -18,6 +18,7 @@ */ package org.apache.pulsar.zookeeper; +import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; @@ -174,7 +175,7 @@ public void testBasic() throws Exception { ensemble = isolationPolicy.newEnsemble(1, 1, 1, Collections.emptyMap(), bookieToExclude).getResult(); BookieSocketAddress chosenBookie = isolationPolicy.replaceBookie(1, 1, 1, Collections.emptyMap(), ensemble, ensemble.get(0), new HashSet<>()).getResult(); - assertTrue(chosenBookie.equals(new BookieSocketAddress(BOOKIE1))); + assertEquals(new BookieSocketAddress(BOOKIE1), chosenBookie); localZkc.delete(ZkBookieRackAffinityMapping.BOOKIE_INFO_ROOT_PATH, -1); } diff --git a/tests/integration/src/test/java/org/apache/pulsar/tests/integration/cli/AdminMultiHostTest.java b/tests/integration/src/test/java/org/apache/pulsar/tests/integration/cli/AdminMultiHostTest.java index 8103143af2823..e11d499346760 100644 --- a/tests/integration/src/test/java/org/apache/pulsar/tests/integration/cli/AdminMultiHostTest.java +++ b/tests/integration/src/test/java/org/apache/pulsar/tests/integration/cli/AdminMultiHostTest.java @@ -19,7 +19,6 @@ package org.apache.pulsar.tests.integration.cli; import java.util.UUID; -import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; diff --git a/tests/pulsar-storm-test/src/test/java/org/apache/pulsar/storm/PulsarSpoutTest.java b/tests/pulsar-storm-test/src/test/java/org/apache/pulsar/storm/PulsarSpoutTest.java index b13cefd247e6f..719adab21a379 100644 --- a/tests/pulsar-storm-test/src/test/java/org/apache/pulsar/storm/PulsarSpoutTest.java +++ b/tests/pulsar-storm-test/src/test/java/org/apache/pulsar/storm/PulsarSpoutTest.java @@ -20,6 +20,10 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import java.lang.reflect.Method; @@ -36,7 +40,6 @@ import org.apache.storm.task.TopologyContext; import org.apache.storm.topology.OutputFieldsDeclarer; import org.apache.storm.tuple.Values; -import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @@ -113,8 +116,8 @@ public void testBasic() throws Exception { String msgContent = "hello world"; producer.send(msgContent.getBytes()); spout.nextTuple(); - Assert.assertTrue(mockCollector.emitted()); - Assert.assertTrue(msgContent.equals(mockCollector.getTupleData())); + assertTrue(mockCollector.emitted()); + assertEquals(mockCollector.getTupleData(), msgContent); spout.ack(mockCollector.getLastMessage()); } @@ -127,8 +130,8 @@ public void testRedeliverOnFail() throws Exception { mockCollector.reset(); Thread.sleep(150); spout.nextTuple(); - Assert.assertTrue(mockCollector.emitted()); - Assert.assertTrue(msgContent.equals(mockCollector.getTupleData())); + assertTrue(mockCollector.emitted()); + assertEquals(mockCollector.getTupleData(), msgContent); spout.ack(mockCollector.getLastMessage()); } @@ -140,8 +143,8 @@ public void testNoRedeliverOnAck() throws Exception { spout.ack(mockCollector.getLastMessage()); mockCollector.reset(); spout.nextTuple(); - Assert.assertFalse(mockCollector.emitted()); - Assert.assertNull(mockCollector.getTupleData()); + assertFalse(mockCollector.emitted()); + assertNull(mockCollector.getTupleData()); } @Test @@ -154,8 +157,8 @@ public void testLimitedRedeliveriesOnTimeout() throws Exception { .currentTimeMillis()) { mockCollector.reset(); spout.nextTuple(); - Assert.assertTrue(mockCollector.emitted()); - Assert.assertTrue(msgContent.equals(mockCollector.getTupleData())); + assertTrue(mockCollector.emitted()); + assertEquals(mockCollector.getTupleData(), msgContent); spout.fail(mockCollector.getLastMessage()); // wait to avoid backoff Thread.sleep(500); @@ -165,8 +168,8 @@ public void testLimitedRedeliveriesOnTimeout() throws Exception { mockCollector.reset(); Thread.sleep(500); spout.nextTuple(); - Assert.assertFalse(mockCollector.emitted()); - Assert.assertNull(mockCollector.getTupleData()); + assertFalse(mockCollector.emitted()); + assertNull(mockCollector.getTupleData()); } @Test @@ -175,31 +178,31 @@ public void testLimitedRedeliveriesOnCount() throws Exception { producer.send(msgContent.getBytes()); spout.nextTuple(); - Assert.assertTrue(mockCollector.emitted()); - Assert.assertTrue(msgContent.equals(mockCollector.getTupleData())); + assertTrue(mockCollector.emitted()); + assertEquals(mockCollector.getTupleData(), msgContent); spout.fail(mockCollector.getLastMessage()); mockCollector.reset(); Thread.sleep(150); spout.nextTuple(); - Assert.assertTrue(mockCollector.emitted()); - Assert.assertTrue(msgContent.equals(mockCollector.getTupleData())); + assertTrue(mockCollector.emitted()); + assertEquals(mockCollector.getTupleData(), msgContent); spout.fail(mockCollector.getLastMessage()); mockCollector.reset(); Thread.sleep(300); spout.nextTuple(); - Assert.assertTrue(mockCollector.emitted()); - Assert.assertTrue(msgContent.equals(mockCollector.getTupleData())); + assertTrue(mockCollector.emitted()); + assertEquals(mockCollector.getTupleData(), msgContent); spout.fail(mockCollector.getLastMessage()); mockCollector.reset(); Thread.sleep(500); spout.nextTuple(); - Assert.assertFalse(mockCollector.emitted()); - Assert.assertNull(mockCollector.getTupleData()); + assertFalse(mockCollector.emitted()); + assertNull(mockCollector.getTupleData()); } @Test @@ -211,12 +214,12 @@ public void testBackoffOnRetry() throws Exception { mockCollector.reset(); // due to backoff we should not get the message again immediately spout.nextTuple(); - Assert.assertFalse(mockCollector.emitted()); - Assert.assertNull(mockCollector.getTupleData()); + assertFalse(mockCollector.emitted()); + assertNull(mockCollector.getTupleData()); Thread.sleep(100); spout.nextTuple(); - Assert.assertTrue(mockCollector.emitted()); - Assert.assertTrue(msgContent.equals(mockCollector.getTupleData())); + assertTrue(mockCollector.emitted()); + assertEquals(mockCollector.getTupleData(), msgContent); spout.ack(mockCollector.getLastMessage()); } @@ -225,8 +228,8 @@ public void testMessageDrop() throws Exception { String msgContent = "message to be dropped"; producer.send(msgContent.getBytes()); spout.nextTuple(); - Assert.assertFalse(mockCollector.emitted()); - Assert.assertNull(mockCollector.getTupleData()); + assertFalse(mockCollector.emitted()); + assertNull(mockCollector.getTupleData()); } @SuppressWarnings({ "rawtypes" }) @@ -237,39 +240,39 @@ public void testMetrics() throws Exception { producer.send(msgContent.getBytes()); spout.nextTuple(); Map metrics = spout.getMetrics(); - Assert.assertEquals(((Long) metrics.get(PulsarSpout.NO_OF_MESSAGES_RECEIVED)).longValue(), 1); - Assert.assertEquals(((Long) metrics.get(PulsarSpout.NO_OF_MESSAGES_EMITTED)).longValue(), 1); - Assert.assertEquals(((Long) metrics.get(PulsarSpout.NO_OF_PENDING_FAILED_MESSAGES)).longValue(), 0); - Assert.assertEquals(((Long) metrics.get(PulsarSpout.NO_OF_PENDING_ACKS)).longValue(), 1); - Assert.assertEquals(((Double) metrics.get(PulsarSpout.CONSUMER_RATE)).doubleValue(), + assertEquals(((Long) metrics.get(PulsarSpout.NO_OF_MESSAGES_RECEIVED)).longValue(), 1); + assertEquals(((Long) metrics.get(PulsarSpout.NO_OF_MESSAGES_EMITTED)).longValue(), 1); + assertEquals(((Long) metrics.get(PulsarSpout.NO_OF_PENDING_FAILED_MESSAGES)).longValue(), 0); + assertEquals(((Long) metrics.get(PulsarSpout.NO_OF_PENDING_ACKS)).longValue(), 1); + assertEquals(((Double) metrics.get(PulsarSpout.CONSUMER_RATE)).doubleValue(), 1.0 / pulsarSpoutConf.getMetricsTimeIntervalInSecs()); - Assert.assertEquals(((Double) metrics.get(PulsarSpout.CONSUMER_THROUGHPUT_BYTES)).doubleValue(), + assertEquals(((Double) metrics.get(PulsarSpout.CONSUMER_THROUGHPUT_BYTES)).doubleValue(), ((double) msgContent.getBytes().length) / pulsarSpoutConf.getMetricsTimeIntervalInSecs()); spout.fail(mockCollector.getLastMessage()); metrics = spout.getMetrics(); - Assert.assertEquals(((Long) metrics.get(PulsarSpout.NO_OF_MESSAGES_RECEIVED)).longValue(), 1); - Assert.assertEquals(((Long) metrics.get(PulsarSpout.NO_OF_MESSAGES_EMITTED)).longValue(), 1); - Assert.assertEquals(((Long) metrics.get(PulsarSpout.NO_OF_PENDING_FAILED_MESSAGES)).longValue(), 1); - Assert.assertEquals(((Long) metrics.get(PulsarSpout.NO_OF_PENDING_ACKS)).longValue(), 0); + assertEquals(((Long) metrics.get(PulsarSpout.NO_OF_MESSAGES_RECEIVED)).longValue(), 1); + assertEquals(((Long) metrics.get(PulsarSpout.NO_OF_MESSAGES_EMITTED)).longValue(), 1); + assertEquals(((Long) metrics.get(PulsarSpout.NO_OF_PENDING_FAILED_MESSAGES)).longValue(), 1); + assertEquals(((Long) metrics.get(PulsarSpout.NO_OF_PENDING_ACKS)).longValue(), 0); Thread.sleep(150); spout.nextTuple(); metrics = spout.getMetrics(); - Assert.assertEquals(((Long) metrics.get(PulsarSpout.NO_OF_MESSAGES_RECEIVED)).longValue(), 1); - Assert.assertEquals(((Long) metrics.get(PulsarSpout.NO_OF_MESSAGES_EMITTED)).longValue(), 2); - Assert.assertEquals(((Long) metrics.get(PulsarSpout.NO_OF_PENDING_FAILED_MESSAGES)).longValue(), 1); - Assert.assertEquals(((Long) metrics.get(PulsarSpout.NO_OF_PENDING_ACKS)).longValue(), 1); + assertEquals(((Long) metrics.get(PulsarSpout.NO_OF_MESSAGES_RECEIVED)).longValue(), 1); + assertEquals(((Long) metrics.get(PulsarSpout.NO_OF_MESSAGES_EMITTED)).longValue(), 2); + assertEquals(((Long) metrics.get(PulsarSpout.NO_OF_PENDING_FAILED_MESSAGES)).longValue(), 1); + assertEquals(((Long) metrics.get(PulsarSpout.NO_OF_PENDING_ACKS)).longValue(), 1); spout.ack(mockCollector.getLastMessage()); metrics = (Map) spout.getValueAndReset(); - Assert.assertEquals(((Long) metrics.get(PulsarSpout.NO_OF_MESSAGES_RECEIVED)).longValue(), 1); - Assert.assertEquals(((Long) metrics.get(PulsarSpout.NO_OF_MESSAGES_EMITTED)).longValue(), 2); - Assert.assertEquals(((Long) metrics.get(PulsarSpout.NO_OF_PENDING_FAILED_MESSAGES)).longValue(), 0); - Assert.assertEquals(((Long) metrics.get(PulsarSpout.NO_OF_PENDING_ACKS)).longValue(), 0); + assertEquals(((Long) metrics.get(PulsarSpout.NO_OF_MESSAGES_RECEIVED)).longValue(), 1); + assertEquals(((Long) metrics.get(PulsarSpout.NO_OF_MESSAGES_EMITTED)).longValue(), 2); + assertEquals(((Long) metrics.get(PulsarSpout.NO_OF_PENDING_FAILED_MESSAGES)).longValue(), 0); + assertEquals(((Long) metrics.get(PulsarSpout.NO_OF_PENDING_ACKS)).longValue(), 0); } @Test public void testSharedConsumer() throws Exception { TopicStats topicStats = admin.topics().getStats(topic); - Assert.assertEquals(topicStats.subscriptions.get(subscriptionName).consumers.size(), 1); + assertEquals(topicStats.subscriptions.get(subscriptionName).consumers.size(), 1); PulsarSpout otherSpout = new PulsarSpout(pulsarSpoutConf, PulsarClient.builder()); MockSpoutOutputCollector otherMockCollector = new MockSpoutOutputCollector(); SpoutOutputCollector collector = new SpoutOutputCollector(otherMockCollector); @@ -279,18 +282,18 @@ public void testSharedConsumer() throws Exception { otherSpout.open(Maps.newHashMap(), context, collector); topicStats = admin.topics().getStats(topic); - Assert.assertEquals(topicStats.subscriptions.get(subscriptionName).consumers.size(), 1); + assertEquals(topicStats.subscriptions.get(subscriptionName).consumers.size(), 1); otherSpout.close(); topicStats = admin.topics().getStats(topic); - Assert.assertEquals(topicStats.subscriptions.get(subscriptionName).consumers.size(), 1); + assertEquals(topicStats.subscriptions.get(subscriptionName).consumers.size(), 1); } @Test public void testNoSharedConsumer() throws Exception { TopicStats topicStats = admin.topics().getStats(topic); - Assert.assertEquals(topicStats.subscriptions.get(subscriptionName).consumers.size(), 1); + assertEquals(topicStats.subscriptions.get(subscriptionName).consumers.size(), 1); pulsarSpoutConf.setSharedConsumerEnabled(false); PulsarSpout otherSpout = new PulsarSpout(pulsarSpoutConf, PulsarClient.builder()); MockSpoutOutputCollector otherMockCollector = new MockSpoutOutputCollector(); @@ -301,12 +304,12 @@ public void testNoSharedConsumer() throws Exception { otherSpout.open(Maps.newHashMap(), context, collector); topicStats = admin.topics().getStats(topic); - Assert.assertEquals(topicStats.subscriptions.get(subscriptionName).consumers.size(), 2); + assertEquals(topicStats.subscriptions.get(subscriptionName).consumers.size(), 2); otherSpout.close(); topicStats = admin.topics().getStats(topic); - Assert.assertEquals(topicStats.subscriptions.get(subscriptionName).consumers.size(), 1); + assertEquals(topicStats.subscriptions.get(subscriptionName).consumers.size(), 1); } @Test diff --git a/tiered-storage/file-system/src/test/java/org/apache/bookkeeper/mledger/offload/filesystem/impl/FileSystemManagedLedgerOffloaderTest.java b/tiered-storage/file-system/src/test/java/org/apache/bookkeeper/mledger/offload/filesystem/impl/FileSystemManagedLedgerOffloaderTest.java index e03c5e14ce543..951dd27f79c6d 100644 --- a/tiered-storage/file-system/src/test/java/org/apache/bookkeeper/mledger/offload/filesystem/impl/FileSystemManagedLedgerOffloaderTest.java +++ b/tiered-storage/file-system/src/test/java/org/apache/bookkeeper/mledger/offload/filesystem/impl/FileSystemManagedLedgerOffloaderTest.java @@ -36,7 +36,6 @@ import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.MockZooKeeper; import org.apache.zookeeper.data.ACL; -import org.testng.Assert; import org.testng.annotations.Test; import java.net.URI; @@ -48,6 +47,9 @@ import java.util.UUID; import static java.nio.charset.StandardCharsets.UTF_8; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertTrue; public class FileSystemManagedLedgerOffloaderTest extends FileStoreTestBase { private final PulsarMockBookKeeper bk; @@ -100,7 +102,7 @@ public void testOffloadAndRead() throws Exception { UUID uuid = UUID.randomUUID(); offloader.offload(toWrite, uuid, map).get(); ReadHandle toTest = offloader.readOffloaded(toWrite.getId(), uuid, map).get(); - Assert.assertEquals(toTest.getLastAddConfirmed(), toWrite.getLastAddConfirmed()); + assertEquals(toTest.getLastAddConfirmed(), toWrite.getLastAddConfirmed()); LedgerEntries toTestEntries = toTest.read(0, numberOfEntries - 1); LedgerEntries toWriteEntries = toWrite.read(0,numberOfEntries - 1); Iterator toTestIter = toTestEntries.iterator(); @@ -109,10 +111,10 @@ public void testOffloadAndRead() throws Exception { LedgerEntry toWriteEntry = toWriteIter.next(); LedgerEntry toTestEntry = toTestIter.next(); - Assert.assertEquals(toWriteEntry.getLedgerId(), toTestEntry.getLedgerId()); - Assert.assertEquals(toWriteEntry.getEntryId(), toTestEntry.getEntryId()); - Assert.assertEquals(toWriteEntry.getLength(), toTestEntry.getLength()); - Assert.assertEquals(toWriteEntry.getEntryBuffer(), toTestEntry.getEntryBuffer()); + assertEquals(toWriteEntry.getLedgerId(), toTestEntry.getLedgerId()); + assertEquals(toWriteEntry.getEntryId(), toTestEntry.getEntryId()); + assertEquals(toWriteEntry.getLength(), toTestEntry.getLength()); + assertEquals(toWriteEntry.getEntryBuffer(), toTestEntry.getEntryBuffer()); } toTestEntries = toTest.read(1, numberOfEntries - 1); toWriteEntries = toWrite.read(1,numberOfEntries - 1); @@ -122,10 +124,10 @@ public void testOffloadAndRead() throws Exception { LedgerEntry toWriteEntry = toWriteIter.next(); LedgerEntry toTestEntry = toTestIter.next(); - Assert.assertEquals(toWriteEntry.getLedgerId(), toTestEntry.getLedgerId()); - Assert.assertEquals(toWriteEntry.getEntryId(), toTestEntry.getEntryId()); - Assert.assertEquals(toWriteEntry.getLength(), toTestEntry.getLength()); - Assert.assertEquals(toWriteEntry.getEntryBuffer(), toTestEntry.getEntryBuffer()); + assertEquals(toWriteEntry.getLedgerId(), toTestEntry.getLedgerId()); + assertEquals(toWriteEntry.getEntryId(), toTestEntry.getEntryId()); + assertEquals(toWriteEntry.getLength(), toTestEntry.getLength()); + assertEquals(toWriteEntry.getEntryBuffer(), toTestEntry.getEntryBuffer()); } } @@ -136,11 +138,11 @@ public void testDeleteOffload() throws Exception { offloader.offload(toWrite, uuid, map).get(); Configuration configuration = new Configuration(); FileSystem fileSystem = FileSystem.get(new URI(getURI()), configuration); - Assert.assertEquals(true, fileSystem.exists(new Path(createDataFilePath(storagePath, lh.getId(), uuid)))); - Assert.assertEquals(true, fileSystem.exists(new Path(createIndexFilePath(storagePath, lh.getId(), uuid)))); + assertTrue(fileSystem.exists(new Path(createDataFilePath(storagePath, lh.getId(), uuid)))); + assertTrue(fileSystem.exists(new Path(createIndexFilePath(storagePath, lh.getId(), uuid)))); offloader.deleteOffloaded(lh.getId(), uuid, map); - Assert.assertEquals(false, fileSystem.exists(new Path(createDataFilePath(storagePath, lh.getId(), uuid)))); - Assert.assertEquals(false, fileSystem.exists(new Path(createIndexFilePath(storagePath, lh.getId(), uuid)))); + assertFalse(fileSystem.exists(new Path(createDataFilePath(storagePath, lh.getId(), uuid)))); + assertFalse(fileSystem.exists(new Path(createIndexFilePath(storagePath, lh.getId(), uuid)))); } private String createStoragePath(String managedLedgerName) {