001/** 002 * Copyright (C) 2006-2024 Talend Inc. - www.talend.com 003 * 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 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 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 org.talend.sdk.component.junit5.environment; 017 018import static org.junit.platform.commons.util.AnnotationUtils.findAnnotation; 019import static org.junit.platform.commons.util.AnnotationUtils.isAnnotated; 020 021import java.util.stream.Stream; 022 023import org.junit.jupiter.api.extension.ExtensionContext; 024import org.junit.jupiter.api.extension.TestTemplateInvocationContext; 025import org.junit.jupiter.api.extension.TestTemplateInvocationContextProvider; 026import org.talend.sdk.component.junit.environment.DecoratingEnvironmentProvider; 027import org.talend.sdk.component.junit.environment.EnvironmentsConfigurationParser; 028import org.talend.sdk.component.junit5.ComponentExtension; 029import org.talend.sdk.component.junit5.WithComponents; 030 031public class EnvironmentsExtension implements TestTemplateInvocationContextProvider { 032 033 @Override 034 public boolean supportsTestTemplate(final ExtensionContext context) { 035 return isAnnotated(context.getTestMethod(), EnvironmentalTest.class); 036 } 037 038 @Override 039 public Stream<TestTemplateInvocationContext> provideTestTemplateInvocationContexts(final ExtensionContext context) { 040 final String format = findAnnotation(context.getRequiredTestMethod(), EnvironmentalTest.class).get().format(); 041 return new EnvironmentsConfigurationParser(context.getRequiredTestClass()) 042 .stream() 043 .map(e -> new EnvironmentalContext(e, 044 format 045 .replace("${displayName}", context.getDisplayName()) 046 .replace("${environment}", DecoratingEnvironmentProvider.class.cast(e).getName()), 047 createComponentExtension(context))); 048 } 049 050 private ComponentExtension createComponentExtension(final ExtensionContext context) { 051 return context 052 .getElement() 053 .map(it -> it.isAnnotationPresent(WithComponents.class)) 054 .filter(it -> it) 055 .orElseGet(() -> context 056 .getParent() 057 .flatMap(it -> it.getElement().map(e -> e.isAnnotationPresent(WithComponents.class))) 058 .orElse(false)) 059 ? context 060 .getStore(ExtensionContext.Namespace.create(ComponentExtension.class.getName())) 061 .get(ComponentExtension.class.getName() + ".instance", ComponentExtension.class) 062 : null; 063 } 064}