Search in sources :

Example 1 with TestResourceManager

use of io.quarkus.test.common.TestResourceManager in project quarkus by quarkusio.

the class QuarkusTestExtension method doJavaStart.

private ExtensionState doJavaStart(ExtensionContext context, Class<? extends QuarkusTestProfile> profile) throws Throwable {
    TracingHandler.quarkusStarting();
    hangDetectionExecutor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "Quarkus hang detection timer thread");
        }
    });
    String time = "10m";
    // config is not established yet
    // we can only read from system properties
    String sysPropString = System.getProperty(QUARKUS_TEST_HANG_DETECTION_TIMEOUT);
    if (sysPropString != null) {
        time = sysPropString;
    }
    hangTimeout = new DurationConverter().convert(time);
    hangTaskKey = hangDetectionExecutor.schedule(hangDetectionTask, hangTimeout.toMillis(), TimeUnit.MILLISECONDS);
    quarkusTestProfile = profile;
    Class<?> requiredTestClass = context.getRequiredTestClass();
    Closeable testResourceManager = null;
    try {
        final LinkedBlockingDeque<Runnable> shutdownTasks = new LinkedBlockingDeque<>();
        PrepareResult result = createAugmentor(context, profile, shutdownTasks);
        AugmentAction augmentAction = result.augmentAction;
        QuarkusTestProfile profileInstance = result.profileInstance;
        testHttpEndpointProviders = TestHttpEndpointProvider.load();
        StartupAction startupAction = augmentAction.createInitialRuntimeApplication();
        Thread.currentThread().setContextClassLoader(startupAction.getClassLoader());
        populateDeepCloneField(startupAction);
        // must be done after the TCCL has been set
        testResourceManager = (Closeable) startupAction.getClassLoader().loadClass(TestResourceManager.class.getName()).getConstructor(Class.class, Class.class, List.class, boolean.class, Map.class, Optional.class).newInstance(requiredTestClass, profile != null ? profile : null, getAdditionalTestResources(profileInstance, startupAction.getClassLoader()), profileInstance != null && profileInstance.disableGlobalTestResources(), startupAction.getDevServicesProperties(), Optional.empty());
        testResourceManager.getClass().getMethod("init", String.class).invoke(testResourceManager, profile != null ? profile.getName() : null);
        Map<String, String> properties = (Map<String, String>) testResourceManager.getClass().getMethod("start").invoke(testResourceManager);
        startupAction.overrideConfig(properties);
        hasPerTestResources = (boolean) testResourceManager.getClass().getMethod("hasPerTestResources").invoke(testResourceManager);
        populateCallbacks(startupAction.getClassLoader());
        populateTestMethodInvokers(startupAction.getClassLoader());
        if (profileInstance == null || !profileInstance.runMainMethod()) {
            runningQuarkusApplication = startupAction.run(profileInstance == null ? new String[0] : profileInstance.commandLineParameters());
        } else {
            Class<?> lifecycleManager = Class.forName(ApplicationLifecycleManager.class.getName(), true, startupAction.getClassLoader());
            lifecycleManager.getDeclaredMethod("setDefaultExitCodeHandler", Consumer.class).invoke(null, (Consumer<Integer>) integer -> {
            });
            runningQuarkusApplication = startupAction.runMainClass(profileInstance.commandLineParameters());
        }
        String patternString = runningQuarkusApplication.getConfigValue("quarkus.test.class-clone-pattern", String.class).orElse("java\\..*");
        clonePattern = Pattern.compile(patternString);
        TracingHandler.quarkusStarted();
        if (hangTaskKey != null) {
            hangTaskKey.cancel(false);
            hangTimeout = runningQuarkusApplication.getConfigValue(QUARKUS_TEST_HANG_DETECTION_TIMEOUT, Duration.class).orElse(Duration.of(10, ChronoUnit.MINUTES));
            hangTaskKey = hangDetectionExecutor.schedule(hangDetectionTask, hangTimeout.toMillis(), TimeUnit.MILLISECONDS);
        }
        ConfigProviderResolver.setInstance(new RunningAppConfigResolver(runningQuarkusApplication));
        RestorableSystemProperties restorableSystemProperties = RestorableSystemProperties.setProperties(Collections.singletonMap("test.url", TestHTTPResourceManager.getUri(runningQuarkusApplication)));
        Closeable tm = testResourceManager;
        Closeable shutdownTask = new Closeable() {

            @Override
            public void close() throws IOException {
                TracingHandler.quarkusStopping();
                try {
                    runningQuarkusApplication.close();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    TracingHandler.quarkusStopped();
                    try {
                        while (!shutdownTasks.isEmpty()) {
                            shutdownTasks.pop().run();
                        }
                    } finally {
                        try {
                            tm.close();
                        } finally {
                            restorableSystemProperties.close();
                            GroovyCacheCleaner.clearGroovyCache();
                            shutdownHangDetection();
                        }
                    }
                    try {
                        TestClassIndexer.removeIndex(requiredTestClass);
                    } catch (Exception ignored) {
                    }
                }
            }
        };
        ExtensionState state = new ExtensionState(testResourceManager, shutdownTask);
        return state;
    } catch (Throwable e) {
        if (!InitialConfigurator.DELAYED_HANDLER.isActivated()) {
            activateLogging();
        }
        try {
            if (testResourceManager != null) {
                testResourceManager.close();
            }
        } catch (Exception ex) {
            e.addSuppressed(ex);
        }
        throw e;
    } finally {
        if (originalCl != null) {
            Thread.currentThread().setContextClassLoader(originalCl);
        }
    }
}
Also used : ApplicationLifecycleManager(io.quarkus.runtime.ApplicationLifecycleManager) RestAssuredURLManager(io.quarkus.test.common.RestAssuredURLManager) FieldInfo(org.jboss.jandex.FieldInfo) ApplicationLifecycleManager(io.quarkus.runtime.ApplicationLifecycleManager) ThreadInfo(java.lang.management.ThreadInfo) TestClassPredicateBuildItem(io.quarkus.deployment.builditem.TestClassPredicateBuildItem) Duration(java.time.Duration) Map(java.util.Map) AugmentAction(io.quarkus.bootstrap.app.AugmentAction) QuarkusTestAfterEachCallback(io.quarkus.test.junit.callback.QuarkusTestAfterEachCallback) InitialConfigurator(io.quarkus.bootstrap.logging.InitialConfigurator) Path(java.nio.file.Path) DurationConverter(io.quarkus.runtime.configuration.DurationConverter) TestAbortedException(org.opentest4j.TestAbortedException) TestHttpEndpointProvider(io.quarkus.runtime.test.TestHttpEndpointProvider) Set(java.util.Set) QuarkusClassLoader(io.quarkus.bootstrap.classloading.QuarkusClassLoader) Executors(java.util.concurrent.Executors) StartupAction(io.quarkus.bootstrap.app.StartupAction) InvocationTargetException(java.lang.reflect.InvocationTargetException) ReflectiveInvocationContext(org.junit.jupiter.api.extension.ReflectiveInvocationContext) BuildStep(io.quarkus.builder.BuildStep) TestClassBeanBuildItem(io.quarkus.deployment.builditem.TestClassBeanBuildItem) AnnotationInstance(org.jboss.jandex.AnnotationInstance) QuarkusTestMethodContext(io.quarkus.test.junit.callback.QuarkusTestMethodContext) PropertyTestUtil(io.quarkus.test.common.PropertyTestUtil) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ExtensionContext(org.junit.jupiter.api.extension.ExtensionContext) Constructor(java.lang.reflect.Constructor) Supplier(java.util.function.Supplier) Nested(org.junit.jupiter.api.Nested) RestorableSystemProperties(io.quarkus.test.common.RestorableSystemProperties) ArrayList(java.util.ArrayList) BuildChainBuilder(io.quarkus.builder.BuildChainBuilder) Parameter(java.lang.reflect.Parameter) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ManagementFactory(java.lang.management.ManagementFactory) IntegrationTestUtil.getAdditionalTestResources(io.quarkus.test.junit.IntegrationTestUtil.getAdditionalTestResources) ParameterResolutionException(org.junit.jupiter.api.extension.ParameterResolutionException) IOException(java.io.IOException) ParameterContext(org.junit.jupiter.api.extension.ParameterContext) ChronoUnit(java.time.temporal.ChronoUnit) BeforeAllCallback(org.junit.jupiter.api.extension.BeforeAllCallback) LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) BeforeEachCallback(org.junit.jupiter.api.extension.BeforeEachCallback) TestResourceManager(io.quarkus.test.common.TestResourceManager) TestHTTPResourceManager(io.quarkus.test.common.http.TestHTTPResourceManager) QuarkusTestContext(io.quarkus.test.junit.callback.QuarkusTestContext) TestHTTPEndpoint(io.quarkus.test.common.http.TestHTTPEndpoint) ScheduledFuture(java.util.concurrent.ScheduledFuture) QuarkusTestBeforeEachCallback(io.quarkus.test.junit.callback.QuarkusTestBeforeEachCallback) QuarkusTestBeforeClassCallback(io.quarkus.test.junit.callback.QuarkusTestBeforeClassCallback) ClassInfo(org.jboss.jandex.ClassInfo) DeepClone(io.quarkus.test.junit.internal.DeepClone) ConfigProviderResolver(org.eclipse.microprofile.config.spi.ConfigProviderResolver) AfterEachCallback(org.junit.jupiter.api.extension.AfterEachCallback) Locale(java.util.Locale) AnnotationTarget(org.jboss.jandex.AnnotationTarget) ThreadFactory(java.util.concurrent.ThreadFactory) Method(java.lang.reflect.Method) GroovyCacheCleaner(io.quarkus.test.common.GroovyCacheCleaner) Predicate(java.util.function.Predicate) ServiceLoader(java.util.ServiceLoader) TestInfo(org.junit.jupiter.api.TestInfo) Objects(java.util.Objects) List(java.util.List) TestBuildChainCustomizerProducer(io.quarkus.test.junit.buildchain.TestBuildChainCustomizerProducer) BuildContext(io.quarkus.builder.BuildContext) Optional(java.util.Optional) Pattern(java.util.regex.Pattern) TestScopeManager(io.quarkus.test.common.TestScopeManager) PathTestHelper(io.quarkus.test.common.PathTestHelper) TestClassIndexer(io.quarkus.test.common.TestClassIndexer) RunningQuarkusApplication(io.quarkus.bootstrap.app.RunningQuarkusApplication) TestAnnotationBuildItem(io.quarkus.deployment.builditem.TestAnnotationBuildItem) Logger(org.jboss.logging.Logger) Type(org.jboss.jandex.Type) TracingHandler(io.quarkus.dev.testing.TracingHandler) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) LaunchMode(io.quarkus.runtime.LaunchMode) HashMap(java.util.HashMap) IntegrationTestUtil.activateLogging(io.quarkus.test.junit.IntegrationTestUtil.activateLogging) Function(java.util.function.Function) QuarkusTestAfterAllCallback(io.quarkus.test.junit.callback.QuarkusTestAfterAllCallback) QuarkusTestAfterConstructCallback(io.quarkus.test.junit.callback.QuarkusTestAfterConstructCallback) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) TestMethodInvoker(io.quarkus.test.TestMethodInvoker) ApplicationClassPredicateBuildItem(io.quarkus.deployment.builditem.ApplicationClassPredicateBuildItem) Index(org.jboss.jandex.Index) ClassPathElement(io.quarkus.bootstrap.classloading.ClassPathElement) InvocationInterceptor(org.junit.jupiter.api.extension.InvocationInterceptor) TestInstantiationException(org.junit.jupiter.api.extension.TestInstantiationException) SerializationWithXStreamFallbackDeepClone(io.quarkus.test.junit.internal.SerializationWithXStreamFallbackDeepClone) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) AbstractMap(java.util.AbstractMap) ConditionEvaluationResult(org.junit.jupiter.api.extension.ConditionEvaluationResult) ExecutionCondition(org.junit.jupiter.api.extension.ExecutionCondition) AfterAllCallback(org.junit.jupiter.api.extension.AfterAllCallback) ExceptionReporting(io.quarkus.dev.testing.ExceptionReporting) Closeable(java.io.Closeable) ProfileManager(io.quarkus.runtime.configuration.ProfileManager) Collections(java.util.Collections) ParameterResolver(org.junit.jupiter.api.extension.ParameterResolver) ThreadFactory(java.util.concurrent.ThreadFactory) LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) Closeable(java.io.Closeable) Consumer(java.util.function.Consumer) DurationConverter(io.quarkus.runtime.configuration.DurationConverter) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) List(java.util.List) AugmentAction(io.quarkus.bootstrap.app.AugmentAction) StartupAction(io.quarkus.bootstrap.app.StartupAction) Optional(java.util.Optional) TestAbortedException(org.opentest4j.TestAbortedException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ParameterResolutionException(org.junit.jupiter.api.extension.ParameterResolutionException) IOException(java.io.IOException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) TestInstantiationException(org.junit.jupiter.api.extension.TestInstantiationException) RestorableSystemProperties(io.quarkus.test.common.RestorableSystemProperties) Map(java.util.Map) HashMap(java.util.HashMap) AbstractMap(java.util.AbstractMap) TestResourceManager(io.quarkus.test.common.TestResourceManager)

Example 2 with TestResourceManager

use of io.quarkus.test.common.TestResourceManager in project quarkus by quarkusio.

the class QuarkusIntegrationTestExtension method doProcessStart.

private IntegrationTestExtensionState doProcessStart(Properties quarkusArtifactProperties, Class<? extends QuarkusTestProfile> profile, ExtensionContext context) throws Throwable {
    String artifactType = getArtifactType(quarkusArtifactProperties);
    boolean isDockerLaunch = isContainer(artifactType);
    ArtifactLauncher.InitContext.DevServicesLaunchResult devServicesLaunchResult = handleDevServices(context, isDockerLaunch);
    devServicesProps = devServicesLaunchResult.properties();
    containerNetworkId = devServicesLaunchResult.networkId();
    quarkusTestProfile = profile;
    currentJUnitTestClass = context.getRequiredTestClass();
    TestResourceManager testResourceManager = null;
    try {
        Class<?> requiredTestClass = context.getRequiredTestClass();
        Map<String, String> sysPropRestore = getSysPropsToRestore();
        TestProfileAndProperties testProfileAndProperties = determineTestProfileAndProperties(profile, sysPropRestore);
        testResourceManager = new TestResourceManager(requiredTestClass, quarkusTestProfile, getAdditionalTestResources(testProfileAndProperties.testProfile, context.getRequiredTestClass().getClassLoader()), testProfileAndProperties.testProfile != null && testProfileAndProperties.testProfile.disableGlobalTestResources(), devServicesProps, containerNetworkId == null ? Optional.empty() : Optional.of(containerNetworkId));
        testResourceManager.init(testProfileAndProperties.testProfile != null ? testProfileAndProperties.testProfile.getClass().getName() : null);
        hasPerTestResources = testResourceManager.hasPerTestResources();
        Map<String, String> additionalProperties = new HashMap<>(testProfileAndProperties.properties);
        additionalProperties.putAll(QuarkusIntegrationTestExtension.devServicesProps);
        Map<String, String> resourceManagerProps = testResourceManager.start();
        Map<String, String> old = new HashMap<>();
        for (Map.Entry<String, String> i : resourceManagerProps.entrySet()) {
            old.put(i.getKey(), System.getProperty(i.getKey()));
            if (i.getValue() == null) {
                System.clearProperty(i.getKey());
            } else {
                System.setProperty(i.getKey(), i.getValue());
            }
        }
        context.getStore(ExtensionContext.Namespace.GLOBAL).put(NativeTestExtension.class.getName() + ".systemProps", new ExtensionContext.Store.CloseableResource() {

            @Override
            public void close() throws Throwable {
                for (Map.Entry<String, String> i : old.entrySet()) {
                    old.put(i.getKey(), System.getProperty(i.getKey()));
                    if (i.getValue() == null) {
                        System.clearProperty(i.getKey());
                    } else {
                        System.setProperty(i.getKey(), i.getValue());
                    }
                }
            }
        });
        additionalProperties.putAll(resourceManagerProps);
        ArtifactLauncher<?> launcher = null;
        String testHost = System.getProperty("quarkus.http.test-host");
        if ((testHost != null) && !testHost.isEmpty()) {
            launcher = new TestHostLauncher();
        } else {
            ServiceLoader<ArtifactLauncherProvider> loader = ServiceLoader.load(ArtifactLauncherProvider.class);
            for (ArtifactLauncherProvider launcherProvider : loader) {
                if (launcherProvider.supportsArtifactType(artifactType)) {
                    launcher = launcherProvider.create(new DefaultArtifactLauncherCreateContext(quarkusArtifactProperties, context, requiredTestClass, devServicesLaunchResult));
                    break;
                }
            }
        }
        if (launcher == null) {
            throw new IllegalStateException("Artifact type + '" + artifactType + "' is not supported by @QuarkusIntegrationTest");
        }
        activateLogging();
        startLauncher(launcher, additionalProperties, () -> ssl = true);
        IntegrationTestExtensionState state = new IntegrationTestExtensionState(testResourceManager, launcher, sysPropRestore);
        testHttpEndpointProviders = TestHttpEndpointProvider.load();
        return state;
    } catch (Throwable e) {
        if (!InitialConfigurator.DELAYED_HANDLER.isActivated()) {
            activateLogging();
        }
        try {
            if (testResourceManager != null) {
                testResourceManager.close();
            }
        } catch (Exception ex) {
            e.addSuppressed(ex);
        }
        throw e;
    }
}
Also used : HashMap(java.util.HashMap) ArtifactLauncherProvider(io.quarkus.test.junit.launcher.ArtifactLauncherProvider) TestAbortedException(org.opentest4j.TestAbortedException) HashMap(java.util.HashMap) Map(java.util.Map) TestHostLauncher(io.quarkus.test.common.TestHostLauncher) TestResourceManager(io.quarkus.test.common.TestResourceManager) IntegrationTestUtil.determineTestProfileAndProperties(io.quarkus.test.junit.IntegrationTestUtil.determineTestProfileAndProperties)

Example 3 with TestResourceManager

use of io.quarkus.test.common.TestResourceManager in project quarkus by quarkusio.

the class QuarkusMainIntegrationTestExtension method doProcessStart.

private ArtifactLauncher.LaunchResult doProcessStart(ExtensionContext context, String[] args) {
    try {
        Class<? extends QuarkusTestProfile> profile = IntegrationTestUtil.findProfile(context.getRequiredTestClass());
        TestResourceManager testResourceManager = null;
        Map<String, String> old = new HashMap<>();
        String artifactType = quarkusArtifactProperties.getProperty("type");
        try {
            Class<?> requiredTestClass = context.getRequiredTestClass();
            Map<String, String> sysPropRestore = getSysPropsToRestore();
            TestProfileAndProperties testProfileAndProperties = determineTestProfileAndProperties(profile, sysPropRestore);
            testResourceManager = new TestResourceManager(requiredTestClass, profile, getAdditionalTestResources(testProfileAndProperties.testProfile, context.getRequiredTestClass().getClassLoader()), testProfileAndProperties.testProfile != null && testProfileAndProperties.testProfile.disableGlobalTestResources());
            testResourceManager.init(testProfileAndProperties.testProfile != null ? testProfileAndProperties.testProfile.getClass().getName() : null);
            Map<String, String> additionalProperties = new HashMap<>(testProfileAndProperties.properties);
            additionalProperties.putAll(QuarkusMainIntegrationTestExtension.devServicesProps);
            Map<String, String> resourceManagerProps = testResourceManager.start();
            for (Map.Entry<String, String> i : resourceManagerProps.entrySet()) {
                old.put(i.getKey(), System.getProperty(i.getKey()));
                if (i.getValue() == null) {
                    System.clearProperty(i.getKey());
                } else {
                    System.setProperty(i.getKey(), i.getValue());
                }
            }
            additionalProperties.putAll(resourceManagerProps);
            testResourceManager.inject(context.getRequiredTestInstance());
            ArtifactLauncher<?> launcher = null;
            ServiceLoader<ArtifactLauncherProvider> loader = ServiceLoader.load(ArtifactLauncherProvider.class);
            for (ArtifactLauncherProvider launcherProvider : loader) {
                if (launcherProvider.supportsArtifactType(artifactType)) {
                    launcher = launcherProvider.create(new DefaultArtifactLauncherCreateContext(quarkusArtifactProperties, context, requiredTestClass, devServicesLaunchResult));
                    break;
                }
            }
            if (launcher == null) {
                throw new IllegalStateException("Artifact type + '" + artifactType + "' is not supported by @QuarkusMainIntegrationTest");
            }
            launcher.includeAsSysProps(additionalProperties);
            activateLogging();
            return launcher.runToCompletion(args);
        } finally {
            for (Map.Entry<String, String> i : old.entrySet()) {
                old.put(i.getKey(), System.getProperty(i.getKey()));
                if (i.getValue() == null) {
                    System.clearProperty(i.getKey());
                } else {
                    System.setProperty(i.getKey(), i.getValue());
                }
            }
            if (testResourceManager != null) {
                testResourceManager.close();
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : HashMap(java.util.HashMap) ArtifactLauncherProvider(io.quarkus.test.junit.launcher.ArtifactLauncherProvider) ParameterResolutionException(org.junit.jupiter.api.extension.ParameterResolutionException) HashMap(java.util.HashMap) Map(java.util.Map) TestResourceManager(io.quarkus.test.common.TestResourceManager) IntegrationTestUtil.determineTestProfileAndProperties(io.quarkus.test.junit.IntegrationTestUtil.determineTestProfileAndProperties)

Example 4 with TestResourceManager

use of io.quarkus.test.common.TestResourceManager in project quarkus by quarkusio.

the class NativeTestExtension method doNativeStart.

private IntegrationTestExtensionState doNativeStart(ExtensionContext context, Class<? extends QuarkusTestProfile> profile) throws Throwable {
    Map<String, String> devServicesProps = handleDevServices(context, false).properties();
    quarkusTestProfile = profile;
    currentJUnitTestClass = context.getRequiredTestClass();
    TestResourceManager testResourceManager = null;
    try {
        Class<?> requiredTestClass = context.getRequiredTestClass();
        Map<String, String> sysPropRestore = getSysPropsToRestore();
        TestProfileAndProperties testProfileAndProperties = determineTestProfileAndProperties(profile, sysPropRestore);
        testResourceManager = new TestResourceManager(requiredTestClass, quarkusTestProfile, getAdditionalTestResources(testProfileAndProperties.testProfile, currentJUnitTestClass.getClassLoader()), testProfileAndProperties.testProfile != null && testProfileAndProperties.testProfile.disableGlobalTestResources());
        testResourceManager.init(testProfileAndProperties.testProfile != null ? testProfileAndProperties.testProfile.getClass().getName() : null);
        hasPerTestResources = testResourceManager.hasPerTestResources();
        Map<String, String> additionalProperties = new HashMap<>(testProfileAndProperties.properties);
        additionalProperties.putAll(devServicesProps);
        Map<String, String> resourceManagerProps = testResourceManager.start();
        Map<String, String> old = new HashMap<>();
        for (Map.Entry<String, String> i : resourceManagerProps.entrySet()) {
            old.put(i.getKey(), System.getProperty(i.getKey()));
            if (i.getValue() == null) {
                System.clearProperty(i.getKey());
            } else {
                System.setProperty(i.getKey(), i.getValue());
            }
        }
        context.getStore(ExtensionContext.Namespace.GLOBAL).put(NativeTestExtension.class.getName() + ".systemProps", new ExtensionContext.Store.CloseableResource() {

            @Override
            public void close() throws Throwable {
                for (Map.Entry<String, String> i : old.entrySet()) {
                    old.put(i.getKey(), System.getProperty(i.getKey()));
                    if (i.getValue() == null) {
                        System.clearProperty(i.getKey());
                    } else {
                        System.setProperty(i.getKey(), i.getValue());
                    }
                }
            }
        });
        additionalProperties.putAll(resourceManagerProps);
        NativeImageLauncher launcher = createLauncher(requiredTestClass);
        startLauncher(launcher, additionalProperties, () -> ssl = true);
        final IntegrationTestExtensionState state = new IntegrationTestExtensionState(testResourceManager, launcher, sysPropRestore);
        testHttpEndpointProviders = TestHttpEndpointProvider.load();
        return state;
    } catch (Throwable e) {
        try {
            if (testResourceManager != null) {
                testResourceManager.close();
            }
        } catch (Exception ex) {
            e.addSuppressed(ex);
        }
        throw e;
    }
}
Also used : HashMap(java.util.HashMap) NativeImageLauncher(io.quarkus.test.common.NativeImageLauncher) DefaultNativeImageLauncher(io.quarkus.test.common.DefaultNativeImageLauncher) TestAbortedException(org.opentest4j.TestAbortedException) HashMap(java.util.HashMap) Map(java.util.Map) TestResourceManager(io.quarkus.test.common.TestResourceManager) IntegrationTestUtil.determineTestProfileAndProperties(io.quarkus.test.junit.IntegrationTestUtil.determineTestProfileAndProperties)

Example 5 with TestResourceManager

use of io.quarkus.test.common.TestResourceManager in project quarkus by quarkusio.

the class QuarkusMainTestExtension method doJavaStart.

private int doJavaStart(ExtensionContext context, Class<? extends QuarkusTestProfile> profile, String[] arguments) throws Exception {
    TracingHandler.quarkusStarting();
    Closeable testResourceManager = null;
    try {
        StartupAction startupAction = prepareResult.augmentAction.createInitialRuntimeApplication();
        Thread.currentThread().setContextClassLoader(startupAction.getClassLoader());
        QuarkusConsole.installRedirects();
        flushAllLoggers();
        installLoggerRedirect();
        QuarkusTestProfile profileInstance = prepareResult.profileInstance;
        // must be done after the TCCL has been set
        testResourceManager = (Closeable) startupAction.getClassLoader().loadClass(TestResourceManager.class.getName()).getConstructor(Class.class, Class.class, List.class, boolean.class, Map.class, Optional.class).newInstance(context.getRequiredTestClass(), profile != null ? profile : null, getAdditionalTestResources(profileInstance, startupAction.getClassLoader()), profileInstance != null && profileInstance.disableGlobalTestResources(), startupAction.getDevServicesProperties(), Optional.empty());
        testResourceManager.getClass().getMethod("init", String.class).invoke(testResourceManager, profile != null ? profile.getName() : null);
        Map<String, String> properties = (Map<String, String>) testResourceManager.getClass().getMethod("start").invoke(testResourceManager);
        startupAction.overrideConfig(properties);
        hasPerTestResources = (boolean) testResourceManager.getClass().getMethod("hasPerTestResources").invoke(testResourceManager);
        testResourceManager.getClass().getMethod("inject", Object.class).invoke(testResourceManager, context.getRequiredTestInstance());
        var result = startupAction.runMainClassBlocking(arguments);
        flushAllLoggers();
        return result;
    } catch (Throwable e) {
        if (!InitialConfigurator.DELAYED_HANDLER.isActivated()) {
            activateLogging();
        }
        try {
            if (testResourceManager != null) {
                testResourceManager.close();
            }
        } catch (Exception ex) {
            e.addSuppressed(ex);
        }
        throw e;
    } finally {
        uninstallLoggerRedirect();
        QuarkusConsole.uninstallRedirects();
        if (originalCl != null) {
            Thread.currentThread().setContextClassLoader(originalCl);
        }
    }
}
Also used : StartupAction(io.quarkus.bootstrap.app.StartupAction) Closeable(java.io.Closeable) ParameterResolutionException(org.junit.jupiter.api.extension.ParameterResolutionException) TestResourceManager(io.quarkus.test.common.TestResourceManager)

Aggregations

TestResourceManager (io.quarkus.test.common.TestResourceManager)9 HashMap (java.util.HashMap)6 Map (java.util.Map)5 ParameterResolutionException (org.junit.jupiter.api.extension.ParameterResolutionException)4 IntegrationTestUtil.determineTestProfileAndProperties (io.quarkus.test.junit.IntegrationTestUtil.determineTestProfileAndProperties)3 IOException (java.io.IOException)3 UncheckedIOException (java.io.UncheckedIOException)3 Path (java.nio.file.Path)3 ExtensionContext (org.junit.jupiter.api.extension.ExtensionContext)3 AugmentAction (io.quarkus.bootstrap.app.AugmentAction)2 QuarkusBootstrap (io.quarkus.bootstrap.app.QuarkusBootstrap)2 StartupAction (io.quarkus.bootstrap.app.StartupAction)2 ClassPathElement (io.quarkus.bootstrap.classloading.ClassPathElement)2 QuarkusClassLoader (io.quarkus.bootstrap.classloading.QuarkusClassLoader)2 BuildChainBuilder (io.quarkus.builder.BuildChainBuilder)2 BuildContext (io.quarkus.builder.BuildContext)2 BuildStep (io.quarkus.builder.BuildStep)2 ApplicationClassPredicateBuildItem (io.quarkus.deployment.builditem.ApplicationClassPredicateBuildItem)2 TestHTTPResourceManager (io.quarkus.test.common.http.TestHTTPResourceManager)2 ArtifactLauncherProvider (io.quarkus.test.junit.launcher.ArtifactLauncherProvider)2