Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

refactor(test): share the wait-until-parked and POSIX permission helpers (#6313)

Ben Wart7b2f0737ee38
diff --git a/src/test/java/io/github/hectorvent/floci/core/storage/PartitionedFileStorageJournalTest.java b/src/test/java/io/github/hectorvent/floci/core/storage/PartitionedFileStorageJournalTest.java
index 50a735ff7e..ce47161ae1 100644
--- a/src/test/java/io/github/hectorvent/floci/core/storage/PartitionedFileStorageJournalTest.java
+++ b/src/test/java/io/github/hectorvent/floci/core/storage/PartitionedFileStorageJournalTest.java
@@ -1,5 +1,7 @@
package io.github.hectorvent.floci.core.storage;
+import io.github.hectorvent.floci.testing.FileSystemAssumptions;
+import io.github.hectorvent.floci.testing.ThreadStates;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
@@ -274,7 +276,7 @@ class PartitionedFileStorageJournalTest {
// The shards are written and the journal is about to be emptied. A write now must
// wait for the compaction to finish, or its journal record is dropped unwritten.
writer[0] = Thread.ofPlatform().start(() -> live.putEntry("table", "late", "2"));
- StorageTestThreads.awaitParkedOrDone(writer[0]);
+ ThreadStates.awaitParkedOrDone(writer[0]);
});
live.flush();
@@ -294,7 +296,7 @@ class PartitionedFileStorageJournalTest {
// entry must wait, or its record lands first and a replay ends on the older value.
live.setBeforeJournalAppend(() -> { });
second[0] = Thread.ofPlatform().start(() -> live.putEntry("table", "a", "second"));
- StorageTestThreads.awaitParkedOrDone(second[0]);
+ ThreadStates.awaitParkedOrDone(second[0]);
});
live.putEntry("table", "a", "first");
@@ -370,7 +372,7 @@ class PartitionedFileStorageJournalTest {
void aJournalThatCannotBeReadFailsLoadAndIsNeverCompactedAway() throws Exception {
PartitionedFileStorage<String> crashed = open(1);
crashed.putEntry("table", "a", "1");
- StorageTestFiles.assumePosixPermissions(journal());
+ FileSystemAssumptions.assumePosixPermissions(journal());
Set<PosixFilePermission> original = Files.getPosixFilePermissions(journal());
PartitionedFileStorage<String> restarting = new PartitionedFileStorage<>(tempDir.resolve("items"),
tempDir.resolve("items.json"), String.class, 1, PartitionedFileStorage.Mode.JOURNAL, Long.MAX_VALUE);
@@ -434,7 +436,7 @@ class PartitionedFileStorageJournalTest {
PartitionedFileStorage<String> crashed = open(1);
crashed.putEntry("table", "a", "1");
Path directory = tempDir.resolve("items");
- StorageTestFiles.assumePosixPermissions(directory);
+ FileSystemAssumptions.assumePosixPermissions(directory);
Set<PosixFilePermission> original = Files.getPosixFilePermissions(directory);
crashed.setBeforeJournalTruncate(() -> {
// The shards are written; now make emptying the journal fail.
diff --git a/src/test/java/io/github/hectorvent/floci/core/storage/PartitionedFileStorageTest.java b/src/test/java/io/github/hectorvent/floci/core/storage/PartitionedFileStorageTest.java
index 3f0918e26d..092f0bd001 100644
--- a/src/test/java/io/github/hectorvent/floci/core/storage/PartitionedFileStorageTest.java
+++ b/src/test/java/io/github/hectorvent/floci/core/storage/PartitionedFileStorageTest.java
@@ -1,6 +1,8 @@
package io.github.hectorvent.floci.core.storage;
import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.testing.FileSystemAssumptions;
+import io.github.hectorvent.floci.testing.ThreadStates;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
@@ -177,7 +179,7 @@ class PartitionedFileStorageTest {
storage.flush();
storage.putEntry("busy", "node-1", "beat-1");
Path directory = tempDir.resolve("items");
- StorageTestFiles.assumePosixPermissions(directory);
+ FileSystemAssumptions.assumePosixPermissions(directory);
Set<PosixFilePermission> original = Files.getPosixFilePermissions(directory);
Files.setPosixFilePermissions(directory, PosixFilePermissions.fromString("r-xr-xr-x"));
try {
@@ -300,7 +302,7 @@ class PartitionedFileStorageTest {
void aMigrationThatCannotWriteFailsAndKeepsTheLegacyFile() throws Exception {
Path legacy = tempDir.resolve("items.json");
new ObjectMapper().writeValue(legacy.toFile(), Map.of("a", Map.of("k", "1")));
- StorageTestFiles.assumePosixPermissions(tempDir);
+ FileSystemAssumptions.assumePosixPermissions(tempDir);
Set<PosixFilePermission> original = Files.getPosixFilePermissions(tempDir);
Files.setPosixFilePermissions(tempDir, PosixFilePermissions.fromString("r-xr-xr-x"));
try {
@@ -367,7 +369,7 @@ class PartitionedFileStorageTest {
Path old = current.resolveSibling("old-name.json");
Files.move(current, old);
Path directory = tempDir.resolve("items");
- StorageTestFiles.assumePosixPermissions(directory);
+ FileSystemAssumptions.assumePosixPermissions(directory);
Set<PosixFilePermission> original = Files.getPosixFilePermissions(directory);
PartitionedFileStorage<String> blocked = new PartitionedFileStorage<>(directory,
@@ -408,7 +410,7 @@ class PartitionedFileStorageTest {
// the write, or the write puts the cleared file back.
storage.setBeforeShardWrite(() -> { });
clearer[0] = Thread.ofPlatform().start(storage::clear);
- StorageTestThreads.awaitParkedOrDone(clearer[0]);
+ ThreadStates.awaitParkedOrDone(clearer[0]);
});
storage.flush();
diff --git a/src/test/java/io/github/hectorvent/floci/core/storage/StorageFactoryPartitionedTest.java b/src/test/java/io/github/hectorvent/floci/core/storage/StorageFactoryPartitionedTest.java
index 59d5132d1d..c6b5a16c86 100644
--- a/src/test/java/io/github/hectorvent/floci/core/storage/StorageFactoryPartitionedTest.java
+++ b/src/test/java/io/github/hectorvent/floci/core/storage/StorageFactoryPartitionedTest.java
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.ServiceConfigAccess;
+import io.github.hectorvent.floci.testing.FileSystemAssumptions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
@@ -164,7 +165,7 @@ class StorageFactoryPartitionedTest {
@Test
void aMigrationThatCannotWriteLeavesTheLegacyLogInPlace() throws Exception {
- StorageTestFiles.assumePosixPermissions(tempDir);
+ FileSystemAssumptions.assumePosixPermissions(tempDir);
WalStorage<String, Map<String, String>> legacy = new WalStorage<>(tempDir.resolve("svc-items-snapshot.json"),
tempDir.resolve("svc-items.wal"), TYPE, Long.MAX_VALUE);
legacy.load();
diff --git a/src/test/java/io/github/hectorvent/floci/core/storage/StorageTestFiles.java b/src/test/java/io/github/hectorvent/floci/core/storage/StorageTestFiles.java
deleted file mode 100644
index 21ddfd16f4..0000000000
--- a/src/test/java/io/github/hectorvent/floci/core/storage/StorageTestFiles.java
+++ /dev/null
@@ -1,25 +0,0 @@
-package io.github.hectorvent.floci.core.storage;
-
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.attribute.PosixFileAttributeView;
-
-import static org.junit.jupiter.api.Assumptions.assumeTrue;
-
-/** File system helpers for the storage tests. */
-final class StorageTestFiles {
-
- private StorageTestFiles() {
- }
-
- /**
- * Skips the calling test unless {@code path}'s file store supports POSIX permissions. Tests
- * that make a directory read-only to force a write to fail call it first, because the POSIX
- * permission calls throw on a file system without them, such as Windows.
- */
- static void assumePosixPermissions(Path path) throws IOException {
- assumeTrue(Files.getFileStore(path).supportsFileAttributeView(PosixFileAttributeView.class),
- "POSIX file permissions are not supported here");
- }
-}
diff --git a/src/test/java/io/github/hectorvent/floci/core/storage/StorageTestThreads.java b/src/test/java/io/github/hectorvent/floci/core/storage/StorageTestThreads.java
deleted file mode 100644
index a80c10c2ab..0000000000
--- a/src/test/java/io/github/hectorvent/floci/core/storage/StorageTestThreads.java
+++ /dev/null
@@ -1,29 +0,0 @@
-package io.github.hectorvent.floci.core.storage;
-
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.locks.LockSupport;
-
-import static org.junit.jupiter.api.Assertions.fail;
-
-/** Thread helpers for the storage race tests. */
-final class StorageTestThreads {
-
- private StorageTestThreads() {
- }
-
- /**
- * Waits until the thread has finished or is parked, on a lock for instance. Fails by name
- * after ten seconds, so a thread that neither finishes nor waits cannot hang the test.
- */
- static void awaitParkedOrDone(Thread thread) {
- long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
- while (System.nanoTime() < deadline) {
- Thread.State state = thread.getState();
- if (state == Thread.State.TERMINATED || state == Thread.State.WAITING) {
- return;
- }
- LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(1));
- }
- fail("the thread neither finished nor waited: " + thread.getState());
- }
-}
diff --git a/src/test/java/io/github/hectorvent/floci/core/storage/WalStorageTest.java b/src/test/java/io/github/hectorvent/floci/core/storage/WalStorageTest.java
index 26a4c1904e..e4c898ca9f 100644
--- a/src/test/java/io/github/hectorvent/floci/core/storage/WalStorageTest.java
+++ b/src/test/java/io/github/hectorvent/floci/core/storage/WalStorageTest.java
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.core.storage;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
+import io.github.hectorvent.floci.testing.FileSystemAssumptions;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -14,7 +15,6 @@ import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.file.Files;
import java.nio.file.Path;
-import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.List;
@@ -23,7 +23,6 @@ import java.util.Set;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
-import static org.junit.jupiter.api.Assumptions.assumeTrue;
class WalStorageTest {
@@ -394,8 +393,7 @@ class WalStorageTest {
Path walDirectory = Files.createDirectories(tempDir.resolve("stuck-wal"));
Path walPath = walDirectory.resolve("data.wal");
// The test makes the directory read-only through POSIX permissions, which Windows lacks.
- assumeTrue(Files.getFileStore(walDirectory).supportsFileAttributeView(PosixFileAttributeView.class),
- "POSIX file permissions are not supported here");
+ FileSystemAssumptions.assumePosixPermissions(walDirectory);
Set<PosixFilePermission> original = Files.getPosixFilePermissions(walDirectory);
WalStorage<String, String> store1 = new WalStorage<>(snapshotPath, walPath,
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsServiceTest.java
index e752e71c40..fccd4e85ca 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsServiceTest.java
@@ -8,12 +8,14 @@ import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogEvent;
import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogGroup;
import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogStream;
import io.github.hectorvent.floci.services.cloudwatch.logs.model.SubscriptionFilter;
+import io.github.hectorvent.floci.testing.ThreadStates;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
+import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
@@ -441,18 +443,14 @@ class CloudWatchLogsServiceTest {
assertEquals(List.of(), logs.describeLogStreams("/app", null, REGION));
}
- /** Runs the thread until it ends or waits on a lock the caller may hold. */
+ /**
+ * Runs the thread until it ends or waits on a lock the caller may hold. Gives up after five
+ * seconds, well inside the callers' ten-second timeout, so a stuck thread is reported by its
+ * state and the test still has time to finish.
+ */
private static void startAndWaitUntilFinishedOrStuck(Thread thread) {
thread.start();
- long deadline = System.nanoTime() + 5_000_000_000L;
- while (thread.isAlive() && System.nanoTime() < deadline) {
- Thread.State state = thread.getState();
- if (state == Thread.State.BLOCKED || state == Thread.State.WAITING
- || state == Thread.State.TIMED_WAITING) {
- return;
- }
- Thread.onSpinWait();
- }
+ ThreadStates.awaitState(thread, ThreadStates.PARKED_OR_DONE, Duration.ofSeconds(5), "the worker");
}
@Test
diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyTlsCertificatesTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyTlsCertificatesTest.java
index b00c938322..f1cb35b223 100644
--- a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyTlsCertificatesTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyTlsCertificatesTest.java
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.rds.proxy;
import io.github.hectorvent.floci.config.FlociCertificateAuthority;
import io.github.hectorvent.floci.core.common.Pem;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
+import io.github.hectorvent.floci.testing.FileSystemAssumptions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
@@ -12,7 +13,6 @@ import org.junit.jupiter.params.provider.ValueSource;
import javax.net.ssl.SSLContext;
import java.nio.file.Files;
import java.nio.file.Path;
-import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.security.cert.CertificateExpiredException;
@@ -30,7 +30,6 @@ import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assumptions.assumeTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -153,8 +152,7 @@ class RdsProxyTlsCertificatesTest {
@Test
void privateKeyAndTlsDirAreRestrictedToOwnerOnly() throws Exception {
Path tlsDir = tempDir.resolve("tls");
- assumeTrue(Files.getFileStore(tempDir).supportsFileAttributeView(PosixFileAttributeView.class),
- "POSIX permissions are not supported on this filesystem");
+ FileSystemAssumptions.assumePosixPermissions(tempDir);
RdsProxyTlsCertificates certs = newCertificates();
certs.ensureHost("172.17.0.5");
diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftDynamoDbZeroEtlConsumerTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftDynamoDbZeroEtlConsumerTest.java
index 272d1d0356..016b0bf417 100644
--- a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftDynamoDbZeroEtlConsumerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftDynamoDbZeroEtlConsumerTest.java
@@ -18,6 +18,7 @@ import io.github.hectorvent.floci.services.dynamodb.model.AttributeDefinition;
import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;
import io.github.hectorvent.floci.services.redshift.model.Integration;
import io.github.hectorvent.floci.services.redshiftdata.RedshiftZeroEtlWriter;
+import io.github.hectorvent.floci.testing.ThreadStates;
import io.quarkus.test.junit.QuarkusTest;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
@@ -25,7 +26,9 @@ import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
+import java.time.Duration;
import java.util.ArrayList;
+import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -39,7 +42,6 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyLong;
@@ -433,27 +435,14 @@ class RedshiftDynamoDbZeroEtlConsumerTest {
/** Observes the thread park in a timed wait, or end, instead of sleeping to hope for either. */
private static Thread.State awaitTimedWaitingOrTerminated(Thread thread) {
- long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
- Thread.State state = thread.getState();
- while (state != Thread.State.TIMED_WAITING && state != Thread.State.TERMINATED) {
- if (System.nanoTime() > deadline) {
- fail("the thread neither parked in a timed wait nor ended");
- }
- Thread.onSpinWait();
- state = thread.getState();
- }
- return state;
+ return ThreadStates.awaitState(thread, EnumSet.of(Thread.State.TIMED_WAITING, Thread.State.TERMINATED),
+ Duration.ofSeconds(10), "the thread");
}
/** Observes the reset thread park on the poll's lock instead of sleeping to hope for it. */
private static void awaitWaiting(Thread thread) {
- long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
- while (thread.getState() != Thread.State.WAITING) {
- if (System.nanoTime() > deadline) {
- fail("beforeReset() returned or never waited while a write was in progress");
- }
- Thread.onSpinWait();
- }
+ ThreadStates.awaitState(thread, EnumSet.of(Thread.State.WAITING), Duration.ofSeconds(10),
+ "beforeReset(), while a write was in progress,");
}
private static Integration streamingIntegration() {
diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3MultipartBucketDeletionRaceTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3MultipartBucketDeletionRaceTest.java
index cdcfb4e1eb..5379f18970 100644
--- a/src/test/java/io/github/hectorvent/floci/services/s3/S3MultipartBucketDeletionRaceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3MultipartBucketDeletionRaceTest.java
@@ -3,12 +3,15 @@ package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.s3.model.MultipartUpload;
+import io.github.hectorvent.floci.testing.ThreadStates;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.nio.file.Path;
+import java.time.Duration;
+import java.util.EnumSet;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@@ -229,15 +232,10 @@ class S3MultipartBucketDeletionRaceTest {
assertNotNull(service.getObject("race-bucket", "object"));
}
- private static void awaitWaiting(Thread thread) throws InterruptedException {
- long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
- while (System.nanoTime() < deadline && thread.getState() != Thread.State.WAITING) {
- if (!thread.isAlive()) {
- break;
- }
- Thread.sleep(10);
- }
- assertEquals(Thread.State.WAITING, thread.getState(), "operation should wait for the multipart lock");
+ private static void awaitWaiting(Thread thread) {
+ Thread.State state = ThreadStates.awaitState(thread, EnumSet.of(Thread.State.WAITING, Thread.State.TERMINATED),
+ Duration.ofSeconds(5), "the operation");
+ assertEquals(Thread.State.WAITING, state, "operation should wait for the multipart lock");
}
private static final class BlockingService extends S3Service {
diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesExportJobServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesExportJobServiceTest.java
index 7722f15d8f..74aee56bc3 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ses/SesExportJobServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesExportJobServiceTest.java
@@ -12,15 +12,18 @@ import io.github.hectorvent.floci.services.ses.model.EmailInsights;
import io.github.hectorvent.floci.services.ses.model.ExportJob;
import io.github.hectorvent.floci.services.ses.model.InsightsEvent;
import io.github.hectorvent.floci.services.ses.model.SentEmail;
+import io.github.hectorvent.floci.testing.ThreadStates;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
+import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.ArrayList;
+import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
@@ -314,15 +317,8 @@ class SesExportJobServiceTest {
/** Both waits here park in {@code Object.wait(timeout)}, so the state is timed, not WAITING. */
private static void awaitParked(Thread thread, String what) {
- long deadline = System.currentTimeMillis() + 5_000;
- while (System.currentTimeMillis() < deadline) {
- Thread.State state = thread.getState();
- if (state == Thread.State.TIMED_WAITING || state == Thread.State.WAITING) {
- return;
- }
- Thread.onSpinWait();
- }
- throw new AssertionError(what + " never parked, it was " + thread.getState());
+ ThreadStates.awaitState(thread, EnumSet.of(Thread.State.TIMED_WAITING, Thread.State.WAITING),
+ Duration.ofSeconds(5), what);
}
@Test
diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesIdentityServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesIdentityServiceTest.java
index 84df7bb21e..a0ebdd99f9 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ses/SesIdentityServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesIdentityServiceTest.java
@@ -4,6 +4,7 @@ import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.ses.model.Identity;
import io.github.hectorvent.floci.services.ses.model.Tag;
+import io.github.hectorvent.floci.testing.ThreadStates;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
@@ -12,6 +13,7 @@ import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.Mockito;
import java.time.Clock;
+import java.time.Duration;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
@@ -27,6 +29,7 @@ import java.util.stream.Stream;
import static io.github.hectorvent.floci.testing.ThreadStates.awaitBlockedOrDone;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
@@ -205,12 +208,6 @@ class SesIdentityServiceTest {
assertEquals("AlreadyExistsException", e.getErrorCode());
}
- /** Any parked state counts as contending, so a switch to e.g. ReentrantLock stays green. */
- private static boolean isParked(Thread.State state) {
- return state == Thread.State.BLOCKED || state == Thread.State.WAITING
- || state == Thread.State.TIMED_WAITING;
- }
-
/** Counts put calls so the single-write guarantee is asserted, not inferred. */
private static final class CountingStorage extends InMemoryStorage<String, Identity> {
final AtomicInteger puts = new AtomicInteger();
@@ -272,14 +269,9 @@ class SesIdentityServiceTest {
second.start();
// The second create must park on the creation lock before the first is released; a
// TERMINATED second thread means it completed without contending, i.e. the lock is gone.
- long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
- while (!isParked(second.getState())) {
- assertTrue(second.getState() != Thread.State.TERMINATED,
- "second create finished without blocking on the creation lock");
- assertTrue(System.nanoTime() < deadline,
- "second create never blocked on the creation lock");
- Thread.onSpinWait();
- }
+ assertNotEquals(Thread.State.TERMINATED, ThreadStates.awaitState(second, ThreadStates.PARKED_OR_DONE,
+ Duration.ofSeconds(5), "second create"),
+ "second create finished without blocking on the creation lock");
} finally {
proceed.countDown();
}
@@ -319,16 +311,11 @@ class SesIdentityServiceTest {
try {
assertTrue(insideLock.await(5, TimeUnit.SECONDS), "create never entered the lock");
verifier.start();
- long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
// The v1 verify path takes the same creation lock, so it must park here rather than
// overwrite the in-flight create with a bare identity (the lost-update it used to allow).
- while (!isParked(verifier.getState())) {
- assertTrue(verifier.getState() != Thread.State.TERMINATED,
- "verify finished without contending on the creation lock");
- assertTrue(System.nanoTime() < deadline,
- "verify never blocked on the creation lock");
- Thread.onSpinWait();
- }
+ assertNotEquals(Thread.State.TERMINATED, ThreadStates.awaitState(verifier, ThreadStates.PARKED_OR_DONE,
+ Duration.ofSeconds(5), "verify"),
+ "verify finished without contending on the creation lock");
} finally {
proceed.countDown();
}
diff --git a/src/test/java/io/github/hectorvent/floci/testing/FileSystemAssumptions.java b/src/test/java/io/github/hectorvent/floci/testing/FileSystemAssumptions.java
new file mode 100644
index 0000000000..ea8a80db41
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/testing/FileSystemAssumptions.java
@@ -0,0 +1,24 @@
+package io.github.hectorvent.floci.testing;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.PosixFileAttributeView;
+
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
+
+/** File system checks for tests that depend on what the host's file system supports. */
+public final class FileSystemAssumptions {
+
+ private FileSystemAssumptions() {}
+
+ /**
+ * Skips the calling test unless {@code path}'s file store supports POSIX permissions. Call it
+ * before any POSIX permission call: those throw on a file system without them, such as Windows,
+ * which would fail the test instead of skipping it.
+ */
+ public static void assumePosixPermissions(Path path) throws IOException {
+ assumeTrue(Files.getFileStore(path).supportsFileAttributeView(PosixFileAttributeView.class),
+ "POSIX file permissions are not supported here");
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/testing/ThreadStates.java b/src/test/java/io/github/hectorvent/floci/testing/ThreadStates.java
index 41afad566b..1acdf9ea28 100644
--- a/src/test/java/io/github/hectorvent/floci/testing/ThreadStates.java
+++ b/src/test/java/io/github/hectorvent/floci/testing/ThreadStates.java
@@ -1,16 +1,26 @@
package io.github.hectorvent.floci.testing;
+import java.time.Duration;
+import java.util.Collections;
+import java.util.EnumSet;
+import java.util.Set;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
+import java.util.concurrent.locks.LockSupport;
import java.util.function.BooleanSupplier;
import java.util.function.Supplier;
import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/** Waiting for a thread to reach a lock, for tests that force two requests to overlap. */
public final class ThreadStates {
+ /** Every state a thread is in once it has stopped running: parked in any way, or ended. */
+ public static final Set<Thread.State> PARKED_OR_DONE = Collections.unmodifiableSet(EnumSet.of(
+ Thread.State.BLOCKED, Thread.State.WAITING, Thread.State.TIMED_WAITING, Thread.State.TERMINATED));
+
private ThreadStates() {}
/**
@@ -54,4 +64,30 @@ public final class ThreadStates {
Thread.State state = thread.getState();
return state == Thread.State.BLOCKED || state == Thread.State.WAITING;
}
+
+ /**
+ * Waits until {@code thread} is parked in any way (blocked on a monitor, waiting or timed
+ * waiting) or has ended, and returns the state it reached. Fails after ten seconds.
+ */
+ public static Thread.State awaitParkedOrDone(Thread thread) {
+ return awaitState(thread, PARKED_OR_DONE, Duration.ofSeconds(10), "the thread");
+ }
+
+ /**
+ * Waits until {@code thread} is in one of {@code states} and returns the one it reached, checking
+ * every millisecond. Fails naming {@code what} and the state it was left in once {@code timeout}
+ * passes, so a thread that never gets there fails the test instead of hanging it.
+ */
+ public static Thread.State awaitState(Thread thread, Set<Thread.State> states, Duration timeout, String what) {
+ long deadline = System.nanoTime() + timeout.toNanos();
+ Thread.State state = thread.getState();
+ while (!states.contains(state)) {
+ if (System.nanoTime() - deadline > 0) {
+ fail(what + " never reached " + states + ", it was " + state);
+ }
+ LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(1));
+ state = thread.getState();
+ }
+ return state;
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/testing/ThreadStatesTest.java b/src/test/java/io/github/hectorvent/floci/testing/ThreadStatesTest.java
new file mode 100644
index 0000000000..a513a09873
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/testing/ThreadStatesTest.java
@@ -0,0 +1,45 @@
+package io.github.hectorvent.floci.testing;
+
+import org.junit.jupiter.api.Test;
+
+import java.time.Duration;
+import java.util.EnumSet;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class ThreadStatesTest {
+
+ @Test
+ void awaitStateReturnsTheStateTheThreadReached() throws Exception {
+ CountDownLatch release = new CountDownLatch(1);
+ Thread waiter = Thread.ofPlatform().start(() -> {
+ try {
+ release.await();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ });
+ try {
+ assertEquals(Thread.State.WAITING, ThreadStates.awaitParkedOrDone(waiter));
+ } finally {
+ release.countDown();
+ waiter.join(TimeUnit.SECONDS.toMillis(10));
+ }
+ assertEquals(Thread.State.TERMINATED, ThreadStates.awaitParkedOrDone(waiter));
+ }
+
+ @Test
+ void awaitStateFailsNamingTheThreadWhenItNeverGetsThere() {
+ Thread unstarted = new Thread(() -> { });
+
+ AssertionError failure = assertThrows(AssertionError.class, () -> ThreadStates.awaitState(
+ unstarted, EnumSet.of(Thread.State.WAITING), Duration.ofMillis(20), "the worker"));
+
+ assertTrue(failure.getMessage().startsWith("the worker never reached [WAITING], it was NEW"),
+ failure.getMessage());
+ }
+}