@Test public void springSocialUserInfo() { TestPropertyValues .of("security.oauth2.resource.userInfoUri:http://example.com", "spring.social.facebook.app-id=foo", "spring.social.facebook.app-secret=bar") .applyTo(this.environment); this.context = new SpringApplicationBuilder(SocialResourceConfiguration.class) .environment(this.environment).web(WebApplicationType.SERVLET).run(); ConnectionFactoryLocator connectionFactory = this.context .getBean(ConnectionFactoryLocator.class); assertThat(connectionFactory).isNotNull(); SpringSocialTokenServices services = this.context .getBean(SpringSocialTokenServices.class); assertThat(services).isNotNull(); }
@Test public void testEnvironmentalOverrides() { this.context = new AnnotationConfigServletWebServerApplicationContext(); TestPropertyValues .of("security.oauth2.client.clientId:myclientid", "security.oauth2.client.clientSecret:mysecret", "security.oauth2.client.autoApproveScopes:read,write", "security.oauth2.client.accessTokenValiditySeconds:40", "security.oauth2.client.refreshTokenValiditySeconds:80") .applyTo(this.context); this.context.register(AuthorizationAndResourceServerConfiguration.class, MinimalSecureWebApplication.class); this.context.refresh(); ClientDetails config = this.context.getBean(ClientDetails.class); assertThat(config.getClientId()).isEqualTo("myclientid"); assertThat(config.getClientSecret()).isEqualTo("mysecret"); assertThat(config.isAutoApprove("read")).isTrue(); assertThat(config.isAutoApprove("write")).isTrue(); assertThat(config.isAutoApprove("foo")).isFalse(); assertThat(config.getAccessTokenValiditySeconds()).isEqualTo(40); assertThat(config.getRefreshTokenValiditySeconds()).isEqualTo(80); verifyAuthentication(config); }
@Test public void testCanUseClientCredentials() { this.context = new AnnotationConfigServletWebServerApplicationContext(); this.context.register(TestSecurityConfiguration.class, MinimalSecureWebApplication.class); TestPropertyValues .of("security.oauth2.client.clientId=client", "security.oauth2.client.grantType=client_credentials") .applyTo(this.context); ConfigurationPropertySources.attach(this.context.getEnvironment()); this.context.refresh(); OAuth2ClientContext bean = this.context.getBean(OAuth2ClientContext.class); assertThat(bean.getAccessTokenRequest()).isNotNull(); assertThat(countBeans(ClientCredentialsResourceDetails.class)).isEqualTo(1); assertThat(countBeans(OAuth2ClientContext.class)).isEqualTo(1); }
@Test public void testCanUseClientCredentialsWithEnableOAuth2Client() { this.context = new AnnotationConfigServletWebServerApplicationContext(); this.context.register(ClientConfiguration.class, MinimalSecureWebApplication.class); TestPropertyValues .of("security.oauth2.client.clientId=client", "security.oauth2.client.grantType=client_credentials") .applyTo(this.context); ConfigurationPropertySources.attach(this.context.getEnvironment()); this.context.refresh(); // The primary context is fine (not session scoped): OAuth2ClientContext bean = this.context.getBean(OAuth2ClientContext.class); assertThat(bean.getAccessTokenRequest()).isNotNull(); assertThat(countBeans(ClientCredentialsResourceDetails.class)).isEqualTo(1); // Kind of a bug (should ideally be 1), but the cause is in Spring OAuth2 (there // is no need for the extra session-scoped bean). What this test proves is that // even if the user screws up and does @EnableOAuth2Client for client credentials, // it will still just about work (because of the @Primary annotation on the // Boot-created instance of OAuth2ClientContext). assertThat(countBeans(OAuth2ClientContext.class)).isEqualTo(2); }
@Test public void testAuthorizationServerOverride() { this.context = new AnnotationConfigServletWebServerApplicationContext(); TestPropertyValues.of("security.oauth2.resourceId:resource-id") .applyTo(this.context); this.context.register(AuthorizationAndResourceServerConfiguration.class, CustomAuthorizationServer.class, MinimalSecureWebApplication.class); this.context.refresh(); BaseClientDetails config = new BaseClientDetails(); config.setClientId("client"); config.setClientSecret("secret"); config.setResourceIds(Arrays.asList("resource-id")); config.setAuthorizedGrantTypes(Arrays.asList("password")); config.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList("USER")); config.setScope(Arrays.asList("read")); assertThat(countBeans(AUTHORIZATION_SERVER_CONFIG)).isEqualTo(0); assertThat(countBeans(RESOURCE_SERVER_CONFIG)).isEqualTo(1); verifyAuthentication(config); }
@Test public void testWithCheckConfigLocationFileDoesNotExists() { TestPropertyValues.of("mybatis.config-location:foo.xml", "mybatis.check-config-location=true") .applyTo(this.context); this.context.register(EmbeddedDataSourceConfiguration.class, MybatisAutoConfiguration.class); try { this.context.refresh(); fail("Should be occurred a BeanCreationException."); } catch (BeanCreationException e) { assertThat(e.getMessage()).isEqualTo("Error creating bean with name 'mybatisAutoConfiguration': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Cannot find config location: class path resource [foo.xml] (please add config file or check your Mybatis configuration)"); } }
@Test public void testMixedWithConfigurationFileAndInterceptor() { TestPropertyValues.of( "mybatis.config-location:mybatis-config-settings-only.xml") .applyTo(this.context); this.context.register(EmbeddedDataSourceConfiguration.class, MybatisInterceptorConfiguration.class); this.context.refresh(); org.apache.ibatis.session.Configuration configuration = this.context.getBean( SqlSessionFactory.class).getConfiguration(); assertThat(this.context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); assertThat(this.context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); assertThat(this.context.getBeanNamesForType(CityMapper.class)).hasSize(1); assertThat(configuration.getDefaultFetchSize()).isEqualTo(1000); assertThat(configuration.getInterceptors()).hasSize(1); assertThat(configuration.getInterceptors().get(0)).isInstanceOf(MyInterceptor.class); }
@Test public void testMixedWithConfigurationFileAndDatabaseIdProvider() { TestPropertyValues.of( "mybatis.config-location:mybatis-config-settings-only.xml") .applyTo(this.context); this.context.register(EmbeddedDataSourceConfiguration.class, MybatisBootMapperScanAutoConfiguration.class, DatabaseProvidersConfiguration.class); this.context.refresh(); org.apache.ibatis.session.Configuration configuration = this.context.getBean( SqlSessionFactory.class).getConfiguration(); assertThat(this.context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); assertThat(this.context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); assertThat(this.context.getBeanNamesForType(CityMapper.class)).hasSize(1); assertThat(configuration.getDefaultFetchSize()).isEqualTo(1000); assertThat(configuration.getDatabaseId()).isEqualTo("h2"); }
@Test public void testMixedWithConfigurationFileAndTypeHandlersPackage() { TestPropertyValues.of( "mybatis.config-location:mybatis-config-settings-only.xml", "mybatis.type-handlers-package:org.mybatis.spring.boot.autoconfigure.handler") .applyTo(this.context); this.context.register(EmbeddedDataSourceConfiguration.class, MybatisBootMapperScanAutoConfiguration.class); this.context.refresh(); org.apache.ibatis.session.Configuration configuration = this.context.getBean( SqlSessionFactory.class).getConfiguration(); assertThat(this.context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); assertThat(this.context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); assertThat(this.context.getBeanNamesForType(CityMapper.class)).hasSize(1); assertThat(configuration.getDefaultFetchSize()).isEqualTo(1000); assertThat(configuration.getTypeHandlerRegistry().getTypeHandler(BigInteger.class)).isInstanceOf(DummyTypeHandler.class); }
@Test public void testMixedWithConfigurationFileAndTypeAliasesPackageAndMapperLocations() { TestPropertyValues.of( "mybatis.config-location:mybatis-config-settings-only.xml", "mybatis.type-aliases-package:org.mybatis.spring.boot.autoconfigure.domain", "mybatis.mapper-locations:classpath:org/mybatis/spring/boot/autoconfigure/repository/CityMapper.xml") .applyTo(this.context); this.context.register(EmbeddedDataSourceConfiguration.class, MybatisBootMapperScanAutoConfiguration.class); this.context.refresh(); org.apache.ibatis.session.Configuration configuration = this.context.getBean( SqlSessionFactory.class).getConfiguration(); assertThat(this.context.getBeanNamesForType(SqlSessionFactory.class)).hasSize(1); assertThat(this.context.getBeanNamesForType(SqlSessionTemplate.class)).hasSize(1); assertThat(this.context.getBeanNamesForType(CityMapper.class)).hasSize(1); assertThat(configuration.getDefaultFetchSize()).isEqualTo(1000); assertThat(configuration.getMappedStatementNames()).contains("selectCityById"); assertThat(configuration.getMappedStatementNames()).contains("org.mybatis.spring.boot.autoconfigure.repository.CityMapperImpl.selectCityById"); }
@Test public void testConfigFileAndConfigurationWithTogether() { TestPropertyValues.of( "mybatis.config-location:mybatis-config.xml", "mybatis.configuration.default-statement-timeout:30") .applyTo(this.context); this.context.register(EmbeddedDataSourceConfiguration.class, MybatisAutoConfiguration.class); try { this.context.refresh(); fail("Should be occurred a BeanCreationException."); } catch (BeanCreationException e) { assertThat(e.getMessage()).contains("Property 'configuration' and 'configLocation' can not specified with together"); } }
@Test public void testWithConfigurationVariablesAndPropertiesOtherKey() { TestPropertyValues.of( "mybatis.configuration.variables.key1:value1", "mybatis.configuration-properties.key2:value2") .applyTo(this.context); this.context.register(EmbeddedDataSourceConfiguration.class, MybatisAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); Properties variables = this.context.getBean(SqlSessionFactory.class).getConfiguration().getVariables(); assertThat(variables).hasSize(2); assertThat(variables.getProperty("key1")).isEqualTo("value1"); assertThat(variables.getProperty("key2")).isEqualTo("value2"); }
@Test public void shouldDoNothingIfNoServersAreSet() throws Exception { // given TestPropertyValues .of("edison.serviceregistry.enabled=true") .and("edison.serviceregistry.servers=") .applyTo(context); context.register(DefaultAsyncHttpClient.class); context.register(ApplicationInfoConfiguration.class); context.register(AsyncHttpRegistryClient.class); context.refresh(); RegistryClient bean = context.getBean(RegistryClient.class); assertThat(bean.isRunning(), is(false)); }
@Test public void shouldDoNothingIfNoServiceAreSet() throws Exception { // given TestPropertyValues .of("edison.serviceregistry.enabled=true") .and("edison.serviceregistry.service=") .applyTo(context); context.register(DefaultAsyncHttpClient.class); context.register(ApplicationInfoConfiguration.class); context.register(AsyncHttpRegistryClient.class); context.refresh(); RegistryClient bean = context.getBean(RegistryClient.class); assertThat(bean.isRunning(), is(false)); }
@Test public void shouldDoNothingIfRegistryDisabled() throws Exception { // given TestPropertyValues .of("edison.serviceregistry.enabled=false") .and("edison.serviceregistry.servers=http://foo") .and("edison.serviceregistry.service=http://test") .applyTo(context); context.register(DefaultAsyncHttpClient.class); context.register(ApplicationInfoConfiguration.class); context.register(AsyncHttpRegistryClient.class); context.refresh(); RegistryClient bean = context.getBean(RegistryClient.class); assertThat(bean.isRunning(), is(false)); }
@Test public void bootstrapPropertySourceAlwaysFirst() { // Use spring.cloud.bootstrap.name to switch off the defaults (which would pick up // a bootstrapProperties immediately try (ConfigurableApplicationContext context = SpringApplication.run(Empty.class, "--spring.main.webEnvironment=false", "--debug=false", "--spring.main.bannerMode=OFF", "--spring.cloud.bootstrap.name=refresh")) { List<String> names = names(context.getEnvironment().getPropertySources()); System.err.println("***** " + context.getEnvironment().getPropertySources()); assertThat(names).doesNotContain("bootstrapProperties"); ContextRefresher refresher = new ContextRefresher(context, scope); TestPropertyValues.of( "spring.cloud.bootstrap.sources: org.springframework.cloud.context.refresh.ContextRefresherTests.PropertySourceConfiguration") .applyTo(context.getEnvironment(), Type.MAP, "defaultProperties"); refresher.refresh(); names = names(context.getEnvironment().getPropertySources()); assertThat(names).first().isEqualTo("bootstrapProperties"); } }
@Test public void parentContextIsClosed() { // Use spring.cloud.bootstrap.name to switch off the defaults (which would pick up // a bootstrapProperties immediately try (ConfigurableApplicationContext context = SpringApplication.run( ContextRefresherTests.class, "--spring.main.webEnvironment=false", "--debug=false", "--spring.main.bannerMode=OFF", "--spring.cloud.bootstrap.name=refresh")) { ContextRefresher refresher = new ContextRefresher(context, scope); TestPropertyValues.of( "spring.cloud.bootstrap.sources: org.springframework.cloud.context.refresh.ContextRefresherTests.PropertySourceConfiguration") .applyTo(context); ConfigurableApplicationContext refresherContext = refresher .addConfigFilesToEnvironment(); assertThat(refresherContext.getParent()).isNotNull() .isInstanceOf(ConfigurableApplicationContext.class); ConfigurableApplicationContext parent = (ConfigurableApplicationContext) refresherContext .getParent(); assertThat(parent.isActive()).isFalse(); } }
@Test @DirtiesContext public void testRefresh() throws Exception { assertEquals(1, properties.getCount()); assertEquals("Hello scope!", properties.getMessage()); assertEquals(1, properties.getCount()); // Change the dynamic property source... TestPropertyValues.of("message:Foo").applyTo(this.environment); // ...rebind, but the bean is not re-initialized: rebinder.rebind(); assertEquals("Hello scope!", properties.getMessage()); assertEquals(1, properties.getCount()); // ...and then refresh, so the bean is re-initialized: refreshScope.refreshAll(); assertEquals("Foo", properties.getMessage()); // It's a new instance so the initialization count is 1 assertEquals(1, properties.getCount()); }
@Test @DirtiesContext public void testRefresh() throws Exception { assertEquals("Hello scope!", this.service.getMessage()); String id1 = this.service.toString(); // Change the dynamic property source... TestPropertyValues.of("message:Foo").applyTo(this.environment, Type.MAP, "morerefreshtests"); // ...and then refresh, so the bean is re-initialized: this.scope.refreshAll(); String id2 = this.service.toString(); String message = this.service.getMessage(); assertEquals("Foo", message); assertEquals(1, TestService.getInitCount()); assertEquals(1, TestService.getDestroyCount()); assertNotSame(id1, id2); }
@Test @DirtiesContext public void testRefreshFails() throws Exception { assertEquals("Hello scope!", this.service.getMessage()); // Change the dynamic property source... TestPropertyValues.of("message:Foo", "delay:foo").applyTo(this.environment); // ...and then refresh, so the bean is re-initialized: this.scope.refreshAll(); try { // If a refresh fails (e.g. a binding error in this case) the application is // basically hosed. assertEquals("Hello scope!", this.service.getMessage()); fail("expected BeanCreationException"); } catch (BeanCreationException e) { } // But we can fix it by fixing the binding error: TestPropertyValues.of("delay:0").applyTo(this.environment); // ...and then refresh, so the bean is re-initialized: this.scope.refreshAll(); assertEquals("Foo", this.service.getMessage()); }
@Test public void testDecryptNonStandardParent() { ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(); EnvironmentDecryptApplicationInitializer initializer = new EnvironmentDecryptApplicationInitializer( Encryptors.noOpText()); TestPropertyValues.of("key:{cipher}value").applyTo(ctx); ApplicationContext ctxParent = mock(ApplicationContext.class); when(ctxParent.getEnvironment()).thenReturn(mock(Environment.class)); ctx.setParent(ctxParent); initializer.initialize(ctx); assertEquals("value", ctx.getEnvironment().getProperty("key")); }
@Test public void keysComputedWhenChangesInExternalProperties() throws Exception { this.context = new SpringApplicationBuilder(Empty.class) .web(WebApplicationType.NONE).bannerMode(Mode.OFF) .properties("spring.cloud.bootstrap.name:none").run(); RefreshScope scope = new RefreshScope(); scope.setApplicationContext(this.context); TestPropertyValues .of("spring.cloud.bootstrap.sources=" + ExternalPropertySourceLocator.class.getName()) .applyTo(this.context.getEnvironment(), Type.MAP, "defaultProperties"); ContextRefresher contextRefresher = new ContextRefresher(this.context, scope); RefreshEndpoint endpoint = new RefreshEndpoint(contextRefresher); Collection<String> keys = endpoint.refresh(); assertTrue("Wrong keys: " + keys, keys.contains("external.message")); }
@Test public void springMainSourcesEmptyInRefreshCycle() throws Exception { this.context = new SpringApplicationBuilder(Empty.class) .web(WebApplicationType.NONE).bannerMode(Mode.OFF) .properties("spring.cloud.bootstrap.name:none").run(); RefreshScope scope = new RefreshScope(); scope.setApplicationContext(this.context); // spring.main.sources should be empty when the refresh cycle starts (we don't // want any config files from the application context getting into the one used to // construct the environment for refresh) TestPropertyValues .of("spring.main.sources=" + ExternalPropertySourceLocator.class.getName()) .applyTo(this.context); ContextRefresher contextRefresher = new ContextRefresher(this.context, scope); RefreshEndpoint endpoint = new RefreshEndpoint(contextRefresher); Collection<String> keys = endpoint.refresh(); assertFalse("Wrong keys: " + keys, keys.contains("external.message")); }
private void load(Class<?> config, String... environment) { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(); if (config != null) { applicationContext.register(config); } applicationContext.register(RestTemplateAutoConfiguration.class); applicationContext.register(HazelcastAutoConfiguration.class); applicationContext.register(UtilAutoConfiguration.class); applicationContext.register(AdminServerMarkerConfiguration.class); applicationContext.register(AdminServerHazelcastAutoConfiguration.class); applicationContext.register(AdminServerAutoConfiguration.class); applicationContext.register(AdminServerDiscoveryAutoConfiguration.class); TestPropertyValues.of(environment).applyTo(applicationContext); applicationContext.refresh(); this.context = applicationContext; }
@Test public void configureBean_withCustomDataBaseName_configuresFactoryBeanWithCustomDatabaseName() throws Exception { //Arrange this.context = new AnnotationConfigApplicationContext(); this.context.register(ApplicationConfigurationWithoutReadReplica.class); this.context.register(AmazonRdsDatabaseAutoConfiguration.class); TestPropertyValues.of("cloud.aws.rds.test.password:secret", "cloud.aws.rds.test.databaseName:fooDb").applyTo(this.context); //Act this.context.refresh(); //Assert DataSource dataSource = this.context.getBean(DataSource.class); assertNotNull(dataSource); assertNotNull(this.context.getBean(AmazonRdsDataSourceFactoryBean.class)); assertTrue(dataSource instanceof org.apache.tomcat.jdbc.pool.DataSource); assertTrue(((org.apache.tomcat.jdbc.pool.DataSource) dataSource).getUrl().endsWith("fooDb")); }
@Test public void configureBean_withDefaultClientSpecifiedAndNoReadReplicaAndMultipleDatabases_configuresBothDatabases() throws Exception { //Arrange this.context = new AnnotationConfigApplicationContext(); this.context.register(ApplicationConfigurationWithMultipleDatabases.class); this.context.register(AmazonRdsDatabaseAutoConfiguration.class); TestPropertyValues.of("cloud.aws.rds.test.password:secret", "cloud.aws.rds.anotherOne.password:verySecret").applyTo(this.context); //Act this.context.refresh(); //Assert assertNotNull(this.context.getBean("test", DataSource.class)); assertNotNull(this.context.getBean("&test", AmazonRdsDataSourceFactoryBean.class)); assertNotNull(this.context.getBean("anotherOne", DataSource.class)); assertNotNull(this.context.getBean("&anotherOne", AmazonRdsDataSourceFactoryBean.class)); }
@Test public void configureBean_withDefaultClientSpecifiedAndReadReplica_configuresFactoryBeanWithReadReplicaEnabled() throws Exception { //Arrange this.context = new AnnotationConfigApplicationContext(); this.context.register(ApplicationConfigurationWithReadReplica.class); this.context.register(AmazonRdsDatabaseAutoConfiguration.class); TestPropertyValues.of("cloud.aws.rds.test.password:secret", "cloud.aws.rds.test.readReplicaSupport:true").applyTo(this.context); //Act this.context.refresh(); //Assert assertNotNull(this.context.getBean(DataSource.class)); assertNotNull(this.context.getBean(AmazonRdsReadReplicaAwareDataSourceFactoryBean.class)); }
@Test public void credentialsProvider_accessKeyAndSecretKeyConfigured_configuresStaticCredentialsProviderWithAccessAndSecretKey() { this.context = new AnnotationConfigApplicationContext(); this.context.register(ContextCredentialsAutoConfiguration.class); TestPropertyValues.of( "cloud.aws.credentials.accessKey:foo", "cloud.aws.credentials.secretKey:bar").applyTo(this.context); this.context.refresh(); AWSCredentialsProvider awsCredentialsProvider = this.context.getBean(AmazonWebserviceClientConfigurationUtils.CREDENTIALS_PROVIDER_BEAN_NAME, AWSCredentialsProviderChain.class); assertNotNull(awsCredentialsProvider); @SuppressWarnings("unchecked") List<CredentialsProvider> credentialsProviders = (List<CredentialsProvider>) ReflectionTestUtils.getField(awsCredentialsProvider, "credentialsProviders"); assertEquals(2, credentialsProviders.size()); assertTrue(AWSStaticCredentialsProvider.class.isInstance(credentialsProviders.get(0))); assertTrue(ProfileCredentialsProvider.class.isInstance(credentialsProviders.get(1))); assertEquals("foo", awsCredentialsProvider.getCredentials().getAWSAccessKeyId()); assertEquals("bar", awsCredentialsProvider.getCredentials().getAWSSecretKey()); }
@Test public void credentialsProvider_instanceProfileConfigured_configuresInstanceProfileCredentialsProvider() { this.context = new AnnotationConfigApplicationContext(); this.context.register(ContextCredentialsAutoConfiguration.class); TestPropertyValues.of( "cloud.aws.credentials.instanceProfile").applyTo(this.context); this.context.refresh(); AWSCredentialsProvider awsCredentialsProvider = this.context.getBean(AmazonWebserviceClientConfigurationUtils.CREDENTIALS_PROVIDER_BEAN_NAME, AWSCredentialsProvider.class); assertNotNull(awsCredentialsProvider); @SuppressWarnings("unchecked") List<CredentialsProvider> credentialsProviders = (List<CredentialsProvider>) ReflectionTestUtils.getField(awsCredentialsProvider, "credentialsProviders"); assertEquals(2, credentialsProviders.size()); assertTrue(EC2ContainerCredentialsProviderWrapper.class.isInstance(credentialsProviders.get(0))); assertTrue(ProfileCredentialsProvider.class.isInstance(credentialsProviders.get(1))); }
@Test public void credentialsProvider_profileNameConfigured_configuresProfileCredentialsProvider() { this.context = new AnnotationConfigApplicationContext(); this.context.register(ContextCredentialsAutoConfiguration.class); TestPropertyValues.of( "cloud.aws.credentials.profileName:test").applyTo(this.context); this.context.refresh(); AWSCredentialsProvider awsCredentialsProvider = this.context.getBean(AmazonWebserviceClientConfigurationUtils.CREDENTIALS_PROVIDER_BEAN_NAME, AWSCredentialsProvider.class); assertNotNull(awsCredentialsProvider); @SuppressWarnings("unchecked") List<CredentialsProvider> credentialsProviders = (List<CredentialsProvider>) ReflectionTestUtils.getField(awsCredentialsProvider, "credentialsProviders"); assertEquals(2, credentialsProviders.size()); assertTrue(EC2ContainerCredentialsProviderWrapper.class.isInstance(credentialsProviders.get(0))); assertTrue(ProfileCredentialsProvider.class.isInstance(credentialsProviders.get(1))); assertEquals("test", ReflectionTestUtils.getField(credentialsProviders.get(1), "profileName")); }
@Test public void credentialsProvider_profileNameAndPathConfigured_configuresProfileCredentialsProvider() throws IOException { this.context = new AnnotationConfigApplicationContext(); this.context.register(ContextCredentialsAutoConfiguration.class); TestPropertyValues.of( "cloud.aws.credentials.profileName:customProfile", "cloud.aws.credentials.profilePath:" + new ClassPathResource(getClass().getSimpleName() + "-profile", getClass()).getFile().getAbsolutePath()).applyTo(this.context); this.context.refresh(); AWSCredentialsProvider awsCredentialsProvider = this.context.getBean(AmazonWebserviceClientConfigurationUtils.CREDENTIALS_PROVIDER_BEAN_NAME, AWSCredentialsProvider.class); assertNotNull(awsCredentialsProvider); @SuppressWarnings("unchecked") List<CredentialsProvider> credentialsProviders = (List<CredentialsProvider>) ReflectionTestUtils.getField(awsCredentialsProvider, "credentialsProviders"); assertEquals(2, credentialsProviders.size()); assertTrue(EC2ContainerCredentialsProviderWrapper.class.isInstance(credentialsProviders.get(0))); assertTrue(ProfileCredentialsProvider.class.isInstance(credentialsProviders.get(1))); ProfileCredentialsProvider provider = (ProfileCredentialsProvider) credentialsProviders.get(1); assertEquals("testAccessKey", provider.getCredentials().getAWSAccessKeyId()); assertEquals("testSecretKey", provider.getCredentials().getAWSSecretKey()); }
@Test public void createResourceLoader_withCustomTaskExecutorSettings_executorConfigured() throws Exception { //Arrange this.context = new AnnotationConfigApplicationContext(); this.context.register(ContextResourceLoaderAutoConfiguration.class); this.context.register(ApplicationBean.class); TestPropertyValues.of("cloud.aws.loader.corePoolSize:10", "cloud.aws.loader.maxPoolSize:20", "cloud.aws.loader.queueCapacity:0").applyTo(this.context); //Act this.context.refresh(); //Assert PathMatchingSimpleStorageResourcePatternResolver resourceLoader = this.context.getBean(ApplicationBean.class).getResourceLoader(); assertNotNull(resourceLoader); SimpleStorageResourceLoader simpleStorageResourceLoader = (SimpleStorageResourceLoader) ReflectionTestUtils.getField(resourceLoader, "simpleStorageResourceLoader"); ThreadPoolTaskExecutor taskExecutor = (ThreadPoolTaskExecutor) ReflectionTestUtils.getField(simpleStorageResourceLoader, "taskExecutor"); assertNotNull(taskExecutor); assertEquals(10, taskExecutor.getCorePoolSize()); assertEquals(20, taskExecutor.getMaxPoolSize()); assertEquals(0, ReflectionTestUtils.getField(taskExecutor, "queueCapacity")); }
@Test public void placeHolder_customValueSeparator_createInstanceDataResolverThatResolvesWithCustomValueSeparator() throws Exception { // Arrange HttpServer httpServer = MetaDataServer.setupHttpServer(); HttpContext instanceIdHttpContext = httpServer.createContext("/latest/meta-data/instance-id", new MetaDataServer.HttpResponseWriterHandler("testInstanceId")); HttpContext userDataHttpContext = httpServer.createContext("/latest/user-data", new MetaDataServer.HttpResponseWriterHandler("a=b;c=d")); this.context = new AnnotationConfigApplicationContext(); TestPropertyValues.of("cloud.aws.instance.data.valueSeparator:=").applyTo(this.context); this.context.register(ContextInstanceDataAutoConfiguration.class); // Act this.context.refresh(); // Assert assertEquals("b", this.context.getEnvironment().getProperty("a")); assertEquals("d", this.context.getEnvironment().getProperty("c")); httpServer.removeContext(instanceIdHttpContext); httpServer.removeContext(userDataHttpContext); }
@Test public void placeHolder_customAttributeSeparator_createInstanceDataResolverThatResolvesWithCustomAttribute() throws Exception { // Arrange HttpServer httpServer = MetaDataServer.setupHttpServer(); HttpContext instanceIdHttpContext = httpServer.createContext("/latest/meta-data/instance-id", new MetaDataServer.HttpResponseWriterHandler("testInstanceId")); HttpContext userDataHttpContext = httpServer.createContext("/latest/user-data", new MetaDataServer.HttpResponseWriterHandler("a:b/c:d")); this.context = new AnnotationConfigApplicationContext(); TestPropertyValues.of("cloud.aws.instance.data.attributeSeparator:/").applyTo(this.context); this.context.register(ContextInstanceDataAutoConfiguration.class); // Act this.context.refresh(); // Assert assertEquals("b", this.context.getEnvironment().getProperty("a")); assertEquals("d", this.context.getEnvironment().getProperty("c")); httpServer.removeContext(instanceIdHttpContext); httpServer.removeContext(userDataHttpContext); }
private void setup(String... env) { AnnotationConfigApplicationContext parent = new AnnotationConfigApplicationContext(); TestPropertyValues.of(env).applyTo(parent); parent.register(UtilAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, EnvironmentKnobbler.class, ConsulDiscoveryClientConfigServiceBootstrapConfiguration.class, DiscoveryClientConfigServiceBootstrapConfiguration.class, ConfigClientProperties.class); parent.refresh(); this.context = new AnnotationConfigApplicationContext(); this.context.setParent(parent); this.context.register(PropertyPlaceholderAutoConfiguration.class, ConsulConfigServerAutoConfiguration.class, ConsulAutoConfiguration.class, ConsulDiscoveryClientConfiguration.class); this.context.refresh(); }
private void load(Class<?>[] configs, String... environment) { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(); applicationContext .register(WebDriverAutoConfiguration.class); if (configs.length > 0) { applicationContext.register(configs); } TestPropertyValues.of(environment) .applyTo(applicationContext); applicationContext.refresh(); this.context = applicationContext; }
@Test public void orderIsUnchangedWhenThereAreMultipleResourceServerConfigurations() { this.context = new AnnotationConfigWebApplicationContext(); this.context.register(DoubleResourceConfiguration.class); TestPropertyValues.of("security.oauth2.resource.tokenInfoUri:http://example.com", "security.oauth2.client.clientId=acme").applyTo(this.context); this.context.refresh(); assertThat(this.context .getBean("adminResources", ResourceServerConfiguration.class).getOrder()) .isEqualTo(3); assertThat(this.context .getBean("otherResources", ResourceServerConfiguration.class).getOrder()) .isEqualTo(4); }
@Test public void useRemoteTokenServices() { TestPropertyValues.of("security.oauth2.resource.tokenInfoUri:http://example.com") .applyTo(this.environment); this.context = new SpringApplicationBuilder(ResourceConfiguration.class) .environment(this.environment).web(WebApplicationType.NONE).run(); RemoteTokenServices services = this.context.getBean(RemoteTokenServices.class); assertThat(services).isNotNull(); }
@Test public void switchToUserInfo() { TestPropertyValues.of("security.oauth2.resource.userInfoUri:http://example.com") .applyTo(this.environment); this.context = new SpringApplicationBuilder(ResourceConfiguration.class) .environment(this.environment).web(WebApplicationType.NONE).run(); UserInfoTokenServices services = this.context .getBean(UserInfoTokenServices.class); assertThat(services).isNotNull(); }
@Test public void userInfoWithAuthorities() { TestPropertyValues.of("security.oauth2.resource.userInfoUri:http://example.com") .applyTo(this.environment); this.context = new SpringApplicationBuilder(AuthoritiesConfiguration.class) .environment(this.environment).web(WebApplicationType.NONE).run(); UserInfoTokenServices services = this.context .getBean(UserInfoTokenServices.class); assertThat(services).isNotNull(); assertThat(services).extracting("authoritiesExtractor") .containsExactly(this.context.getBean(AuthoritiesExtractor.class)); }