001package de.cuioss.test.juli.junit5; 002 003import static de.cuioss.test.juli.TestLoggerFactory.addLogger; 004 005import java.util.Optional; 006 007import org.junit.jupiter.api.extension.AfterAllCallback; 008import org.junit.jupiter.api.extension.BeforeAllCallback; 009import org.junit.jupiter.api.extension.BeforeEachCallback; 010import org.junit.jupiter.api.extension.ExtensionContext; 011 012import de.cuioss.test.juli.TestLogLevel; 013import de.cuioss.test.juli.TestLoggerFactory; 014import de.cuioss.tools.reflect.MoreReflection; 015 016/** 017 * Extension for setting up the {@link TestLoggerFactory} properly 018 * 019 * @author Oliver Wolff 020 * 021 */ 022public class TestLoggerController implements BeforeAllCallback, AfterAllCallback, BeforeEachCallback { 023 024 @Override 025 public void beforeEach(ExtensionContext context) { 026 TestLoggerFactory.configureLogger(); 027 TestLoggerFactory.getTestHandler().clearRecords(); 028 Class<?> testClass = context.getTestClass() 029 .orElseThrow(() -> new IllegalStateException("Unable to determine Test-class")); 030 Optional<EnableTestLogger> annotation = MoreReflection.extractAnnotation(testClass, 031 EnableTestLogger.class); 032 annotation.ifPresent(this::handleEnableTestLoggerAnnotation); 033 } 034 035 @Override 036 public void afterAll(ExtensionContext context) { 037 TestLoggerFactory.uninstall(); 038 } 039 040 @Override 041 public void beforeAll(ExtensionContext context) { 042 TestLoggerFactory.install(); 043 } 044 045 private void handleEnableTestLoggerAnnotation(EnableTestLogger annotation) { 046 addLogger(annotation.rootLevel(), ""); 047 048 for (Class<?> clazz : annotation.trace()) { 049 TestLogLevel.TRACE.addLogger(clazz); 050 } 051 for (Class<?> clazz : annotation.debug()) { 052 TestLogLevel.DEBUG.addLogger(clazz); 053 } 054 for (Class<?> clazz : annotation.info()) { 055 TestLogLevel.INFO.addLogger(clazz); 056 } 057 for (Class<?> clazz : annotation.warn()) { 058 TestLogLevel.WARN.addLogger(clazz); 059 } 060 for (Class<?> clazz : annotation.error()) { 061 TestLogLevel.ERROR.addLogger(clazz); 062 } 063 } 064}