Skip to content

Commit

Permalink
Add test to ensure thread safety
Browse files Browse the repository at this point in the history
Signed-off-by: nscuro <[email protected]>
  • Loading branch information
nscuro committed Dec 20, 2023
1 parent 700cfdb commit c5034a2
Showing 1 changed file with 37 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static org.assertj.core.api.Assertions.assertThat;
Expand Down Expand Up @@ -130,7 +134,7 @@ public void testEvaluateWithMultipleMatchingPolicies() {
}

@Test
public void testEvaluateWithAdditionalRequiredFields() {
public void testEvaluateWithAdditionalRequiredFields() throws Exception {
final var persistentProject = new org.dependencytrack.model.Project();
persistentProject.setName("acme-app");
persistentProject.setVersion("1.0.0");
Expand Down Expand Up @@ -183,8 +187,38 @@ public void testEvaluateWithAdditionalRequiredFields() {
doReturn(List.of(policy))
.when(policyProviderMock).getApplicablePolicies(any(Project.class));

assertThat(policyEvaluator.evaluate(List.of(vuln), component, project))
.containsOnly(Map.entry(persistentVuln.getUuid(), policy));
// We want evaluation as a whole to be thread safe!
final var startLatch = new CountDownLatch(1);
final ExecutorService executor = Executors.newFixedThreadPool(10);
final var exceptionsThrown = new ConcurrentLinkedQueue<Exception>();
try {
for (int i = 0; i < 1000; i++) {
executor.submit(() -> {
try {
startLatch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}

try {
assertThat(policyEvaluator.evaluate(List.of(vuln), component, project))
.containsOnly(Map.entry(persistentVuln.getUuid(), policy));
} catch (Exception e) {
// If we throw here, the exception won't bubble up to the test.
// Collect all encountered exceptions here and assert on all of them later.
exceptionsThrown.add(e);
}
});
}

// Open the flood gates :)
startLatch.countDown();
} finally {
executor.shutdown();
assertThat(executor.awaitTermination(1, TimeUnit.DAYS)).isTrue();
}

assertThat(exceptionsThrown).isEmpty();
}

private static final class TestCacheManager extends AbstractCacheManager {
Expand Down

0 comments on commit c5034a2

Please sign in to comment.