|
| 1 | +package io.github.netmikey.testprocesses.extensions; |
| 2 | + |
| 3 | +import org.junit.jupiter.api.extension.AfterEachCallback; |
| 4 | +import org.junit.jupiter.api.extension.Extension; |
| 5 | +import org.junit.jupiter.api.extension.ExtensionContext; |
| 6 | +import org.springframework.test.context.junit.jupiter.SpringExtension; |
| 7 | +import org.springframework.util.StringUtils; |
| 8 | + |
| 9 | +import io.github.netmikey.testprocesses.TestProcessDefinition; |
| 10 | +import io.github.netmikey.testprocesses.TestProcessDefinitionBy; |
| 11 | +import io.github.netmikey.testprocesses.TestProcessesRegistry; |
| 12 | +import io.github.netmikey.testprocesses.utils.StreamStart; |
| 13 | + |
| 14 | +/** |
| 15 | + * A JUnit {@link Extension} that logs <code>stdOut</code> and |
| 16 | + * <code>stdErr</code> streams of each currently running test process after each |
| 17 | + * test. Only the output that has been produced on the stdOut/stdErr streams |
| 18 | + * during the current test is logged. If no output has been produced on a |
| 19 | + * stream, it is not logged. |
| 20 | + */ |
| 21 | +public class LogTestProcessesOutputExtension implements AfterEachCallback { |
| 22 | + |
| 23 | + private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory |
| 24 | + .getLogger(LogTestProcessesOutputExtension.class); |
| 25 | + |
| 26 | + @Override |
| 27 | + public void afterEach(ExtensionContext context) throws Exception { |
| 28 | + TestProcessesRegistry registry = SpringExtension.getApplicationContext(context) |
| 29 | + .getBean(TestProcessesRegistry.class); |
| 30 | + registry.runningProcessIdentifiers().forEach(processIdentifier -> { |
| 31 | + TestProcessDefinitionBy<? extends TestProcessDefinition> selector = TestProcessDefinitionBy |
| 32 | + .processIdentifier(processIdentifier); |
| 33 | + logStream(processIdentifier, "stdOut", registry.stdOutAsStringOf(selector, StreamStart.CURRENT_TEST)); |
| 34 | + logStream(processIdentifier, "stdErr", registry.stdErrAsStringOf(selector, StreamStart.CURRENT_TEST)); |
| 35 | + }); |
| 36 | + } |
| 37 | + |
| 38 | + private void logStream(String processIdentifier, String streamName, String content) { |
| 39 | + if (StringUtils.hasText(content)) { |
| 40 | + String title = processIdentifier; |
| 41 | + String delimiter = "-------------------- %s %s --------------------" |
| 42 | + .formatted(title, streamName); |
| 43 | + LOG.info("\n{}\n{}\n{}", |
| 44 | + delimiter, |
| 45 | + content.replaceAll("\r?\n$", "").replaceAll("(^|\r?\n)", "$1 "), |
| 46 | + "-".repeat(delimiter.length())); |
| 47 | + } |
| 48 | + } |
| 49 | +} |
0 commit comments