From e8dfd10c114b6c80dd2c9e15b84fc0cc3a005f04 Mon Sep 17 00:00:00 2001 From: Ben Manes Date: Sun, 9 Jun 2024 09:50:12 -0700 Subject: [PATCH] fix sonarlint warnings for tests, remove duplicative, add missing --- .../benmanes/caffeine/cache/AsMapTest.java | 2 +- .../caffeine/cache/AsyncAsMapTest.java | 18 +---- .../caffeine/cache/CaffeineSpecTest.java | 5 +- .../benmanes/caffeine/cache/CaffeineTest.java | 4 +- .../benmanes/caffeine/cache/EvictionTest.java | 79 +++++++++++-------- .../caffeine/cache/ExpirationTest.java | 6 +- .../caffeine/cache/ExpireAfterVarTest.java | 50 ++++++++++++ .../caffeine/cache/FrequencySketchTest.java | 8 +- .../caffeine/cache/LoadingCacheTest.java | 2 +- .../caffeine/cache/QueueSanityTest.java | 1 - .../caffeine/cache/RefreshAfterWriteTest.java | 3 +- .../caffeine/cache/TimerWheelTest.java | 2 +- .../caffeine/cache/buffer/BufferTest.java | 2 +- .../caffeine/cache/issues/Issue193Test.java | 18 ++--- .../caffeine/cache/issues/Issue298Test.java | 30 +++---- .../caffeine/cache/testing/CacheContext.java | 10 +-- .../cache/testing/CacheContextSubject.java | 4 +- .../caffeine/guava/CaffeinatedGuavaTest.java | 4 +- .../guava/compatibility/CacheLoadingTest.java | 6 +- .../caffeine/jcache/JCacheProfiler.java | 6 +- .../benmanes/caffeine/jcache/OSGiTest.java | 5 +- .../TypesafeConfigurationTest.java | 2 +- 22 files changed, 154 insertions(+), 113 deletions(-) diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/AsMapTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/AsMapTest.java index c88bb28693..03a13b4941 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/AsMapTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/AsMapTest.java @@ -2752,7 +2752,7 @@ public void entrySet_removeAll_bySet(Map map, CacheContext context) { @CheckNoStats @Test(dataProvider = "caches") public void entrySet_remove_null(Map map, CacheContext context) { - assertThat(map.values().remove(null)).isFalse(); + assertThat(map.entrySet().remove(null)).isFalse(); assertThat(map).isEqualTo(context.original()); } diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/AsyncAsMapTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/AsyncAsMapTest.java index b423c5ac1d..d3f0776323 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/AsyncAsMapTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/AsyncAsMapTest.java @@ -2507,7 +2507,7 @@ public void entrySet_removeAll_bySet(AsyncCache cache, CacheContext co @CheckNoStats @Test(dataProvider = "caches") public void entrySet_remove_null(AsyncCache cache, CacheContext context) { - assertThat(cache.asMap().values().remove(null)).isFalse(); + assertThat(cache.asMap().entrySet().remove(null)).isFalse(); assertThat(cache.synchronous().asMap()).isEqualTo(context.original()); } @@ -2586,7 +2586,6 @@ public void entrySet_removeIf_partial(AsyncCache cache, CacheContext c Predicate>> isEven = entry -> (entry.getValue().join().intValue() % 2) == 0; boolean hasEven = cache.asMap().entrySet().stream().anyMatch(isEven); - boolean removedIfEven = cache.asMap().entrySet().removeIf(isEven); assertThat(cache.asMap().entrySet().stream().anyMatch(isEven)).isFalse(); assertThat(removedIfEven).isEqualTo(hasEven); @@ -2610,21 +2609,6 @@ public void entrySet_removeIf_all(AsyncCache cache, CacheContext conte } } - @CacheSpec - @CheckNoStats - @Test(dataProvider = "caches") - public void entrySet_removeIf(AsyncCache cache, CacheContext context) { - Predicate>> isEven = - entry -> (entry.getValue().join().intValue() % 2) == 0; - boolean hasEven = cache.asMap().entrySet().stream().anyMatch(isEven); - boolean removedIfEven = cache.asMap().entrySet().removeIf(isEven); - assertThat(cache.asMap().entrySet().stream().anyMatch(isEven)).isFalse(); - assertThat(removedIfEven).isEqualTo(hasEven); - if (removedIfEven) { - assertThat(cache).hasSizeLessThan(context.initialSize()); - } - } - @CacheSpec @CheckNoStats @Test(dataProvider = "caches") diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/CaffeineSpecTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/CaffeineSpecTest.java index 97b1308a76..5d6803b30b 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/CaffeineSpecTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/CaffeineSpecTest.java @@ -118,7 +118,7 @@ private void runScenarios(CacheContext context, Epoch epoch) { } private void runTest(CacheContext context, Epoch epoch, Function formatter) { - CaffeineSpec spec = toSpec(context, epoch, formatter); + CaffeineSpec spec = toSpec(context, formatter); Caffeine builder = Caffeine.from(spec); checkInitialCapacity(spec, context, builder); @@ -134,8 +134,7 @@ private void runTest(CacheContext context, Epoch epoch, Function formatter) { + static CaffeineSpec toSpec(CacheContext context, Function formatter) { var options = new ArrayList(); if (context.initialCapacity() != InitialCapacity.DEFAULT) { options.add("initialCapacity=" + context.initialCapacity().size()); diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/CaffeineTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/CaffeineTest.java index ca95e74cb4..2c8fac5015 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/CaffeineTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/CaffeineTest.java @@ -205,13 +205,13 @@ public void loading_nullLoader() { @Test public void async_weakValues() { var builder = Caffeine.newBuilder().weakValues(); - assertThrows(IllegalStateException.class, () -> builder.buildAsync(loader)); + assertThrows(IllegalStateException.class, () -> builder.buildAsync()); } @Test public void async_softValues() { var builder = Caffeine.newBuilder().softValues(); - assertThrows(IllegalStateException.class, () -> builder.buildAsync(loader)); + assertThrows(IllegalStateException.class, () -> builder.buildAsync()); } @Test diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/EvictionTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/EvictionTest.java index a8c2043c2f..4aac036b00 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/EvictionTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/EvictionTest.java @@ -69,6 +69,7 @@ import com.github.benmanes.caffeine.cache.testing.CheckNoStats; import com.github.benmanes.caffeine.cache.testing.RemovalListeners.RejectingRemovalListener; import com.github.benmanes.caffeine.testing.Int; +import com.google.common.collect.HashBiMap; import com.google.common.collect.ImmutableList; import com.google.common.collect.Maps; import com.google.common.collect.Range; @@ -325,6 +326,46 @@ public void getAll_weigherFails_async(AsyncCache cache, CacheContext c .hasSize(context.absentKeys().size()); } + @Test(dataProvider = "caches") + @CacheSpec(population = Population.FULL, + maximumSize = Maximum.FULL, weigher = CacheWeigher.MOCKITO) + public void getAll_weigherFails_newEntries(Cache cache, CacheContext context) { + when(context.weigher().weigh(any(), any())).thenThrow(IllegalStateException.class); + assertThrows(IllegalStateException.class, () -> + cache.getAll(context.absentKeys(), keys -> HashBiMap.create(context.original()).inverse())); + assertThat(cache).containsExactlyEntriesIn(context.original()); + if (context.isCaffeine()) { + assertThat(logEvents() + .withMessage("Exception thrown during asynchronous load") + .withThrowable(IllegalStateException.class) + .withLevel(WARN) + .exclusively()) + .hasSize(context.isAsync() ? context.original().size() : 0); + } + } + + @Test(dataProvider = "caches") + @CacheSpec(population = Population.FULL, + maximumSize = Maximum.FULL, weigher = CacheWeigher.MOCKITO) + public void getAll_weigherFails_newEntries_async( + AsyncCache cache, CacheContext context) { + when(context.weigher().weigh(any(), any())).thenThrow(IllegalStateException.class); + var future = new CompletableFuture>(); + var result = cache.getAll(context.absentKeys(), (keys, executor) -> future); + future.complete(HashBiMap.create(context.original()).inverse()); + + assertThat(context).stats().failures(1); + assertThat(result).failsWith(CompletionException.class) + .hasCauseThat().isInstanceOf(IllegalStateException.class); + assertThat(cache).containsExactlyEntriesIn(context.original()); + assertThat(logEvents() + .withMessage("Exception thrown during asynchronous load") + .withThrowable(IllegalStateException.class) + .withLevel(WARN) + .exclusively()) + .hasSize(context.original().size()); + } + @Test(dataProvider = "caches") @CacheSpec(population = Population.EMPTY, maximumSize = Maximum.FULL, weigher = CacheWeigher.NEGATIVE) @@ -563,41 +604,9 @@ public void replaceConditionally_weigherFails_absent( public void replaceConditionally_weigherFails_presentKey( Cache cache, CacheContext context, Eviction eviction) { when(context.weigher().weigh(any(), any())).thenThrow(IllegalStateException.class); - assertThrows(IllegalStateException.class, () -> cache.asMap().replace( - context.firstKey(), context.original().get(context.firstKey()), context.absentValue())); - assertThat(cache).containsExactlyEntriesIn(context.original()); - assertThat(eviction.weightOf(context.firstKey())).hasValue(1); - } - - @Test(dataProvider = "caches") - @CacheSpec(population = Population.FULL, - maximumSize = Maximum.FULL, weigher = CacheWeigher.MOCKITO) - public void replaceConditionally_weigherFails_presentKey_async( - AsyncCache cache, CacheContext context) { - when(context.weigher().weigh(any(), any())).thenThrow(IllegalStateException.class); - var future = new CompletableFuture(); - cache.asMap().replace(context.firstKey(), cache.getIfPresent(context.firstKey()), future); - future.complete(context.absentValue()); - assertThat(context).stats().failures(1); - assertThat(cache).doesNotContainKey(context.absentKey()); - assertThat(logEvents() - .withMessage("Exception thrown during asynchronous load") - .withThrowable(IllegalStateException.class) - .withLevel(WARN) - .exclusively()) - .hasSize(1); - } - - @Test(dataProvider = "caches") - @CacheSpec(population = Population.FULL, - maximumSize = Maximum.FULL, weigher = CacheWeigher.MOCKITO) - public void replaceConditionally_weigherFails_presentKeyAndValue( - Cache cache, CacheContext context, Eviction eviction) { - when(context.weigher().weigh(any(), any())).thenThrow(IllegalStateException.class); - assertThrows(IllegalStateException.class, () -> { + assertThrows(IllegalStateException.class, () -> cache.asMap().replace(context.firstKey(), - context.original().get(context.firstKey()), context.absentValue()); - }); + context.original().get(context.firstKey()), context.absentValue())); assertThat(cache).containsExactlyEntriesIn(context.original()); assertThat(eviction.weightOf(context.firstKey())).hasValue(1); } @@ -605,7 +614,7 @@ public void replaceConditionally_weigherFails_presentKeyAndValue( @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, maximumSize = Maximum.FULL, weigher = CacheWeigher.MOCKITO) - public void replaceConditionally_weigherFails_presentKeyAndValue_async( + public void replaceConditionally_weigherFails_presentKey_async( AsyncCache cache, CacheContext context) { when(context.weigher().weigh(any(), any())).thenThrow(IllegalStateException.class); var future = new CompletableFuture(); diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ExpirationTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ExpirationTest.java index eea96ad211..c78d03dd39 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ExpirationTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ExpirationTest.java @@ -1557,7 +1557,7 @@ public void entrySet_toArray(Map map, CacheContext context) { expireAfterWrite = {Expire.DISABLED, Expire.ONE_MINUTE}, expiryTime = Expire.ONE_MINUTE) public void entrySet_iterator(Map map, CacheContext context) { context.ticker().advance(Duration.ofMinutes(10)); - assertThat(map.keySet().iterator().hasNext()).isFalse(); + assertThat(map.entrySet().iterator().hasNext()).isFalse(); assertThat(map).isExhaustivelyEmpty(); assertThat(context).notifications().withCause(EXPIRED) .contains(context.original()).exclusively(); @@ -1630,10 +1630,10 @@ public void entrySet_hashCode(Map map, CacheContext context) { map.putAll(context.absent()); context.ticker().advance(Duration.ofSeconds(45)); - assertThat(map.hashCode()).isEqualTo(context.absent().hashCode()); + assertThat(map.entrySet().hashCode()).isEqualTo(context.absent().entrySet().hashCode()); context.cleanUp(); - assertThat(map.hashCode()).isEqualTo(context.absent().hashCode()); + assertThat(map.entrySet().hashCode()).isEqualTo(context.absent().entrySet().hashCode()); } @Test(dataProvider = "caches") diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ExpireAfterVarTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ExpireAfterVarTest.java index acfe70b48a..e6e1fcce5f 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ExpireAfterVarTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ExpireAfterVarTest.java @@ -78,6 +78,7 @@ import com.github.benmanes.caffeine.cache.testing.CheckNoStats; import com.github.benmanes.caffeine.testing.ConcurrentTestHarness; import com.github.benmanes.caffeine.testing.Int; +import com.google.common.collect.HashBiMap; import com.google.common.collect.ImmutableList; import com.google.common.collect.Maps; import com.google.common.testing.SerializableTester; @@ -412,6 +413,14 @@ public void getAll_expiryFails(Cache cache, CacheContext context) { cache.getAll(context.absentKeys(), keys -> Maps.toMap(keys, Int::negate))); context.ticker().advance(Duration.ofHours(-1)); assertThat(cache).containsExactlyEntriesIn(context.original()); + if (context.isCaffeine()) { + assertThat(logEvents() + .withMessage("Exception thrown during asynchronous load") + .withThrowable(ExpirationException.class) + .withLevel(WARN) + .exclusively()) + .hasSize(context.isAsync() ? context.absentKeys().size() : 0); + } } @Test(dataProvider = "caches") @@ -434,6 +443,47 @@ public void getAll_expiryFails_async(AsyncCache cache, CacheContext co .hasSize(context.absentKeys().size()); } + @Test(dataProvider = "caches") + @CacheSpec(population = Population.FULL, expiry = CacheExpiry.MOCKITO) + public void getAll_expiryFails_newEntries(Cache cache, CacheContext context) { + context.ticker().advance(Duration.ofHours(1)); + when(context.expiry().expireAfterCreate(any(), any(), anyLong())) + .thenThrow(ExpirationException.class); + assertThrows(ExpirationException.class, () -> + cache.getAll(context.absentKeys(), keys -> HashBiMap.create(context.original()).inverse())); + context.ticker().advance(Duration.ofHours(-1)); + assertThat(cache).containsExactlyEntriesIn(context.original()); + if (context.isCaffeine()) { + assertThat(logEvents() + .withMessage("Exception thrown during asynchronous load") + .withThrowable(ExpirationException.class) + .withLevel(WARN) + .exclusively()) + .hasSize(context.isAsync() ? context.original().size() : 0); + } + } + + @Test(dataProvider = "caches") + @CacheSpec(population = Population.FULL, expiry = CacheExpiry.MOCKITO) + public void getAll_expiryFails_newEntries_async( + AsyncCache cache, CacheContext context) { + context.ticker().advance(Duration.ofHours(1)); + when(context.expiry().expireAfterCreate(any(), any(), anyLong())) + .thenThrow(ExpirationException.class); + var future = new CompletableFuture>(); + var result = cache.getAll(context.absentKeys(), (keys, executor) -> future); + future.complete(HashBiMap.create(context.original()).inverse()); + assertThat(result).failsWith(CompletionException.class) + .hasCauseThat().isInstanceOf(ExpirationException.class); + assertThat(cache).containsExactlyEntriesIn(context.original()); + assertThat(logEvents() + .withMessage("Exception thrown during asynchronous load") + .withThrowable(ExpirationException.class) + .withLevel(WARN) + .exclusively()) + .hasSize(context.original().size()); + } + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.MOCKITO) public void getAllPresent_expiryFails(Cache cache, CacheContext context) { diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/FrequencySketchTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/FrequencySketchTest.java index 442a87be1d..d6e851be8c 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/FrequencySketchTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/FrequencySketchTest.java @@ -125,13 +125,13 @@ public void full() { for (int i = 0; i < 100_000; i++) { sketch.increment(i); } - for (long item : sketch.table) { - assertThat(Long.bitCount(item)).isEqualTo(64); + for (long slot : sketch.table) { + assertThat(Long.bitCount(slot)).isEqualTo(64); } sketch.reset(); - for (long item : sketch.table) { - assertThat(item).isEqualTo(FrequencySketch.RESET_MASK); + for (long slot : sketch.table) { + assertThat(slot).isEqualTo(FrequencySketch.RESET_MASK); } } diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/LoadingCacheTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/LoadingCacheTest.java index 65a7dd08af..3b7864c1fe 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/LoadingCacheTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/LoadingCacheTest.java @@ -1110,7 +1110,7 @@ public void refreshAll_nullFuture_reload(CacheContext context) { /* --------------- CacheLoader --------------- */ @Test - public void loadAll() throws Exception { + public void loadAll() { CacheLoader loader = key -> key; assertThrows(UnsupportedOperationException.class, () -> loader.loadAll(Set.of())); } diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/QueueSanityTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/QueueSanityTest.java index 08e3522e63..e3baffdc05 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/QueueSanityTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/QueueSanityTest.java @@ -87,7 +87,6 @@ public void sanity() { } else { // expect sum of elements is (size - 1) * size / 2 = 0 + 1 + .... + (size - 1) int sum = (size - 1) * size / 2; - i = 0; Integer e; while ((e = queue.poll()) != null) { assertEquals(--size, queue.size()); diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/RefreshAfterWriteTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/RefreshAfterWriteTest.java index 29d4736430..326ae2fbbf 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/RefreshAfterWriteTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/RefreshAfterWriteTest.java @@ -964,9 +964,10 @@ public void setRefreshAfter_excessive(Cache cache, } @Test(dataProvider = "caches") + @SuppressWarnings("PreferJavaTimeOverload") @CacheSpec(refreshAfterWrite = Expire.ONE_MINUTE) public void setRefreshesAfter(CacheContext context, FixedRefresh refreshAfterWrite) { - refreshAfterWrite.setRefreshesAfter(Duration.ofMinutes(2)); + refreshAfterWrite.setRefreshesAfter(2, TimeUnit.MINUTES); assertThat(refreshAfterWrite.getRefreshesAfter().toMinutes()).isEqualTo(2); assertThat(refreshAfterWrite.getRefreshesAfter(TimeUnit.MINUTES)).isEqualTo(2); } diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/TimerWheelTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/TimerWheelTest.java index 7a04601e88..871c2ddc18 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/TimerWheelTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/TimerWheelTest.java @@ -82,7 +82,7 @@ public void beforeMethod() throws Exception { } @AfterMethod - public void afterMethod(ITestResult testResult) throws Exception { + public void afterMethod(ITestResult testResult) { if (!testResult.isSuccess()) { printTimerWheel(); } diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/buffer/BufferTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/buffer/BufferTest.java index 93f1d649a0..2a593bbca2 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/buffer/BufferTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/buffer/BufferTest.java @@ -42,7 +42,7 @@ public Iterator buffers() { @Test(dataProvider = "buffers") @SuppressWarnings("ThreadPriorityCheck") - public void record(ReadBuffer buffer) { + public void offer(ReadBuffer buffer) { ConcurrentTestHarness.timeTasks(100, () -> { for (int i = 0; i < 1000; i++) { int added = buffer.offer(Boolean.TRUE); diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/issues/Issue193Test.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/issues/Issue193Test.java index 5b2d523cad..d21afdf528 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/issues/Issue193Test.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/issues/Issue193Test.java @@ -42,23 +42,23 @@ * @author boschb (Robert Bosch) */ public final class Issue193Test { + private final String testKey = Issue193Test.class.getSimpleName(); private final AtomicLong counter = new AtomicLong(0); private final FakeTicker ticker = new FakeTicker(); private ListenableFutureTask loadingTask; - private final AsyncCacheLoader loader = (key, exec) -> { + private final AsyncCacheLoader loader = (key, executor) -> { // Fools the cache into thinking there is a future that's not immediately ready. // (The Cache has optimizations for this that we want to avoid) loadingTask = ListenableFutureTask.create(counter::getAndIncrement); var f = new CompletableFuture(); loadingTask.addListener(() -> { f.complete(Futures.getUnchecked(loadingTask)); - }, exec); + }, executor); return f; }; - private final String key = Issue193Test.class.getSimpleName(); /** This ensures that any outstanding async loading is completed as well */ private long loadGet(AsyncLoadingCache cache, String key) { @@ -70,7 +70,7 @@ private long loadGet(AsyncLoadingCache cache, String key) { } @Test - public void invalidateDuringRefreshRemovalCheck() throws Exception { + public void invalidateDuringRefreshRemovalCheck() { var removed = new ArrayList(); AsyncLoadingCache cache = Caffeine.newBuilder() .removalListener((String key, Long value, RemovalCause reason) -> removed.add(value)) @@ -80,17 +80,17 @@ public void invalidateDuringRefreshRemovalCheck() throws Exception { .buildAsync(loader); // Load so there is an initial value. - assertThat(loadGet(cache, key)).isEqualTo(0); + assertThat(loadGet(cache, testKey)).isEqualTo(0); ticker.advance(Duration.ofNanos(11)); // Refresh should fire on next access - assertThat(cache).containsEntry(key, 0); // Old value + assertThat(cache).containsEntry(testKey, 0); // Old value - cache.synchronous().invalidate(key); // Invalidate key entirely - assertThat(cache).doesNotContainKey(key); // No value in cache (good) + cache.synchronous().invalidate(testKey); // Invalidate key entirely + assertThat(cache).doesNotContainKey(testKey); // No value in cache (good) loadingTask.run(); // Completes refresh // FIXME: java.lang.AssertionError: Not true that <1> is null - assertThat(cache).doesNotContainKey(key); // Value in cache (bad) + assertThat(cache).doesNotContainKey(testKey); // Value in cache (bad) // FIXME: Maybe? This is what I wanted to actually test :) assertThat(removed).containsExactly(0L, 1L).inOrder(); // 1L was sent to removalListener anyway diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/issues/Issue298Test.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/issues/Issue298Test.java index 4fa2494fef..371e2aca1a 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/issues/Issue298Test.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/issues/Issue298Test.java @@ -49,19 +49,19 @@ public final class Issue298Test { static final long EXPIRE_NS = Duration.ofDays(1).toNanos(); - AtomicBoolean startedLoad; - AtomicBoolean doLoad; + private AtomicBoolean startedLoad; + private AtomicBoolean doLoad; - AtomicBoolean startedCreate; - AtomicBoolean doCreate; + private AtomicBoolean startedCreate; + private AtomicBoolean doCreate; - AtomicBoolean startedRead; - AtomicBoolean doRead; - AtomicBoolean endRead; + private AtomicBoolean startedRead; + private AtomicBoolean doRead; + private AtomicBoolean endRead; - AsyncLoadingCache cache; - VarExpiration policy; - String key; + private AsyncLoadingCache cache; + private VarExpiration policy; + private String testKey; @BeforeMethod public void before() { @@ -73,7 +73,7 @@ public void before() { doLoad = new AtomicBoolean(); doRead = new AtomicBoolean(); - key = "key"; + testKey = "key"; cache = makeAsyncCache(); policy = cache.synchronous().policy().expireVariably().orElseThrow(); } @@ -87,7 +87,7 @@ public void after() { @SuppressWarnings("FutureReturnValueIgnored") public void readDuringCreate() { // Loaded value and waiting at expireAfterCreate (expire: infinite) - var initialValue = cache.get(key); + var initialValue = cache.get(testKey); assertThat(initialValue).isNotNull(); await().untilTrue(startedLoad); @@ -97,14 +97,14 @@ public void readDuringCreate() { // Async read trying to wait at expireAfterRead var reader = CompletableFuture.runAsync(() -> { do { - var value = cache.get(key); + var value = cache.get(testKey); assertThat(value).isEqualTo(initialValue); } while (!endRead.get()); }, executor); // Ran expireAfterCreate (expire: infinite -> create) doCreate.set(true); - await().until(() -> policy.getExpiresAfter(key).orElseThrow().toNanos() <= EXPIRE_NS); + await().until(() -> policy.getExpiresAfter(testKey).orElseThrow().toNanos() <= EXPIRE_NS); await().untilTrue(startedRead); // Ran reader (expire: create -> ?) @@ -113,7 +113,7 @@ public void readDuringCreate() { reader.join(); // Ensure expire is [expireAfterCreate], not [infinite] - assertThat(policy.getExpiresAfter(key).orElseThrow().toNanos()).isAtMost(EXPIRE_NS); + assertThat(policy.getExpiresAfter(testKey).orElseThrow().toNanos()).isAtMost(EXPIRE_NS); } private AsyncLoadingCache makeAsyncCache() { diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/testing/CacheContext.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/testing/CacheContext.java index 050da3c207..4b8ad2e878 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/testing/CacheContext.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/testing/CacheContext.java @@ -441,15 +441,15 @@ public FakeTicker ticker() { } public LoadingCache build(CacheLoader loader) { - LoadingCache cache; + LoadingCache loading; if (isCaffeine()) { - cache = isAsync() ? caffeine.buildAsync(loader).synchronous() : caffeine.build(loader); + loading = isAsync() ? caffeine.buildAsync(loader).synchronous() : caffeine.build(loader); } else { var guavaLoader = new SingleLoader<>(loader); - cache = new GuavaLoadingCache<>(guava.build(asyncReloading(guavaLoader, executor)), this); + loading = new GuavaLoadingCache<>(guava.build(asyncReloading(guavaLoader, executor)), this); } - this.cache = cache; - return cache; + this.cache = loading; + return loading; } public AsyncLoadingCache buildAsync(CacheLoader loader) { diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/testing/CacheContextSubject.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/testing/CacheContextSubject.java index dbe13ceaf3..2e73a71e49 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/testing/CacheContextSubject.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/testing/CacheContextSubject.java @@ -378,8 +378,8 @@ public Exclusive contains(Entry... entries) { var notifications = Arrays.stream(entries) .map(entry -> new RemovalNotification<>(entry.getKey(), entry.getValue(), cause)) .collect(toImmutableListMultimap(RemovalNotification::getCause, identity())); - var actual = Multimaps.index(listener.removed(), RemovalNotification::getCause); - check(type).that(actual).containsAtLeastEntriesIn(notifications); + var removed = Multimaps.index(listener.removed(), RemovalNotification::getCause); + check(type).that(removed).containsAtLeastEntriesIn(notifications); }); return new Exclusive(entries.length); } diff --git a/guava/src/test/java/com/github/benmanes/caffeine/guava/CaffeinatedGuavaTest.java b/guava/src/test/java/com/github/benmanes/caffeine/guava/CaffeinatedGuavaTest.java index e8076bdd33..be5420d358 100644 --- a/guava/src/test/java/com/github/benmanes/caffeine/guava/CaffeinatedGuavaTest.java +++ b/guava/src/test/java/com/github/benmanes/caffeine/guava/CaffeinatedGuavaTest.java @@ -96,7 +96,7 @@ public void testReload_throwable() { cache.refresh(1); } - public void testCacheLoader_null() throws Exception { + public void testCacheLoader_null() { assertThrows(NullPointerException.class, () -> CaffeinatedGuava.caffeinate(null)); var caffeine1 = CaffeinatedGuava.caffeinate(CacheLoader.from(key -> null)); @@ -127,7 +127,7 @@ public void testCacheLoader_exception() throws Exception { runCacheLoaderExceptionTest(new Exception()); } - public void runCacheLoaderExceptionTest(Exception error) throws Exception { + public void runCacheLoaderExceptionTest(Exception error) { var guava = new CacheLoader() { @Override public Integer load(Integer key) throws Exception { throw error; diff --git a/guava/src/test/java/com/github/benmanes/caffeine/guava/compatibility/CacheLoadingTest.java b/guava/src/test/java/com/github/benmanes/caffeine/guava/compatibility/CacheLoadingTest.java index e511222039..ee4ae81e59 100644 --- a/guava/src/test/java/com/github/benmanes/caffeine/guava/compatibility/CacheLoadingTest.java +++ b/guava/src/test/java/com/github/benmanes/caffeine/guava/compatibility/CacheLoadingTest.java @@ -1264,7 +1264,7 @@ public void testLoadInterruptedException() { public void testReloadCheckedException() { final Object one = new Object(); - final RuntimeException e = new RuntimeException(); + final Exception e = new Exception(); CacheLoader loader = new CacheLoader() { @Override public Object load(Object key) { @@ -1272,7 +1272,7 @@ public Object load(Object key) { } @Override - public ListenableFuture reload(Object key, Object oldValue) { + public ListenableFuture reload(Object key, Object oldValue) throws Exception { throw e; } }; @@ -1536,7 +1536,7 @@ public void testLoadUncheckedException() throws ExecutionException { assertEquals(0, stats.hitCount()); } - public void testReloadUncheckedException() throws ExecutionException { + public void testReloadUncheckedException() { final Object one = new Object(); final RuntimeException e = new RuntimeException(); CacheLoader loader = new CacheLoader() { diff --git a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/JCacheProfiler.java b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/JCacheProfiler.java index b373decfa5..f94a87cf9d 100644 --- a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/JCacheProfiler.java +++ b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/JCacheProfiler.java @@ -86,9 +86,9 @@ public void start() { private ScheduledFuture scheduleStatusTask() { var stopwatch = Stopwatch.createStarted(); return Executors.newSingleThreadScheduledExecutor().scheduleWithFixedDelay(() -> { - long count = this.count.longValue(); - long rate = count / stopwatch.elapsed(TimeUnit.SECONDS); - System.out.printf(US, "%s - %,d [%,d / sec]%n", stopwatch, count, rate); + long iterations = count.longValue(); + long rate = iterations / stopwatch.elapsed(TimeUnit.SECONDS); + System.out.printf(US, "%s - %,d [%,d / sec]%n", stopwatch, iterations, rate); }, 5, 5, TimeUnit.SECONDS); } diff --git a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/OSGiTest.java b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/OSGiTest.java index 51e0a4acc4..9580d4f334 100644 --- a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/OSGiTest.java +++ b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/OSGiTest.java @@ -67,11 +67,10 @@ public Option[] config() { @Test public void sanity() { - var cachingProvider = Caching.getCachingProvider( + var provider = Caching.getCachingProvider( "com.github.benmanes.caffeine.jcache.spi.CaffeineCachingProvider", getClass().getClassLoader()); - var cache = cachingProvider.getCacheManager() - .getCache("osgi-cache", String.class, Integer.class); + var cache = provider.getCacheManager().getCache("osgi-cache", String.class, Integer.class); assertNull(cache.get("a")); } diff --git a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/configuration/TypesafeConfigurationTest.java b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/configuration/TypesafeConfigurationTest.java index ade405b10b..b1b951527e 100644 --- a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/configuration/TypesafeConfigurationTest.java +++ b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/configuration/TypesafeConfigurationTest.java @@ -65,7 +65,7 @@ public void setConfigSource_supplier() { @Test public void setConfigSource_function() { - TypesafeConfigurator.setConfigSource((uri, classloader) -> null); + TypesafeConfigurator.setConfigSource((uri, loader) -> null); assertThat(configSource()).isNotSameInstanceAs(defaultConfigSource); assertThrows(NullPointerException.class, () ->