8000 Tests, mocks, test parallelism by andrewaylett · Pull Request #107 · andrewaylett/arc · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Tests, mocks, test parallelism #107

New issue

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

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

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 29, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions gradle/gradle-daemon-jvm.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
#This file is generated by updateDaemonJvm
toolchainUrl.FREE_BSD.AARCH64=https\://api.foojay.io/disco/v3.0/ids/44715d7d372da8362a7c7e78c011e897/redirect
toolchainUrl.FREE_BSD.X86_64=https\://api.foojay.io/disco/v3.0/ids/ce3ff383a4a3e769ac7d9ca5903aa698/redirect
toolchainUrl.LINUX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/44715d7d372da8362a7c7e78c011e897/redirect
toolchainUrl.LINUX.X86_64=https\://api.foojay.io/disco/v3.0/ids/ce3ff383a4a3e769ac7d9ca5903aa698/redirect
toolchainUrl.MAC_OS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/5956054eea3fda78f9a8d1b47e24e080/redirect
toolchainUrl.MAC_OS.X86_64=https\://api.foojay.io/disco/v3.0/ids/d73443cae2d063f4bc06ff437f9a3e6b/redirect
toolchainUrl.UNIX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/44715d7d372da8362a7c7e78c011e897/redirect
toolchainUrl.UNIX.X86_64=https\://api.foojay.io/disco/v3.0/ids/ce3ff383a4a3e769ac7d9ca5903aa698/redirect
toolchainUrl.WINDOWS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/7fe1613e82362b3e87de352406cbc016/redirect
toolchainUrl.WINDOWS.X86_64=https\://api.foojay.io/disco/v3.0/ids/747369971f89e1f6bc182b737d168306/redirect
toolchainVersion=24
4 changes: 4 additions & 0 deletions gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ arcmutate = "1.2.2"
checkerframework = "3.49.3"
checkstyle = "10.24.0"
hamcrest = "3.0"
jetbrains = "26.0.2"
jspecify = "1.0.0"
junit = "5.12.2"
logback = "1.5.18"
mockito = "5.17.0"
pitest = "1.19.4"
pitest-accelerator-junit5 = "1.0.6"
pitest-git-plugin = "1.1.4"
Expand All @@ -19,9 +21,11 @@ arcmutate-base = { module = "com.groupcdg.arcmutate:base", version.ref = "arcmut
checkerframework = { module = "org.checkerframework:checker", version.ref = "checkerframework" }
checkerframework-qual = { module = "org.checkerframework:checker-qual", version.ref = "checkerframework" }
hamcrest = { module = "org.hamcrest:hamcrest", version.ref = "hamcrest" }
jetbrains-annotations = { module = "org.jetbrains:annotations", version.ref = "jetbrains" }
jspecify = { module = "org.jspecify:jspecify", version.ref = "jspecify" }
junit-jupiter = { module = "org.junit.jupiter:junit-jupiter", version.ref = "junit" }
logback-classic = { module = "ch.qos.logback:logback-classic", version.ref = "logback" }
mockito = { module = "org.mockito:mockito-core", version.ref = "mockito" }
pitest = { module = "org.pitest:pitest", version.ref = "pitest" }
pitest-accelerator-junit5 = { module = "com.groupcdg.pitest:pitest-accelerator-junit5", version.ref = "pitest-accelerator-junit5" }
pitest-git-plugin = { module = "com.groupcdg:pitest-git-plugin", version.ref = "pitest-git-plugin" }
Expand Down
2 changes: 2 additions & 0 deletions lib/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,11 @@ val internal: Configuration by configurations.creating

dependencies {
implementation(libs.checkerframework.qual)
implementation(libs.jetbrains.annotations)
implementation(libs.jspecify)
implementation(libs.spotbugs.annotations)
testImplementation(libs.hamcrest)
testImplementation(libs.mockito)

checkerFramework(libs.checkerframework)

Expand Down
7 changes: 5 additions & 2 deletions lib/src/main/java/eu/aylett/arc/Arc.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@
import java.util.function.BiFunction;
import java.util.function.Function;

import static eu.aylett.arc.internal.Invariants.checkNotNull;

/**
* The Arc class provides a cache mechanism with a specified capacity. It uses a
* loader function to load values and a ForkJoinPool for parallel processing.
Expand Down Expand Up @@ -126,8 +128,8 @@ public Arc(int capacity, Function<? super K, V> loader, Duration expiry, Duratio
if (!refresh.isPositive()) {
throw new IllegalArgumentException("Refresh must be positive");
}
this.loader = loader;
this.pool = pool;
this.loader = checkNotNull(loader);
this.pool = checkNotNull(pool);
elements = new ConcurrentHashMap<>();
inner = new InnerArc(Math.max(capacity / 2, 1), new DelayManager(expiry, refresh, clock));
unowned = inner.unowned;
Expand Down Expand Up @@ -165,6 +167,7 @@ public void weakExpire() {
*/
@MayReleaseLocks
public V get(K key) {
checkNotNull(key, "key cannot be null");
while (true) {
var ref = elements.computeIfAbsent(key, k -> {
var element = new Element<>(k, loader, (l) -> CompletableFuture.supplyAsync(l, pool), unowned);
Expand Down
31 changes: 16 additions & 15 deletions lib/src/main/java/eu/aylett/arc/internal/Element.java
Original file line number Diff line number Diff line change
Expand Up @@ -103,26 +103,27 @@
}

var currentValue = this.value;
if (currentValue != null) {
if (currentValue.isDone()) {
var v = currentValue.join();
var currentWeakValue = this.weakValue;
if (currentWeakValue == null || !currentWeakValue.refersTo(v)) {
this.weakValue = new WeakReference<>(v);
if (currentValue == null || currentValue.isCompletedExceptionally()) {
8000 Copy link
Preview
Copilot AI May 29, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add a comment to clarify why elements with a completed exceptional future trigger a reload, to improve code maintainability and future understanding.

Copilot uses AI. Check for mistakes.

var currentWeakValue = this.weakValue;
if (currentWeakValue != null) {

Check warning on line 108 in lib/src/main/java/eu/aylett/arc/internal/Element.java

View workflow job for this annotation

GitHub Actions / pitest

A change can be made to line 108 without causing a test to fail

removed conditional - replaced equality check with false (covered by 17 tests RemoveConditionalMutator_EQUAL_ELSE)
var v = currentWeakValue.get();
if (v != null) {

Check warning on line 110 in lib/src/main/java/eu/aylett/arc/internal/Element.java

View workflow job for this annotation

GitHub Actions / pitest

2 different changes can be made to line 110 without causing a test to fail

removed conditional - replaced equality check with false (covered by 1 tests RemoveConditionalMutator_EQUAL_ELSE) removed conditional - replaced equality check with true (covered by 1 tests RemoveConditionalMutator_EQUAL_IF)
return (this.value = CompletableFuture.completedFuture(v)).copy();
Copy link
Preview
Copilot AI May 29, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider adding a comment explaining the need to call copy() after creating the completed future to preserve immutability or prevent side effects.

Copilot uses AI. Check for mistakes.

} else {
this.weakValue = null;
}
}
return currentValue.copy();
return load().copy();
}
var currentWeakValue = this.weakValue;
if (currentWeakValue != null) {
var v = currentWeakValue.get();
if (v != null) {
return (this.value = CompletableFuture.completedFuture(v));
} else {
this.weakValue = null;

if (currentValue.isDone()) {

Check warning on line 119 in lib/src/main/java/eu/aylett/arc/internal/Element.java

View workflow job for this annotation

GitHub Actions / pitest

A change can be made to line 119 without causing a test to fail

removed conditional - replaced equality check with false (covered by 12 tests RemoveConditionalMutator_EQUAL_ELSE)
var v = currentValue.join();
var currentWeakValue = this.weakValue;
if (currentWeakValue == null || !currentWeakValue.refersTo(v)) {

Check warning on line 122 in lib/src/main/java/eu/aylett/arc/internal/Element.java

View workflow job for this annotation

GitHub Actions / pitest

2 different changes can be made to line 122 without causing a test to fail

removed conditional - replaced equality check with false (covered by 12 tests RemoveConditionalMutator_EQUAL_ELSE) removed conditional - replaced equality check with false (covered by 5 tests RemoveConditionalMutator_EQUAL_ELSE)
this.weakValue = new WeakReference<>(v);
}
}
return load().copy();
return currentValue.copy();
}

@Holding("this.lock")
Expand Down
35 changes: 35 additions & 0 deletions lib/src/main/java/eu/aylett/arc/internal/Invariants.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
* Copyright 2025 Andrew Aylett
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package eu.aylett.arc.internal;

import org.jetbrains.annotations.Contract;
import org.jspecify.annotations.Nullable;

public final class Invariants {
@Contract(value = "null -> fail; !null -> param1", pure = true)
public static <T> T checkNotNull(@Nullable T reference) {
return checkNotNull(reference, "Invariant failed: value is null");
}

@Contract(value = "null, _ -> fail; !null, _ -> param1", pure = true)
public static <T> T checkNotNull(@Nullable T reference, String message) {
if (reference == null) {
throw new NullPointerException(message);
}
return reference;
}
}
1 change: 1 addition & 0 deletions lib/src/main/java/module-info.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
requires org.jspecify;
requires org.checkerframework.checker.qual;
requires com.github.spotbugs.annotations;
requires org.jetbrains.annotations;

exports eu.aylett.arc;
}
140 changes: 138 additions & 2 deletions lib/src/test/java/eu/aylett/arc/ArcTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import org.checkerframework.checker.nullness.qual.PolyNull;
import org.hamcrest.Matcher;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;

import java.time.Duration;
Expand All @@ -32,26 +33,31 @@
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.lessThan;
import static org.junit.jupiter.api.Assertions.assertThrowsExactly;

import static java.util.Collections.synchronizedList;
import static java.util.concurrent.TimeUnit.SECONDS;

@SuppressWarnings({"argument", "type.argument", "method.guarantee.violated"})
@SuppressWarnings({"argument", "type.argument", "method.guarantee.violated", "type.arguments.not.inferred", "argument",
"methodref.receiver", "dereference.of.nullable"})
class ArcTest {
public static <T> org.hamcrest.Matcher<@GuardedBy @PolyNull @Initialized T> equalTo(@GuardedBy @PolyNull T operand) {
return org.hamcrest.core.IsEqual.equalTo(operand);
Expand Down Expand Up @@ -80,6 +86,7 @@ void testEviction() {

assertThat(arc.get(1), equalTo("1"));
assertThat(arc.get(2), equalTo("2"));
arc.checkSafety();
arc.weakExpire();
assertThat(arc.get(2), equalTo("2"));
assertThat(arc.get(1), equalTo("1")); // This should reload "1" as it was evicted
Expand Down Expand Up @@ -269,7 +276,7 @@ record = recordedValues.stream().collect(Collectors.groupingBy((v) -> v, Collect
.forEach(adjacentPair -> {
var start = adjacentPair.getFirst();
var end = adjacentPair.getLast();
assertThat(end.toEpochMilli(), lessThan(start.plusSeconds(35).toEpochMilli()));
assertThat(end.toEpochMilli(), lessThan(start.plusSeconds(55).toEpochMilli()));
Copy link
Preview
Copilot AI May 29, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider adding a comment explaining the rationale for increasing the timing threshold from 35 to 55 seconds in the eviction test to clarify the expected behavior.

Copilot uses AI. Check for mistakes.

assertThat(end.toEpochMilli(), greaterThan(start.plusSeconds(29).toEpochMilli()));
});
}
Expand All @@ -296,4 +303,133 @@ public Instant instant() {
return Instant.ofEpochMilli(value.get() * 100);
}
}

@Test
void testNullKeyHandling() {
var arc = new Arc<@NonNull Integer, String>(10, Object::toString, ForkJoinPool.commonPool());
@SuppressWarnings("DataFlowIssue")
var e = assertThrowsExactly(NullPointerException.class, () -> arc.get(null));
assertThat(e.getMessage(), equalTo("key cannot be null"));
}

@Test
void testLargeCapacity() {
var arc = new Arc<Integer, String>(100_000, Object::toString, ForkJoinPool.commonPool());
for (var i = 0; i < 100_000; i++) {
assertThat(arc.get(i), equalTo(String.valueOf(i)));
}
}

@Test
void testWeakExpireWithNoGC() {
var arc = new Arc<Integer, String>(10, Object::toString, ForkJoinPool.commonPool());
arc.get(1);
arc.get(2);
arc.weakExpire();
assertThat(arc.get(1), equalTo("1"));
assertThat(arc.get(2), equalTo("2"));
}

@Test
void testWeakExpireWithGC() {
var arc = new Arc<Integer, String>(10, Object::toString, ForkJoinPool.commonPool());
arc.get(1);
arc.get(2);
System.gc(); // Suggest garbage collection
arc.weakExpire();
assertThat(arc.get(1), equalTo("1")); // Should reload
assertThat(arc.get(2), equalTo("2")); // Should reload
}

@Test
void testLoaderExceptionHandling() {
var loaderFailed = new UnsupportedOperationException("Loader failed");

var arc = new Arc<Integer, String>(10, i -> {
if (i == 1) {
throw loaderFailed;
}
return i.toString();
}, ForkJoinPool.commonPool());

var ex = assertThrowsExactly(CompletionException.class, () -> arc.get(1));
assertThat(ex.getCause(), is(loaderFailed));

assertThat(arc.get(2), equalTo("2"));
}

@Test
void testLoaderRetriesAfterException() {
var shouldThrow = new AtomicBoolean(true);

var arc = new Arc<Integer, String>(10, i -> {
if (i == 1 && shouldThrow.getAndSet(false)) {
throw new UnsupportedOperationException("Loader failed");
}
return i.toString();
}, ForkJoinPool.commonPool());

var ex = assertThrowsExactly(CompletionException.class, () -> arc.get(1));
var cause = ex.getCause();
assertThat(cause.getMessage(), Matchers.equalTo("Loader failed"));

assertThat(arc.get(2), equalTo("2"));
assertThat(arc.get(1), equalTo("1"));
}

@Test
void testConcurrentAccessWithSameKey() throws InterruptedException {
var pool = ForkJoinPool.commonPool();
var arc = new Arc<Integer, String>(10, i -> {
try {
Thread.sleep(100); // Simulate delay in loading
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return i.toString();
}, pool);

var tasks = new ArrayList<ForkJoinTask<String>>();
for (var i = 0; i < 10; i++) {
tasks.add(pool.submit(() -> arc.get(1)));
}

tasks.forEach(ForkJoinTask::join);
assertThat(arc.get(1), equalTo("1"));
}

@Test
void testEvictionWithHighTurnover() {
var arc = new Arc<Integer, String>(5, Object::toString, ForkJoinPool.commonPool());
for (var i = 0; i < 20; i++) {
arc.get(i);
}
arc.weakExpire();
assertThat(arc.get(19), equalTo("19"));
assertThat(arc.get(0), equalTo("0")); // Should reload
}

@Test
void testCustomForkJoinPool() {
var customPool = new ForkJoinPool(2);
var arc = new Arc<Integer, String>(10, Object::toString, customPool);

var tasks = new ArrayList<ForkJoinTask<String>>();
for (var i = 0; i < 10; i++) {
var finalI = i;
tasks.add(customPool.submit(() -> arc.get(finalI)));
}

tasks.forEach(ForkJoinTask::join);
for (var i = 0; i < 10; i++) {
assertThat(arc.get(i), equalTo(String.valueOf(i)));
}
}

@Test
void testLoaderWithComplexValues() {
var arc = new Arc<Integer, List<Integer>>(10, i -> List.of(i, i * 2, i * 3), ForkJoinPool.commonPool());
assertThat(arc.get(2), equalTo(List.of(2, 4, 6)));
assertThat(arc.get(3), equalTo(List.of(3, 6, 9)));
}
}
2 changes: 2 additions & 0 deletions lib/src/test/resources/junit-platform.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
junit.jupiter.execution.parallel.enabled = true
junit.jupiter.execution.parallel.mode.default = concurrent
Loading
0