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.valueobjects.junit5.extension;
017
018import java.util.Collections;
019
020import org.junit.jupiter.api.extension.AfterAllCallback;
021import org.junit.jupiter.api.extension.ExtensionContext;
022import org.junit.jupiter.api.extension.TestInstancePostProcessor;
023
024import de.cuioss.test.valueobjects.generator.TypedGeneratorRegistry;
025import de.cuioss.test.valueobjects.util.GeneratorAnnotationHelper;
026import de.cuioss.test.valueobjects.util.GeneratorRegistry;
027import de.cuioss.tools.logging.CuiLogger;
028
029/**
030 * This extension handles the test-generator handling, see
031 * {@link GeneratorRegistry} for details
032 *
033 * @author Oliver Wolff
034 *
035 */
036public class GeneratorRegistryController implements TestInstancePostProcessor, AfterAllCallback {
037
038    private static final CuiLogger LOGGER = new CuiLogger(GeneratorRegistryController.class);
039
040    @Override
041    public void postProcessTestInstance(Object testInstance, ExtensionContext context) {
042        LOGGER.debug(() -> "Clearing TypedGeneratorRegistry registry");
043        TypedGeneratorRegistry.clear();
044        if (testInstance instanceof GeneratorRegistry registry) {
045            LOGGER.debug(() -> "Test-class '" + testInstance.getClass()
046                    + "' is of type de.cuioss.test.valueobjects.util.GeneratorRegistry, initializing Generator framework");
047            GeneratorAnnotationHelper.handleGeneratorsForTestClass(registry, registry.registerAdditionalGenerators());
048        } else {
049            LOGGER.debug(() -> "Test-class '{" + testInstance.getClass()
050                    + "}' is NOT of type de.cuioss.test.valueobjects.util.GeneratorRegistry, initializing Generator framework without local Generator");
051            GeneratorAnnotationHelper.handleGeneratorsForTestClass(testInstance, Collections.emptyList());
052        }
053
054    }
055
056    @Override
057    public void afterAll(ExtensionContext context) {
058        LOGGER.debug(() -> "Tearing down TypedGeneratorRegistry registry");
059        TypedGeneratorRegistry.clear();
060    }
061
062}