001/*
002 * Copyright 2023 the original author or authors.
003 * <p>
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 * <p>
008 * https://www.apache.org/licenses/LICENSE-2.0
009 * <p>
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package de.cuioss.test.juli.junit5;
017
018import static de.cuioss.test.juli.TestLoggerFactory.addLogger;
019
020import java.util.Optional;
021
022import org.junit.jupiter.api.extension.AfterAllCallback;
023import org.junit.jupiter.api.extension.BeforeAllCallback;
024import org.junit.jupiter.api.extension.BeforeEachCallback;
025import org.junit.jupiter.api.extension.ExtensionContext;
026
027import de.cuioss.test.juli.TestLogLevel;
028import de.cuioss.test.juli.TestLoggerFactory;
029import de.cuioss.tools.reflect.MoreReflection;
030
031/**
032 * Extension for setting up the {@link TestLoggerFactory} properly
033 *
034 * @author Oliver Wolff
035 *
036 */
037public class TestLoggerController implements BeforeAllCallback, AfterAllCallback, BeforeEachCallback {
038
039    @Override
040    public void beforeEach(ExtensionContext context) {
041        TestLoggerFactory.configureLogger();
042        TestLoggerFactory.getTestHandler().clearRecords();
043        Class<?> testClass = context.getTestClass()
044                .orElseThrow(() -> new IllegalStateException("Unable to determine Test-class"));
045        Optional<EnableTestLogger> annotation = MoreReflection.extractAnnotation(testClass, EnableTestLogger.class);
046        annotation.ifPresent(this::handleEnableTestLoggerAnnotation);
047    }
048
049    @Override
050    public void afterAll(ExtensionContext context) {
051        TestLoggerFactory.uninstall();
052    }
053
054    @Override
055    public void beforeAll(ExtensionContext context) {
056        TestLoggerFactory.install();
057    }
058
059    private void handleEnableTestLoggerAnnotation(EnableTestLogger annotation) {
060        addLogger(annotation.rootLevel(), "");
061
062        for (Class<?> clazz : annotation.trace()) {
063            TestLogLevel.TRACE.addLogger(clazz);
064        }
065        for (Class<?> clazz : annotation.debug()) {
066            TestLogLevel.DEBUG.addLogger(clazz);
067        }
068        for (Class<?> clazz : annotation.info()) {
069            TestLogLevel.INFO.addLogger(clazz);
070        }
071        for (Class<?> clazz : annotation.warn()) {
072            TestLogLevel.WARN.addLogger(clazz);
073        }
074        for (Class<?> clazz : annotation.error()) {
075            TestLogLevel.ERROR.addLogger(clazz);
076        }
077    }
078}