From 44dea210a67ddae6bd7028a3825a57c976122baa Mon Sep 17 00:00:00 2001 From: mrfelek <17274927+mrfelek@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:01:26 +0100 Subject: [PATCH] test: share the log record formatting in LogCapture (#8475) Nine test classes each formatted a captured LogRecord themselves, running MessageFormat on the pattern when the backend still carried the parameters beside it. LogCapture.formatted now does it once, next to LogCapture.capture, and they use it. It asks the backend instead of running MessageFormat itself: a JBoss LogManager record formats itself in its own style, so printf-style records (infof, warnf) come out filled in, and any other record is formatted as java.util.logging.Formatter.formatMessage does, leaving a pattern it cannot read as it is. A record without a message reads "null". The assertions are unchanged. --- .../aws/lifecycle/EmulatorLifecycleTest.java | 7 +--- ...dFormationUnsupportedResourceTypeTest.java | 24 +++--------- .../SamTransformProcessorTest.java | 17 ++------- .../ElastiCacheCfnProvisionerTest.java | 3 +- .../CloudWatchLogsMetricFilterRetryTest.java | 19 ++++------ .../services/eks/EksClusterManagerTest.java | 3 +- .../proxy/PostgresProtocolHandlerTest.java | 3 +- .../rds/proxy/RdsSigV4ValidatorTest.java | 9 +---- .../StepFunctionsServicePersistenceTest.java | 17 ++------- .../io/floci/aws/testutil/LogCapture.java | 18 +++++++++ .../io/floci/aws/testutil/LogCaptureTest.java | 38 +++++++++++++++++++ 11 files changed, 83 insertions(+), 75 deletions(-) diff --git a/src/test/java/io/floci/aws/lifecycle/EmulatorLifecycleTest.java b/src/test/java/io/floci/aws/lifecycle/EmulatorLifecycleTest.java index b43239c66b..e38b9eb4f2 100644 --- a/src/test/java/io/floci/aws/lifecycle/EmulatorLifecycleTest.java +++ b/src/test/java/io/floci/aws/lifecycle/EmulatorLifecycleTest.java @@ -43,6 +43,7 @@ import io.floci.aws.services.rds.proxy.RdsProxyManager; import io.floci.aws.services.redshift.RedshiftDynamoDbZeroEtlConsumer; import io.floci.aws.services.stepfunctions.StepFunctionsService; import io.floci.aws.services.timestreaminfluxdb.TimestreamInfluxDbService; +import io.floci.aws.testutil.LogCapture; import io.quarkus.runtime.Quarkus; import io.quarkus.runtime.ShutdownDelayInitiatedEvent; import io.quarkus.runtime.ShutdownEvent; @@ -62,7 +63,6 @@ import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import java.io.IOException; -import java.text.MessageFormat; import java.util.Collections; import java.util.List; import java.util.concurrent.CompletableFuture; @@ -791,10 +791,7 @@ class EmulatorLifecycleTest { Handler handler = new Handler() { @Override public void publish(LogRecord logRecord) { - Object[] parameters = logRecord.getParameters(); - messages.add(parameters == null || parameters.length == 0 - ? logRecord.getMessage() - : MessageFormat.format(logRecord.getMessage(), parameters)); + messages.add(LogCapture.formatted(logRecord)); } @Override diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationUnsupportedResourceTypeTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationUnsupportedResourceTypeTest.java index 24c5b06bad..93f7ab7d4a 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationUnsupportedResourceTypeTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationUnsupportedResourceTypeTest.java @@ -6,10 +6,10 @@ import io.floci.aws.config.EmulatorConfig; import io.floci.aws.services.cloudformation.model.StackResource; import io.floci.aws.services.cloudformation.provisioners.CfnResourceDispatcher; import io.floci.aws.services.ecr.EcrService; +import io.floci.aws.testutil.LogCapture; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.text.MessageFormat; import java.util.List; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; @@ -76,7 +76,7 @@ class CloudFormationUnsupportedResourceTypeTest { assertEquals(STUB_REASON, resource.getStatusReason()); assertTrue(logged.stream().anyMatch(r -> r.getLevel().intValue() >= Level.WARNING.intValue() - && STUB_WARNING.equals(formatted(r))), + && STUB_WARNING.equals(LogCapture.formatted(r))), "expected the stub to be reported at warn, got: " + rendered(logged)); } @@ -130,7 +130,7 @@ class CloudFormationUnsupportedResourceTypeTest { assertTrue(logged.stream().anyMatch(r -> r.getLevel().intValue() >= Level.WARNING.intValue() - && DELETE_WARNING.equals(formatted(r))), + && DELETE_WARNING.equals(LogCapture.formatted(r))), "expected the skipped delete to be reported at warn, got: " + rendered(logged)); } @@ -153,9 +153,9 @@ class CloudFormationUnsupportedResourceTypeTest { assertTrue(logged.stream().anyMatch(r -> r.getLevel().intValue() >= Level.WARNING.intValue() && ("Stubbing resource type AWS::ECR::Repository (Repo): its service is disabled, " + "so nothing is created for it. Set floci.services.ecr.enabled=true to provision it.") - .equals(formatted(r))), + .equals(LogCapture.formatted(r))), "expected the disabled-service warning, got: " + rendered(logged)); - assertTrue(logged.stream().noneMatch(r -> formatted(r).contains("allow-stub-unsupported-resource-types")), + assertTrue(logged.stream().noneMatch(r -> LogCapture.formatted(r).contains("allow-stub-unsupported-resource-types")), "the warning must not blame the unsupported-type flag: " + rendered(logged)); } @@ -228,20 +228,8 @@ class CloudFormationUnsupportedResourceTypeTest { } } - /** - * The record's text. Which logging backend is in play decides whether the parameters are - * already substituted or still carried alongside the pattern, so substitute them here when - * they are still there. - */ - private static String formatted(LogRecord record) { - Object[] parameters = record.getParameters(); - return parameters == null || parameters.length == 0 - ? record.getMessage() - : MessageFormat.format(record.getMessage(), parameters); - } - private static List rendered(List records) { - return records.stream().map(r -> r.getLevel() + " " + formatted(r)).toList(); + return records.stream().map(r -> r.getLevel() + " " + LogCapture.formatted(r)).toList(); } private JsonNode props() { diff --git a/src/test/java/io/floci/aws/services/cloudformation/SamTransformProcessorTest.java b/src/test/java/io/floci/aws/services/cloudformation/SamTransformProcessorTest.java index 4101e6ade3..fdb38e001a 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/SamTransformProcessorTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/SamTransformProcessorTest.java @@ -3,10 +3,10 @@ package io.floci.aws.services.cloudformation; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.aws.core.common.AwsException; +import io.floci.aws.testutil.LogCapture; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.text.MessageFormat; import java.util.Iterator; import java.util.List; import java.util.Map; @@ -3278,19 +3278,8 @@ class SamTransformProcessorTest { + "left in the template for the CloudFormation provisioner."; assertTrue(logged.stream().anyMatch(r -> r.getLevel().intValue() >= Level.WARNING.intValue() - && expected.equals(text(r))), + && expected.equals(LogCapture.formatted(r))), "expected the unexpanded SAM type to be reported at warn, got: " - + logged.stream().map(r -> r.getLevel() + " " + text(r)).toList()); - } - - /** - * The record's text. Which logging backend is in play decides whether the parameters are - * already substituted or still carried alongside the pattern. - */ - private static String text(LogRecord record) { - Object[] parameters = record.getParameters(); - return parameters == null || parameters.length == 0 - ? record.getMessage() - : MessageFormat.format(record.getMessage(), parameters); + + logged.stream().map(r -> r.getLevel() + " " + LogCapture.formatted(r)).toList()); } } diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/ElastiCacheCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/ElastiCacheCfnProvisionerTest.java index 64a8745568..ec7815108e 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/ElastiCacheCfnProvisionerTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/ElastiCacheCfnProvisionerTest.java @@ -21,7 +21,6 @@ import io.floci.aws.testutil.LogCapture; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; -import java.text.MessageFormat; import java.time.Instant; import java.util.ArrayList; import java.util.HashMap; @@ -196,7 +195,7 @@ class ElastiCacheCfnProvisionerTest { throw new IllegalStateException(e); } }).stream() - .map(record -> MessageFormat.format(record.getMessage(), record.getParameters())) + .map(LogCapture::formatted) .filter(message -> message.contains("in-place modification is not supported")) .toList(); } diff --git a/src/test/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsMetricFilterRetryTest.java b/src/test/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsMetricFilterRetryTest.java index ece3ca5bb9..7f440dcb79 100644 --- a/src/test/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsMetricFilterRetryTest.java +++ b/src/test/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsMetricFilterRetryTest.java @@ -4,12 +4,12 @@ import io.floci.aws.core.storage.InMemoryStorage; import io.floci.aws.services.cloudwatch.logs.model.MetricFilter; import io.floci.aws.services.cloudwatch.metrics.model.Dimension; import io.floci.aws.services.cloudwatch.metrics.model.MetricDatum; +import io.floci.aws.testutil.LogCapture; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; -import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -157,10 +157,11 @@ class CloudWatchLogsMetricFilterRetryTest { try { f.ingest(null, GROUP, REGION, TIME, Collections.nCopies(10_003, "INFO")); assertEquals(10_000, f.service.pendingSamples(), "bound counts samples, not batches"); - assertTrue(records.stream().anyMatch(r -> r.getLevel().intValue() >= Level.SEVERE.intValue() - && formatted(r).contains(ACCOUNT) && formatted(r).contains(GROUP) - && formatted(r).contains("region=" + REGION) && formatted(r).contains("filter=bound") - && formatted(r).contains("dropped=3")), "overflow must be ERROR with ownership and dropped count"); + assertTrue(records.stream().filter(r -> r.getLevel().intValue() >= Level.SEVERE.intValue()) + .map(LogCapture::formatted) + .anyMatch(text -> text.contains(ACCOUNT) && text.contains(GROUP) && text.contains("region=" + REGION) + && text.contains("filter=bound") && text.contains("dropped=3")), + "overflow must be ERROR with ownership and dropped count"); List queuedKeys = List.copyOf(sink.attempts.subList(0, 10_000)); sink.fail = false; f.service.retryPending(); @@ -351,8 +352,8 @@ class CloudWatchLogsMetricFilterRetryTest { assertEquals(filters, logs.details(), "one stack per owning filter outage, not per tick or sample"); assertEquals(1, logs.summaries(), "one aggregate stack-free warning after 60 failed ticks, even for 100 filters"); LogRecord summary = logs.warnings.stream().filter(record -> record.getThrown() == null).findFirst().orElseThrow(); - assertTrue(formatted(summary).contains("failedSamples=" + filters)); - assertTrue(formatted(summary).contains("filters=" + filters)); + assertTrue(LogCapture.formatted(summary).contains("failedSamples=" + filters)); + assertTrue(LogCapture.formatted(summary).contains("filters=" + filters)); } } @@ -473,10 +474,6 @@ class CloudWatchLogsMetricFilterRetryTest { catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IllegalStateException(e); } } - private static String formatted(LogRecord r) { - return MessageFormat.format(r.getMessage(), r.getParameters() == null ? new Object[0] : r.getParameters()); - } - static class FaultStore extends InMemoryStorage { volatile boolean fail; volatile BiConsumer before = (key, value) -> {}; diff --git a/src/test/java/io/floci/aws/services/eks/EksClusterManagerTest.java b/src/test/java/io/floci/aws/services/eks/EksClusterManagerTest.java index 1e6cd94d8a..b98f5be38e 100644 --- a/src/test/java/io/floci/aws/services/eks/EksClusterManagerTest.java +++ b/src/test/java/io/floci/aws/services/eks/EksClusterManagerTest.java @@ -83,7 +83,6 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.PosixFilePermission; import java.nio.file.attribute.PosixFilePermissions; -import java.text.MessageFormat; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; @@ -1353,7 +1352,7 @@ class EksClusterManagerTest { // Compared by severity, not identity: JBoss LogManager has its own Level constants. List warnings = logs.stream() .filter(record -> record.getLevel().intValue() >= Level.WARNING.intValue()) - .map(record -> MessageFormat.format(record.getMessage(), record.getParameters())) + .map(LogCapture::formatted) .toList(); assertTrue(warnings.contains(warning), String.valueOf(warnings)); } diff --git a/src/test/java/io/floci/aws/services/rds/proxy/PostgresProtocolHandlerTest.java b/src/test/java/io/floci/aws/services/rds/proxy/PostgresProtocolHandlerTest.java index de1c41d223..3c09f11de5 100644 --- a/src/test/java/io/floci/aws/services/rds/proxy/PostgresProtocolHandlerTest.java +++ b/src/test/java/io/floci/aws/services/rds/proxy/PostgresProtocolHandlerTest.java @@ -35,7 +35,6 @@ import java.nio.file.Path; import java.security.KeyStore; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; -import java.text.MessageFormat; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; @@ -1700,7 +1699,7 @@ class PostgresProtocolHandlerTest { writeReadyForQuery(out); assertEquals(-1, in.read()); }))); - List logs = records.stream().map(record -> MessageFormat.format(record.getMessage(), record.getParameters())).toList(); + List logs = records.stream().map(LogCapture::formatted).toList(); assertTrue(logs.stream().anyMatch(line -> line.contains("user approle: catalog query returned an error"))); assertFalse(logs.stream().anyMatch(line -> line.contains("SECRET_") || line.contains("X-Amz-") || line.contains("\n") || line.contains("\r"))); diff --git a/src/test/java/io/floci/aws/services/rds/proxy/RdsSigV4ValidatorTest.java b/src/test/java/io/floci/aws/services/rds/proxy/RdsSigV4ValidatorTest.java index 577ccd1ea0..230dc54eb5 100644 --- a/src/test/java/io/floci/aws/services/rds/proxy/RdsSigV4ValidatorTest.java +++ b/src/test/java/io/floci/aws/services/rds/proxy/RdsSigV4ValidatorTest.java @@ -9,7 +9,6 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import java.lang.reflect.Method; -import java.text.MessageFormat; import java.time.Instant; import java.util.List; import java.util.logging.LogRecord; @@ -688,7 +687,7 @@ class RdsSigV4ValidatorTest { () -> assertFalse(validator.validate(token, dbUser, exampleBinding()))); List refusals = records.stream() - .map(RdsSigV4ValidatorTest::render) + .map(LogCapture::formatted) .filter(message -> message.contains("rds-db:connect")) .toList(); assertEquals(1, refusals.size(), "expected one refusal warning, got: " + records); @@ -697,12 +696,6 @@ class RdsSigV4ValidatorTest { "control characters must be stripped from the warning: " + refusals.get(0)); } - private static String render(LogRecord record) { - return record.getParameters() == null - ? record.getMessage() - : MessageFormat.format(record.getMessage(), record.getParameters()); - } - @Test void sanitizeForLogStripsControlCharacters() throws Exception { // A forged accessKeyId containing CR/LF must not be able to inject fake log lines into diff --git a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsServicePersistenceTest.java b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsServicePersistenceTest.java index 09395e59df..1ea28c3e0b 100644 --- a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsServicePersistenceTest.java +++ b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsServicePersistenceTest.java @@ -14,13 +14,13 @@ import io.floci.aws.services.stepfunctions.model.Execution; import io.floci.aws.services.stepfunctions.model.HistoryEvent; import io.floci.aws.services.stepfunctions.model.MockedTestCase; import io.floci.aws.services.stepfunctions.model.StateMachine; +import io.floci.aws.testutil.LogCapture; import jakarta.enterprise.inject.Instance; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.mockito.Mockito; import java.nio.file.Path; -import java.text.MessageFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -235,9 +235,9 @@ class StepFunctionsServicePersistenceTest { List warnings = warningsIn(logRecords); assertEquals(1, warnings.size(), "expected one WARN record for the sweep, got: " + formattedAll(logRecords)); - assertTrue(formatted(warnings.getFirst()).contains("1"), + assertTrue(LogCapture.formatted(warnings.getFirst()).contains("1"), "expected the WARN record to name how many executions were aborted, got: " - + formatted(warnings.getFirst())); + + LogCapture.formatted(warnings.getFirst())); Optional owned = executions.getForAccount(OTHER_ACCOUNT, OTHER_ACCOUNT_EXECUTION_ARN); @@ -326,7 +326,7 @@ class StepFunctionsServicePersistenceTest { } private static List formattedAll(List records) { - return records.stream().map(StepFunctionsServicePersistenceTest::formatted).toList(); + return records.stream().map(LogCapture::formatted).toList(); } /** @@ -339,15 +339,6 @@ class StepFunctionsServicePersistenceTest { "stopDate is not a plausible epoch-seconds instant: " + stopDate); } - /** The record as a reader sees it, whether the handler receives it formatted or as a pattern. */ - private static String formatted(LogRecord record) { - Object[] parameters = record.getParameters(); - if (parameters == null || parameters.length == 0) { - return String.valueOf(record.getMessage()); - } - return MessageFormat.format(record.getMessage(), parameters); - } - private static Execution running(String executionArn) { Execution execution = new Execution(); execution.setExecutionArn(executionArn); diff --git a/src/test/java/io/floci/aws/testutil/LogCapture.java b/src/test/java/io/floci/aws/testutil/LogCapture.java index 2e96118cf3..6b04a17f23 100644 --- a/src/test/java/io/floci/aws/testutil/LogCapture.java +++ b/src/test/java/io/floci/aws/testutil/LogCapture.java @@ -1,5 +1,7 @@ package io.floci.aws.testutil; +import org.jboss.logmanager.ExtLogRecord; + import java.time.Duration; import java.util.ArrayList; import java.util.List; @@ -8,14 +10,18 @@ import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.function.Supplier; +import java.util.logging.Formatter; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; +import java.util.logging.SimpleFormatter; /** Captures a class logger for the duration of one test action. */ public final class LogCapture { + private static final Formatter JUL = new SimpleFormatter(); + private LogCapture() { } @@ -28,6 +34,18 @@ public final class LogCapture { return records; } + /** + * The record's text as a reader sees it, formatted the way its logging backend formats it: a JBoss + * LogManager record, which the tests' {@code java.util.logging.manager} hands out, in its own + * format style ({@code printf} for {@code infof}, {@code MessageFormat} for {@code infov}), and any + * other record as {@link java.util.logging.Formatter#formatMessage} does, which leaves a pattern it + * cannot format as it is. A record without a message reads {@code "null"}. + */ + public static String formatted(LogRecord record) { + String text = record instanceof ExtLogRecord ext ? ext.getFormattedMessage() : JUL.formatMessage(record); + return String.valueOf(text); + } + /** Runs the action with capture installed, then waits for a matching asynchronous record. */ public static T awaitRecord(Class source, Duration timeout, Predicate matches, Supplier action) { diff --git a/src/test/java/io/floci/aws/testutil/LogCaptureTest.java b/src/test/java/io/floci/aws/testutil/LogCaptureTest.java index 687ed235a1..833676e938 100644 --- a/src/test/java/io/floci/aws/testutil/LogCaptureTest.java +++ b/src/test/java/io/floci/aws/testutil/LogCaptureTest.java @@ -1,6 +1,7 @@ package io.floci.aws.testutil; import io.floci.aws.testing.ThreadStates; +import org.jboss.logmanager.ExtLogRecord; import org.junit.jupiter.api.Test; import java.time.Duration; @@ -104,6 +105,43 @@ class LogCaptureTest { assertEquals(originalHandlerCount, logger.getHandlers().length); } + @Test + void formattedSubstitutesTheParametersARecordStillCarries() { + LogRecord pattern = new LogRecord(Level.WARNING, "key {0} in account {1}"); + pattern.setParameters(new Object[]{"AKIAEXAMPLE", "123456789012"}); + LogRecord plain = new LogRecord(Level.WARNING, "the user's key {0}"); + + assertEquals("key AKIAEXAMPLE in account 123456789012", LogCapture.formatted(pattern)); + assertEquals("the user's key {0}", LogCapture.formatted(plain)); + } + + /** A JBoss record is formatted in its own style: printf for {@code infof}, MessageFormat for {@code infov}. */ + @Test + void formattedReadsAJbossRecordInItsOwnFormatStyle() { + ExtLogRecord printf = new ExtLogRecord(Level.INFO, "=== Floci %s Starting ===", + ExtLogRecord.FormatStyle.PRINTF, LogCaptureTest.class.getName()); + printf.setParameters(new Object[]{"2.5.0"}); + ExtLogRecord messageFormat = new ExtLogRecord(Level.INFO, "broker {0} is now RUNNING", + ExtLogRecord.FormatStyle.MESSAGE_FORMAT, LogCaptureTest.class.getName()); + messageFormat.setParameters(new Object[]{"orders"}); + + assertEquals("=== Floci 2.5.0 Starting ===", LogCapture.formatted(printf)); + assertEquals("broker orders is now RUNNING", LogCapture.formatted(messageFormat)); + } + + /** A pattern MessageFormat cannot read, an empty parameter list and no message at all don't throw. */ + @Test + void formattedLeavesWhatItCannotFormatAsItIs() { + LogRecord braces = new LogRecord(Level.WARNING, "bad payload {0 {\"a\":1}"); + braces.setParameters(new Object[]{"x"}); + LogRecord empty = new LogRecord(Level.WARNING, "role ''{0}''"); + empty.setParameters(new Object[0]); + + assertEquals("bad payload {0 {\"a\":1}", LogCapture.formatted(braces)); + assertEquals("role ''{0}''", LogCapture.formatted(empty)); + assertEquals("null", LogCapture.formatted(new LogRecord(Level.WARNING, null))); + } + @Test void awaitRestoresLoggerWhenActionThrows() { Logger logger = Logger.getLogger(LogCaptureTest.class.getName());