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.
This commit is contained in:
mrfelek authored and GitHub committed 2026-11-15 14:01:26 -04:00
1 parent 88867ae9d7
commit 44dea210a6
11 files changed
+83 -75

No files matched your search

@@ -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
@@ -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<String> rendered(List<LogRecord> 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() {
@@ -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());
}
}
@@ -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();
}
@@ -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<String> 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<String, MetricDatum> {
volatile boolean fail;
volatile BiConsumer<String, MetricDatum> before = (key, value) -> {};
@@ -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<String> 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));
}
@@ -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<String> logs = records.stream().map(record -> MessageFormat.format(record.getMessage(), record.getParameters())).toList();
List<String> 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")));
@@ -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<String> 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
@@ -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<LogRecord> 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<Execution> owned =
executions.getForAccount(OTHER_ACCOUNT, OTHER_ACCOUNT_EXECUTION_ARN);
@@ -326,7 +326,7 @@ class StepFunctionsServicePersistenceTest {
}
private static List<String> formattedAll(List<LogRecord> 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);
@@ -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> T awaitRecord(Class<?> source, Duration timeout, Predicate<LogRecord> matches,
Supplier<T> action) {
@@ -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());