Skip to content

Commit

Permalink
fix sonarlint warnings for tests, remove duplicative, add missing
Browse files Browse the repository at this point in the history
  • Loading branch information
ben-manes committed Jun 9, 2024
1 parent 7e3fe4e commit 7a9f709
Show file tree
Hide file tree
Showing 13 changed files with 112 additions and 70 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2752,7 +2752,7 @@ public void entrySet_removeAll_bySet(Map<Int, Int> map, CacheContext context) {
@CheckNoStats
@Test(dataProvider = "caches")
public void entrySet_remove_null(Map<Int, Int> map, CacheContext context) {
assertThat(map.values().remove(null)).isFalse();
assertThat(map.entrySet().remove(null)).isFalse();
assertThat(map).isEqualTo(context.original());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2507,7 +2507,7 @@ public void entrySet_removeAll_bySet(AsyncCache<Int, Int> cache, CacheContext co
@CheckNoStats
@Test(dataProvider = "caches")
public void entrySet_remove_null(AsyncCache<Int, Int> cache, CacheContext context) {
assertThat(cache.asMap().values().remove(null)).isFalse();
assertThat(cache.asMap().entrySet().remove(null)).isFalse();
assertThat(cache.synchronous().asMap()).isEqualTo(context.original());
}

Expand Down Expand Up @@ -2586,7 +2586,6 @@ public void entrySet_removeIf_partial(AsyncCache<Int, Int> cache, CacheContext c
Predicate<Map.Entry<Int, CompletableFuture<Int>>> 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);
Expand All @@ -2610,21 +2609,6 @@ public void entrySet_removeIf_all(AsyncCache<Int, Int> cache, CacheContext conte
}
}

@CacheSpec
@CheckNoStats
@Test(dataProvider = "caches")
public void entrySet_removeIf(AsyncCache<Int, Int> cache, CacheContext context) {
Predicate<Map.Entry<Int, CompletableFuture<Int>>> 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")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ private void runScenarios(CacheContext context, Epoch epoch) {
}

private void runTest(CacheContext context, Epoch epoch, Function<Duration, String> formatter) {
CaffeineSpec spec = toSpec(context, epoch, formatter);
CaffeineSpec spec = toSpec(context, formatter);
Caffeine<Object, Object> builder = Caffeine.from(spec);

checkInitialCapacity(spec, context, builder);
Expand All @@ -134,8 +134,7 @@ private void runTest(CacheContext context, Epoch epoch, Function<Duration, Strin
assertThat(spec).isEqualTo(CaffeineSpec.parse(spec.toParsableString().replaceAll(",", ",,")));
}

static CaffeineSpec toSpec(CacheContext context,
Epoch epoch, Function<Duration, String> formatter) {
static CaffeineSpec toSpec(CacheContext context, Function<Duration, String> formatter) {
var options = new ArrayList<String>();
if (context.initialCapacity() != InitialCapacity.DEFAULT) {
options.add("initialCapacity=" + context.initialCapacity().size());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -325,6 +326,46 @@ public void getAll_weigherFails_async(AsyncCache<Int, Int> 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<Int, Int> 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<Int, Int> cache, CacheContext context) {
when(context.weigher().weigh(any(), any())).thenThrow(IllegalStateException.class);
var future = new CompletableFuture<Map<Int, Int>>();
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)
Expand Down Expand Up @@ -563,49 +604,17 @@ public void replaceConditionally_weigherFails_absent(
public void replaceConditionally_weigherFails_presentKey(
Cache<Int, Int> cache, CacheContext context, Eviction<Int, Int> 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<Int, Int> cache, CacheContext context) {
when(context.weigher().weigh(any(), any())).thenThrow(IllegalStateException.class);
var future = new CompletableFuture<Int>();
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<Int, Int> cache, CacheContext context, Eviction<Int, Int> 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);
}

@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<Int, Int> cache, CacheContext context) {
when(context.weigher().weigh(any(), any())).thenThrow(IllegalStateException.class);
var future = new CompletableFuture<Int>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1557,7 +1557,7 @@ public void entrySet_toArray(Map<Int, Int> map, CacheContext context) {
expireAfterWrite = {Expire.DISABLED, Expire.ONE_MINUTE}, expiryTime = Expire.ONE_MINUTE)
public void entrySet_iterator(Map<Int, Int> 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();
Expand Down Expand Up @@ -1630,10 +1630,10 @@ public void entrySet_hashCode(Map<Int, Int> 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")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -412,6 +413,14 @@ public void getAll_expiryFails(Cache<Int, Int> 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")
Expand All @@ -434,6 +443,47 @@ public void getAll_expiryFails_async(AsyncCache<Int, Int> cache, CacheContext co
.hasSize(context.absentKeys().size());
}

@Test(dataProvider = "caches")
@CacheSpec(population = Population.FULL, expiry = CacheExpiry.MOCKITO)
public void getAll_expiryFails_newEntries(Cache<Int, Int> 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<Int, Int> cache, CacheContext context) {
context.ticker().advance(Duration.ofHours(1));
when(context.expiry().expireAfterCreate(any(), any(), anyLong()))
.thenThrow(ExpirationException.class);
var future = new CompletableFuture<Map<Int, Int>>();
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<Int, Int> cache, CacheContext context) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1110,7 +1110,7 @@ public void refreshAll_nullFuture_reload(CacheContext context) {
/* --------------- CacheLoader --------------- */

@Test
public void loadAll() throws Exception {
public void loadAll() {
CacheLoader<Object, ?> loader = key -> key;
assertThrows(UnsupportedOperationException.class, () -> loader.loadAll(Set.of()));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -966,7 +966,7 @@ public void setRefreshAfter_excessive(Cache<Int, Int> cache,
@Test(dataProvider = "caches")
@CacheSpec(refreshAfterWrite = Expire.ONE_MINUTE)
public void setRefreshesAfter(CacheContext context, FixedRefresh<Int, Int> refreshAfterWrite) {
refreshAfterWrite.setRefreshesAfter(Duration.ofMinutes(2));
refreshAfterWrite.setRefreshesAfter(2, TimeUnit.MINUTES);

Check warning on line 969 in caffeine/src/test/java/com/github/benmanes/caffeine/cache/RefreshAfterWriteTest.java

View workflow job for this annotation

GitHub Actions / pmd

[PreferJavaTimeOverload] Prefer using java.time-based APIs when available. Note that this checker does not and cannot guarantee that the overloads have equivalent semantics, but that is generally the case with overloaded methods.

Check warning on line 969 in caffeine/src/test/java/com/github/benmanes/caffeine/cache/RefreshAfterWriteTest.java

View workflow job for this annotation

GitHub Actions / spotbugs

[PreferJavaTimeOverload] Prefer using java.time-based APIs when available. Note that this checker does not and cannot guarantee that the overloads have equivalent semantics, but that is generally the case with overloaded methods.

Check warning on line 969 in caffeine/src/test/java/com/github/benmanes/caffeine/cache/RefreshAfterWriteTest.java

View workflow job for this annotation

GitHub Actions / Compile (11)

[PreferJavaTimeOverload] Prefer using java.time-based APIs when available. Note that this checker does not and cannot guarantee that the overloads have equivalent semantics, but that is generally the case with overloaded methods.

Check warning on line 969 in caffeine/src/test/java/com/github/benmanes/caffeine/cache/RefreshAfterWriteTest.java

View workflow job for this annotation

GitHub Actions / Compile (22)

[PreferJavaTimeOverload] Prefer using java.time-based APIs when available. Note that this checker does not and cannot guarantee that the overloads have equivalent semantics, but that is generally the case with overloaded methods.

Check warning on line 969 in caffeine/src/test/java/com/github/benmanes/caffeine/cache/RefreshAfterWriteTest.java

View workflow job for this annotation

GitHub Actions / benchmarks (GraalVM)

[PreferJavaTimeOverload] Prefer using java.time-based APIs when available. Note that this checker does not and cannot guarantee that the overloads have equivalent semantics, but that is generally the case with overloaded methods.

Check warning on line 969 in caffeine/src/test/java/com/github/benmanes/caffeine/cache/RefreshAfterWriteTest.java

View workflow job for this annotation

GitHub Actions / Compile (GraalVM)

[PreferJavaTimeOverload] Prefer using java.time-based APIs when available. Note that this checker does not and cannot guarantee that the overloads have equivalent semantics, but that is generally the case with overloaded methods.

Check warning on line 969 in caffeine/src/test/java/com/github/benmanes/caffeine/cache/RefreshAfterWriteTest.java

View workflow job for this annotation

GitHub Actions / Tests (caffeine:fuzzTest, 11)

[PreferJavaTimeOverload] Prefer using java.time-based APIs when available. Note that this checker does not and cannot guarantee that the overloads have equivalent semantics, but that is generally the case with overloaded methods.

Check warning on line 969 in caffeine/src/test/java/com/github/benmanes/caffeine/cache/RefreshAfterWriteTest.java

View workflow job for this annotation

GitHub Actions / qodana

[PreferJavaTimeOverload] Prefer using java.time-based APIs when available. Note that this checker does not and cannot guarantee that the overloads have equivalent semantics, but that is generally the case with overloaded methods.
assertThat(refreshAfterWrite.getRefreshesAfter().toMinutes()).isEqualTo(2);
assertThat(refreshAfterWrite.getRefreshesAfter(TimeUnit.MINUTES)).isEqualTo(2);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ private long loadGet(AsyncLoadingCache<String, Long> cache, String key) {
}

@Test
public void invalidateDuringRefreshRemovalCheck() throws Exception {
public void invalidateDuringRefreshRemovalCheck() {
var removed = new ArrayList<Long>();
AsyncLoadingCache<String, Long> cache = Caffeine.newBuilder()
.removalListener((String key, Long value, RemovalCause reason) -> removed.add(value))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down Expand Up @@ -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<Integer, Integer>() {
@Override public Integer load(Integer key) throws Exception {
throw error;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1264,15 +1264,15 @@ public void testLoadInterruptedException() {

public void testReloadCheckedException() {
final Object one = new Object();
final RuntimeException e = new RuntimeException();
final Exception e = new Exception();
CacheLoader<Object, Object> loader = new CacheLoader<Object, Object>() {
@Override
public Object load(Object key) {
return one;
}

@Override
public ListenableFuture<Object> reload(Object key, Object oldValue) {
public ListenableFuture<Object> reload(Object key, Object oldValue) throws Exception {
throw e;
}
};
Expand Down Expand Up @@ -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<Object, Object> loader = new CacheLoader<Object, Object>() {
Expand Down

0 comments on commit 7a9f709

Please sign in to comment.