Light, fluffy, and always free - The AWS Local Emulator alternative
test(core): share log capture helper across tests (#4588)
XuJian954bf8debb6f
diff --git a/src/test/java/io/github/hectorvent/floci/core/storage/PersistentPathValidatorTest.java b/src/test/java/io/github/hectorvent/floci/core/storage/PersistentPathValidatorTest.javaindex e72870653b..af24d42e44 100644--- a/src/test/java/io/github/hectorvent/floci/core/storage/PersistentPathValidatorTest.java+++ b/src/test/java/io/github/hectorvent/floci/core/storage/PersistentPathValidatorTest.java@@ -4,6 +4,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig;import io.github.hectorvent.floci.core.common.ResolvedServiceCatalog;import io.github.hectorvent.floci.core.common.ServiceDescriptor;import io.github.hectorvent.floci.core.common.ServiceProtocol;+import io.github.hectorvent.floci.testutil.LogCapture;import org.junit.jupiter.api.Assumptions;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.condition.DisabledOnOs;@@ -16,11 +17,8 @@ import org.mockito.junit.jupiter.MockitoExtension;import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;-import java.util.ArrayList;import java.util.List;import java.util.Set;-import java.util.logging.Handler;-import java.util.logging.Level;import java.util.logging.LogRecord;import static org.junit.jupiter.api.Assertions.assertEquals;@@ -122,7 +120,8 @@ class PersistentPathValidatorTest {descriptor("s3", true, "s3", "memory"),descriptor("sqs", true, "sqs", "memory")));- List<LogRecord> records = captureLogs(() -> validator().validateAtBoot());+ List<LogRecord> records = LogCapture.capture(PersistentPathValidator.class,+ () -> validator().validateAtBoot());assertTrue(records.stream().anyMatch(r -> r.getMessage() != null&& r.getMessage().contains("memory")@@ -136,7 +135,8 @@ class PersistentPathValidatorTest {when(catalog.all()).thenReturn(List.of(descriptor("sqs", true, "sqs", "hybrid")));when(storageConfig.persistentPath()).thenReturn(root.toString());- List<LogRecord> records = captureLogs(() -> validator().validateAtBoot());+ List<LogRecord> records = LogCapture.capture(PersistentPathValidator.class,+ () -> validator().validateAtBoot());assertTrue(records.stream().anyMatch(r -> r.getMessage() != null&& r.getMessage().contains("persistent")@@ -146,33 +146,4 @@ class PersistentPathValidatorTest {&& String.valueOf(r.getParameters()[1]).contains(root.toString())),"expected a boot log announcing persistent mode with the effective path, got: " + records);}-- private static List<LogRecord> captureLogs(Runnable action) {- java.util.logging.Logger julLogger =- java.util.logging.Logger.getLogger(PersistentPathValidator.class.getName());- julLogger.setLevel(Level.ALL);- List<LogRecord> records = new ArrayList<>();- Handler handler = new Handler() {- @Override- public void publish(LogRecord record) {- records.add(record);- }-- @Override- public void flush() {- }-- @Override- public void close() {- }- };- handler.setLevel(Level.ALL);- julLogger.addHandler(handler);- try {- action.run();- } finally {- julLogger.removeHandler(handler);- }- return records;- }}diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.javaindex edb2fe22f2..fa3a9c2d69 100644--- a/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java@@ -22,6 +22,7 @@ import io.github.hectorvent.floci.services.eks.model.LogSetup;import io.github.hectorvent.floci.services.eks.model.Logging;import io.github.hectorvent.floci.services.eks.model.OidcIdentity;import io.github.hectorvent.floci.services.eks.model.ResourcesVpcConfig;+import io.github.hectorvent.floci.testutil.LogCapture;import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.ObjectMapper;@@ -64,7 +65,6 @@ import java.util.List;import java.util.Map;import java.util.Optional;import java.util.Set;-import java.util.logging.Handler;import java.util.logging.Level;import java.util.logging.LogRecord;@@ -1044,7 +1044,7 @@ class EksClusterManagerTest {vpcConfig.setVpcId("vpc-12345678");cluster.setResourcesVpcConfig(vpcConfig);- List<LogRecord> logs = captureClusterManagerLogs(+ List<LogRecord> logs = LogCapture.capture(EksClusterManager.class,() -> manager.registerClusterNodeInstance(cluster, "container-unreachable"));assertTrue(manager.vpcForClient("172.17.0.2").isEmpty());@@ -1057,35 +1057,6 @@ class EksClusterManagerTest {+ logs.stream().map(LogRecord::getMessage).toList());}- private static List<LogRecord> captureClusterManagerLogs(Runnable action) {- java.util.logging.Logger julLogger =- java.util.logging.Logger.getLogger(EksClusterManager.class.getName());- julLogger.setLevel(Level.ALL);- List<LogRecord> records = new ArrayList<>();- Handler handler = new Handler() {- @Override- public void publish(LogRecord record) {- records.add(record);- }-- @Override- public void flush() {- }-- @Override- public void close() {- }- };- handler.setLevel(Level.ALL);- julLogger.addHandler(handler);- try {- action.run();- } finally {- julLogger.removeHandler(handler);- }- return records;- }-@Testvoid clusterNodeInstanceProviderFindsAndListsRegisteredInstances() {Cluster cluster = new Cluster();diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsSigV4ValidatorTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsSigV4ValidatorTest.javaindex 102d04714a..1c86c703c4 100644--- a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsSigV4ValidatorTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsSigV4ValidatorTest.java@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.rds.proxy;import io.github.hectorvent.floci.services.iam.IamService;import io.github.hectorvent.floci.testutil.IamServiceTestHelper;+import io.github.hectorvent.floci.testutil.LogCapture;import io.github.hectorvent.floci.testutil.SigV4TokenTestHelper;import org.junit.jupiter.api.Test;import org.junit.jupiter.params.ParameterizedTest;@@ -10,10 +11,7 @@ import org.junit.jupiter.params.provider.ValueSource;import java.lang.reflect.Method;import java.text.MessageFormat;import java.time.Instant;-import java.util.ArrayList;import java.util.List;-import java.util.logging.Handler;-import java.util.logging.Level;import java.util.logging.LogRecord;import static org.junit.jupiter.api.Assertions.assertEquals;@@ -629,7 +627,7 @@ class RdsSigV4ValidatorTest {"db.example.local", 3307, dbUser, "AKIDRDS", "secret-rds",Instant.now().minusSeconds(60), 900);- List<LogRecord> records = captureLogs(+ List<LogRecord> records = LogCapture.capture(RdsSigV4Validator.class,() -> assertFalse(validator.validate(token, dbUser, exampleBinding())));List<String> refusals = records.stream()@@ -648,35 +646,6 @@ class RdsSigV4ValidatorTest {: MessageFormat.format(record.getMessage(), record.getParameters());}- private static List<LogRecord> captureLogs(Runnable action) {- java.util.logging.Logger julLogger =- java.util.logging.Logger.getLogger(RdsSigV4Validator.class.getName());- julLogger.setLevel(Level.ALL);- List<LogRecord> records = new ArrayList<>();- Handler handler = new Handler() {- @Override- public void publish(LogRecord record) {- records.add(record);- }-- @Override- public void flush() {- }-- @Override- public void close() {- }- };- handler.setLevel(Level.ALL);- julLogger.addHandler(handler);- try {- action.run();- } finally {- julLogger.removeHandler(handler);- }- return records;- }-@Testvoid sanitizeForLogStripsControlCharacters() throws Exception {// A forged accessKeyId containing CR/LF must not be able to inject fake log lines intodiff --git a/src/test/java/io/github/hectorvent/floci/testutil/LogCapture.java b/src/test/java/io/github/hectorvent/floci/testutil/LogCapture.javanew file mode 100644index 0000000000..87289dd16e--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/testutil/LogCapture.java@@ -0,0 +1,45 @@+package io.github.hectorvent.floci.testutil;++import java.util.ArrayList;+import java.util.List;+import java.util.logging.Handler;+import java.util.logging.Level;+import java.util.logging.LogRecord;+import java.util.logging.Logger;++/** Captures a class logger for the duration of one test action. */+public final class LogCapture {++ private LogCapture() {+ }++ public static List<LogRecord> capture(Class<?> source, Runnable action) {+ Logger logger = Logger.getLogger(source.getName());+ Level originalLevel = logger.getLevel();+ List<LogRecord> records = new ArrayList<>();+ Handler handler = new Handler() {+ @Override+ public void publish(LogRecord record) {+ records.add(record);+ }++ @Override+ public void flush() {+ }++ @Override+ public void close() {+ }+ };+ handler.setLevel(Level.ALL);+ logger.addHandler(handler);+ try {+ logger.setLevel(Level.ALL);+ action.run();+ } finally {+ logger.removeHandler(handler);+ logger.setLevel(originalLevel);+ }+ return records;+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/testutil/LogCaptureTest.java b/src/test/java/io/github/hectorvent/floci/testutil/LogCaptureTest.javanew file mode 100644index 0000000000..6c91f09702--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/testutil/LogCaptureTest.java@@ -0,0 +1,52 @@+package io.github.hectorvent.floci.testutil;++import org.junit.jupiter.api.Test;++import java.util.List;+import java.util.logging.Level;+import java.util.logging.LogRecord;+import java.util.logging.Logger;++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 LogCaptureTest {++ @Test+ void captureRestoresLoggerLevelAndHandlers() {+ Logger logger = Logger.getLogger(LogCaptureTest.class.getName());+ Level originalLevel = logger.getLevel();+ int originalHandlerCount = logger.getHandlers().length;+ try {+ logger.setLevel(Level.SEVERE);++ List<LogRecord> records = LogCapture.capture(LogCaptureTest.class,+ () -> logger.info("captured message"));++ assertTrue(records.stream().anyMatch(record -> "captured message".equals(record.getMessage())));+ assertEquals(Level.SEVERE, logger.getLevel());+ assertEquals(originalHandlerCount, logger.getHandlers().length);+ } finally {+ logger.setLevel(originalLevel);+ }+ }++ @Test+ void captureRestoresLoggerWhenActionThrows() {+ Logger logger = Logger.getLogger(LogCaptureTest.class.getName());+ Level originalLevel = logger.getLevel();+ int originalHandlerCount = logger.getHandlers().length;+ try {+ logger.setLevel(Level.WARNING);++ assertThrows(IllegalStateException.class, () -> LogCapture.capture(LogCaptureTest.class,+ () -> { throw new IllegalStateException("failed action"); }));++ assertEquals(Level.WARNING, logger.getLevel());+ assertEquals(originalHandlerCount, logger.getHandlers().length);+ } finally {+ logger.setLevel(originalLevel);+ }+ }+}