This is an automated email from the ASF dual-hosted git repository. gnodet pushed a commit to branch master in repository https://gitbox.apache.org/repos/asf/camel.git
commit e10ccef1e57277456c30aa843ba676eefbadebb8 Author: Guillaume Nodet <gno...@gmail.com> AuthorDate: Wed Jun 17 12:25:54 2020 +0200 [CAMEL-15215] Simplify and homogenize spring testing --- .../apache/camel/spring/SpringCamelContext.java | 24 +- .../org/apache/camel/spring/SpringTestSupport.java | 9 + .../spring/junit5/CamelAnnotationsHandler.java | 73 +++-- .../junit5/CamelSpringBootExecutionListener.java | 10 +- .../test/spring/junit5/CamelSpringBootTest.java | 9 +- .../camel/test/spring/junit5/CamelSpringTest.java | 8 +- .../junit5/CamelSpringTestContextLoader.java | 321 +------------------- .../test/spring/junit5/CamelSpringTestHelper.java | 11 +- .../junit5/DisableJmxTestExecutionListener.java | 50 ---- .../junit5/SpringTestExecutionListenerSorter.java | 4 - .../SpringTestExecutionListenerSorterTest.java | 4 - .../camel/test/spring/CamelAnnotationsHandler.java | 73 +++-- .../spring/CamelSpringBootExecutionListener.java | 95 ------ .../camel/test/spring/CamelSpringBootRunner.java | 51 +--- .../CamelSpringDelegatingTestContextLoader.java | 21 +- .../camel/test/spring/CamelSpringRunner.java | 18 +- .../test/spring/CamelSpringTestContextLoader.java | 323 ++------------------- .../camel/test/spring/CamelSpringTestHelper.java | 17 +- .../spring/DisableJmxTestExecutionListener.java | 39 --- 19 files changed, 229 insertions(+), 931 deletions(-) diff --git a/components/camel-spring/src/main/java/org/apache/camel/spring/SpringCamelContext.java b/components/camel-spring/src/main/java/org/apache/camel/spring/SpringCamelContext.java index 100f857..baf7aa4 100644 --- a/components/camel-spring/src/main/java/org/apache/camel/spring/SpringCamelContext.java +++ b/components/camel-spring/src/main/java/org/apache/camel/spring/SpringCamelContext.java @@ -16,21 +16,28 @@ */ package org.apache.camel.spring; +import java.util.HashSet; +import java.util.Set; + import org.apache.camel.Endpoint; import org.apache.camel.api.management.JmxSystemPropertyKeys; import org.apache.camel.component.bean.BeanProcessor; import org.apache.camel.component.event.EventComponent; import org.apache.camel.component.event.EventEndpoint; import org.apache.camel.impl.DefaultCamelContext; +import org.apache.camel.impl.scan.AssignableToPackageScanFilter; +import org.apache.camel.impl.scan.InvertingPackageScanFilter; import org.apache.camel.spi.BeanRepository; import org.apache.camel.spi.Injector; import org.apache.camel.spi.ModelJAXBContextFactory; +import org.apache.camel.spi.PackageScanClassResolver; import org.apache.camel.spi.Registry; import org.apache.camel.spring.spi.ApplicationContextBeanRepository; import org.apache.camel.spring.spi.SpringInjector; import org.apache.camel.spring.spi.SpringManagementMBeanAssembler; import org.apache.camel.support.DefaultRegistry; import org.apache.camel.support.ProcessorEndpoint; +import org.apache.camel.util.ObjectHelper; import org.apache.camel.util.StopWatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -58,6 +65,8 @@ import static org.apache.camel.RuntimeCamelException.wrapRuntimeCamelException; public class SpringCamelContext extends DefaultCamelContext implements Lifecycle, ApplicationContextAware, Phased, ApplicationListener<ApplicationEvent>, Ordered { + public static final String EXCLUDE_ROUTES = "CamelTestSpringExcludeRoutes"; + private static final Logger LOG = LoggerFactory.getLogger(SpringCamelContext.class); private static final ThreadLocal<Boolean> NO_START = new ThreadLocal<>(); private ApplicationContext applicationContext; @@ -144,7 +153,7 @@ public class SpringCamelContext extends DefaultCamelContext implements Lifecycle if (event instanceof ContextRefreshedEvent && ((ContextRefreshedEvent) event).getApplicationContext() == this.applicationContext) { // nominally we would prefer to use Lifecycle interface that - // would invoke start() method, but in order to do that + // would invoke start() method, but in order to do that // SpringCamelContext needs to implement SmartLifecycle // (look at DefaultLifecycleProcessor::startBeans), but it // cannot implement it as it already implements @@ -296,4 +305,17 @@ public class SpringCamelContext extends DefaultCamelContext implements Lifecycle return !isStopping() && !isStopped(); } + protected PackageScanClassResolver createPackageScanClassResolver() { + PackageScanClassResolver resolver = super.createPackageScanClassResolver(); + String excluded = System.getProperty(EXCLUDE_ROUTES); + if (ObjectHelper.isNotEmpty(excluded)) { + Set<Class<?>> excludedClasses = new HashSet<>(); + for (String str : excluded.split(",")) { + excludedClasses.add(getClassResolver().resolveClass(str)); + } + resolver.addFilter(new InvertingPackageScanFilter(new AssignableToPackageScanFilter(excludedClasses))); + } + return resolver; + } + } diff --git a/components/camel-spring/src/test/java/org/apache/camel/spring/SpringTestSupport.java b/components/camel-spring/src/test/java/org/apache/camel/spring/SpringTestSupport.java index ebf87f1..1a94744 100644 --- a/components/camel-spring/src/test/java/org/apache/camel/spring/SpringTestSupport.java +++ b/components/camel-spring/src/test/java/org/apache/camel/spring/SpringTestSupport.java @@ -28,6 +28,7 @@ import org.apache.camel.api.management.JmxSystemPropertyKeys; import org.apache.camel.impl.engine.DefaultPackageScanClassResolver; import org.apache.camel.impl.scan.AssignableToPackageScanFilter; import org.apache.camel.impl.scan.InvertingPackageScanFilter; +import org.apache.camel.util.CollectionStringBuffer; import org.apache.camel.util.IOHelper; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -48,6 +49,14 @@ public abstract class SpringTestSupport extends ContextTestSupport { // we want SpringTestSupport to startup faster and not use JMX by default and should stop seda quicker System.setProperty("CamelSedaPollTimeout", "10"); System.setProperty(JmxSystemPropertyKeys.DISABLED, Boolean.toString(!useJmx())); + Class<?>[] excluded = excludeRoutes(); + if (excluded != null && excluded.length > 0) { + CollectionStringBuffer csb = new CollectionStringBuffer(","); + for (Class<?> clazz : excluded) { + csb.append(clazz.getName()); + } + System.setProperty(SpringCamelContext.EXCLUDE_ROUTES, csb.toString()); + } applicationContext = createApplicationContext(); assertNotNull(applicationContext, "Should have created a valid spring context"); diff --git a/components/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/CamelAnnotationsHandler.java b/components/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/CamelAnnotationsHandler.java index a06b946..23e2b6c 100644 --- a/components/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/CamelAnnotationsHandler.java +++ b/components/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/CamelAnnotationsHandler.java @@ -40,11 +40,10 @@ import org.apache.camel.test.junit5.CamelTestSupport; import org.apache.camel.util.CollectionStringBuffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.annotation.AnnotationUtils; -import static org.apache.camel.test.spring.junit5.CamelSpringTestHelper.getAllMethods; - public final class CamelAnnotationsHandler { private static final Logger LOGGER = LoggerFactory.getLogger(CamelAnnotationsHandler.class); @@ -53,11 +52,37 @@ public final class CamelAnnotationsHandler { } /** - * Handles @ExcludeRoutes to make it easier to exclude other routes when testing with Spring Boot. + * Cleanup/restore global state to defaults / pre-test values after the test setup + * is complete. + * + * @param testClass the test class being executed + */ + public static void cleanup(Class<?> testClass) { + SpringCamelContext.setNoStart(false); + + if (CamelSpringTestHelper.getOriginalJmxDisabled() == null) { + System.clearProperty(JmxSystemPropertyKeys.DISABLED); + } else { + System.setProperty(JmxSystemPropertyKeys.DISABLED, + CamelSpringTestHelper.getOriginalJmxDisabled()); + } + if (CamelSpringTestHelper.getOriginalExcludeRoutes() == null) { + System.clearProperty(SpringCamelContext.EXCLUDE_ROUTES); + } else { + System.setProperty(SpringCamelContext.EXCLUDE_ROUTES, + CamelSpringTestHelper.getOriginalExcludeRoutes()); + } + } + + /** + * Handles @ExcludeRoutes to make it easier to exclude other routes when testing with Spring. * + * @param context the initialized Spring context * @param testClass the test class being executed */ - public static void handleExcludeRoutesForSpringBoot(Class<?> testClass) { + public static void handleExcludeRoutes(ConfigurableApplicationContext context, Class<?> testClass) { + CamelSpringTestHelper.setOriginalExcludeRoutesValue(System.getProperty(SpringCamelContext.EXCLUDE_ROUTES)); + if (testClass.isAnnotationPresent(ExcludeRoutes.class)) { Class[] routes = testClass.getAnnotation(ExcludeRoutes.class).value(); // need to setup this as a JVM system property @@ -65,7 +90,7 @@ public final class CamelAnnotationsHandler { for (Class clazz : routes) { csb.append(clazz.getName()); } - String key = "CamelTestSpringExcludeRoutes"; + String key = SpringCamelContext.EXCLUDE_ROUTES; String value = csb.toString(); String exists = System.getProperty(key); @@ -91,14 +116,17 @@ public final class CamelAnnotationsHandler { if (testClass.getAnnotation(DisableJmx.class).value()) { LOGGER.info("Disabling Camel JMX globally as DisableJmx annotation was found and disableJmx is set to true."); System.setProperty(JmxSystemPropertyKeys.DISABLED, "true"); - } else { LOGGER.info("Enabling Camel JMX as DisableJmx annotation was found and disableJmx is set to false."); System.clearProperty(JmxSystemPropertyKeys.DISABLED); } - } else { - LOGGER.info("Disabling Camel JMX globally for tests by default. Use the DisableJMX annotation to override the default setting."); + } else if (!testClass.isAnnotationPresent(EnableRouteCoverage.class)) { + // route coverage need JMX so do not disable it by default + LOGGER.info("Disabling Camel JMX globally for tests by default. Use the DisableJMX annotation to override the default setting."); System.setProperty(JmxSystemPropertyKeys.DISABLED, "true"); + } else { + LOGGER.info("Enabling Camel JMX as EnableRouteCoverage is used."); + System.setProperty(JmxSystemPropertyKeys.DISABLED, "false"); } } @@ -156,7 +184,7 @@ public final class CamelAnnotationsHandler { } public static void handleProvidesBreakpoint(ConfigurableApplicationContext context, Class<?> testClass) throws Exception { - Collection<Method> methods = getAllMethods(testClass); + Collection<Method> methods = CamelSpringTestHelper.getAllMethods(testClass); final List<Breakpoint> breakpoints = new LinkedList<>(); for (Method method : methods) { @@ -283,7 +311,7 @@ public final class CamelAnnotationsHandler { * @param testClass the test class being executed */ public static void handleUseOverridePropertiesWithPropertiesComponent(ConfigurableApplicationContext context, Class<?> testClass) throws Exception { - Collection<Method> methods = getAllMethods(testClass); + Collection<Method> methods = CamelSpringTestHelper.getAllMethods(testClass); final List<Properties> properties = new LinkedList<>(); for (Method method : methods) { @@ -312,20 +340,23 @@ public final class CamelAnnotationsHandler { } } - if (properties.size() != 0) { - CamelSpringTestHelper.doToSpringCamelContexts(context, new CamelSpringTestHelper.DoToSpringCamelContextsStrategy() { - public void execute(String contextName, SpringCamelContext camelContext) throws Exception { - PropertiesComponent pc = camelContext.getPropertiesComponent(); - Properties extra = new Properties(); - for (Properties prop : properties) { - extra.putAll(prop); - } - if (!extra.isEmpty()) { - LOGGER.info("Using {} properties to override any existing properties on the PropertiesComponent on CamelContext with name [{}].", extra.size(), contextName); + Properties extra = new Properties(); + for (Properties prop : properties) { + extra.putAll(prop); + } + + if (!extra.isEmpty()) { + context.addBeanFactoryPostProcessor(beanFactory -> beanFactory.addBeanPostProcessor(new BeanPostProcessor() { + @Override + public Object postProcessBeforeInitialization(Object bean, String beanName) { + if (bean instanceof PropertiesComponent) { + PropertiesComponent pc = (PropertiesComponent) bean; + LOGGER.info("Using {} properties to override any existing properties on the PropertiesComponent", extra.size()); pc.setOverrideProperties(extra); } + return bean; } - }); + })); } } diff --git a/components/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/CamelSpringBootExecutionListener.java b/components/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/CamelSpringBootExecutionListener.java index 898f058..187ec9e 100644 --- a/components/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/CamelSpringBootExecutionListener.java +++ b/components/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/CamelSpringBootExecutionListener.java @@ -32,7 +32,7 @@ public class CamelSpringBootExecutionListener extends AbstractTestExecutionListe /** * Returns the precedence that is used by Spring to choose the appropriate * execution order of test listeners. - * + * * See {@link SpringTestExecutionListenerSorter#getPrecedence(Class)} for more. */ @Override @@ -47,7 +47,8 @@ public class CamelSpringBootExecutionListener extends AbstractTestExecutionListe Class<?> testClass = testContext.getTestClass(); // need to prepare this before we load spring application context - CamelAnnotationsHandler.handleExcludeRoutesForSpringBoot(testClass); + CamelAnnotationsHandler.handleDisableJmx(null, testClass); + CamelAnnotationsHandler.handleExcludeRoutes(null, testClass); // we are customizing the Camel context with // CamelAnnotationsHandler so we do not want to start it @@ -56,7 +57,9 @@ public class CamelSpringBootExecutionListener extends AbstractTestExecutionListe // not to start it just yet SpringCamelContext.setNoStart(true); System.setProperty("skipStartingCamelContext", "true"); - ConfigurableApplicationContext context = (ConfigurableApplicationContext)testContext.getApplicationContext(); + ConfigurableApplicationContext context = (ConfigurableApplicationContext) testContext.getApplicationContext(); + + CamelAnnotationsHandler.handleUseOverridePropertiesWithPropertiesComponent(context, testClass); // Post CamelContext(s) instantiation but pre CamelContext(s) start // setup @@ -64,7 +67,6 @@ public class CamelSpringBootExecutionListener extends AbstractTestExecutionListe CamelAnnotationsHandler.handleShutdownTimeout(context, testClass); CamelAnnotationsHandler.handleMockEndpoints(context, testClass); CamelAnnotationsHandler.handleMockEndpointsAndSkip(context, testClass); - CamelAnnotationsHandler.handleUseOverridePropertiesWithPropertiesComponent(context, testClass); System.clearProperty("skipStartingCamelContext"); SpringCamelContext.setNoStart(false); diff --git a/components/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/CamelSpringBootTest.java b/components/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/CamelSpringBootTest.java index c915c07..e5ee59c 100644 --- a/components/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/CamelSpringBootTest.java +++ b/components/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/CamelSpringBootTest.java @@ -30,8 +30,13 @@ import org.springframework.test.context.junit.jupiter.SpringExtension; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) @ExtendWith(SpringExtension.class) -@TestExecutionListeners(value = {CamelSpringTestContextLoaderTestExecutionListener.class, DisableJmxTestExecutionListener.class, CamelSpringBootExecutionListener.class, - StopWatchTestExecutionListener.class}, mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS) +@TestExecutionListeners( + value = { + CamelSpringTestContextLoaderTestExecutionListener.class, + CamelSpringBootExecutionListener.class, + StopWatchTestExecutionListener.class + }, + mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS) public @interface CamelSpringBootTest { } diff --git a/components/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/CamelSpringTest.java b/components/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/CamelSpringTest.java index 5049a57..5f9bc6e 100644 --- a/components/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/CamelSpringTest.java +++ b/components/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/CamelSpringTest.java @@ -32,8 +32,12 @@ import org.springframework.test.context.junit.jupiter.SpringExtension; @Target({ElementType.TYPE}) @ExtendWith(SpringExtension.class) @BootstrapWith(CamelTestContextBootstrapper.class) -@TestExecutionListeners(value = {CamelSpringTestContextLoaderTestExecutionListener.class, DisableJmxTestExecutionListener.class, - StopWatchTestExecutionListener.class}, mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS) +@TestExecutionListeners( + value = { + CamelSpringTestContextLoaderTestExecutionListener.class, + StopWatchTestExecutionListener.class + }, + mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS) public @interface CamelSpringTest { } \ No newline at end of file diff --git a/components/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/CamelSpringTestContextLoader.java b/components/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/CamelSpringTestContextLoader.java index ff7e5c8..2a62194 100644 --- a/components/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/CamelSpringTestContextLoader.java +++ b/components/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/CamelSpringTestContextLoader.java @@ -38,6 +38,7 @@ import org.apache.camel.spring.SpringCamelContext; import org.apache.camel.test.ExcludingPackageScanClassResolver; import org.apache.camel.test.junit5.CamelTestSupport; import org.apache.camel.test.spring.junit5.CamelSpringTestHelper.DoToSpringCamelContextsStrategy; +import org.apache.camel.util.CollectionStringBuffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.config.BeanPostProcessor; @@ -45,6 +46,7 @@ import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.AnnotatedBeanDefinitionReader; import org.springframework.context.annotation.AnnotationConfigUtils; import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.annotation.AnnotationUtils; @@ -91,7 +93,7 @@ public class CamelSpringTestContextLoader extends AbstractContextLoader { loadBeanDefinitions(context, mergedConfig); return loadContext(context, testClass); } finally { - cleanup(testClass); + CamelAnnotationsHandler.cleanup(testClass); } } @@ -110,7 +112,6 @@ public class CamelSpringTestContextLoader extends AbstractContextLoader { */ @Override public ApplicationContext loadContext(String... locations) throws Exception { - Class<?> testClass = getTestClass(); if (LOG.isDebugEnabled()) { @@ -122,7 +123,7 @@ public class CamelSpringTestContextLoader extends AbstractContextLoader { loadBeanDefinitions(context, locations); return loadContext(context, testClass); } finally { - cleanup(testClass); + CamelAnnotationsHandler.cleanup(testClass); } } @@ -148,8 +149,9 @@ public class CamelSpringTestContextLoader extends AbstractContextLoader { AnnotationConfigUtils.registerAnnotationConfigProcessors(context); // Pre CamelContext(s) instantiation setup - handleDisableJmx(context, testClass); - handleUseOverridePropertiesWithPropertiesComponent(context, testClass); + CamelAnnotationsHandler.handleDisableJmx(context, testClass); + CamelAnnotationsHandler.handleExcludeRoutes(context, testClass); + CamelAnnotationsHandler.handleUseOverridePropertiesWithPropertiesComponent(context, testClass); // Temporarily disable CamelContext start while the contexts are instantiated. SpringCamelContext.setNoStart(true); @@ -159,43 +161,25 @@ public class CamelSpringTestContextLoader extends AbstractContextLoader { SpringCamelContext.setNoStart(false); // Post CamelContext(s) instantiation but pre CamelContext(s) start setup - handleRouteCoverage(context, testClass); - handleProvidesBreakpoint(context, testClass); - handleShutdownTimeout(context, testClass); - handleMockEndpoints(context, testClass); - handleMockEndpointsAndSkip(context, testClass); + CamelAnnotationsHandler.handleRouteCoverage(context, testClass, s -> getTestMethod().getName()); + CamelAnnotationsHandler.handleProvidesBreakpoint(context, testClass); + CamelAnnotationsHandler.handleShutdownTimeout(context, testClass); + CamelAnnotationsHandler.handleMockEndpoints(context, testClass); + CamelAnnotationsHandler.handleMockEndpointsAndSkip(context, testClass); // CamelContext(s) startup - handleCamelContextStartup(context, testClass); + CamelAnnotationsHandler.handleCamelContextStartup(context, testClass); return context; } - /** - * Cleanup/restore global state to defaults / pre-test values after the test setup - * is complete. - * - * @param testClass the test class being executed - */ - protected void cleanup(Class<?> testClass) { - SpringCamelContext.setNoStart(false); - - if (testClass.isAnnotationPresent(DisableJmx.class)) { - if (CamelSpringTestHelper.getOriginalJmxDisabled() == null) { - System.clearProperty(JmxSystemPropertyKeys.DISABLED); - } else { - System.setProperty(JmxSystemPropertyKeys.DISABLED, - CamelSpringTestHelper.getOriginalJmxDisabled()); - } - } - } - protected void loadBeanDefinitions(GenericApplicationContext context, MergedContextConfiguration mergedConfig) { - (new XmlBeanDefinitionReader(context)).loadBeanDefinitions(mergedConfig.getLocations()); + new XmlBeanDefinitionReader(context).loadBeanDefinitions(mergedConfig.getLocations()); + new AnnotatedBeanDefinitionReader(context).register(mergedConfig.getClasses()); } protected void loadBeanDefinitions(GenericApplicationContext context, String... locations) { - (new XmlBeanDefinitionReader(context)).loadBeanDefinitions(locations); + new XmlBeanDefinitionReader(context).loadBeanDefinitions(locations); } /** @@ -256,279 +240,6 @@ public class CamelSpringTestContextLoader extends AbstractContextLoader { } /** - * Handles disabling of JMX on Camel contexts based on {@link DisableJmx}. - * - * @param context the initialized Spring context - * @param testClass the test class being executed - */ - protected void handleDisableJmx(GenericApplicationContext context, Class<?> testClass) { - CamelSpringTestHelper.setOriginalJmxDisabledValue(System.getProperty(JmxSystemPropertyKeys.DISABLED)); - - if (testClass.isAnnotationPresent(DisableJmx.class)) { - if (testClass.getAnnotation(DisableJmx.class).value()) { - LOG.info("Disabling Camel JMX globally as DisableJmx annotation was found and disableJmx is set to true."); - System.setProperty(JmxSystemPropertyKeys.DISABLED, "true"); - } else { - LOG.info("Enabling Camel JMX as DisableJmx annotation was found and disableJmx is set to false."); - System.clearProperty(JmxSystemPropertyKeys.DISABLED); - } - } else if (!testClass.isAnnotationPresent(EnableRouteCoverage.class)) { - LOG.info("Disabling Camel JMX globally for tests by default. Use the DisableJMX annotation to override the default setting."); - System.setProperty(JmxSystemPropertyKeys.DISABLED, "true"); - } else { - LOG.info("Enabling Camel JMX as DisableJmx annotation was NOT found but EnableRouteCoverage annotation was found."); - System.clearProperty(JmxSystemPropertyKeys.DISABLED); - } - } - - /** - * Handles disabling of JMX on Camel contexts based on {@link DisableJmx}. - * - * @param context the initialized Spring context - * @param testClass the test class being executed - */ - private void handleRouteCoverage(GenericApplicationContext context, Class<?> testClass) throws Exception { - if (testClass.isAnnotationPresent(EnableRouteCoverage.class)) { - System.setProperty(CamelTestSupport.ROUTE_COVERAGE_ENABLED, "true"); - - CamelSpringTestHelper.doToSpringCamelContexts(context, new DoToSpringCamelContextsStrategy() { - - @Override - public void execute(String contextName, SpringCamelContext camelContext) throws Exception { - LOG.info("Enabling RouteCoverage"); - EventNotifier notifier = new RouteCoverageEventNotifier(testClass.getName(), s -> getTestMethod().getName()); - camelContext.addService(notifier, true); - camelContext.getManagementStrategy().addEventNotifier(notifier); - } - }); - } - } - - /** - * Handles the processing of the {@link ProvidesBreakpoint} annotation on a test class. Exists here - * as it is needed in - * - * @param context the initialized Spring context containing the Camel context(s) to insert breakpoints into - * @param testClass the test class being processed - * - * @throws Exception if there is an error processing the class - */ - protected void handleProvidesBreakpoint(GenericApplicationContext context, Class<?> testClass) throws Exception { - Collection<Method> methods = getAllMethods(testClass); - final List<Breakpoint> breakpoints = new LinkedList<>(); - - for (Method method : methods) { - if (AnnotationUtils.findAnnotation(method, ProvidesBreakpoint.class) != null) { - Class<?>[] argTypes = method.getParameterTypes(); - if (argTypes.length != 0) { - throw new IllegalArgumentException("Method [" + method.getName() - + "] is annotated with ProvidesBreakpoint but is not a no-argument method."); - } else if (!Breakpoint.class.isAssignableFrom(method.getReturnType())) { - throw new IllegalArgumentException("Method [" + method.getName() - + "] is annotated with ProvidesBreakpoint but does not return a Breakpoint."); - } else if (!Modifier.isStatic(method.getModifiers())) { - throw new IllegalArgumentException("Method [" + method.getName() - + "] is annotated with ProvidesBreakpoint but is not static."); - } else if (!Modifier.isPublic(method.getModifiers())) { - throw new IllegalArgumentException("Method [" + method.getName() - + "] is annotated with ProvidesBreakpoint but is not public."); - } - - try { - breakpoints.add((Breakpoint) method.invoke(null)); - } catch (Exception e) { - throw new RuntimeException("Method [" + method.getName() - + "] threw exception during evaluation.", e); - } - } - } - - if (breakpoints.size() != 0) { - CamelSpringTestHelper.doToSpringCamelContexts(context, new DoToSpringCamelContextsStrategy() { - - @Override - public void execute(String contextName, SpringCamelContext camelContext) - throws Exception { - Debugger debugger = camelContext.getDebugger(); - if (debugger == null) { - debugger = new DefaultDebugger(); - camelContext.setDebugger(debugger); - } - - for (Breakpoint breakpoint : breakpoints) { - LOG.info("Adding Breakpoint [{}] to CamelContext with name [{}].", breakpoint, contextName); - debugger.addBreakpoint(breakpoint); - } - } - }); - } - } - - - /** - * Handles updating shutdown timeouts on Camel contexts based on {@link ShutdownTimeout}. - * - * @param context the initialized Spring context - * @param testClass the test class being executed - */ - protected void handleShutdownTimeout(GenericApplicationContext context, Class<?> testClass) throws Exception { - final int shutdownTimeout; - final TimeUnit shutdownTimeUnit; - if (testClass.isAnnotationPresent(ShutdownTimeout.class)) { - shutdownTimeout = testClass.getAnnotation(ShutdownTimeout.class).value(); - shutdownTimeUnit = testClass.getAnnotation(ShutdownTimeout.class).timeUnit(); - } else { - shutdownTimeout = 10; - shutdownTimeUnit = TimeUnit.SECONDS; - } - - CamelSpringTestHelper.doToSpringCamelContexts(context, new DoToSpringCamelContextsStrategy() { - - @Override - public void execute(String contextName, SpringCamelContext camelContext) - throws Exception { - LOG.info("Setting shutdown timeout to [{} {}] on CamelContext with name [{}].", shutdownTimeout, shutdownTimeUnit, contextName); - camelContext.getShutdownStrategy().setTimeout(shutdownTimeout); - camelContext.getShutdownStrategy().setTimeUnit(shutdownTimeUnit); - } - }); - } - - /** - * Handles auto-intercepting of endpoints with mocks based on {@link MockEndpoints}. - * - * @param context the initialized Spring context - * @param testClass the test class being executed - */ - protected void handleMockEndpoints(GenericApplicationContext context, Class<?> testClass) throws Exception { - if (testClass.isAnnotationPresent(MockEndpoints.class)) { - final String mockEndpoints = testClass.getAnnotation(MockEndpoints.class).value(); - CamelSpringTestHelper.doToSpringCamelContexts(context, new DoToSpringCamelContextsStrategy() { - - @Override - public void execute(String contextName, SpringCamelContext camelContext) - throws Exception { - LOG.info("Enabling auto mocking of endpoints matching pattern [{}] on CamelContext with name [{}].", mockEndpoints, contextName); - camelContext.adapt(ExtendedCamelContext.class).registerEndpointCallback(new InterceptSendToMockEndpointStrategy(mockEndpoints)); - } - }); - } - } - - /** - * Handles auto-intercepting of endpoints with mocks based on {@link MockEndpointsAndSkip} and skipping the - * original endpoint. - * - * @param context the initialized Spring context - * @param testClass the test class being executed - */ - protected void handleMockEndpointsAndSkip(GenericApplicationContext context, Class<?> testClass) throws Exception { - if (testClass.isAnnotationPresent(MockEndpointsAndSkip.class)) { - final String mockEndpoints = testClass.getAnnotation(MockEndpointsAndSkip.class).value(); - CamelSpringTestHelper.doToSpringCamelContexts(context, new DoToSpringCamelContextsStrategy() { - - @Override - public void execute(String contextName, SpringCamelContext camelContext) - throws Exception { - // resovle the property place holders of the mockEndpoints - String mockEndpointsValue = camelContext.resolvePropertyPlaceholders(mockEndpoints); - LOG.info("Enabling auto mocking and skipping of endpoints matching pattern [{}] on CamelContext with name [{}].", mockEndpointsValue, contextName); - camelContext.adapt(ExtendedCamelContext.class).registerEndpointCallback(new InterceptSendToMockEndpointStrategy(mockEndpointsValue, true)); - } - }); - } - } - - /** - * Sets property overrides for the Camel {@link org.apache.camel.component.properties.PropertiesComponent}. - * - * @param context the pre-refresh Spring context - * @param testClass the test class being executed - */ - protected void handleUseOverridePropertiesWithPropertiesComponent(ConfigurableApplicationContext context, Class<?> testClass) throws Exception { - Collection<Method> methods = getAllMethods(testClass); - final List<Properties> properties = new LinkedList<>(); - - for (Method method : methods) { - if (AnnotationUtils.findAnnotation(method, UseOverridePropertiesWithPropertiesComponent.class) != null) { - Class<?>[] argTypes = method.getParameterTypes(); - if (argTypes.length > 0) { - throw new IllegalArgumentException("Method [" + method.getName() - + "] is annotated with UseOverridePropertiesWithPropertiesComponent but is not a no-argument method."); - } else if (!Properties.class.isAssignableFrom(method.getReturnType())) { - throw new IllegalArgumentException("Method [" + method.getName() - + "] is annotated with UseOverridePropertiesWithPropertiesComponent but does not return a java.util.Properties."); - } else if (!Modifier.isStatic(method.getModifiers())) { - throw new IllegalArgumentException("Method [" + method.getName() - + "] is annotated with UseOverridePropertiesWithPropertiesComponent but is not static."); - } else if (!Modifier.isPublic(method.getModifiers())) { - throw new IllegalArgumentException("Method [" + method.getName() - + "] is annotated with UseOverridePropertiesWithPropertiesComponent but is not public."); - } - - try { - properties.add((Properties) method.invoke(null)); - } catch (Exception e) { - throw new RuntimeException("Method [" + method.getName() - + "] threw exception during evaluation.", e); - } - } - } - - Properties extra = new Properties(); - for (Properties prop : properties) { - extra.putAll(prop); - } - - if (!extra.isEmpty()) { - context.addBeanFactoryPostProcessor(beanFactory -> beanFactory.addBeanPostProcessor(new BeanPostProcessor() { - @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) { - if (bean instanceof PropertiesComponent) { - PropertiesComponent pc = (PropertiesComponent) bean; - LOG.info("Using {} properties to override any existing properties on the PropertiesComponent", extra.size()); - pc.setOverrideProperties(extra); - } - return bean; - } - })); - } - } - - /** - * Handles starting of Camel contexts based on {@link UseAdviceWith} and other state in the JVM. - * - * @param context the initialized Spring context - * @param testClass the test class being executed - */ - protected void handleCamelContextStartup(GenericApplicationContext context, Class<?> testClass) throws Exception { - boolean skip = "true".equalsIgnoreCase(System.getProperty("skipStartingCamelContext")); - if (skip) { - LOG.info("Skipping starting CamelContext(s) as system property skipStartingCamelContext is set to be true."); - } else if (testClass.isAnnotationPresent(UseAdviceWith.class)) { - if (testClass.getAnnotation(UseAdviceWith.class).value()) { - LOG.info("Skipping starting CamelContext(s) as UseAdviceWith annotation was found and isUseAdviceWith is set to true."); - skip = true; - } else { - LOG.info("Starting CamelContext(s) as UseAdviceWith annotation was found, but isUseAdviceWith is set to false."); - skip = false; - } - } - - if (!skip) { - CamelSpringTestHelper.doToSpringCamelContexts(context, new DoToSpringCamelContextsStrategy() { - - @Override - public void execute(String contextName, - SpringCamelContext camelContext) throws Exception { - LOG.info("Starting CamelContext with name [{}].", contextName); - camelContext.start(); - } - }); - } - } - - /** * Returns the class under test in order to enable inspection of annotations while the * Spring context is being created. * diff --git a/components/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/CamelSpringTestHelper.java b/components/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/CamelSpringTestHelper.java index 8d12f93..e990f41 100644 --- a/components/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/CamelSpringTestHelper.java +++ b/components/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/CamelSpringTestHelper.java @@ -40,6 +40,7 @@ import org.springframework.test.context.TestContext; public final class CamelSpringTestHelper { private static ThreadLocal<String> originalJmxDisabledValue = new ThreadLocal<>(); + private static ThreadLocal<String> originalExcludeRoutesValue = new ThreadLocal<>(); private static ThreadLocal<Class<?>> testClazz = new ThreadLocal<>(); private static ThreadLocal<TestContext> testContext = new ThreadLocal<>(); @@ -53,7 +54,15 @@ public final class CamelSpringTestHelper { public static void setOriginalJmxDisabledValue(String originalValue) { originalJmxDisabledValue.set(originalValue); } - + + public static String getOriginalExcludeRoutes() { + return originalExcludeRoutesValue.get(); + } + + public static void setOriginalExcludeRoutesValue(String originalValue) { + originalExcludeRoutesValue.set(originalValue); + } + public static Class<?> getTestClass() { return testClazz.get(); } diff --git a/components/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/DisableJmxTestExecutionListener.java b/components/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/DisableJmxTestExecutionListener.java deleted file mode 100644 index 11f85b7..0000000 --- a/components/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/DisableJmxTestExecutionListener.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.camel.test.spring.junit5; - -import org.apache.camel.api.management.JmxSystemPropertyKeys; -import org.springframework.test.context.TestContext; -import org.springframework.test.context.support.AbstractTestExecutionListener; - -/** - * Provides reset to pre-test state behavior for global enable/disable of JMX - * support in Camel through the use of {@link DisableJmx}. Tries to ensure that - * the pre-test value is restored. - */ -public class DisableJmxTestExecutionListener extends AbstractTestExecutionListener { - - @Override - public void afterTestClass(TestContext testContext) throws Exception { - if (CamelSpringTestHelper.getOriginalJmxDisabled() == null) { - System.clearProperty(JmxSystemPropertyKeys.DISABLED); - } else { - System.setProperty(JmxSystemPropertyKeys.DISABLED, CamelSpringTestHelper.getOriginalJmxDisabled()); - } - } - - /** - * Returns the precedence that is used by Spring to choose the appropriate - * execution order of test listeners. - * - * See {@link SpringTestExecutionListenerSorter#getPrecedence(Class)} for more. - */ - @Override - public int getOrder() { - return SpringTestExecutionListenerSorter.getPrecedence(getClass()); - } - -} diff --git a/components/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/SpringTestExecutionListenerSorter.java b/components/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/SpringTestExecutionListenerSorter.java index 94b2c75..cd4526c 100644 --- a/components/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/SpringTestExecutionListenerSorter.java +++ b/components/camel-test-spring-junit5/src/main/java/org/apache/camel/test/spring/junit5/SpringTestExecutionListenerSorter.java @@ -22,8 +22,6 @@ import org.springframework.core.Ordered; * This class centralizes the order of execution of spring test execution listeners: * <ol> * <li>{@link CamelSpringTestContextLoaderTestExecutionListener}</li> - * <li>{@link DisableJmxTestExecutionListener}</li> - * <li>{@link CamelSpringBootExecutionListener}</li> * <li>{@link StopWatchTestExecutionListener}</li> * <li>Spring default listeners</li> * </ol> @@ -38,8 +36,6 @@ public final class SpringTestExecutionListenerSorter { return Ordered.HIGHEST_PRECEDENCE + 4000; } else if (clazz == CamelSpringBootExecutionListener.class) { return Ordered.HIGHEST_PRECEDENCE + 3000; - } else if (clazz == DisableJmxTestExecutionListener.class) { - return Ordered.HIGHEST_PRECEDENCE + 2000; } else if (clazz == CamelSpringTestContextLoaderTestExecutionListener.class) { return Ordered.HIGHEST_PRECEDENCE + 1000; } diff --git a/components/camel-test-spring-junit5/src/test/java/org/apache/camel/test/spring/SpringTestExecutionListenerSorterTest.java b/components/camel-test-spring-junit5/src/test/java/org/apache/camel/test/spring/SpringTestExecutionListenerSorterTest.java index f39542d..b73f886 100644 --- a/components/camel-test-spring-junit5/src/test/java/org/apache/camel/test/spring/SpringTestExecutionListenerSorterTest.java +++ b/components/camel-test-spring-junit5/src/test/java/org/apache/camel/test/spring/SpringTestExecutionListenerSorterTest.java @@ -19,9 +19,7 @@ package org.apache.camel.test.spring; import java.util.ArrayList; import java.util.List; -import org.apache.camel.test.spring.junit5.CamelSpringBootExecutionListener; import org.apache.camel.test.spring.junit5.CamelSpringTestContextLoaderTestExecutionListener; -import org.apache.camel.test.spring.junit5.DisableJmxTestExecutionListener; import org.apache.camel.test.spring.junit5.StopWatchTestExecutionListener; import org.junit.jupiter.api.Test; @@ -36,8 +34,6 @@ public class SpringTestExecutionListenerSorterTest { List<Class<?>> listenersInExpectedOrder = new ArrayList<>(); listenersInExpectedOrder.add(CamelSpringTestContextLoaderTestExecutionListener.class); - listenersInExpectedOrder.add(DisableJmxTestExecutionListener.class); - listenersInExpectedOrder.add(CamelSpringBootExecutionListener.class); listenersInExpectedOrder.add(StopWatchTestExecutionListener.class); List<Class<?>> listenersSortedByPrecedence = new ArrayList<>(listenersInExpectedOrder); diff --git a/components/camel-test-spring/src/main/java/org/apache/camel/test/spring/CamelAnnotationsHandler.java b/components/camel-test-spring/src/main/java/org/apache/camel/test/spring/CamelAnnotationsHandler.java index 92bbc11..faf1a3b 100644 --- a/components/camel-test-spring/src/main/java/org/apache/camel/test/spring/CamelAnnotationsHandler.java +++ b/components/camel-test-spring/src/main/java/org/apache/camel/test/spring/CamelAnnotationsHandler.java @@ -40,11 +40,10 @@ import org.apache.camel.test.junit4.CamelTestSupport; import org.apache.camel.util.CollectionStringBuffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.annotation.AnnotationUtils; -import static org.apache.camel.test.spring.CamelSpringTestHelper.getAllMethods; - public final class CamelAnnotationsHandler { private static final Logger LOGGER = LoggerFactory.getLogger(CamelAnnotationsHandler.class); @@ -53,11 +52,37 @@ public final class CamelAnnotationsHandler { } /** - * Handles @ExcludeRoutes to make it easier to exclude other routes when testing with Spring Boot. + * Cleanup/restore global state to defaults / pre-test values after the test setup + * is complete. + * + * @param testClass the test class being executed + */ + public static void cleanup(Class<?> testClass) { + SpringCamelContext.setNoStart(false); + + if (CamelSpringTestHelper.getOriginalJmxDisabled() == null) { + System.clearProperty(JmxSystemPropertyKeys.DISABLED); + } else { + System.setProperty(JmxSystemPropertyKeys.DISABLED, + CamelSpringTestHelper.getOriginalJmxDisabled()); + } + if (CamelSpringTestHelper.getOriginalExcludeRoutes() == null) { + System.clearProperty(SpringCamelContext.EXCLUDE_ROUTES); + } else { + System.setProperty(SpringCamelContext.EXCLUDE_ROUTES, + CamelSpringTestHelper.getOriginalExcludeRoutes()); + } + } + + /** + * Handles @ExcludeRoutes to make it easier to exclude other routes when testing with Spring. * + * @param context the initialized Spring context * @param testClass the test class being executed */ - public static void handleExcludeRoutesForSpringBoot(Class<?> testClass) { + public static void handleExcludeRoutes(ConfigurableApplicationContext context, Class<?> testClass) { + CamelSpringTestHelper.setOriginalExcludeRoutesValue(System.getProperty(SpringCamelContext.EXCLUDE_ROUTES)); + if (testClass.isAnnotationPresent(ExcludeRoutes.class)) { Class[] routes = testClass.getAnnotation(ExcludeRoutes.class).value(); // need to setup this as a JVM system property @@ -65,7 +90,7 @@ public final class CamelAnnotationsHandler { for (Class clazz : routes) { csb.append(clazz.getName()); } - String key = "CamelTestSpringExcludeRoutes"; + String key = SpringCamelContext.EXCLUDE_ROUTES; String value = csb.toString(); String exists = System.getProperty(key); @@ -91,14 +116,17 @@ public final class CamelAnnotationsHandler { if (testClass.getAnnotation(DisableJmx.class).value()) { LOGGER.info("Disabling Camel JMX globally as DisableJmx annotation was found and disableJmx is set to true."); System.setProperty(JmxSystemPropertyKeys.DISABLED, "true"); - } else { LOGGER.info("Enabling Camel JMX as DisableJmx annotation was found and disableJmx is set to false."); System.clearProperty(JmxSystemPropertyKeys.DISABLED); } - } else { - LOGGER.info("Disabling Camel JMX globally for tests by default. Use the DisableJMX annotation to override the default setting."); + } else if (!testClass.isAnnotationPresent(EnableRouteCoverage.class)) { + // route coverage need JMX so do not disable it by default + LOGGER.info("Disabling Camel JMX globally for tests by default. Use the DisableJMX annotation to override the default setting."); System.setProperty(JmxSystemPropertyKeys.DISABLED, "true"); + } else { + LOGGER.info("Enabling Camel JMX as EnableRouteCoverage is used."); + System.setProperty(JmxSystemPropertyKeys.DISABLED, "false"); } } @@ -156,7 +184,7 @@ public final class CamelAnnotationsHandler { } public static void handleProvidesBreakpoint(ConfigurableApplicationContext context, Class<?> testClass) throws Exception { - Collection<Method> methods = getAllMethods(testClass); + Collection<Method> methods = CamelSpringTestHelper.getAllMethods(testClass); final List<Breakpoint> breakpoints = new LinkedList<>(); for (Method method : methods) { @@ -283,7 +311,7 @@ public final class CamelAnnotationsHandler { * @param testClass the test class being executed */ public static void handleUseOverridePropertiesWithPropertiesComponent(ConfigurableApplicationContext context, Class<?> testClass) throws Exception { - Collection<Method> methods = getAllMethods(testClass); + Collection<Method> methods = CamelSpringTestHelper.getAllMethods(testClass); final List<Properties> properties = new LinkedList<>(); for (Method method : methods) { @@ -312,20 +340,23 @@ public final class CamelAnnotationsHandler { } } - if (properties.size() != 0) { - CamelSpringTestHelper.doToSpringCamelContexts(context, new CamelSpringTestHelper.DoToSpringCamelContextsStrategy() { - public void execute(String contextName, SpringCamelContext camelContext) throws Exception { - PropertiesComponent pc = camelContext.getPropertiesComponent(); - Properties extra = new Properties(); - for (Properties prop : properties) { - extra.putAll(prop); - } - if (!extra.isEmpty()) { - LOGGER.info("Using {} properties to override any existing properties on the PropertiesComponent on CamelContext with name [{}].", extra.size(), contextName); + Properties extra = new Properties(); + for (Properties prop : properties) { + extra.putAll(prop); + } + + if (!extra.isEmpty()) { + context.addBeanFactoryPostProcessor(beanFactory -> beanFactory.addBeanPostProcessor(new BeanPostProcessor() { + @Override + public Object postProcessBeforeInitialization(Object bean, String beanName) { + if (bean instanceof PropertiesComponent) { + PropertiesComponent pc = (PropertiesComponent) bean; + LOGGER.info("Using {} properties to override any existing properties on the PropertiesComponent", extra.size()); pc.setOverrideProperties(extra); } + return bean; } - }); + })); } } diff --git a/components/camel-test-spring/src/main/java/org/apache/camel/test/spring/CamelSpringBootExecutionListener.java b/components/camel-test-spring/src/main/java/org/apache/camel/test/spring/CamelSpringBootExecutionListener.java deleted file mode 100644 index 9b59ba8..0000000 --- a/components/camel-test-spring/src/main/java/org/apache/camel/test/spring/CamelSpringBootExecutionListener.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.camel.test.spring; - -import org.apache.camel.spring.SpringCamelContext; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.test.context.TestContext; -import org.springframework.test.context.support.AbstractTestExecutionListener; - -public class CamelSpringBootExecutionListener extends AbstractTestExecutionListener { - - protected static ThreadLocal<ConfigurableApplicationContext> threadApplicationContext = new ThreadLocal<>(); - - private static final Logger LOG = LoggerFactory.getLogger(CamelSpringBootExecutionListener.class); - - @Override - public void prepareTestInstance(TestContext testContext) throws Exception { - LOG.info("@RunWith(CamelSpringBootRunner.class) preparing: {}", testContext.getTestClass()); - - Class<?> testClass = testContext.getTestClass(); - - // need to prepare this before we load spring application context - CamelAnnotationsHandler.handleExcludeRoutesForSpringBoot(testClass); - - // we are customizing the Camel context with - // CamelAnnotationsHandler so we do not want to start it - // automatically, which would happen when SpringCamelContext - // is added to Spring ApplicationContext, so we set the flag - // not to start it just yet - SpringCamelContext.setNoStart(true); - System.setProperty("skipStartingCamelContext", "true"); - ConfigurableApplicationContext context = (ConfigurableApplicationContext) testContext.getApplicationContext(); - - // Post CamelContext(s) instantiation but pre CamelContext(s) start setup - CamelAnnotationsHandler.handleProvidesBreakpoint(context, testClass); - CamelAnnotationsHandler.handleShutdownTimeout(context, testClass); - CamelAnnotationsHandler.handleMockEndpoints(context, testClass); - CamelAnnotationsHandler.handleMockEndpointsAndSkip(context, testClass); - CamelAnnotationsHandler.handleUseOverridePropertiesWithPropertiesComponent(context, testClass); - - System.clearProperty("skipStartingCamelContext"); - SpringCamelContext.setNoStart(false); - } - - @Override - public void beforeTestMethod(TestContext testContext) throws Exception { - LOG.info("@RunWith(CamelSpringBootRunner.class) before: {}.{}", testContext.getTestClass(), testContext.getTestMethod().getName()); - - Class<?> testClass = testContext.getTestClass(); - String testName = testContext.getTestMethod().getName(); - - ConfigurableApplicationContext context = (ConfigurableApplicationContext) testContext.getApplicationContext(); - threadApplicationContext.set(context); - - // mark Camel to be startable again and start Camel - System.clearProperty("skipStartingCamelContext"); - - // route coverage need to know the test method - CamelAnnotationsHandler.handleRouteCoverage(context, testClass, s -> testName); - - LOG.info("Initialized CamelSpringBootRunner now ready to start CamelContext"); - CamelAnnotationsHandler.handleCamelContextStartup(context, testClass); - } - - @Override - public void afterTestMethod(TestContext testContext) throws Exception { - LOG.info("@RunWith(CamelSpringBootRunner.class) after: {}.{}", testContext.getTestClass(), testContext.getTestMethod().getName()); - - Class<?> testClass = testContext.getTestClass(); - String testName = testContext.getTestMethod().getName(); - - ConfigurableApplicationContext context = threadApplicationContext.get(); - if (context != null && context.isRunning()) { - // dump route coverage for each test method so its accurate statistics - // even if spring application context is running (i.e. its not dirtied per test method) - CamelAnnotationsHandler.handleRouteCoverageDump(context, testClass, s -> testName); - } - } -} diff --git a/components/camel-test-spring/src/main/java/org/apache/camel/test/spring/CamelSpringBootRunner.java b/components/camel-test-spring/src/main/java/org/apache/camel/test/spring/CamelSpringBootRunner.java index d499bb8..dd80e82 100644 --- a/components/camel-test-spring/src/main/java/org/apache/camel/test/spring/CamelSpringBootRunner.java +++ b/components/camel-test-spring/src/main/java/org/apache/camel/test/spring/CamelSpringBootRunner.java @@ -29,59 +29,10 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; * for their Spring Boot based applications/routes using the typical Spring Test conventions * for test development. */ -public class CamelSpringBootRunner extends SpringJUnit4ClassRunner { +public class CamelSpringBootRunner extends CamelSpringRunner { public CamelSpringBootRunner(Class<?> clazz) throws InitializationError { super(clazz); } - /** - * Returns the specialized manager instance that provides tight integration between Camel testing - * features and Spring. - * - * @return a new instance of {@link CamelTestContextManager}. - */ - @Override - protected TestContextManager createTestContextManager(Class<?> clazz) { - return new CamelTestContextManager(clazz); - } - - /** - * An implementation providing additional integration between Spring Test and Camel - * testing features. - */ - public static final class CamelTestContextManager extends TestContextManager { - - public CamelTestContextManager(Class<?> testClass) { - super(testClass); - - // turn off auto starting spring as we need to do this later - System.setProperty("skipStartingCamelContext", "true"); - - // is Camel already registered - if (!alreadyRegistered()) { - // inject Camel first, and then disable jmx and add the stop-watch - List<TestExecutionListener> list = getTestExecutionListeners(); - list.add(0, new CamelSpringTestContextLoaderTestExecutionListener()); - list.add(1, new DisableJmxTestExecutionListener()); - list.add(2, new CamelSpringBootExecutionListener()); - list.add(3, new StopWatchTestExecutionListener()); - } - } - - private boolean alreadyRegistered() { - List<TestExecutionListener> list = getTestExecutionListeners(); - if (list != null) { - for (TestExecutionListener listener : list) { - if (listener instanceof CamelSpringTestContextLoaderTestExecutionListener) { - return true; - } - } - } - - return false; - } - - } - } diff --git a/components/camel-test-spring/src/main/java/org/apache/camel/test/spring/CamelSpringDelegatingTestContextLoader.java b/components/camel-test-spring/src/main/java/org/apache/camel/test/spring/CamelSpringDelegatingTestContextLoader.java index 3c22382..2fd7904 100644 --- a/components/camel-test-spring/src/main/java/org/apache/camel/test/spring/CamelSpringDelegatingTestContextLoader.java +++ b/components/camel-test-spring/src/main/java/org/apache/camel/test/spring/CamelSpringDelegatingTestContextLoader.java @@ -63,7 +63,7 @@ public class CamelSpringDelegatingTestContextLoader extends DelegatingSmartConte System.clearProperty("skipStartingCamelContext"); return loadContext(context, testClass); } finally { - cleanup(testClass); + CamelAnnotationsHandler.cleanup(testClass); } } @@ -94,25 +94,6 @@ public class CamelSpringDelegatingTestContextLoader extends DelegatingSmartConte return context; } - - /** - * Cleanup/restore global state to defaults / pre-test values after the test setup - * is complete. - * - * @param testClass the test class being executed - */ - protected void cleanup(Class<?> testClass) { - SpringCamelContext.setNoStart(false); - - if (testClass.isAnnotationPresent(DisableJmx.class)) { - if (CamelSpringTestHelper.getOriginalJmxDisabled() == null) { - System.clearProperty(JmxSystemPropertyKeys.DISABLED); - } else { - System.setProperty(JmxSystemPropertyKeys.DISABLED, - CamelSpringTestHelper.getOriginalJmxDisabled()); - } - } - } /** * Returns the class under test in order to enable inspection of annotations while the diff --git a/components/camel-test-spring/src/main/java/org/apache/camel/test/spring/CamelSpringRunner.java b/components/camel-test-spring/src/main/java/org/apache/camel/test/spring/CamelSpringRunner.java index 9f2569a..2753561 100644 --- a/components/camel-test-spring/src/main/java/org/apache/camel/test/spring/CamelSpringRunner.java +++ b/components/camel-test-spring/src/main/java/org/apache/camel/test/spring/CamelSpringRunner.java @@ -19,9 +19,14 @@ package org.apache.camel.test.spring; import java.util.List; import org.junit.runners.model.InitializationError; +import org.springframework.test.context.BootstrapContext; +import org.springframework.test.context.CacheAwareContextLoaderDelegate; +import org.springframework.test.context.TestContextBootstrapper; import org.springframework.test.context.TestContextManager; import org.springframework.test.context.TestExecutionListener; +import org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.DefaultBootstrapContext; /** * An implementation bringing the functionality of {@link org.apache.camel.test.spring.CamelSpringTestSupport} to @@ -53,18 +58,25 @@ public class CamelSpringRunner extends SpringJUnit4ClassRunner { public static final class CamelTestContextManager extends TestContextManager { public CamelTestContextManager(Class<?> testClass) { - super(testClass); + super(createTestContextBootstrapper(testClass)); // is Camel already registered if (!alreadyRegistered()) { // inject Camel first, and then disable jmx and add the stop-watch List<TestExecutionListener> list = getTestExecutionListeners(); list.add(0, new CamelSpringTestContextLoaderTestExecutionListener()); - list.add(1, new DisableJmxTestExecutionListener()); - list.add(2, new StopWatchTestExecutionListener()); + list.add(1, new StopWatchTestExecutionListener()); } } + static TestContextBootstrapper createTestContextBootstrapper(Class<?> testClass) { + CacheAwareContextLoaderDelegate cacheAwareContextLoaderDelegate = new DefaultCacheAwareContextLoaderDelegate(); + BootstrapContext bootstrapContext = new DefaultBootstrapContext(testClass, cacheAwareContextLoaderDelegate); + TestContextBootstrapper testContextBootstrapper = new CamelTestContextBootstrapper(); + testContextBootstrapper.setBootstrapContext(bootstrapContext); + return testContextBootstrapper; + } + private boolean alreadyRegistered() { List<TestExecutionListener> list = getTestExecutionListeners(); if (list != null) { diff --git a/components/camel-test-spring/src/main/java/org/apache/camel/test/spring/CamelSpringTestContextLoader.java b/components/camel-test-spring/src/main/java/org/apache/camel/test/spring/CamelSpringTestContextLoader.java index f408fd0..9ca04e3 100644 --- a/components/camel-test-spring/src/main/java/org/apache/camel/test/spring/CamelSpringTestContextLoader.java +++ b/components/camel-test-spring/src/main/java/org/apache/camel/test/spring/CamelSpringTestContextLoader.java @@ -38,6 +38,7 @@ import org.apache.camel.spring.SpringCamelContext; import org.apache.camel.test.ExcludingPackageScanClassResolver; import org.apache.camel.test.junit4.CamelTestSupport; import org.apache.camel.test.spring.CamelSpringTestHelper.DoToSpringCamelContextsStrategy; +import org.apache.camel.util.CollectionStringBuffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.config.BeanPostProcessor; @@ -45,6 +46,7 @@ import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.AnnotatedBeanDefinitionReader; import org.springframework.context.annotation.AnnotationConfigUtils; import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.annotation.AnnotationUtils; @@ -91,7 +93,7 @@ public class CamelSpringTestContextLoader extends AbstractContextLoader { loadBeanDefinitions(context, mergedConfig); return loadContext(context, testClass); } finally { - cleanup(testClass); + CamelAnnotationsHandler.cleanup(testClass); } } @@ -110,7 +112,6 @@ public class CamelSpringTestContextLoader extends AbstractContextLoader { */ @Override public ApplicationContext loadContext(String... locations) throws Exception { - Class<?> testClass = getTestClass(); if (LOG.isDebugEnabled()) { @@ -122,7 +123,7 @@ public class CamelSpringTestContextLoader extends AbstractContextLoader { loadBeanDefinitions(context, locations); return loadContext(context, testClass); } finally { - cleanup(testClass); + CamelAnnotationsHandler.cleanup(testClass); } } @@ -148,8 +149,9 @@ public class CamelSpringTestContextLoader extends AbstractContextLoader { AnnotationConfigUtils.registerAnnotationConfigProcessors(context); // Pre CamelContext(s) instantiation setup - handleDisableJmx(context, testClass); - handleUseOverridePropertiesWithPropertiesComponent(context, testClass); + CamelAnnotationsHandler.handleDisableJmx(context, testClass); + CamelAnnotationsHandler.handleExcludeRoutes(context, testClass); + CamelAnnotationsHandler.handleUseOverridePropertiesWithPropertiesComponent(context, testClass); // Temporarily disable CamelContext start while the contexts are instantiated. SpringCamelContext.setNoStart(true); @@ -159,43 +161,25 @@ public class CamelSpringTestContextLoader extends AbstractContextLoader { SpringCamelContext.setNoStart(false); // Post CamelContext(s) instantiation but pre CamelContext(s) start setup - handleRouteCoverage(context, testClass); - handleProvidesBreakpoint(context, testClass); - handleShutdownTimeout(context, testClass); - handleMockEndpoints(context, testClass); - handleMockEndpointsAndSkip(context, testClass); + CamelAnnotationsHandler.handleRouteCoverage(context, testClass, s -> getTestMethod().getName()); + CamelAnnotationsHandler.handleProvidesBreakpoint(context, testClass); + CamelAnnotationsHandler.handleShutdownTimeout(context, testClass); + CamelAnnotationsHandler.handleMockEndpoints(context, testClass); + CamelAnnotationsHandler.handleMockEndpointsAndSkip(context, testClass); // CamelContext(s) startup - handleCamelContextStartup(context, testClass); + CamelAnnotationsHandler.handleCamelContextStartup(context, testClass); return context; } - - /** - * Cleanup/restore global state to defaults / pre-test values after the test setup - * is complete. - * - * @param testClass the test class being executed - */ - protected void cleanup(Class<?> testClass) { - SpringCamelContext.setNoStart(false); - - if (testClass.isAnnotationPresent(DisableJmx.class)) { - if (CamelSpringTestHelper.getOriginalJmxDisabled() == null) { - System.clearProperty(JmxSystemPropertyKeys.DISABLED); - } else { - System.setProperty(JmxSystemPropertyKeys.DISABLED, - CamelSpringTestHelper.getOriginalJmxDisabled()); - } - } - } - + protected void loadBeanDefinitions(GenericApplicationContext context, MergedContextConfiguration mergedConfig) { - (new XmlBeanDefinitionReader(context)).loadBeanDefinitions(mergedConfig.getLocations()); + new XmlBeanDefinitionReader(context).loadBeanDefinitions(mergedConfig.getLocations()); + new AnnotatedBeanDefinitionReader(context).register(mergedConfig.getClasses()); } protected void loadBeanDefinitions(GenericApplicationContext context, String... locations) { - (new XmlBeanDefinitionReader(context)).loadBeanDefinitions(locations); + new XmlBeanDefinitionReader(context).loadBeanDefinitions(locations); } /** @@ -239,7 +223,7 @@ public class CamelSpringTestContextLoader extends AbstractContextLoader { } } } - + GenericApplicationContext context; if (routeExcludingContext != null) { @@ -254,279 +238,8 @@ public class CamelSpringTestContextLoader extends AbstractContextLoader { return context; } - - /** - * Handles disabling of JMX on Camel contexts based on {@link DisableJmx}. - * - * @param context the initialized Spring context - * @param testClass the test class being executed - */ - protected void handleDisableJmx(GenericApplicationContext context, Class<?> testClass) { - CamelSpringTestHelper.setOriginalJmxDisabledValue(System.getProperty(JmxSystemPropertyKeys.DISABLED)); - - if (testClass.isAnnotationPresent(DisableJmx.class)) { - if (testClass.getAnnotation(DisableJmx.class).value()) { - LOG.info("Disabling Camel JMX globally as DisableJmx annotation was found and disableJmx is set to true."); - System.setProperty(JmxSystemPropertyKeys.DISABLED, "true"); - } else { - LOG.info("Enabling Camel JMX as DisableJmx annotation was found and disableJmx is set to false."); - System.clearProperty(JmxSystemPropertyKeys.DISABLED); - } - } else if (!testClass.isAnnotationPresent(EnableRouteCoverage.class)) { - // route coverage need JMX so do not disable it by default - LOG.info("Disabling Camel JMX globally for tests by default. Use the DisableJMX annotation to override the default setting."); - System.setProperty(JmxSystemPropertyKeys.DISABLED, "true"); - } - } - - /** - * Handles disabling of JMX on Camel contexts based on {@link DisableJmx}. - * - * @param context the initialized Spring context - * @param testClass the test class being executed - */ - private void handleRouteCoverage(GenericApplicationContext context, Class<?> testClass) throws Exception { - if (testClass.isAnnotationPresent(EnableRouteCoverage.class)) { - System.setProperty(CamelTestSupport.ROUTE_COVERAGE_ENABLED, "true"); - - CamelSpringTestHelper.doToSpringCamelContexts(context, new DoToSpringCamelContextsStrategy() { - - @Override - public void execute(String contextName, SpringCamelContext camelContext) throws Exception { - LOG.info("Enabling RouteCoverage"); - EventNotifier notifier = new RouteCoverageEventNotifier(testClass.getName(), s -> getTestMethod().getName()); - camelContext.addService(notifier, true); - camelContext.getManagementStrategy().addEventNotifier(notifier); - } - }); - } - } - - /** - * Handles the processing of the {@link ProvidesBreakpoint} annotation on a test class. Exists here - * as it is needed in - * - * @param context the initialized Spring context containing the Camel context(s) to insert breakpoints into - * @param testClass the test class being processed - * - * @throws Exception if there is an error processing the class - */ - protected void handleProvidesBreakpoint(GenericApplicationContext context, Class<?> testClass) throws Exception { - Collection<Method> methods = getAllMethods(testClass); - final List<Breakpoint> breakpoints = new LinkedList<>(); - - for (Method method : methods) { - if (AnnotationUtils.findAnnotation(method, ProvidesBreakpoint.class) != null) { - Class<?>[] argTypes = method.getParameterTypes(); - if (argTypes.length != 0) { - throw new IllegalArgumentException("Method [" + method.getName() - + "] is annotated with ProvidesBreakpoint but is not a no-argument method."); - } else if (!Breakpoint.class.isAssignableFrom(method.getReturnType())) { - throw new IllegalArgumentException("Method [" + method.getName() - + "] is annotated with ProvidesBreakpoint but does not return a Breakpoint."); - } else if (!Modifier.isStatic(method.getModifiers())) { - throw new IllegalArgumentException("Method [" + method.getName() - + "] is annotated with ProvidesBreakpoint but is not static."); - } else if (!Modifier.isPublic(method.getModifiers())) { - throw new IllegalArgumentException("Method [" + method.getName() - + "] is annotated with ProvidesBreakpoint but is not public."); - } - - try { - breakpoints.add((Breakpoint) method.invoke(null)); - } catch (Exception e) { - throw new RuntimeException("Method [" + method.getName() - + "] threw exception during evaluation.", e); - } - } - } - - if (breakpoints.size() != 0) { - CamelSpringTestHelper.doToSpringCamelContexts(context, new DoToSpringCamelContextsStrategy() { - - @Override - public void execute(String contextName, SpringCamelContext camelContext) - throws Exception { - Debugger debugger = camelContext.getDebugger(); - if (debugger == null) { - debugger = new DefaultDebugger(); - camelContext.setDebugger(debugger); - } - - for (Breakpoint breakpoint : breakpoints) { - LOG.info("Adding Breakpoint [{}] to CamelContext with name [{}].", breakpoint, contextName); - debugger.addBreakpoint(breakpoint); - } - } - }); - } - } - - - /** - * Handles updating shutdown timeouts on Camel contexts based on {@link ShutdownTimeout}. - * - * @param context the initialized Spring context - * @param testClass the test class being executed - */ - protected void handleShutdownTimeout(GenericApplicationContext context, Class<?> testClass) throws Exception { - final int shutdownTimeout; - final TimeUnit shutdownTimeUnit; - if (testClass.isAnnotationPresent(ShutdownTimeout.class)) { - shutdownTimeout = testClass.getAnnotation(ShutdownTimeout.class).value(); - shutdownTimeUnit = testClass.getAnnotation(ShutdownTimeout.class).timeUnit(); - } else { - shutdownTimeout = 10; - shutdownTimeUnit = TimeUnit.SECONDS; - } - - CamelSpringTestHelper.doToSpringCamelContexts(context, new DoToSpringCamelContextsStrategy() { - - @Override - public void execute(String contextName, SpringCamelContext camelContext) - throws Exception { - LOG.info("Setting shutdown timeout to [{} {}] on CamelContext with name [{}].", shutdownTimeout, shutdownTimeUnit, contextName); - camelContext.getShutdownStrategy().setTimeout(shutdownTimeout); - camelContext.getShutdownStrategy().setTimeUnit(shutdownTimeUnit); - } - }); - } - - /** - * Handles auto-intercepting of endpoints with mocks based on {@link MockEndpoints}. - * - * @param context the initialized Spring context - * @param testClass the test class being executed - */ - protected void handleMockEndpoints(GenericApplicationContext context, Class<?> testClass) throws Exception { - if (testClass.isAnnotationPresent(MockEndpoints.class)) { - final String mockEndpoints = testClass.getAnnotation(MockEndpoints.class).value(); - CamelSpringTestHelper.doToSpringCamelContexts(context, new DoToSpringCamelContextsStrategy() { - - @Override - public void execute(String contextName, SpringCamelContext camelContext) - throws Exception { - LOG.info("Enabling auto mocking of endpoints matching pattern [{}] on CamelContext with name [{}].", mockEndpoints, contextName); - camelContext.adapt(ExtendedCamelContext.class).registerEndpointCallback(new InterceptSendToMockEndpointStrategy(mockEndpoints)); - } - }); - } - } - - /** - * Handles auto-intercepting of endpoints with mocks based on {@link MockEndpointsAndSkip} and skipping the - * original endpoint. - * - * @param context the initialized Spring context - * @param testClass the test class being executed - */ - protected void handleMockEndpointsAndSkip(GenericApplicationContext context, Class<?> testClass) throws Exception { - if (testClass.isAnnotationPresent(MockEndpointsAndSkip.class)) { - final String mockEndpoints = testClass.getAnnotation(MockEndpointsAndSkip.class).value(); - CamelSpringTestHelper.doToSpringCamelContexts(context, new DoToSpringCamelContextsStrategy() { - - @Override - public void execute(String contextName, SpringCamelContext camelContext) - throws Exception { - // resovle the property place holders of the mockEndpoints - String mockEndpointsValue = camelContext.resolvePropertyPlaceholders(mockEndpoints); - LOG.info("Enabling auto mocking and skipping of endpoints matching pattern [{}] on CamelContext with name [{}].", mockEndpointsValue, contextName); - camelContext.adapt(ExtendedCamelContext.class).registerEndpointCallback(new InterceptSendToMockEndpointStrategy(mockEndpointsValue, true)); - } - }); - } - } - - /** - * Sets property overrides for the Camel {@link org.apache.camel.component.properties.PropertiesComponent}. - * - * @param context the pre-refresh Spring context - * @param testClass the test class being executed - */ - protected void handleUseOverridePropertiesWithPropertiesComponent(ConfigurableApplicationContext context, Class<?> testClass) throws Exception { - Collection<Method> methods = getAllMethods(testClass); - final List<Properties> properties = new LinkedList<>(); - - for (Method method : methods) { - if (AnnotationUtils.findAnnotation(method, UseOverridePropertiesWithPropertiesComponent.class) != null) { - Class<?>[] argTypes = method.getParameterTypes(); - if (argTypes.length > 0) { - throw new IllegalArgumentException("Method [" + method.getName() - + "] is annotated with UseOverridePropertiesWithPropertiesComponent but is not a no-argument method."); - } else if (!Properties.class.isAssignableFrom(method.getReturnType())) { - throw new IllegalArgumentException("Method [" + method.getName() - + "] is annotated with UseOverridePropertiesWithPropertiesComponent but does not return a java.util.Properties."); - } else if (!Modifier.isStatic(method.getModifiers())) { - throw new IllegalArgumentException("Method [" + method.getName() - + "] is annotated with UseOverridePropertiesWithPropertiesComponent but is not static."); - } else if (!Modifier.isPublic(method.getModifiers())) { - throw new IllegalArgumentException("Method [" + method.getName() - + "] is annotated with UseOverridePropertiesWithPropertiesComponent but is not public."); - } - - try { - properties.add((Properties) method.invoke(null)); - } catch (Exception e) { - throw new RuntimeException("Method [" + method.getName() - + "] threw exception during evaluation.", e); - } - } - } - - Properties extra = new Properties(); - for (Properties prop : properties) { - extra.putAll(prop); - } - - if (!extra.isEmpty()) { - context.addBeanFactoryPostProcessor(beanFactory -> beanFactory.addBeanPostProcessor(new BeanPostProcessor() { - @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) { - if (bean instanceof PropertiesComponent) { - PropertiesComponent pc = (PropertiesComponent) bean; - LOG.info("Using {} properties to override any existing properties on the PropertiesComponent", extra.size()); - pc.setOverrideProperties(extra); - } - return bean; - } - })); - } - } /** - * Handles starting of Camel contexts based on {@link UseAdviceWith} and other state in the JVM. - * - * @param context the initialized Spring context - * @param testClass the test class being executed - */ - protected void handleCamelContextStartup(GenericApplicationContext context, Class<?> testClass) throws Exception { - boolean skip = "true".equalsIgnoreCase(System.getProperty("skipStartingCamelContext")); - if (skip) { - LOG.info("Skipping starting CamelContext(s) as system property skipStartingCamelContext is set to be true."); - } else if (testClass.isAnnotationPresent(UseAdviceWith.class)) { - if (testClass.getAnnotation(UseAdviceWith.class).value()) { - LOG.info("Skipping starting CamelContext(s) as UseAdviceWith annotation was found and isUseAdviceWith is set to true."); - skip = true; - } else { - LOG.info("Starting CamelContext(s) as UseAdviceWith annotation was found, but isUseAdviceWith is set to false."); - skip = false; - } - } - - if (!skip) { - CamelSpringTestHelper.doToSpringCamelContexts(context, new DoToSpringCamelContextsStrategy() { - - @Override - public void execute(String contextName, - SpringCamelContext camelContext) throws Exception { - LOG.info("Starting CamelContext with name [{}].", contextName); - camelContext.start(); - } - }); - } - } - - /** * Returns the class under test in order to enable inspection of annotations while the * Spring context is being created. * diff --git a/components/camel-test-spring/src/main/java/org/apache/camel/test/spring/CamelSpringTestHelper.java b/components/camel-test-spring/src/main/java/org/apache/camel/test/spring/CamelSpringTestHelper.java index 4418b15..b4db697 100644 --- a/components/camel-test-spring/src/main/java/org/apache/camel/test/spring/CamelSpringTestHelper.java +++ b/components/camel-test-spring/src/main/java/org/apache/camel/test/spring/CamelSpringTestHelper.java @@ -38,22 +38,31 @@ import org.springframework.test.context.TestContext; * for this class to work right. */ public final class CamelSpringTestHelper { - + private static ThreadLocal<String> originalJmxDisabledValue = new ThreadLocal<>(); + private static ThreadLocal<String> originalExcludeRoutesValue = new ThreadLocal<>(); private static ThreadLocal<Class<?>> testClazz = new ThreadLocal<>(); private static ThreadLocal<TestContext> testContext = new ThreadLocal<>(); private CamelSpringTestHelper() { } - + public static String getOriginalJmxDisabled() { return originalJmxDisabledValue.get(); } - + public static void setOriginalJmxDisabledValue(String originalValue) { originalJmxDisabledValue.set(originalValue); } - + + public static String getOriginalExcludeRoutes() { + return originalExcludeRoutesValue.get(); + } + + public static void setOriginalExcludeRoutesValue(String originalValue) { + originalExcludeRoutesValue.set(originalValue); + } + public static Class<?> getTestClass() { return testClazz.get(); } diff --git a/components/camel-test-spring/src/main/java/org/apache/camel/test/spring/DisableJmxTestExecutionListener.java b/components/camel-test-spring/src/main/java/org/apache/camel/test/spring/DisableJmxTestExecutionListener.java deleted file mode 100644 index cc04c96..0000000 --- a/components/camel-test-spring/src/main/java/org/apache/camel/test/spring/DisableJmxTestExecutionListener.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.camel.test.spring; - -import org.apache.camel.api.management.JmxSystemPropertyKeys; -import org.springframework.test.context.TestContext; -import org.springframework.test.context.support.AbstractTestExecutionListener; - -/** - * Provides reset to pre-test state behavior for global enable/disable of JMX - * support in Camel through the use of {@link DisableJmx}. - * Tries to ensure that the pre-test value is restored. - */ -public class DisableJmxTestExecutionListener extends AbstractTestExecutionListener { - - @Override - public void afterTestClass(TestContext testContext) throws Exception { - if (CamelSpringTestHelper.getOriginalJmxDisabled() == null) { - System.clearProperty(JmxSystemPropertyKeys.DISABLED); - } else { - System.setProperty(JmxSystemPropertyKeys.DISABLED, CamelSpringTestHelper.getOriginalJmxDisabled()); - } - } - -}