Search in sources :

Example 1 with Property

use of io.micronaut.context.annotation.Property in project micronaut-test by micronaut-projects.

the class AbstractMicronautExtension method beforeEach.

/**
 * To be called by the different implementations before each test method.
 *
 * @param context The test context
 * @param testInstance The test instance
 * @param method The test method
 * @param propertyAnnotations The {@code @Property} annotations found in the test method, if any
 */
protected void beforeEach(C context, @Nullable Object testInstance, @Nullable AnnotatedElement method, List<Property> propertyAnnotations) {
    int testCount = (int) testProperties.compute("micronaut.test.count", (k, oldCount) -> (int) (oldCount != null ? oldCount : 0) + 1);
    if (method != null) {
        if (propertyAnnotations != null && !propertyAnnotations.isEmpty()) {
            for (Property property : propertyAnnotations) {
                final String name = property.name();
                oldValues.put(name, testProperties.put(name, property.value()));
            }
        } else {
            oldValues.forEach((k, v) -> testProperties.put(k, v));
        }
        if (testAnnotationValue.rebuildContext() && testCount > 1) {
            stopEmbeddedApplication();
            if (applicationContext.isRunning()) {
                applicationContext.stop();
            }
            applicationContext = builder.build();
            startApplicationContext();
            startEmbeddedApplication();
        } else if (!oldValues.isEmpty()) {
            final Map<String, Object> diff = applicationContext.getEnvironment().refreshAndDiff();
            refreshScope.onRefreshEvent(new RefreshEvent(diff));
        }
    }
    if (testInstance != null) {
        if (applicationContext != null) {
            if (refreshScope != null) {
                refreshScope.onRefreshEvent(new RefreshEvent(Collections.singletonMap(TestActiveCondition.ACTIVE_MOCKS, "changed")));
            }
            applicationContext.inject(testInstance);
            alignMocks(context, testInstance);
        }
    }
}
Also used : java.util(java.util) TestContext(io.micronaut.test.context.TestContext) RefreshEvent(io.micronaut.runtime.context.scope.refresh.RefreshEvent) ArrayUtils(io.micronaut.core.util.ArrayUtils) SoftServiceLoader(io.micronaut.core.io.service.SoftServiceLoader) ApplicationContext(io.micronaut.context.ApplicationContext) TestExecutionListener(io.micronaut.test.context.TestExecutionListener) InstantiationUtils(io.micronaut.core.reflect.InstantiationUtils) Nullable(io.micronaut.core.annotation.Nullable) AnnotationUtils(io.micronaut.test.annotation.AnnotationUtils) NameUtils(io.micronaut.core.naming.NameUtils) Property(io.micronaut.context.annotation.Property) ResourceResolver(io.micronaut.core.io.ResourceResolver) ClassUtils(io.micronaut.core.reflect.ClassUtils) ApplicationContextBuilder(io.micronaut.context.ApplicationContextBuilder) PropertySource(io.micronaut.context.env.PropertySource) PropertySourceLoader(io.micronaut.context.env.PropertySourceLoader) TestActiveCondition(io.micronaut.test.condition.TestActiveCondition) ServiceDefinition(io.micronaut.core.io.service.ServiceDefinition) IOException(java.io.IOException) EmbeddedApplication(io.micronaut.runtime.EmbeddedApplication) StringUtils(io.micronaut.core.util.StringUtils) MicronautTestValue(io.micronaut.test.annotation.MicronautTestValue) RefreshScope(io.micronaut.runtime.context.scope.refresh.RefreshScope) BeanDefinition(io.micronaut.inject.BeanDefinition) TestPropertyProvider(io.micronaut.test.support.TestPropertyProvider) InputStream(java.io.InputStream) AnnotatedElement(java.lang.reflect.AnnotatedElement) RefreshEvent(io.micronaut.runtime.context.scope.refresh.RefreshEvent) Property(io.micronaut.context.annotation.Property)

Example 2 with Property

use of io.micronaut.context.annotation.Property in project micronaut-test by micronaut-projects.

the class AbstractMicronautExtension method beforeClass.

/**
 * Executed before tests within a class are run.
 *
 * @param context The test context
 * @param testClass The test class
 * @param testAnnotationValue The test annotation values
 */
protected void beforeClass(C context, Class<?> testClass, @Nullable MicronautTestValue testAnnotationValue) {
    if (testAnnotationValue != null) {
        Class<? extends ApplicationContextBuilder>[] cb = testAnnotationValue.contextBuilder();
        if (ArrayUtils.isNotEmpty(cb)) {
            this.builder = InstantiationUtils.instantiate(cb[0]);
        }
        this.testAnnotationValue = testAnnotationValue;
        final Package aPackage = testClass.getPackage();
        builder.packages(aPackage.getName());
        final List<Property> ps = AnnotationUtils.findRepeatableAnnotations(testClass, Property.class);
        for (Property property : ps) {
            testProperties.put(property.name(), property.value());
        }
        String[] propertySources = testAnnotationValue.propertySources();
        if (ArrayUtils.isNotEmpty(propertySources)) {
            Map<String, PropertySourceLoader> loaderMap = readPropertySourceLoaderMap();
            ResourceResolver resourceResolver = new ResourceResolver();
            for (String propertySource : propertySources) {
                String ext = NameUtils.extension(propertySource);
                if (StringUtils.isNotEmpty(ext)) {
                    String filename = NameUtils.filename(propertySource);
                    PropertySourceLoader loader = loaderMap.get(ext);
                    if (loader != null) {
                        Optional<InputStream> resourceAsStream = resourceResolver.getResourceAsStream(propertySource);
                        InputStream inputStream = resourceAsStream.orElse(testClass.getResourceAsStream(propertySource));
                        if (inputStream != null) {
                            Map<String, Object> properties;
                            try {
                                properties = loader.read(filename, inputStream);
                                builder.propertySources(PropertySource.of(filename, properties));
                            } catch (IOException e) {
                                throw new RuntimeException("Error loading property source reference for @MicronautTest: " + filename);
                            } finally {
                                try {
                                    inputStream.close();
                                } catch (IOException e) {
                                // ignore
                                }
                            }
                        }
                    }
                }
            }
        }
        if (TestPropertyProvider.class.isAssignableFrom(testClass)) {
            resolveTestProperties(context, testAnnotationValue, testProperties);
        }
        testProperties.put(TestActiveCondition.ACTIVE_SPEC_CLAZZ, testClass);
        testProperties.put(TEST_ROLLBACK, String.valueOf(testAnnotationValue.rollback()));
        testProperties.put(TEST_TRANSACTIONAL, String.valueOf(testAnnotationValue.transactional()));
        testProperties.put(TEST_TRANSACTION_MODE, String.valueOf(testAnnotationValue.transactionMode()));
        final Class<?> application = testAnnotationValue.application();
        if (application != void.class) {
            builder.mainClass(application);
        }
        String[] environments = testAnnotationValue.environments();
        if (environments.length == 0) {
            environments = new String[] { "test" };
        }
        builder.packages(testAnnotationValue.packages()).environments(environments);
        PropertySource testPropertySource = PropertySource.of(TEST_PROPERTY_SOURCE, testProperties);
        builder.propertySources(testPropertySource);
        postProcessBuilder(builder);
        this.applicationContext = builder.build();
        startApplicationContext();
        specDefinition = applicationContext.findBeanDefinition(testClass).orElse(null);
        if (testAnnotationValue.startApplication() && applicationContext.containsBean(EmbeddedApplication.class)) {
            embeddedApplication = applicationContext.getBean(EmbeddedApplication.class);
            embeddedApplication.start();
        }
        refreshScope = applicationContext.findBean(RefreshScope.class).orElse(null);
    }
}
Also used : InputStream(java.io.InputStream) PropertySourceLoader(io.micronaut.context.env.PropertySourceLoader) IOException(java.io.IOException) PropertySource(io.micronaut.context.env.PropertySource) ResourceResolver(io.micronaut.core.io.ResourceResolver) Property(io.micronaut.context.annotation.Property) ApplicationContextBuilder(io.micronaut.context.ApplicationContextBuilder) EmbeddedApplication(io.micronaut.runtime.EmbeddedApplication)

Example 3 with Property

use of io.micronaut.context.annotation.Property in project micronaut-test by micronaut-projects.

the class MicronautSpockExtension method visitSpecAnnotation.

@Override
public void visitSpecAnnotation(T annotation, SpecInfo spec) {
    spec.getAllFeatures().forEach(feature -> {
        feature.addInterceptor(invocation -> {
            try {
                beforeTestMethod(buildContext(invocation, null));
                invocation.proceed();
            } finally {
                afterTestMethod(buildContext(invocation, null));
            }
        });
        feature.getFeatureMethod().addInterceptor(invocation -> {
            try {
                beforeTestExecution(buildContext(invocation, null));
                invocation.proceed();
                afterTestExecution(buildContext(invocation, null));
            } catch (Throwable e) {
                afterTestExecution(buildContext(invocation, e));
                throw e;
            }
        });
    });
    spec.addSetupSpecInterceptor(invocation -> {
        MicronautTest micronautTest = spec.getAnnotation(MicronautTest.class);
        MicronautTestValue micronautTestValue = buildValueObject(micronautTest);
        beforeClass(invocation, spec.getReflection(), micronautTestValue);
        if (specDefinition == null) {
            if (!isTestSuiteBeanPresent(spec.getReflection())) {
                throw new InvalidSpecException(MISCONFIGURED_MESSAGE);
            } else {
                final List<FeatureInfo> features = invocation.getSpec().getFeatures();
                for (FeatureInfo feature : features) {
                    feature.setSkipped(true);
                }
            }
        } else {
            List<FieldInfo> fields = spec.getAllFields();
            for (FieldInfo field : fields) {
                if (field.isShared() && field.getAnnotation(Inject.class) != null) {
                    applicationContext.inject(invocation.getSharedInstance());
                    break;
                }
            }
        }
        beforeTestClass(buildContext(invocation, null));
        invocation.proceed();
    });
    spec.addCleanupSpecInterceptor(invocation -> {
        afterTestClass(buildContext(invocation, null));
        afterClass(invocation);
        invocation.proceed();
        singletonMocks.clear();
    });
    spec.addSetupInterceptor(invocation -> {
        final Object instance = invocation.getInstance();
        final Method method = invocation.getFeature().getFeatureMethod().getReflection();
        List<Property> propertyAnnotations = Arrays.asList(method.getAnnotationsByType(Property.class));
        beforeEach(invocation, instance, method, propertyAnnotations);
        for (Object mock : creatableMocks) {
            mockUtil.attachMock(mock, (Specification) instance);
        }
        for (Object mock : singletonMocks) {
            mockUtil.attachMock(mock, (Specification) instance);
        }
        try {
            beforeSetupTest(buildContext(invocation, null));
            invocation.proceed();
        } finally {
            afterSetupTest(buildContext(invocation, null));
        }
    });
    spec.addCleanupInterceptor(invocation -> {
        for (Object mock : creatableMocks) {
            mockUtil.detachMock(mock);
        }
        for (Object mock : singletonMocks) {
            mockUtil.detachMock(mock);
        }
        creatableMocks.clear();
        afterEach(invocation);
        try {
            beforeCleanupTest(buildContext(invocation, null));
            invocation.proceed();
        } finally {
            afterCleanupTest(buildContext(invocation, null));
        }
    });
}
Also used : InvalidSpecException(org.spockframework.runtime.InvalidSpecException) FeatureInfo(org.spockframework.runtime.model.FeatureInfo) MicronautTestValue(io.micronaut.test.annotation.MicronautTestValue) Method(java.lang.reflect.Method) Property(io.micronaut.context.annotation.Property) MicronautTest(io.micronaut.test.extensions.spock.annotation.MicronautTest) FieldInfo(org.spockframework.runtime.model.FieldInfo)

Aggregations

Property (io.micronaut.context.annotation.Property)3 ApplicationContextBuilder (io.micronaut.context.ApplicationContextBuilder)2 PropertySource (io.micronaut.context.env.PropertySource)2 PropertySourceLoader (io.micronaut.context.env.PropertySourceLoader)2 ResourceResolver (io.micronaut.core.io.ResourceResolver)2 EmbeddedApplication (io.micronaut.runtime.EmbeddedApplication)2 MicronautTestValue (io.micronaut.test.annotation.MicronautTestValue)2 IOException (java.io.IOException)2 InputStream (java.io.InputStream)2 ApplicationContext (io.micronaut.context.ApplicationContext)1 Nullable (io.micronaut.core.annotation.Nullable)1 ServiceDefinition (io.micronaut.core.io.service.ServiceDefinition)1 SoftServiceLoader (io.micronaut.core.io.service.SoftServiceLoader)1 NameUtils (io.micronaut.core.naming.NameUtils)1 ClassUtils (io.micronaut.core.reflect.ClassUtils)1 InstantiationUtils (io.micronaut.core.reflect.InstantiationUtils)1 ArrayUtils (io.micronaut.core.util.ArrayUtils)1 StringUtils (io.micronaut.core.util.StringUtils)1 BeanDefinition (io.micronaut.inject.BeanDefinition)1 RefreshEvent (io.micronaut.runtime.context.scope.refresh.RefreshEvent)1