Reformat.

This commit is contained in:
Olga Maciaszek-Sharma
2020-09-17 13:41:44 +02:00
committed by Spencer Gibb
parent 034768bc8f
commit 00668991a4
259 changed files with 1955 additions and 3380 deletions

View File

@@ -37,35 +37,29 @@ import static org.assertj.core.api.BDDAssertions.then;
// TODO: super slow. Port to @SpringBootTest
public class LifecycleMvcAutoConfigurationTests {
private static ConfigurableApplicationContext getApplicationContext(
Class<?> configuration, String... properties) {
private static ConfigurableApplicationContext getApplicationContext(Class<?> configuration, String... properties) {
List<String> defaultProperties = Lists.newArrayList(properties);
defaultProperties.add("server.port=0");
defaultProperties.add("spring.jmx.default-domain=${random.uuid}");
return new SpringApplicationBuilder(configuration)
.properties(defaultProperties.toArray(new String[] {})).run();
return new SpringApplicationBuilder(configuration).properties(defaultProperties.toArray(new String[] {})).run();
}
@Test
public void environmentWebEndpointExtensionDisabled() {
beanNotCreated("writableEnvironmentEndpointWebExtension",
"management.endpoint.env.enabled=false");
beanNotCreated("writableEnvironmentEndpointWebExtension", "management.endpoint.env.enabled=false");
}
@Test
public void environmentWebEndpointExtensionGloballyDisabled() {
beanNotCreated("writableEnvironmentEndpointWebExtension",
"management.endpoints.enabled-by-default=false");
beanNotCreated("writableEnvironmentEndpointWebExtension", "management.endpoints.enabled-by-default=false");
}
@Test
public void environmentWebEndpointExtensionEnabled() {
beanCreated("writableEnvironmentEndpointWebExtension",
"management.endpoint.env.enabled=true",
"management.endpoint.env.post.enabled=true",
"management.endpoints.web.exposure.include=env");
beanCreated("writableEnvironmentEndpointWebExtension", "management.endpoint.env.enabled=true",
"management.endpoint.env.post.enabled=true", "management.endpoints.web.exposure.include=env");
}
// restartEndpoint
@@ -81,9 +75,8 @@ public class LifecycleMvcAutoConfigurationTests {
@Test
public void restartEndpointEnabled() {
beanCreatedAndEndpointEnabled("restartEndpoint", RestartEndpoint.class,
RestartEndpoint::restart, "management.endpoint.restart.enabled=true",
"management.endpoints.web.exposure.include=restart");
beanCreatedAndEndpointEnabled("restartEndpoint", RestartEndpoint.class, RestartEndpoint::restart,
"management.endpoint.restart.enabled=true", "management.endpoints.web.exposure.include=restart");
}
// pauseEndpoint
@@ -105,26 +98,22 @@ public class LifecycleMvcAutoConfigurationTests {
@Test
public void pauseEndpointEnabled() {
beanCreatedAndEndpointEnabled("pauseEndpoint",
RestartEndpoint.PauseEndpoint.class, RestartEndpoint.PauseEndpoint::pause,
"management.endpoint.restart.enabled=true",
"management.endpoints.web.exposure.include=restart,pause",
"management.endpoint.pause.enabled=true");
beanCreatedAndEndpointEnabled("pauseEndpoint", RestartEndpoint.PauseEndpoint.class,
RestartEndpoint.PauseEndpoint::pause, "management.endpoint.restart.enabled=true",
"management.endpoints.web.exposure.include=restart,pause", "management.endpoint.pause.enabled=true");
}
// resumeEndpoint
@Test
public void resumeEndpointDisabled() {
beanNotCreated("resumeEndpoint", "management.endpoint.restart.enabled=true",
"management.endpoints.web.exposure.include=restart",
"management.endpoint.resume.enabled=false");
"management.endpoints.web.exposure.include=restart", "management.endpoint.resume.enabled=false");
}
@Test
public void resumeEndpointRestartDisabled() {
beanNotCreated("resumeEndpoint", "management.endpoint.restart.enabled=false",
"management.endpoints.web.exposure.include=resume",
"management.endpoint.resume.enabled=true");
"management.endpoints.web.exposure.include=resume", "management.endpoint.resume.enabled=true");
}
@Test
@@ -134,37 +123,28 @@ public class LifecycleMvcAutoConfigurationTests {
@Test
public void resumeEndpointEnabled() {
beanCreatedAndEndpointEnabled("resumeEndpoint",
RestartEndpoint.ResumeEndpoint.class,
RestartEndpoint.ResumeEndpoint::resume,
"management.endpoint.restart.enabled=true",
"management.endpoint.resume.enabled=true",
"management.endpoints.web.exposure.include=restart,resume");
beanCreatedAndEndpointEnabled("resumeEndpoint", RestartEndpoint.ResumeEndpoint.class,
RestartEndpoint.ResumeEndpoint::resume, "management.endpoint.restart.enabled=true",
"management.endpoint.resume.enabled=true", "management.endpoints.web.exposure.include=restart,resume");
}
private void beanNotCreated(String beanName, String... contextProperties) {
try (ConfigurableApplicationContext context = getApplicationContext(Config.class,
contextProperties)) {
then(context.containsBeanDefinition(beanName))
.as("%s bean was created", beanName).isFalse();
try (ConfigurableApplicationContext context = getApplicationContext(Config.class, contextProperties)) {
then(context.containsBeanDefinition(beanName)).as("%s bean was created", beanName).isFalse();
}
}
private void beanCreated(String beanName, String... contextProperties) {
try (ConfigurableApplicationContext context = getApplicationContext(Config.class,
contextProperties)) {
then(context.containsBeanDefinition(beanName))
.as("%s bean was not created", beanName).isTrue();
try (ConfigurableApplicationContext context = getApplicationContext(Config.class, contextProperties)) {
then(context.containsBeanDefinition(beanName)).as("%s bean was not created", beanName).isTrue();
}
}
@SuppressWarnings("unchecked")
private <T> void beanCreatedAndEndpointEnabled(String beanName, Class<T> type,
Function<T, Object> function, String... properties) {
try (ConfigurableApplicationContext context = getApplicationContext(Config.class,
properties)) {
then(context.containsBeanDefinition(beanName))
.as("%s bean was not created", beanName).isTrue();
private <T> void beanCreatedAndEndpointEnabled(String beanName, Class<T> type, Function<T, Object> function,
String... properties) {
try (ConfigurableApplicationContext context = getApplicationContext(Config.class, properties)) {
then(context.containsBeanDefinition(beanName)).as("%s bean was not created", beanName).isTrue();
Object endpoint = context.getBean(beanName, type);
Object result = function.apply((T) endpoint);

View File

@@ -34,24 +34,19 @@ import static org.assertj.core.api.BDDAssertions.then;
* @author Spencer Gibb
*/
@RunWith(ModifiedClassPathRunner.class)
@ClassPathExclusions({ "spring-boot-actuator-*.jar",
"spring-boot-starter-actuator-*.jar" })
@ClassPathExclusions({ "spring-boot-actuator-*.jar", "spring-boot-starter-actuator-*.jar" })
public class RefreshAutoConfigurationClassPathTests {
private static ConfigurableApplicationContext getApplicationContext(
Class<?> configuration, String... properties) {
return new SpringApplicationBuilder(configuration).web(WebApplicationType.NONE)
.properties(properties).run();
private static ConfigurableApplicationContext getApplicationContext(Class<?> configuration, String... properties) {
return new SpringApplicationBuilder(configuration).web(WebApplicationType.NONE).properties(properties).run();
}
@Test
public void refreshEventListenerCreated() {
try (ConfigurableApplicationContext context = getApplicationContext(
Config.class)) {
then(context.getBeansOfType(RefreshEventListener.class))
.as("RefreshEventListeners not created").isNotEmpty();
then(context.containsBean("refreshEndpoint")).as("refreshEndpoint created")
.isFalse();
try (ConfigurableApplicationContext context = getApplicationContext(Config.class)) {
then(context.getBeansOfType(RefreshEventListener.class)).as("RefreshEventListeners not created")
.isNotEmpty();
then(context.containsBean("refreshEndpoint")).as("refreshEndpoint created").isFalse();
}
}

View File

@@ -35,26 +35,23 @@ import static org.assertj.core.api.BDDAssertions.then;
* @author Spencer Gibb
*/
@RunWith(ModifiedClassPathRunner.class)
@ClassPathExclusions({ "spring-boot-actuator-autoconfigure-*.jar",
"spring-boot-starter-actuator-*.jar" })
@ClassPathExclusions({ "spring-boot-actuator-autoconfigure-*.jar", "spring-boot-starter-actuator-*.jar" })
public class RefreshAutoConfigurationMoreClassPathTests {
@Rule
public OutputCaptureRule outputCapture = new OutputCaptureRule();
private static ConfigurableApplicationContext getApplicationContext(
Class<?> configuration, String... properties) {
return new SpringApplicationBuilder(configuration).web(WebApplicationType.NONE)
.properties(properties).run();
private static ConfigurableApplicationContext getApplicationContext(Class<?> configuration, String... properties) {
return new SpringApplicationBuilder(configuration).web(WebApplicationType.NONE).properties(properties).run();
}
@Test
public void unknownClassProtected() {
try (ConfigurableApplicationContext context = getApplicationContext(Config.class,
"debug=true")) {
try (ConfigurableApplicationContext context = getApplicationContext(Config.class, "debug=true")) {
String output = this.outputCapture.toString();
then(output).doesNotContain("Failed to introspect annotations on "
+ "[class org.springframework.cloud.autoconfigure.RefreshEndpointAutoConfiguration")
then(output)
.doesNotContain("Failed to introspect annotations on "
+ "[class org.springframework.cloud.autoconfigure.RefreshEndpointAutoConfiguration")
.doesNotContain("TypeNotPresentExceptionProxy");
}
}

View File

@@ -43,16 +43,15 @@ public class RefreshAutoConfigurationTests {
@Rule
public OutputCaptureRule output = new OutputCaptureRule();
private static ConfigurableApplicationContext getApplicationContext(
WebApplicationType type, Class<?> configuration, String... properties) {
return new SpringApplicationBuilder(configuration).web(type)
.properties(properties).properties("server.port=0").run();
private static ConfigurableApplicationContext getApplicationContext(WebApplicationType type, Class<?> configuration,
String... properties) {
return new SpringApplicationBuilder(configuration).web(type).properties(properties).properties("server.port=0")
.run();
}
@Test
public void noWarnings() {
try (ConfigurableApplicationContext context = getApplicationContext(
WebApplicationType.NONE, Config.class)) {
try (ConfigurableApplicationContext context = getApplicationContext(WebApplicationType.NONE, Config.class)) {
then(context.containsBean("refreshScope")).isTrue();
then(this.output.toString()).doesNotContain("WARN");
}
@@ -60,8 +59,7 @@ public class RefreshAutoConfigurationTests {
@Test
public void disabled() {
try (ConfigurableApplicationContext context = getApplicationContext(
WebApplicationType.SERVLET, Config.class,
try (ConfigurableApplicationContext context = getApplicationContext(WebApplicationType.SERVLET, Config.class,
"spring.cloud.refresh.enabled:false")) {
then(context.containsBean("refreshScope")).isFalse();
}
@@ -69,10 +67,8 @@ public class RefreshAutoConfigurationTests {
@Test
public void refreshables() {
try (ConfigurableApplicationContext context = getApplicationContext(
WebApplicationType.NONE, Config.class, "config.foo=bar",
"spring.cloud.refresh.refreshable:"
+ SealedConfigProps.class.getName())) {
try (ConfigurableApplicationContext context = getApplicationContext(WebApplicationType.NONE, Config.class,
"config.foo=bar", "spring.cloud.refresh.refreshable:" + SealedConfigProps.class.getName())) {
context.getBean(SealedConfigProps.class);
context.getBean(ContextRefresher.class).refresh();
}
@@ -80,10 +76,9 @@ public class RefreshAutoConfigurationTests {
@Test
public void extraRefreshables() {
try (ConfigurableApplicationContext context = getApplicationContext(
WebApplicationType.NONE, Config.class, "sealedconfig.foo=bar",
"spring.cloud.refresh.extra-refreshable:"
+ SealedConfigProps.class.getName())) {
try (ConfigurableApplicationContext context = getApplicationContext(WebApplicationType.NONE, Config.class,
"sealedconfig.foo=bar",
"spring.cloud.refresh.extra-refreshable:" + SealedConfigProps.class.getName())) {
context.getBean(SealedConfigProps.class);
context.getBean(ContextRefresher.class).refresh();
}
@@ -91,15 +86,12 @@ public class RefreshAutoConfigurationTests {
@Test
public void neverRefreshable() {
try (ConfigurableApplicationContext context = getApplicationContext(
WebApplicationType.NONE, Config.class, "countingconfig.foo=bar",
"spring.cloud.refresh.never-refreshable:"
+ CountingConfigProps.class.getName())) {
try (ConfigurableApplicationContext context = getApplicationContext(WebApplicationType.NONE, Config.class,
"countingconfig.foo=bar",
"spring.cloud.refresh.never-refreshable:" + CountingConfigProps.class.getName())) {
CountingConfigProps configProps = context.getBean(CountingConfigProps.class);
context.getBean(ContextRefresher.class).refresh();
assertThat(configProps.count)
.as("config props was rebound when it should not have been")
.hasValue(1);
assertThat(configProps.count).as("config props was rebound when it should not have been").hasValue(1);
}
}

View File

@@ -30,8 +30,7 @@ import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.BDDAssertions.then;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class,
properties = "spring.cloud.bootstrap.enabled:false")
@SpringBootTest(classes = Application.class, properties = "spring.cloud.bootstrap.enabled:false")
public class BootstrapDisabledAutoConfigurationIntegrationTests {
@Autowired

View File

@@ -31,8 +31,8 @@ import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.BDDAssertions.then;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, properties = { "encrypt.key:deadbeef",
"spring.config.use-legacy-processing=true" })
@SpringBootTest(classes = Application.class,
properties = { "encrypt.key:deadbeef", "spring.config.use-legacy-processing=true" })
@ActiveProfiles("encrypt")
public class BootstrapOrderingAutoConfigurationIntegrationTests {
@@ -41,9 +41,8 @@ public class BootstrapOrderingAutoConfigurationIntegrationTests {
@Test
public void bootstrapPropertiesExist() {
then(this.environment.getPropertySources()
.contains("applicationConfig: [classpath:/bootstrap.properties]"))
.isTrue();
then(this.environment.getPropertySources().contains("applicationConfig: [classpath:/bootstrap.properties]"))
.isTrue();
}
@Test

View File

@@ -42,8 +42,7 @@ import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class,
properties = { "spring.config.use-legacy-processing=true",
"spring.cloud.bootstrap.name:ordering" })
properties = { "spring.config.use-legacy-processing=true", "spring.cloud.bootstrap.name:ordering" })
public class BootstrapOrderingCustomOverrideSystemPropertiesIntegrationTests {
@Autowired
@@ -52,12 +51,9 @@ public class BootstrapOrderingCustomOverrideSystemPropertiesIntegrationTests {
@Test
public void orderingIsCorrect() {
MutablePropertySources propertySources = environment.getPropertySources();
PropertySource<?> test1 = propertySources
.get("bootstrapProperties-testBootstrap1");
PropertySource<?> test2 = propertySources
.get("bootstrapProperties-testBootstrap2");
PropertySource<?> test3 = propertySources
.get("bootstrapProperties-testBootstrap3");
PropertySource<?> test1 = propertySources.get("bootstrapProperties-testBootstrap1");
PropertySource<?> test2 = propertySources.get("bootstrapProperties-testBootstrap2");
PropertySource<?> test3 = propertySources.get("bootstrapProperties-testBootstrap3");
int index1 = propertySources.precedenceOf(test1);
int index2 = propertySources.precedenceOf(test2);
int index3 = propertySources.precedenceOf(test3);
@@ -83,10 +79,8 @@ public class BootstrapOrderingCustomOverrideSystemPropertiesIntegrationTests {
@Override
public Collection<PropertySource<?>> locateCollection(Environment environment) {
ArrayList<PropertySource<?>> sources = new ArrayList<>();
sources.add(new MapPropertySource("testBootstrap1",
singletonMap("key1", "value1")));
sources.add(new MapPropertySource("testBootstrap2",
singletonMap("key2", "value2")));
sources.add(new MapPropertySource("testBootstrap1", singletonMap("key1", "value1")));
sources.add(new MapPropertySource("testBootstrap2", singletonMap("key2", "value2")));
Map<String, Object> map = new HashMap<>();
map.put("key3", "value3");
map.put("spring.cloud.config.override-system-properties", "false");

View File

@@ -39,9 +39,8 @@ import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.BDDAssertions.then;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class,
properties = { "encrypt.key:deadbeef", "spring.cloud.bootstrap.name:custom",
"spring.config.use-legacy-processing=true" })
@SpringBootTest(classes = Application.class, properties = { "encrypt.key:deadbeef",
"spring.cloud.bootstrap.name:custom", "spring.config.use-legacy-processing=true" })
@ActiveProfiles("encrypt")
public class BootstrapOrderingCustomPropertySourceIntegrationTests {
@@ -50,8 +49,8 @@ public class BootstrapOrderingCustomPropertySourceIntegrationTests {
@Test
public void bootstrapPropertiesExist() {
then(this.environment.getPropertySources()
.contains("applicationConfig: [classpath:/custom.properties]")).isTrue();
then(this.environment.getPropertySources().contains("applicationConfig: [classpath:/custom.properties]"))
.isTrue();
}
@Test
@@ -69,9 +68,8 @@ public class BootstrapOrderingCustomPropertySourceIntegrationTests {
// This is added to bootstrap context as a source in bootstrap.properties
protected static class PropertySourceConfiguration implements PropertySourceLocator {
public static Map<String, Object> MAP = new HashMap<String, Object>(
Collections.<String, Object>singletonMap("custom.foo",
"{cipher}6154ca04d4bb6144d672c4e3d750b5147116dd381946d51fa44f8bc25dc256f4"));
public static Map<String, Object> MAP = new HashMap<String, Object>(Collections.<String, Object>singletonMap(
"custom.foo", "{cipher}6154ca04d4bb6144d672c4e3d750b5147116dd381946d51fa44f8bc25dc256f4"));
@Override
public PropertySource<?> locate(Environment environment) {

View File

@@ -32,8 +32,7 @@ import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.BDDAssertions.then;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class,
properties = "spring.cloud.bootstrap.name:json")
@SpringBootTest(classes = Application.class, properties = "spring.cloud.bootstrap.name:json")
public class BootstrapOrderingSpringApplicationJsonIntegrationTests {
@Autowired

View File

@@ -29,8 +29,7 @@ import static org.assertj.core.api.BDDAssertions.then;
import static org.springframework.cloud.bootstrap.TestHigherPriorityBootstrapConfiguration.firstToBeCreated;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class,
properties = "spring.config.use-legacy-processing=true")
@SpringBootTest(classes = Application.class, properties = "spring.config.use-legacy-processing=true")
public class BootstrapSourcesOrderingTests {
@Test

View File

@@ -45,8 +45,7 @@ public class MessageSourceConfigurationTests {
@Test
public void loadsMessage() {
then(this.messageSource.getMessage("hello.message", null, Locale.getDefault()))
.isEqualTo("Hello World!");
then(this.messageSource.getMessage("hello.message", null, Locale.getDefault())).isEqualTo("Hello World!");
}
@Configuration(proxyBeanMethods = false)

View File

@@ -48,8 +48,7 @@ public class TestBootstrapConfiguration {
@Bean
@Qualifier("foo-during-bootstrap")
public String fooDuringBootstrap(ConfigurableEnvironment environment,
ApplicationEventPublisher publisher) {
public String fooDuringBootstrap(ConfigurableEnvironment environment, ApplicationEventPublisher publisher) {
String property = environment.getProperty("test.bootstrap.foo", "undefined");
if (fooSightings != null) {
@@ -66,11 +65,9 @@ public class TestBootstrapConfiguration {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
ConfigurableEnvironment environment = applicationContext.getEnvironment();
environment.getPropertySources()
.addLast(new MapPropertySource("customProperties",
Collections.<String, Object>singletonMap("custom.foo",
environment.resolvePlaceholders(
"${spring.application.name:bar}"))));
environment.getPropertySources().addLast(
new MapPropertySource("customProperties", Collections.<String, Object>singletonMap("custom.foo",
environment.resolvePlaceholders("${spring.application.name:bar}"))));
}
};

View File

@@ -33,8 +33,7 @@ public class TestHigherPriorityBootstrapConfiguration {
public TestHigherPriorityBootstrapConfiguration() {
count.incrementAndGet();
firstToBeCreated.compareAndSet(null,
TestHigherPriorityBootstrapConfiguration.class);
firstToBeCreated.compareAndSet(null, TestHigherPriorityBootstrapConfiguration.class);
}
}

View File

@@ -82,57 +82,46 @@ public class BootstrapConfigurationTests {
public void pickupOnlyExternalBootstrapProperties() {
String externalPropertiesPath = getExternalProperties();
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
.sources(BareConfiguration.class)
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE).sources(BareConfiguration.class)
.properties("spring.cloud.bootstrap.location=" + externalPropertiesPath,
"spring.config.use-legacy-processing=true")
.run();
then(this.context.getEnvironment().getProperty("info.name"))
.isEqualTo("externalPropertiesInfoName");
then(this.context.getEnvironment().getProperty("info.name")).isEqualTo("externalPropertiesInfoName");
then(this.context.getEnvironment().getProperty("info.desc")).isNull();
then(this.context.getEnvironment().getPropertySources().contains(
PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME
+ "-testBootstrap")).isTrue();
then(this.context.getEnvironment().getPropertySources()
.contains(PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME + "-testBootstrap"))
.isTrue();
}
@Test
public void pickupAdditionalExternalBootstrapProperties() {
String externalPropertiesPath = getExternalProperties();
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
.sources(BareConfiguration.class)
.properties(
"spring.cloud.bootstrap.additional-location="
+ externalPropertiesPath,
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE).sources(BareConfiguration.class)
.properties("spring.cloud.bootstrap.additional-location=" + externalPropertiesPath,
"spring.config.use-legacy-processing=true")
.run();
then(this.context.getEnvironment().getProperty("info.name"))
.isEqualTo("externalPropertiesInfoName");
then(this.context.getEnvironment().getProperty("info.desc"))
.isEqualTo("defaultPropertiesInfoDesc");
then(this.context.getEnvironment().getPropertySources().contains(
PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME
+ "-testBootstrap")).isTrue();
then(this.context.getEnvironment().getProperty("info.name")).isEqualTo("externalPropertiesInfoName");
then(this.context.getEnvironment().getProperty("info.desc")).isEqualTo("defaultPropertiesInfoDesc");
then(this.context.getEnvironment().getPropertySources()
.contains(PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME + "-testBootstrap"))
.isTrue();
}
@Test
public void bootstrapPropertiesAvailableInInitializer() {
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
.properties("spring.config.use-legacy-processing=true")
.sources(BareConfiguration.class).initializers(
new ApplicationContextInitializer<ConfigurableApplicationContext>() {
@Override
public void initialize(
ConfigurableApplicationContext applicationContext) {
// This property is defined in bootstrap.properties
then(applicationContext.getEnvironment()
.getProperty("info.name")).isEqualTo("child");
}
})
.run();
then(this.context.getEnvironment().getPropertySources().contains(
PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME
+ "-testBootstrap")).isTrue();
.properties("spring.config.use-legacy-processing=true").sources(BareConfiguration.class)
.initializers(new ApplicationContextInitializer<ConfigurableApplicationContext>() {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
// This property is defined in bootstrap.properties
then(applicationContext.getEnvironment().getProperty("info.name")).isEqualTo("child");
}
}).run();
then(this.context.getEnvironment().getPropertySources()
.contains(PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME + "-testBootstrap"))
.isTrue();
}
/**
@@ -149,12 +138,11 @@ public class BootstrapConfigurationTests {
public void picksUpAdditionalPropertySource() {
PropertySourceConfiguration.MAP.put("bootstrap.foo", "bar");
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
.properties("spring.config.use-legacy-processing=true")
.sources(BareConfiguration.class).run();
.properties("spring.config.use-legacy-processing=true").sources(BareConfiguration.class).run();
then(this.context.getEnvironment().getProperty("bootstrap.foo")).isEqualTo("bar");
then(this.context.getEnvironment().getPropertySources().contains(
PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME
+ "-testBootstrap")).isTrue();
then(this.context.getEnvironment().getPropertySources()
.contains(PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME + "-testBootstrap"))
.isTrue();
}
@Test
@@ -162,8 +150,7 @@ public class BootstrapConfigurationTests {
System.setProperty("expected.fail", "true");
this.expected.expectMessage("Planned");
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
.properties("spring.config.use-legacy-processing=true")
.sources(BareConfiguration.class).run();
.properties("spring.config.use-legacy-processing=true").sources(BareConfiguration.class).run();
}
@Test
@@ -171,52 +158,43 @@ public class BootstrapConfigurationTests {
PropertySourceConfiguration.MAP.put("bootstrap.foo", "bar");
System.setProperty("bootstrap.foo", "system");
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
.properties("spring.config.use-legacy-processing=true")
.sources(BareConfiguration.class).run();
.properties("spring.config.use-legacy-processing=true").sources(BareConfiguration.class).run();
then(this.context.getEnvironment().getProperty("bootstrap.foo")).isEqualTo("bar");
}
@Test
public void systemPropertyOverrideFalse() {
PropertySourceConfiguration.MAP.put("bootstrap.foo", "bar");
PropertySourceConfiguration.MAP
.put("spring.cloud.config.overrideSystemProperties", "false");
PropertySourceConfiguration.MAP.put("spring.cloud.config.overrideSystemProperties", "false");
System.setProperty("bootstrap.foo", "system");
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
.properties("spring.config.use-legacy-processing=true")
.sources(BareConfiguration.class).run();
then(this.context.getEnvironment().getProperty("bootstrap.foo"))
.isEqualTo("system");
.properties("spring.config.use-legacy-processing=true").sources(BareConfiguration.class).run();
then(this.context.getEnvironment().getProperty("bootstrap.foo")).isEqualTo("system");
}
@Test
public void systemPropertyOverrideWhenOverrideDisallowed() {
PropertySourceConfiguration.MAP.put("bootstrap.foo", "bar");
PropertySourceConfiguration.MAP
.put("spring.cloud.config.overrideSystemProperties", "false");
PropertySourceConfiguration.MAP.put("spring.cloud.config.overrideSystemProperties", "false");
// If spring.cloud.config.allowOverride=false is in the remote property sources
// with sufficiently high priority it always wins. Admins can enforce it by adding
// their own remote property source.
PropertySourceConfiguration.MAP.put("spring.cloud.config.allowOverride", "false");
System.setProperty("bootstrap.foo", "system");
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
.properties("spring.config.use-legacy-processing=true")
.sources(BareConfiguration.class).run();
.properties("spring.config.use-legacy-processing=true").sources(BareConfiguration.class).run();
then(this.context.getEnvironment().getProperty("bootstrap.foo")).isEqualTo("bar");
}
@Test
public void systemPropertyOverrideFalseWhenOverrideAllowed() {
PropertySourceConfiguration.MAP.put("bootstrap.foo", "bar");
PropertySourceConfiguration.MAP
.put("spring.cloud.config.overrideSystemProperties", "false");
PropertySourceConfiguration.MAP.put("spring.cloud.config.overrideSystemProperties", "false");
PropertySourceConfiguration.MAP.put("spring.cloud.config.allowOverride", "true");
System.setProperty("bootstrap.foo", "system");
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
.properties("spring.config.use-legacy-processing=true")
.sources(BareConfiguration.class).run();
then(this.context.getEnvironment().getProperty("bootstrap.foo"))
.isEqualTo("system");
.properties("spring.config.use-legacy-processing=true").sources(BareConfiguration.class).run();
then(this.context.getEnvironment().getProperty("bootstrap.foo")).isEqualTo("system");
}
@Test
@@ -225,68 +203,56 @@ public class BootstrapConfigurationTests {
PropertySourceConfiguration.MAP.put("spring.cloud.config.overrideNone", "true");
PropertySourceConfiguration.MAP.put("spring.cloud.config.allowOverride", "true");
ConfigurableEnvironment environment = new StandardEnvironment();
environment.getPropertySources().addLast(new MapPropertySource("last",
Collections.<String, Object>singletonMap("bootstrap.foo", "splat")));
environment.getPropertySources().addLast(
new MapPropertySource("last", Collections.<String, Object>singletonMap("bootstrap.foo", "splat")));
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
.properties("spring.config.use-legacy-processing=true")
.environment(environment).sources(BareConfiguration.class).run();
then(this.context.getEnvironment().getProperty("bootstrap.foo"))
.isEqualTo("splat");
.properties("spring.config.use-legacy-processing=true").environment(environment)
.sources(BareConfiguration.class).run();
then(this.context.getEnvironment().getProperty("bootstrap.foo")).isEqualTo("splat");
}
@Test
public void applicationNameInBootstrapAndMain() {
System.setProperty("expected.name", "main");
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
.properties("spring.cloud.bootstrap.name:other",
"spring.config.use-legacy-processing=true",
"spring.config.name:plain")
this.context = new SpringApplicationBuilder()
.web(WebApplicationType.NONE).properties("spring.cloud.bootstrap.name:other",
"spring.config.use-legacy-processing=true", "spring.config.name:plain")
.sources(BareConfiguration.class).run();
then(this.context.getEnvironment().getProperty("spring.application.name"))
.isEqualTo("app");
then(this.context.getEnvironment().getProperty("spring.application.name")).isEqualTo("app");
// The parent is called "main" because spring.application.name is specified in
// other.properties (the bootstrap properties)
then(this.context.getParent().getEnvironment()
.getProperty("spring.application.name")).isEqualTo("main");
then(this.context.getParent().getEnvironment().getProperty("spring.application.name")).isEqualTo("main");
// The bootstrap context has the same "bootstrap" property source
then(((ConfigurableEnvironment) this.context.getParent().getEnvironment())
.getPropertySources().get("bootstrap"))
.isEqualTo(this.context.getEnvironment().getPropertySources()
.get("bootstrap"));
then(((ConfigurableEnvironment) this.context.getParent().getEnvironment()).getPropertySources()
.get("bootstrap")).isEqualTo(this.context.getEnvironment().getPropertySources().get("bootstrap"));
then(this.context.getId()).isEqualTo("main-1");
}
@Test
public void applicationNameNotInBootstrap() {
System.setProperty("expected.name", "main");
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
.properties("spring.cloud.bootstrap.name:application",
"spring.config.use-legacy-processing=true",
"spring.config.name:other")
this.context = new SpringApplicationBuilder()
.web(WebApplicationType.NONE).properties("spring.cloud.bootstrap.name:application",
"spring.config.use-legacy-processing=true", "spring.config.name:other")
.sources(BareConfiguration.class).run();
then(this.context.getEnvironment().getProperty("spring.application.name"))
.isEqualTo("main");
then(this.context.getEnvironment().getProperty("spring.application.name")).isEqualTo("main");
// The parent has no name because spring.application.name is not
// defined in the bootstrap properties
then(this.context.getParent().getEnvironment()
.getProperty("spring.application.name")).isEqualTo(null);
then(this.context.getParent().getEnvironment().getProperty("spring.application.name")).isEqualTo(null);
}
@Test
public void applicationNameOnlyInBootstrap() {
System.setProperty("expected.name", "main");
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
.properties("spring.cloud.bootstrap.name:other",
"spring.config.use-legacy-processing=true")
.properties("spring.cloud.bootstrap.name:other", "spring.config.use-legacy-processing=true")
.sources(BareConfiguration.class).run();
// The main context is called "main" because spring.application.name is specified
// in other.properties (and not in the main config file)
then(this.context.getEnvironment().getProperty("spring.application.name"))
.isEqualTo("main");
then(this.context.getEnvironment().getProperty("spring.application.name")).isEqualTo("main");
// The parent is called "main" because spring.application.name is specified in
// other.properties (the bootstrap properties this time)
then(this.context.getParent().getEnvironment()
.getProperty("spring.application.name")).isEqualTo("main");
then(this.context.getParent().getEnvironment().getProperty("spring.application.name")).isEqualTo("main");
then(this.context.getId()).isEqualTo("main-1");
}
@@ -294,17 +260,13 @@ public class BootstrapConfigurationTests {
public void environmentEnrichedOnceWhenSharedWithChildContext() {
PropertySourceConfiguration.MAP.put("bootstrap.foo", "bar");
this.context = new SpringApplicationBuilder().sources(BareConfiguration.class)
.properties("spring.config.use-legacy-processing=true")
.environment(new StandardEnvironment()).child(BareConfiguration.class)
.web(WebApplicationType.NONE).run();
.properties("spring.config.use-legacy-processing=true").environment(new StandardEnvironment())
.child(BareConfiguration.class).web(WebApplicationType.NONE).run();
then(this.context.getEnvironment().getProperty("bootstrap.foo")).isEqualTo("bar");
then(this.context.getParent().getEnvironment())
.isEqualTo(this.context.getEnvironment());
MutablePropertySources sources = this.context.getEnvironment()
.getPropertySources();
then(this.context.getParent().getEnvironment()).isEqualTo(this.context.getEnvironment());
MutablePropertySources sources = this.context.getEnvironment().getPropertySources();
PropertySource<?> bootstrap = sources
.get(PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME
+ "-testBootstrap");
.get(PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME + "-testBootstrap");
then(bootstrap).isNotNull();
then(sources.precedenceOf(bootstrap)).isEqualTo(0);
}
@@ -314,8 +276,8 @@ public class BootstrapConfigurationTests {
TestHigherPriorityBootstrapConfiguration.count.set(0);
PropertySourceConfiguration.MAP.put("bootstrap.foo", "bar");
this.context = new SpringApplicationBuilder().sources(BareConfiguration.class)
.properties("spring.config.use-legacy-processing=true")
.child(BareConfiguration.class).web(WebApplicationType.NONE).run();
.properties("spring.config.use-legacy-processing=true").child(BareConfiguration.class)
.web(WebApplicationType.NONE).run();
then(TestHigherPriorityBootstrapConfiguration.count.get()).isEqualTo(1);
then(this.context.getParent()).isNotNull();
then(this.context.getParent().getParent().getId()).isEqualTo("bootstrap");
@@ -326,11 +288,10 @@ public class BootstrapConfigurationTests {
@Test
public void listOverride() {
this.context = new SpringApplicationBuilder().sources(BareConfiguration.class)
.properties("spring.config.use-legacy-processing=true")
.child(BareConfiguration.class).web(WebApplicationType.NONE).run();
.properties("spring.config.use-legacy-processing=true").child(BareConfiguration.class)
.web(WebApplicationType.NONE).run();
ListProperties listProperties = new ListProperties();
Binder.get(this.context.getEnvironment()).bind("list",
Bindable.ofInstance(listProperties));
Binder.get(this.context.getEnvironment()).bind("list", Bindable.ofInstance(listProperties));
then(listProperties.getFoo().size()).isEqualTo(1);
then(listProperties.getFoo().get(0)).isEqualTo("hello world");
}
@@ -340,47 +301,38 @@ public class BootstrapConfigurationTests {
TestHigherPriorityBootstrapConfiguration.count.set(0);
PropertySourceConfiguration.MAP.put("bootstrap.foo", "bar");
SpringApplicationBuilder builder = new SpringApplicationBuilder()
.properties("spring.config.use-legacy-processing=true")
.sources(BareConfiguration.class);
this.sibling = builder.child(BareConfiguration.class)
.properties("spring.application.name=sibling")
.properties("spring.config.use-legacy-processing=true").sources(BareConfiguration.class);
this.sibling = builder.child(BareConfiguration.class).properties("spring.application.name=sibling")
.web(WebApplicationType.NONE).run();
this.context = builder.child(BareConfiguration.class)
.properties("spring.application.name=context")
this.context = builder.child(BareConfiguration.class).properties("spring.application.name=context")
.web(WebApplicationType.NONE).run();
then(TestHigherPriorityBootstrapConfiguration.count.get()).isEqualTo(1);
then(this.context.getParent()).isNotNull();
then(this.context.getParent().getParent().getId()).isEqualTo("bootstrap");
then(this.context.getParent().getParent().getParent()).isNull();
then(this.context.getEnvironment().getProperty("custom.foo"))
.isEqualTo("context");
then(this.context.getEnvironment().getProperty("spring.application.name"))
.isEqualTo("context");
then(this.context.getEnvironment().getProperty("custom.foo")).isEqualTo("context");
then(this.context.getEnvironment().getProperty("spring.application.name")).isEqualTo("context");
then(this.sibling.getParent()).isNotNull();
then(this.sibling.getParent().getParent().getId()).isEqualTo("bootstrap");
then(this.sibling.getParent().getParent().getParent()).isNull();
then(this.sibling.getEnvironment().getProperty("custom.foo"))
.isEqualTo("sibling");
then(this.sibling.getEnvironment().getProperty("spring.application.name"))
.isEqualTo("sibling");
then(this.sibling.getEnvironment().getProperty("custom.foo")).isEqualTo("sibling");
then(this.sibling.getEnvironment().getProperty("spring.application.name")).isEqualTo("sibling");
}
@Test
public void environmentEnrichedInParentContext() {
PropertySourceConfiguration.MAP.put("bootstrap.foo", "bar");
this.context = new SpringApplicationBuilder().sources(BareConfiguration.class)
.properties("spring.config.use-legacy-processing=true")
.child(BareConfiguration.class).web(WebApplicationType.NONE).run();
.properties("spring.config.use-legacy-processing=true").child(BareConfiguration.class)
.web(WebApplicationType.NONE).run();
then(this.context.getEnvironment().getProperty("bootstrap.foo")).isEqualTo("bar");
then(this.context.getParent().getEnvironment())
.isNotSameAs(this.context.getEnvironment());
then(this.context.getEnvironment().getPropertySources().contains(
PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME
+ "-testBootstrap")).isTrue();
then(((ConfigurableEnvironment) this.context.getParent().getEnvironment())
.getPropertySources().contains(
PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME
+ "-testBootstrap")).isTrue();
then(this.context.getParent().getEnvironment()).isNotSameAs(this.context.getEnvironment());
then(this.context.getEnvironment().getPropertySources()
.contains(PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME + "-testBootstrap"))
.isTrue();
then(((ConfigurableEnvironment) this.context.getParent().getEnvironment()).getPropertySources()
.contains(PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME + "-testBootstrap"))
.isTrue();
}
@Test
@@ -388,32 +340,26 @@ public class BootstrapConfigurationTests {
public void differentProfileInChild() {
PropertySourceConfiguration.MAP.put("bootstrap.foo", "bar");
// Profiles are always merged with the child
ConfigurableApplicationContext parent = new SpringApplicationBuilder()
.sources(BareConfiguration.class).profiles("parent")
.web(WebApplicationType.NONE).run();
ConfigurableApplicationContext parent = new SpringApplicationBuilder().sources(BareConfiguration.class)
.profiles("parent").web(WebApplicationType.NONE).run();
this.context = new SpringApplicationBuilder(BareConfiguration.class)
.properties("spring.config.use-legacy-processing=true").profiles("child")
.parent(parent).web(WebApplicationType.NONE).run();
then(this.context.getParent().getEnvironment())
.isNotSameAs(this.context.getEnvironment());
.properties("spring.config.use-legacy-processing=true").profiles("child").parent(parent)
.web(WebApplicationType.NONE).run();
then(this.context.getParent().getEnvironment()).isNotSameAs(this.context.getEnvironment());
// The ApplicationContext merges profiles (profiles and property sources), see
// AbstractEnvironment.merge()
then(this.context.getEnvironment().acceptsProfiles("child", "parent")).isTrue();
// But the parent is not a child
then(this.context.getParent().getEnvironment().acceptsProfiles("child"))
.isFalse();
then(this.context.getParent().getEnvironment().acceptsProfiles("parent"))
.isTrue();
then(((ConfigurableEnvironment) this.context.getParent().getEnvironment())
.getPropertySources().contains(
PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME
+ "-testBootstrap")).isTrue();
then(this.context.getParent().getEnvironment().acceptsProfiles("child")).isFalse();
then(this.context.getParent().getEnvironment().acceptsProfiles("parent")).isTrue();
then(((ConfigurableEnvironment) this.context.getParent().getEnvironment()).getPropertySources()
.contains(PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME + "-testBootstrap"))
.isTrue();
then(this.context.getEnvironment().getProperty("bootstrap.foo")).isEqualTo("bar");
// The "bootstrap" property source is not shared now, but it has the same
// properties in it because they are pulled from the PropertySourceConfiguration
// below
then(this.context.getParent().getEnvironment().getProperty("bootstrap.foo"))
.isEqualTo("bar");
then(this.context.getParent().getEnvironment().getProperty("bootstrap.foo")).isEqualTo("bar");
// The parent property source is there in the child because they are both in the
// "parent" profile (by virtue of the merge in AbstractEnvironment)
then(this.context.getEnvironment().getProperty("info.name")).isEqualTo("parent");
@@ -423,30 +369,24 @@ public class BootstrapConfigurationTests {
public void includeProfileFromBootstrapPropertySource() {
PropertySourceConfiguration.MAP.put("spring.profiles.include", "bar,baz");
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
.properties("spring.config.use-legacy-processing=true").profiles("foo")
.sources(BareConfiguration.class).run();
.properties("spring.config.use-legacy-processing=true").profiles("foo").sources(BareConfiguration.class)
.run();
then(this.context.getEnvironment().acceptsProfiles("baz")).isTrue();
then(this.context.getEnvironment().acceptsProfiles("bar")).isTrue();
}
@Test
public void includeProfileFromBootstrapProperties() {
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
.sources(BareConfiguration.class)
.properties("spring.config.use-legacy-processing=true",
"spring.cloud.bootstrap.name=local")
.run();
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE).sources(BareConfiguration.class)
.properties("spring.config.use-legacy-processing=true", "spring.cloud.bootstrap.name=local").run();
then(this.context.getEnvironment().acceptsProfiles("local")).isTrue();
then(this.context.getEnvironment().getProperty("added"))
.isEqualTo("Hello added!");
then(this.context.getEnvironment().getProperty("added")).isEqualTo("Hello added!");
}
@Test
public void nonEnumerablePropertySourceWorks() {
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
.sources(BareConfiguration.class)
.properties("spring.config.use-legacy-processing=true",
"spring.cloud.bootstrap.name=nonenumerable")
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE).sources(BareConfiguration.class)
.properties("spring.config.use-legacy-processing=true", "spring.cloud.bootstrap.name=nonenumerable")
.run();
then(this.context.getEnvironment().getProperty("foo")).isEqualTo("bar");
}
@@ -459,8 +399,7 @@ public class BootstrapConfigurationTests {
@Configuration(proxyBeanMethods = false)
// This is added to bootstrap context as a source in bootstrap.properties
protected static class SimplePropertySourceConfiguration
implements PropertySourceLocator {
protected static class SimplePropertySourceConfiguration implements PropertySourceLocator {
@Override
public PropertySource<?> locate(Environment environment) {
@@ -489,8 +428,7 @@ public class BootstrapConfigurationTests {
@Override
public PropertySource<?> locate(Environment environment) {
if (this.name != null) {
then(this.name)
.isEqualTo(environment.getProperty("spring.application.name"));
then(this.name).isEqualTo(environment.getProperty("spring.application.name"));
}
if (this.fail) {
throw new RuntimeException("Planned");
@@ -519,8 +457,7 @@ public class BootstrapConfigurationTests {
@Configuration
@ConfigurationProperties("compositeexpected")
// This is added to bootstrap context as a source in bootstrap.properties
protected static class CompositePropertySourceConfiguration
implements PropertySourceLocator {
protected static class CompositePropertySourceConfiguration implements PropertySourceLocator {
public static Map<String, Object> MAP1 = new HashMap<String, Object>();
@@ -539,18 +476,14 @@ public class BootstrapConfigurationTests {
@Override
public PropertySource<?> locate(Environment environment) {
if (this.name != null) {
then(this.name)
.isEqualTo(environment.getProperty("spring.application.name"));
then(this.name).isEqualTo(environment.getProperty("spring.application.name"));
}
if (this.fail) {
throw new RuntimeException("Planned");
}
CompositePropertySource compositePropertySource = new CompositePropertySource(
"listTestBootstrap");
compositePropertySource.addFirstPropertySource(
new MapPropertySource("testBootstrap1", MAP1));
compositePropertySource.addFirstPropertySource(
new MapPropertySource("testBootstrap2", MAP2));
CompositePropertySource compositePropertySource = new CompositePropertySource("listTestBootstrap");
compositePropertySource.addFirstPropertySource(new MapPropertySource("testBootstrap1", MAP1));
compositePropertySource.addFirstPropertySource(new MapPropertySource("testBootstrap2", MAP2));
return compositePropertySource;
}

View File

@@ -37,8 +37,8 @@ public class BootstrapListenerHierarchyIntegrationTests {
@Test
public void shouldAddInABootstrapContext() {
ConfigurableApplicationContext context = new SpringApplicationBuilder()
.properties("spring.config.use-legacy-processing=true")
.sources(BasicConfiguration.class).web(NONE).run();
.properties("spring.config.use-legacy-processing=true").sources(BasicConfiguration.class).web(NONE)
.run();
then(context.getParent()).isNotNull();
}
@@ -46,20 +46,17 @@ public class BootstrapListenerHierarchyIntegrationTests {
@Test
public void shouldAddInOneBootstrapForABasicParentChildHierarchy() {
ConfigurableApplicationContext context = new SpringApplicationBuilder()
.properties("spring.config.use-legacy-processing=true")
.sources(RootConfiguration.class).web(NONE)
.properties("spring.config.use-legacy-processing=true").sources(RootConfiguration.class).web(NONE)
.child(BasicConfiguration.class).web(NONE).run();
// Should be RootConfiguration based context
ConfigurableApplicationContext parent = (ConfigurableApplicationContext) context
.getParent();
ConfigurableApplicationContext parent = (ConfigurableApplicationContext) context.getParent();
then(parent.getBean("rootBean", String.class)).isEqualTo("rootBean");
// Parent should have the bootstrap context as parent
then(parent.getParent()).isNotNull();
ConfigurableApplicationContext bootstrapContext = (ConfigurableApplicationContext) parent
.getParent();
ConfigurableApplicationContext bootstrapContext = (ConfigurableApplicationContext) parent.getParent();
// Bootstrap should be the root, there should be no other parent
then(bootstrapContext.getParent()).isNull();
@@ -68,21 +65,17 @@ public class BootstrapListenerHierarchyIntegrationTests {
@Test
public void shouldAddInOneBootstrapForSiblingsBasedHierarchy() {
ConfigurableApplicationContext context = new SpringApplicationBuilder()
.properties("spring.config.use-legacy-processing=true")
.sources(RootConfiguration.class).web(NONE)
.child(BasicConfiguration.class).web(NONE)
.sibling(BasicConfiguration.class).web(NONE).run();
.properties("spring.config.use-legacy-processing=true").sources(RootConfiguration.class).web(NONE)
.child(BasicConfiguration.class).web(NONE).sibling(BasicConfiguration.class).web(NONE).run();
// Should be RootConfiguration based context
ConfigurableApplicationContext parent = (ConfigurableApplicationContext) context
.getParent();
ConfigurableApplicationContext parent = (ConfigurableApplicationContext) context.getParent();
then(parent.getBean("rootBean", String.class)).isEqualTo("rootBean");
// Parent should have the bootstrap context as parent
then(parent.getParent()).isNotNull();
ConfigurableApplicationContext bootstrapContext = (ConfigurableApplicationContext) parent
.getParent();
ConfigurableApplicationContext bootstrapContext = (ConfigurableApplicationContext) parent.getParent();
// Bootstrap should be the root, there should be no other parent
then(bootstrapContext.getParent()).isNull();

View File

@@ -30,9 +30,8 @@ public class EncryptionBootstrapConfigurationTests {
@Test
public void symmetric() {
ConfigurableApplicationContext context = new SpringApplicationBuilder(
EncryptionBootstrapConfiguration.class).web(WebApplicationType.NONE)
.properties("encrypt.key:pie").run();
ConfigurableApplicationContext context = new SpringApplicationBuilder(EncryptionBootstrapConfiguration.class)
.web(WebApplicationType.NONE).properties("encrypt.key:pie").run();
TextEncryptor encryptor = context.getBean(TextEncryptor.class);
then(encryptor.decrypt(encryptor.encrypt("foo"))).isEqualTo("foo");
context.close();
@@ -40,14 +39,11 @@ public class EncryptionBootstrapConfigurationTests {
@Test
public void rsaKeyStore() {
ConfigurableApplicationContext context = new SpringApplicationBuilder(
EncryptionBootstrapConfiguration.class)
.web(WebApplicationType.NONE)
.properties("encrypt.keyStore.location:classpath:/server.jks",
"encrypt.keyStore.password:letmein",
"encrypt.keyStore.alias:mytestkey",
"encrypt.keyStore.secret:changeme")
.run();
ConfigurableApplicationContext context = new SpringApplicationBuilder(EncryptionBootstrapConfiguration.class)
.web(WebApplicationType.NONE)
.properties("encrypt.keyStore.location:classpath:/server.jks", "encrypt.keyStore.password:letmein",
"encrypt.keyStore.alias:mytestkey", "encrypt.keyStore.secret:changeme")
.run();
TextEncryptor encryptor = context.getBean(TextEncryptor.class);
then(encryptor.decrypt(encryptor.encrypt("foo"))).isEqualTo("foo");
context.close();
@@ -55,14 +51,11 @@ public class EncryptionBootstrapConfigurationTests {
@Test
public void rsaKeyStoreWithRelaxedProperties() {
ConfigurableApplicationContext context = new SpringApplicationBuilder(
EncryptionBootstrapConfiguration.class)
.web(WebApplicationType.NONE)
.properties("encrypt.key-store.location:classpath:/server.jks",
"encrypt.key-store.password:letmein",
"encrypt.key-store.alias:mytestkey",
"encrypt.key-store.secret:changeme")
.run();
ConfigurableApplicationContext context = new SpringApplicationBuilder(EncryptionBootstrapConfiguration.class)
.web(WebApplicationType.NONE)
.properties("encrypt.key-store.location:classpath:/server.jks", "encrypt.key-store.password:letmein",
"encrypt.key-store.alias:mytestkey", "encrypt.key-store.secret:changeme")
.run();
TextEncryptor encryptor = context.getBean(TextEncryptor.class);
then(encryptor.decrypt(encryptor.encrypt("foo"))).isEqualTo("foo");
context.close();
@@ -70,15 +63,12 @@ public class EncryptionBootstrapConfigurationTests {
@Test
public void rsaProperties() {
ConfigurableApplicationContext context = new SpringApplicationBuilder(
EncryptionBootstrapConfiguration.class)
.web(WebApplicationType.NONE)
.properties("encrypt.key-store.location:classpath:/server.jks",
"encrypt.key-store.password:letmein",
"encrypt.key-store.alias:mytestkey",
"encrypt.key-store.secret:changeme",
"encrypt.rsa.strong:true", "encrypt.rsa.salt:foobar")
.run();
ConfigurableApplicationContext context = new SpringApplicationBuilder(EncryptionBootstrapConfiguration.class)
.web(WebApplicationType.NONE)
.properties("encrypt.key-store.location:classpath:/server.jks", "encrypt.key-store.password:letmein",
"encrypt.key-store.alias:mytestkey", "encrypt.key-store.secret:changeme",
"encrypt.rsa.strong:true", "encrypt.rsa.salt:foobar")
.run();
RsaProperties properties = context.getBean(RsaProperties.class);
then(properties.getSalt()).isEqualTo("foobar");
then(properties.isStrong()).isTrue();
@@ -89,16 +79,12 @@ public class EncryptionBootstrapConfigurationTests {
@Test
public void nonExistentKeystoreLocationShouldNotBeAllowed() {
try {
new SpringApplicationBuilder(EncryptionBootstrapConfiguration.class)
.web(WebApplicationType.NONE)
new SpringApplicationBuilder(EncryptionBootstrapConfiguration.class).web(WebApplicationType.NONE)
.properties("encrypt.key-store.location:classpath:/server.jks1",
"encrypt.key-store.password:letmein",
"encrypt.key-store.alias:mytestkey",
"encrypt.key-store.password:letmein", "encrypt.key-store.alias:mytestkey",
"encrypt.key-store.secret:changeme")
.run();
then(false).as(
"Should not create an application context with invalid keystore location")
.isTrue();
then(false).as("Should not create an application context with invalid keystore location").isTrue();
}
catch (Exception e) {
then(e).hasRootCauseInstanceOf(IllegalStateException.class);

View File

@@ -31,21 +31,19 @@ public class EncryptionIntegrationTests {
@Test
public void symmetricPropertyValues() {
ConfigurableApplicationContext context = new SpringApplicationBuilder(
TestConfiguration.class).web(WebApplicationType.NONE).properties(
"spring.config.use-legacy-processing=true", "encrypt.key:pie",
ConfigurableApplicationContext context = new SpringApplicationBuilder(TestConfiguration.class)
.web(WebApplicationType.NONE).properties("spring.config.use-legacy-processing=true", "encrypt.key:pie",
"foo.password:{cipher}bf29452295df354e6153c5b31b03ef23c70e55fba24299aa85c63438f1c43c95")
.run();
.run();
then(context.getEnvironment().getProperty("foo.password")).isEqualTo("test");
}
@Test
public void symmetricConfigurationProperties() {
ConfigurableApplicationContext context = new SpringApplicationBuilder(
TestConfiguration.class).web(WebApplicationType.NONE).properties(
"spring.config.use-legacy-processing=true", "encrypt.key:pie",
ConfigurableApplicationContext context = new SpringApplicationBuilder(TestConfiguration.class)
.web(WebApplicationType.NONE).properties("spring.config.use-legacy-processing=true", "encrypt.key:pie",
"foo.password:{cipher}bf29452295df354e6153c5b31b03ef23c70e55fba24299aa85c63438f1c43c95")
.run();
.run();
then(context.getBean(PasswordProperties.class).getPassword()).isEqualTo("test");
}

View File

@@ -34,8 +34,7 @@ public class EncryptorFactoryTests {
@Test
public void testWithRsaPrivateKey() throws Exception {
String key = StreamUtils.copyToString(
new ClassPathResource("/example-test-rsa-private-key").getInputStream(),
String key = StreamUtils.copyToString(new ClassPathResource("/example-test-rsa-private-key").getInputStream(),
Charset.forName("ASCII"));
TextEncryptor encryptor = new EncryptorFactory().create(key);

View File

@@ -82,16 +82,15 @@ public class EnvironmentDecryptApplicationInitializerTests {
public void propertySourcesOrderedCorrectly() {
ConfigurableApplicationContext context = new AnnotationConfigApplicationContext();
TestPropertyValues.of("foo: {cipher}bar").applyTo(context);
context.getEnvironment().getPropertySources().addFirst(new MapPropertySource(
"test_override", Collections.singletonMap("foo", "{cipher}spam")));
context.getEnvironment().getPropertySources()
.addFirst(new MapPropertySource("test_override", Collections.singletonMap("foo", "{cipher}spam")));
this.listener.initialize(context);
then(context.getEnvironment().getProperty("foo")).isEqualTo("spam");
}
@Test
public void errorOnDecrypt() {
this.listener = new EnvironmentDecryptApplicationInitializer(
Encryptors.text("deadbeef", "AFFE37"));
this.listener = new EnvironmentDecryptApplicationInitializer(Encryptors.text("deadbeef", "AFFE37"));
ConfigurableApplicationContext context = new AnnotationConfigApplicationContext();
TestPropertyValues.of("foo: {cipher}bar").applyTo(context);
// catch IllegalStateException and verify
@@ -108,8 +107,7 @@ public class EnvironmentDecryptApplicationInitializerTests {
@Test
public void errorOnDecryptWithEmpty() {
this.listener = new EnvironmentDecryptApplicationInitializer(
Encryptors.text("deadbeef", "AFFE37"));
this.listener = new EnvironmentDecryptApplicationInitializer(Encryptors.text("deadbeef", "AFFE37"));
this.listener.setFailOnError(false);
ConfigurableApplicationContext context = new AnnotationConfigApplicationContext();
TestPropertyValues.of("foo: {cipher}bar").applyTo(context);
@@ -127,15 +125,12 @@ public class EnvironmentDecryptApplicationInitializerTests {
ConfigurableApplicationContext context = new AnnotationConfigApplicationContext();
// tests that collections in another property source don't get copied into
// "decrypted" property source
TestPropertyValues
.of("yours[0].someValue: yourFoo", "yours[1].someValue: yourBar")
.applyTo(context);
TestPropertyValues.of("yours[0].someValue: yourFoo", "yours[1].someValue: yourBar").applyTo(context);
// collection with some encrypted keys and some not encrypted
TestPropertyValues
.of("mine[0].someValue: Foo", "mine[0].someKey: {cipher}Foo0",
"mine[1].someValue: Bar", "mine[1].someKey: {cipher}Bar1",
"nonindexed: nonindexval")
.of("mine[0].someValue: Foo", "mine[0].someKey: {cipher}Foo0", "mine[1].someValue: Bar",
"mine[1].someKey: {cipher}Bar1", "nonindexed: nonindexval")
.applyTo(context.getEnvironment(), Type.MAP, "combinedTest");
this.listener.initialize(context);
@@ -143,17 +138,13 @@ public class EnvironmentDecryptApplicationInitializerTests {
then(context.getEnvironment().getProperty("mine[0].someKey")).isEqualTo("Foo0");
then(context.getEnvironment().getProperty("mine[1].someValue")).isEqualTo("Bar");
then(context.getEnvironment().getProperty("mine[1].someKey")).isEqualTo("Bar1");
then(context.getEnvironment().getProperty("yours[0].someValue"))
.isEqualTo("yourFoo");
then(context.getEnvironment().getProperty("yours[1].someValue"))
.isEqualTo("yourBar");
then(context.getEnvironment().getProperty("yours[0].someValue")).isEqualTo("yourFoo");
then(context.getEnvironment().getProperty("yours[1].someValue")).isEqualTo("yourBar");
MutablePropertySources propertySources = context.getEnvironment()
.getPropertySources();
MutablePropertySources propertySources = context.getEnvironment().getPropertySources();
PropertySource<Map<?, ?>> decrypted = (PropertySource<Map<?, ?>>) propertySources
.get(DECRYPTED_PROPERTY_SOURCE_NAME);
then(decrypted.getSource().size()).as("decrypted property source had wrong size")
.isEqualTo(4);
then(decrypted.getSource().size()).as("decrypted property source had wrong size").isEqualTo(4);
}
@Test
@@ -189,8 +180,7 @@ public class EnvironmentDecryptApplicationInitializerTests {
CompositePropertySource cps = mock(CompositePropertySource.class);
when(cps.getName()).thenReturn("mock-composite-source");
when(cps.getPropertyNames()).thenReturn(devProfile.getPropertyNames());
when(cps.getPropertySources())
.thenReturn(Arrays.asList(devProfile, defaultProfile));
when(cps.getPropertySources()).thenReturn(Arrays.asList(devProfile, defaultProfile));
ctx.getEnvironment().getPropertySources().addLast(cps);
initializer.initialize(ctx);
@@ -201,8 +191,8 @@ public class EnvironmentDecryptApplicationInitializerTests {
public void propertySourcesOrderedCorrectlyWithUnencryptedOverrides() {
ConfigurableApplicationContext context = new AnnotationConfigApplicationContext();
TestPropertyValues.of("foo: {cipher}bar").applyTo(context);
context.getEnvironment().getPropertySources().addFirst(new MapPropertySource(
"test_override", Collections.singletonMap("foo", "spam")));
context.getEnvironment().getPropertySources()
.addFirst(new MapPropertySource("test_override", Collections.singletonMap("foo", "spam")));
this.listener.initialize(context);
then(context.getEnvironment().getProperty("foo")).isEqualTo("spam");
}
@@ -215,28 +205,25 @@ public class EnvironmentDecryptApplicationInitializerTests {
when(encryptor.decrypt("bar3")).thenReturn("bar3");
when(encryptor.decrypt("baz")).thenReturn("baz");
EnvironmentDecryptApplicationInitializer initializer = new EnvironmentDecryptApplicationInitializer(
encryptor);
EnvironmentDecryptApplicationInitializer initializer = new EnvironmentDecryptApplicationInitializer(encryptor);
ConfigurableApplicationContext context = new AnnotationConfigApplicationContext();
CompositePropertySource bootstrap = new CompositePropertySource(
BOOTSTRAP_PROPERTY_SOURCE_NAME);
bootstrap.addPropertySource(new MapPropertySource("configService",
Collections.singletonMap("foo", "{cipher}bar")));
CompositePropertySource bootstrap = new CompositePropertySource(BOOTSTRAP_PROPERTY_SOURCE_NAME);
bootstrap.addPropertySource(
new MapPropertySource("configService", Collections.singletonMap("foo", "{cipher}bar")));
context.getEnvironment().getPropertySources().addFirst(bootstrap);
Map<String, Object> props = new HashMap<>();
props.put("foo2", "{cipher}bar2");
props.put("bar", "{cipher}baz");
context.getEnvironment().getPropertySources().addAfter(
BOOTSTRAP_PROPERTY_SOURCE_NAME, new MapPropertySource("remote", props));
context.getEnvironment().getPropertySources().addAfter(BOOTSTRAP_PROPERTY_SOURCE_NAME,
new MapPropertySource("remote", props));
initializer.initialize(context);
// Simulate retrieval of new properties via Spring Cloud Config
props.put("foo2", "{cipher}bar3");
context.getEnvironment().getPropertySources().replace("remote",
new MapPropertySource("remote", props));
context.getEnvironment().getPropertySources().replace("remote", new MapPropertySource("remote", props));
initializer.initialize(context);
@@ -246,12 +233,11 @@ public class EnvironmentDecryptApplicationInitializerTests {
verify(encryptor, times(2)).decrypt("baz");
// Check if all encrypted properties are still decrypted
PropertySource<?> decryptedBootstrap = context.getEnvironment()
.getPropertySources().get(DECRYPTED_BOOTSTRAP_PROPERTY_SOURCE_NAME);
PropertySource<?> decryptedBootstrap = context.getEnvironment().getPropertySources()
.get(DECRYPTED_BOOTSTRAP_PROPERTY_SOURCE_NAME);
then(decryptedBootstrap.getProperty("foo")).isEqualTo("bar");
PropertySource<?> decrypted = context.getEnvironment().getPropertySources()
.get(DECRYPTED_PROPERTY_SOURCE_NAME);
PropertySource<?> decrypted = context.getEnvironment().getPropertySources().get(DECRYPTED_PROPERTY_SOURCE_NAME);
then(decrypted.getProperty("foo2")).isEqualTo("bar3");
then(decrypted.getProperty("bar")).isEqualTo("baz");
}
@@ -261,11 +247,10 @@ public class EnvironmentDecryptApplicationInitializerTests {
ConfigurableApplicationContext context = new AnnotationConfigApplicationContext();
TextEncryptor encryptor = mock(TextEncryptor.class);
when(encryptor.decrypt("bar2")).thenReturn("bar2");
EnvironmentDecryptApplicationInitializer initializer = new EnvironmentDecryptApplicationInitializer(
encryptor);
EnvironmentDecryptApplicationInitializer initializer = new EnvironmentDecryptApplicationInitializer(encryptor);
TestPropertyValues.of("foo: {cipher}bar", "foo2: {cipher}bar2").applyTo(context);
context.getEnvironment().getPropertySources().addFirst(new MapPropertySource(
"test_override", Collections.singletonMap("foo", "spam")));
context.getEnvironment().getPropertySources()
.addFirst(new MapPropertySource("test_override", Collections.singletonMap("foo", "spam")));
initializer.initialize(context);
then(context.getEnvironment().getProperty("foo")).isEqualTo("spam");
then(context.getEnvironment().getProperty("foo2")).isEqualTo("bar2");

View File

@@ -43,10 +43,8 @@ public class RsaDisabledTests {
@Before
public void setUp() {
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
.sources(EncryptionBootstrapConfiguration.class)
.web(WebApplicationType.NONE).properties("encrypt.key:mykey",
"encrypt.rsa.strong:true", "encrypt.rsa.salt:foobar")
.run();
.sources(EncryptionBootstrapConfiguration.class).web(WebApplicationType.NONE)
.properties("encrypt.key:mykey", "encrypt.rsa.strong:true", "encrypt.rsa.salt:foobar").run();
}
@After
@@ -58,8 +56,7 @@ public class RsaDisabledTests {
@Test
public void testLoadBalancedRetryFactoryBean() throws Exception {
Map<String, RsaProperties> properties = this.context
.getBeansOfType(RsaProperties.class);
Map<String, RsaProperties> properties = this.context.getBeansOfType(RsaProperties.class);
then(properties.values()).hasSize(0);
}

View File

@@ -52,8 +52,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestConfiguration.class,
properties = { "management.endpoints.web.exposure.include=*",
"management.endpoint.env.post.enabled=true" })
properties = { "management.endpoints.web.exposure.include=*", "management.endpoint.env.post.enabled=true" })
@AutoConfigureMockMvc
public class EnvironmentManagerIntegrationTests {
@@ -76,9 +75,8 @@ public class EnvironmentManagerIntegrationTests {
then(this.properties.getMessage()).isEqualTo("Hello scope!");
String content = property("message", "Foo");
this.mvc.perform(post(BASE_PATH + "/env").content(content)
.contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk())
.andExpect(content().string("{\"message\":\"Foo\"}"));
this.mvc.perform(post(BASE_PATH + "/env").content(content).contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andExpect(content().string("{\"message\":\"Foo\"}"));
then(this.properties.getMessage()).isEqualTo("Foo");
}
@@ -94,9 +92,9 @@ public class EnvironmentManagerIntegrationTests {
@Test
public void testRefreshFails() throws Exception {
try {
this.mvc.perform(post(BASE_PATH + "/env").content(property("delay", "foo"))
.contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk())
.andExpect(status().is5xxServerError());
this.mvc.perform(
post(BASE_PATH + "/env").content(property("delay", "foo")).contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andExpect(status().is5xxServerError());
fail("expected ServletException");
}
catch (ServletException e) {
@@ -107,17 +105,14 @@ public class EnvironmentManagerIntegrationTests {
@Test
public void coreWebExtensionAvailable() throws Exception {
this.mvc.perform(get(BASE_PATH + "/env/" + UUID.randomUUID().toString()))
.andExpect(status().isNotFound());
this.mvc.perform(get(BASE_PATH + "/env/" + UUID.randomUUID().toString())).andExpect(status().isNotFound());
}
@Test
public void environmentBeansConfiguredCorrectly() {
Map<String, EnvironmentEndpoint> envbeans = this.context
.getBeansOfType(EnvironmentEndpoint.class);
Map<String, EnvironmentEndpoint> envbeans = this.context.getBeansOfType(EnvironmentEndpoint.class);
then(envbeans).hasSize(1).containsKey("writableEnvironmentEndpoint");
then(envbeans.get("writableEnvironmentEndpoint"))
.isInstanceOf(WritableEnvironmentEndpoint.class);
then(envbeans.get("writableEnvironmentEndpoint")).isInstanceOf(WritableEnvironmentEndpoint.class);
Map<String, EnvironmentEndpointWebExtension> extbeans = this.context
.getBeansOfType(EnvironmentEndpointWebExtension.class);

View File

@@ -41,8 +41,7 @@ public class EnvironmentManagerTest {
environmentManager.setProperty("foo", "bar");
then(environment.getProperty("foo")).isEqualTo("bar");
ArgumentCaptor<ApplicationEvent> eventCaptor = ArgumentCaptor
.forClass(ApplicationEvent.class);
ArgumentCaptor<ApplicationEvent> eventCaptor = ArgumentCaptor.forClass(ApplicationEvent.class);
verify(publisher, times(1)).publishEvent(eventCaptor.capture());
then(eventCaptor.getValue()).isInstanceOf(EnvironmentChangeEvent.class);
EnvironmentChangeEvent event = (EnvironmentChangeEvent) eventCaptor.getValue();

View File

@@ -39,8 +39,7 @@ public class NamedContextFactoryTests {
parent.refresh();
TestClientFactory factory = new TestClientFactory();
factory.setApplicationContext(parent);
factory.setConfigurations(Arrays.asList(getSpec("foo", FooConfig.class),
getSpec("bar", BarConfig.class)));
factory.setConfigurations(Arrays.asList(getSpec("foo", FooConfig.class), getSpec("bar", BarConfig.class)));
Foo foo = factory.getInstance("foo", Foo.class);
then(foo).as("foo was null").isNotNull();
@@ -48,8 +47,7 @@ public class NamedContextFactoryTests {
Bar bar = factory.getInstance("bar", Bar.class);
then(bar).as("bar was null").isNotNull();
then(factory.getContextNames()).as("context names not exposed").contains("foo",
"bar");
then(factory.getContextNames()).as("context names not exposed").contains("foo", "bar");
Bar foobar = factory.getInstance("foo", Bar.class);
then(foobar).as("bar was not null").isNull();
@@ -78,12 +76,10 @@ public class NamedContextFactoryTests {
AnnotationConfigApplicationContext fooContext = factory.getContext("foo");
AnnotationConfigApplicationContext barContext = factory.getContext("bar");
then(fooContext.getClassLoader())
.as("foo context classloader does not match parent")
then(fooContext.getClassLoader()).as("foo context classloader does not match parent")
.isSameAs(parent.getClassLoader());
Assertions.assertThat(fooContext).hasFieldOrPropertyWithValue("customClassLoader",
true);
Assertions.assertThat(fooContext).hasFieldOrPropertyWithValue("customClassLoader", true);
factory.destroy();

View File

@@ -44,8 +44,7 @@ import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.BDDAssertions.then;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestConfiguration.class,
properties = "spring.config.use-legacy-processing=true")
@SpringBootTest(classes = TestConfiguration.class, properties = "spring.config.use-legacy-processing=true")
@ActiveProfiles("config")
public class ConfigurationPropertiesRebinderIntegrationTests {
@@ -131,8 +130,7 @@ public class ConfigurationPropertiesRebinderIntegrationTests {
@Bean
@ConfigurationProperties("some.service")
public SomeService someService() {
return ProxyFactory.getProxy(SomeService.class,
(MethodInterceptor) methodInvocation -> null);
return ProxyFactory.getProxy(SomeService.class, (MethodInterceptor) methodInvocation -> null);
}
}
@@ -141,8 +139,7 @@ public class ConfigurationPropertiesRebinderIntegrationTests {
protected static class RefreshConfiguration extends RefreshAutoConfiguration {
@Configuration(proxyBeanMethods = false)
protected static class RebinderConfiguration
extends ConfigurationPropertiesRebinderAutoConfiguration {
protected static class RebinderConfiguration extends ConfigurationPropertiesRebinderAutoConfiguration {
}

View File

@@ -67,8 +67,7 @@ public class ConfigurationPropertiesRebinderLifecycleIntegrationTests {
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties
@Import({ RefreshConfiguration.RebinderConfiguration.class,
PropertyPlaceholderAutoConfiguration.class })
@Import({ RefreshConfiguration.RebinderConfiguration.class, PropertyPlaceholderAutoConfiguration.class })
protected static class TestConfiguration {
@Bean
@@ -82,8 +81,7 @@ public class ConfigurationPropertiesRebinderLifecycleIntegrationTests {
protected static class RefreshConfiguration extends RefreshAutoConfiguration {
@Configuration(proxyBeanMethods = false)
protected static class RebinderConfiguration
extends ConfigurationPropertiesRebinderAutoConfiguration {
protected static class RebinderConfiguration extends ConfigurationPropertiesRebinderAutoConfiguration {
}

View File

@@ -102,8 +102,7 @@ public class ConfigurationPropertiesRebinderListIntegrationTests {
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties
@Import({ RefreshConfiguration.RebinderConfiguration.class,
PropertyPlaceholderAutoConfiguration.class })
@Import({ RefreshConfiguration.RebinderConfiguration.class, PropertyPlaceholderAutoConfiguration.class })
protected static class TestConfiguration {
@Bean
@@ -117,8 +116,7 @@ public class ConfigurationPropertiesRebinderListIntegrationTests {
protected static class RefreshConfiguration extends RefreshAutoConfiguration {
@Configuration(proxyBeanMethods = false)
protected static class RebinderConfiguration
extends ConfigurationPropertiesRebinderAutoConfiguration {
protected static class RebinderConfiguration extends ConfigurationPropertiesRebinderAutoConfiguration {
}

View File

@@ -44,8 +44,7 @@ import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.BDDAssertions.then;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestConfiguration.class,
properties = { "messages.expiry.one=168", "messages.expiry.two=76" })
@SpringBootTest(classes = TestConfiguration.class, properties = { "messages.expiry.one=168", "messages.expiry.two=76" })
public class ConfigurationPropertiesRebinderProxyIntegrationTests {
@Autowired
@@ -95,8 +94,7 @@ public class ConfigurationPropertiesRebinderProxyIntegrationTests {
protected static class RefreshConfiguration extends RefreshAutoConfiguration {
@Configuration(proxyBeanMethods = false)
protected static class RebinderConfiguration
extends ConfigurationPropertiesRebinderAutoConfiguration {
protected static class RebinderConfiguration extends ConfigurationPropertiesRebinderAutoConfiguration {
}

View File

@@ -41,8 +41,7 @@ import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.BDDAssertions.then;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestConfiguration.class,
properties = "spring.config.use-legacy-processing=true")
@SpringBootTest(classes = TestConfiguration.class, properties = "spring.config.use-legacy-processing=true")
public class ConfigurationPropertiesRebinderRefreshScopeIntegrationTests {
@Autowired
@@ -89,8 +88,7 @@ public class ConfigurationPropertiesRebinderRefreshScopeIntegrationTests {
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties
@Import({ RefreshAutoConfiguration.class,
ConfigurationPropertiesRebinderAutoConfiguration.class,
@Import({ RefreshAutoConfiguration.class, ConfigurationPropertiesRebinderAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class })
protected static class TestConfiguration {

View File

@@ -37,8 +37,7 @@ import static org.assertj.core.api.BDDAssertions.then;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestConfiguration.class,
properties = { "spring.datasource.hikari.read-only=false",
"spring.config.use-legacy-processing=true" })
properties = { "spring.datasource.hikari.read-only=false", "spring.config.use-legacy-processing=true" })
public class ContextRefresherIntegrationTests {
@Autowired
@@ -75,8 +74,7 @@ public class ContextRefresherIntegrationTests {
@DirtiesContext
public void testUpdateHikari() throws Exception {
then(this.properties.getMessage()).isEqualTo("Hello scope!");
TestPropertyValues.of("spring.datasource.hikari.read-only=true")
.applyTo(this.environment);
TestPropertyValues.of("spring.datasource.hikari.read-only=true").applyTo(this.environment);
// ...and then refresh, so the bean is re-initialized:
this.refresher.refresh();
then(this.properties.getMessage()).isEqualTo("Hello scope!");

View File

@@ -77,12 +77,9 @@ public class ContextRefresherOrderingIntegrationTests {
public void orderingIsCorrect() {
refresher.refresh();
MutablePropertySources propertySources = environment.getPropertySources();
PropertySource<?> test1 = propertySources
.get("bootstrapProperties-testContextRefresherOrdering1");
PropertySource<?> test2 = propertySources
.get("bootstrapProperties-testContextRefresherOrdering2");
PropertySource<?> test3 = propertySources
.get("bootstrapProperties-testContextRefresherOrdering3");
PropertySource<?> test1 = propertySources.get("bootstrapProperties-testContextRefresherOrdering1");
PropertySource<?> test2 = propertySources.get("bootstrapProperties-testContextRefresherOrdering2");
PropertySource<?> test3 = propertySources.get("bootstrapProperties-testContextRefresherOrdering3");
int index1 = propertySources.precedenceOf(test1);
int index2 = propertySources.precedenceOf(test2);
int index3 = propertySources.precedenceOf(test3);
@@ -114,12 +111,9 @@ public class ContextRefresherOrderingIntegrationTests {
return Collections.emptyList();
}
ArrayList<PropertySource<?>> sources = new ArrayList<>();
sources.add(new MapPropertySource("testContextRefresherOrdering1",
singletonMap("key1", "value1")));
sources.add(new MapPropertySource("testContextRefresherOrdering2",
singletonMap("key2", "value2")));
sources.add(new MapPropertySource("testContextRefresherOrdering3",
singletonMap("key3", "value3")));
sources.add(new MapPropertySource("testContextRefresherOrdering1", singletonMap("key1", "value1")));
sources.add(new MapPropertySource("testContextRefresherOrdering2", singletonMap("key2", "value2")));
sources.add(new MapPropertySource("testContextRefresherOrdering3", singletonMap("key3", "value3")));
return sources;
}

View File

@@ -62,21 +62,16 @@ public class ContextRefresherTests {
@Ignore // FIXME: legacy config
public void orderNewPropertiesConsistentWithNewContext() {
try (ConfigurableApplicationContext context = SpringApplication.run(Empty.class,
"--spring.config.use-legacy-processing=true",
"--spring.main.web-application-type=none", "--debug=false",
"--spring.main.bannerMode=OFF")) {
"--spring.config.use-legacy-processing=true", "--spring.main.web-application-type=none",
"--debug=false", "--spring.main.bannerMode=OFF")) {
context.getEnvironment().setActiveProfiles("refresh");
List<String> names = names(context.getEnvironment().getPropertySources());
then(names).doesNotContain(
"applicationConfig: [classpath:/bootstrap-refresh.properties]");
LegacyContextRefresher refresher = new LegacyContextRefresher(context,
this.scope);
then(names).doesNotContain("applicationConfig: [classpath:/bootstrap-refresh.properties]");
LegacyContextRefresher refresher = new LegacyContextRefresher(context, this.scope);
refresher.refresh();
names = names(context.getEnvironment().getPropertySources());
then(names).contains(
"applicationConfig: [classpath:/bootstrap-refresh.properties]");
then(names).containsSequence(
"applicationConfig: [classpath:/application.properties]",
then(names).contains("applicationConfig: [classpath:/bootstrap-refresh.properties]");
then(names).containsSequence("applicationConfig: [classpath:/application.properties]",
"applicationConfig: [classpath:/bootstrap-refresh.properties]",
"applicationConfig: [classpath:/bootstrap.properties]");
}
@@ -88,10 +83,8 @@ public class ContextRefresherTests {
// 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.config.use-legacy-processing=true",
"--spring.main.web-application-type=none", "--debug=false",
"--spring.main.bannerMode=OFF",
"--spring.cloud.bootstrap.name=refresh")) {
"--spring.config.use-legacy-processing=true", "--spring.main.web-application-type=none",
"--debug=false", "--spring.main.bannerMode=OFF", "--spring.cloud.bootstrap.name=refresh")) {
List<String> names = names(context.getEnvironment().getPropertySources());
System.err.println("***** " + context.getEnvironment().getPropertySources());
then(names).doesNotContain("bootstrapProperties");
@@ -101,9 +94,8 @@ public class ContextRefresherTests {
.applyTo(context.getEnvironment(), Type.MAP, "defaultProperties");
refresher.refresh();
names = names(context.getEnvironment().getPropertySources());
then(names).first().isEqualTo(
PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME
+ "-refreshTest");
then(names).first()
.isEqualTo(PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME + "-refreshTest");
}
}
@@ -111,39 +103,29 @@ public class ContextRefresherTests {
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.web-application-type=none",
"--spring.config.use-legacy-processing=true", "--debug=false",
"--spring.main.bannerMode=OFF",
"--spring.cloud.bootstrap.name=refresh")) {
LegacyContextRefresher refresher = new LegacyContextRefresher(context,
this.scope);
try (ConfigurableApplicationContext context = SpringApplication.run(ContextRefresherTests.class,
"--spring.main.web-application-type=none", "--spring.config.use-legacy-processing=true",
"--debug=false", "--spring.main.bannerMode=OFF", "--spring.cloud.bootstrap.name=refresh")) {
LegacyContextRefresher refresher = new LegacyContextRefresher(context, this.scope);
TestPropertyValues.of("spring.cloud.bootstrap.sources: "
+ "org.springframework.cloud.context.refresh.ContextRefresherTests.PropertySourceConfiguration")
.applyTo(context);
ConfigurableApplicationContext refresherContext = refresher
.addConfigFilesToEnvironment();
then(refresherContext.getParent()).isNotNull()
.isInstanceOf(ConfigurableApplicationContext.class);
ConfigurableApplicationContext parent = (ConfigurableApplicationContext) refresherContext
.getParent();
ConfigurableApplicationContext refresherContext = refresher.addConfigFilesToEnvironment();
then(refresherContext.getParent()).isNotNull().isInstanceOf(ConfigurableApplicationContext.class);
ConfigurableApplicationContext parent = (ConfigurableApplicationContext) refresherContext.getParent();
then(parent.isActive()).isFalse();
}
}
@Test
public void loggingSystemNotInitialized() {
System.setProperty(LoggingSystem.SYSTEM_PROPERTY,
TestLoggingSystem.class.getName());
TestLoggingSystem system = (TestLoggingSystem) LoggingSystem
.get(getClass().getClassLoader());
System.setProperty(LoggingSystem.SYSTEM_PROPERTY, TestLoggingSystem.class.getName());
TestLoggingSystem system = (TestLoggingSystem) LoggingSystem.get(getClass().getClassLoader());
then(system.getCount()).isEqualTo(0);
try (ConfigurableApplicationContext context = SpringApplication.run(Empty.class,
"--spring.config.use-legacy-processing=true",
"--spring.main.web-application-type=none", "--debug=false",
"--spring.main.bannerMode=OFF",
"--spring.cloud.bootstrap.name=refresh")) {
"--spring.config.use-legacy-processing=true", "--spring.main.web-application-type=none",
"--debug=false", "--spring.main.bannerMode=OFF", "--spring.cloud.bootstrap.name=refresh")) {
then(system.getCount()).isEqualTo(4);
ContextRefresher refresher = new LegacyContextRefresher(context, this.scope);
refresher.refresh();
@@ -156,10 +138,9 @@ public class ContextRefresherTests {
TestBootstrapConfiguration.fooSightings = new ArrayList<>();
try (ConfigurableApplicationContext context = SpringApplication.run(
ContextRefresherTests.class, "--spring.main.web-application-type=none",
"--spring.config.use-legacy-processing=true", "--debug=false",
"--spring.main.bannerMode=OFF", "--spring.cloud.bootstrap.name=refresh",
try (ConfigurableApplicationContext context = SpringApplication.run(ContextRefresherTests.class,
"--spring.main.web-application-type=none", "--spring.config.use-legacy-processing=true",
"--debug=false", "--spring.main.bannerMode=OFF", "--spring.cloud.bootstrap.name=refresh",
"--test.bootstrap.foo=bar")) {
context.getEnvironment().setActiveProfiles("refresh");
ContextRefresher refresher = new LegacyContextRefresher(context, this.scope);
@@ -172,10 +153,8 @@ public class ContextRefresherTests {
@Test
public void legacyContextRefresherCreatedUsingBootstrapEnabled() {
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(RefreshAutoConfiguration.class))
.withPropertyValues("spring.cloud.bootstrap.enabled=true")
.run(context -> {
new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(RefreshAutoConfiguration.class))
.withPropertyValues("spring.cloud.bootstrap.enabled=true").run(context -> {
assertThat(context).hasSingleBean(LegacyContextRefresher.class);
assertThat(context).hasSingleBean(ContextRefresher.class);
});
@@ -183,10 +162,8 @@ public class ContextRefresherTests {
@Test
public void legacyContextRefresherCreated() {
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(RefreshAutoConfiguration.class))
.withPropertyValues("spring.config.use-legacy-processing=true")
.run(context -> {
new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(RefreshAutoConfiguration.class))
.withPropertyValues("spring.config.use-legacy-processing=true").run(context -> {
assertThat(context).hasSingleBean(LegacyContextRefresher.class);
assertThat(context).hasSingleBean(ContextRefresher.class);
});
@@ -194,8 +171,7 @@ public class ContextRefresherTests {
@Test
public void configDataContextRefresherCreated() {
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(RefreshAutoConfiguration.class))
new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(RefreshAutoConfiguration.class))
.run(context -> {
assertThat(context).hasSingleBean(ConfigDataContextRefresher.class);
assertThat(context).hasSingleBean(ContextRefresher.class);

View File

@@ -45,11 +45,9 @@ public class RestartIntegrationTests {
@Test
public void testRestartTwice() throws Exception {
this.context = SpringApplication.run(TestConfiguration.class,
"--management.endpoint.restart.enabled=true", "--server.port=0",
"--spring.config.use-legacy-processing=true",
"--management.endpoints.web.exposure.include=restart",
"--spring.liveBeansView.mbeanDomain=livebeans");
this.context = SpringApplication.run(TestConfiguration.class, "--management.endpoint.restart.enabled=true",
"--server.port=0", "--spring.config.use-legacy-processing=true",
"--management.endpoints.web.exposure.include=restart", "--spring.liveBeansView.mbeanDomain=livebeans");
RestartEndpoint endpoint = this.context.getBean(RestartEndpoint.class);
then(this.context.getParent()).isNotNull();

View File

@@ -47,8 +47,7 @@ public class ImportRefreshScopeIntegrationTests {
@Test
public void testSimpleProperties() throws Exception {
then(this.service.getMessage()).isEqualTo("Hello scope!");
then(this.beanFactory.getBeanDefinition("scopedTarget.service").getScope())
.isEqualTo("refresh");
then(this.beanFactory.getBeanDefinition("scopedTarget.service").getScope()).isEqualTo("refresh");
then(this.service.getMessage()).isEqualTo("Hello scope!");
}

View File

@@ -88,8 +88,7 @@ public class MoreRefreshScopeIntegrationTests {
then(this.service.getMessage()).isEqualTo("Hello scope!");
String id1 = this.service.toString();
// Change the dynamic property source...
TestPropertyValues.of("message:Foo").applyTo(this.environment, Type.MAP,
"morerefreshtests");
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();

View File

@@ -52,8 +52,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ClientApp.class,
properties = { "management.endpoints.web.exposure.include=*",
"management.endpoint.env.post.enabled=true" },
properties = { "management.endpoints.web.exposure.include=*", "management.endpoint.env.post.enabled=true" },
webEnvironment = RANDOM_PORT)
public class RefreshEndpointIntegrationTests {
@@ -66,25 +65,21 @@ public class RefreshEndpointIntegrationTests {
public void webAccess() throws Exception {
TestRestTemplate template = new TestRestTemplate();
template.exchange(
getUrlEncodedEntity("http://localhost:" + this.port + BASE_PATH + "/env",
"message", "Hello Dave!"),
String.class);
template.postForObject("http://localhost:" + this.port + BASE_PATH + "/refresh",
null, String.class);
String message = template.getForObject("http://localhost:" + this.port + "/",
getUrlEncodedEntity("http://localhost:" + this.port + BASE_PATH + "/env", "message", "Hello Dave!"),
String.class);
template.postForObject("http://localhost:" + this.port + BASE_PATH + "/refresh", null, String.class);
String message = template.getForObject("http://localhost:" + this.port + "/", String.class);
then(message).isEqualTo("Hello Dave!");
}
private RequestEntity<?> getUrlEncodedEntity(String uri, String key, String value)
throws URISyntaxException {
private RequestEntity<?> getUrlEncodedEntity(String uri, String key, String value) throws URISyntaxException {
Map<String, String> property = new HashMap<>();
property.put("name", key);
property.put("value", value);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
RequestEntity<Map<String, String>> entity = new RequestEntity<>(property, headers,
HttpMethod.POST, new URI(uri));
RequestEntity<Map<String, String>> entity = new RequestEntity<>(property, headers, HttpMethod.POST,
new URI(uri));
return entity;
}

View File

@@ -106,8 +106,7 @@ public class RefreshScopeConcurrencyTests {
}
public static class ExampleService
implements Service, InitializingBean, DisposableBean {
public static class ExampleService implements Service, InitializingBean, DisposableBean {
private static Log logger = LogFactory.getLog(ExampleService.class);
@@ -152,8 +151,7 @@ public class RefreshScopeConcurrencyTests {
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(TestProperties.class)
@Import({ RefreshAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class })
@Import({ RefreshAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class })
protected static class TestConfiguration {
@Autowired

View File

@@ -57,8 +57,7 @@ import static org.assertj.core.api.BDDAssertions.then;
"logging.level.org.springframework.cloud.context.scope.refresh.RefreshScopeConfigurationScaleTests=DEBUG" })
public class RefreshScopeConfigurationScaleTests {
private static Log logger = LogFactory
.getLog(RefreshScopeConfigurationScaleTests.class);
private static Log logger = LogFactory.getLog(RefreshScopeConfigurationScaleTests.class);
@Autowired
org.springframework.cloud.context.scope.refresh.RefreshScope scope;
@@ -90,8 +89,7 @@ public class RefreshScopeConfigurationScaleTests {
public String call() throws Exception {
logger.debug("Background started.");
try {
return RefreshScopeConfigurationScaleTests.this.service
.getMessage();
return RefreshScopeConfigurationScaleTests.this.service.getMessage();
}
finally {
latch.countDown();
@@ -120,8 +118,7 @@ public class RefreshScopeConfigurationScaleTests {
}
public static class ExampleService
implements Service, InitializingBean, DisposableBean {
public static class ExampleService implements Service, InitializingBean, DisposableBean {
private static Log logger = LogFactory.getLog(ExampleService.class);
@@ -135,35 +132,30 @@ public class RefreshScopeConfigurationScaleTests {
@Override
public void afterPropertiesSet() throws Exception {
logger.debug("Initializing: " + ObjectUtils.getIdentityHexString(this) + ", "
+ this.message);
logger.debug("Initializing: " + ObjectUtils.getIdentityHexString(this) + ", " + this.message);
try {
Thread.sleep(this.delay);
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
logger.debug("Initialized: " + ObjectUtils.getIdentityHexString(this) + ", "
+ this.message);
logger.debug("Initialized: " + ObjectUtils.getIdentityHexString(this) + ", " + this.message);
}
@Override
public void destroy() throws Exception {
logger.debug("Destroying message: " + ObjectUtils.getIdentityHexString(this)
+ ", " + this.message);
logger.debug("Destroying message: " + ObjectUtils.getIdentityHexString(this) + ", " + this.message);
this.message = null;
}
@Override
public String getMessage() {
logger.debug("Returning message: " + ObjectUtils.getIdentityHexString(this)
+ ", " + this.message);
logger.debug("Returning message: " + ObjectUtils.getIdentityHexString(this) + ", " + this.message);
return this.message;
}
public void setMessage(String message) {
logger.debug("Setting message: " + ObjectUtils.getIdentityHexString(this)
+ ", " + message);
logger.debug("Setting message: " + ObjectUtils.getIdentityHexString(this) + ", " + message);
this.message = message;
}
@@ -171,8 +163,7 @@ public class RefreshScopeConfigurationScaleTests {
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties
@Import({ RefreshAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class })
@Import({ RefreshAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class })
protected static class TestConfiguration {
@Bean

View File

@@ -56,12 +56,10 @@ public class RefreshScopeConfigurationTests {
}
private void refresh() {
EnvironmentManager environmentManager = this.context
.getBean(EnvironmentManager.class);
EnvironmentManager environmentManager = this.context.getBean(EnvironmentManager.class);
environmentManager.setProperty("message", "Hello Dave!");
org.springframework.cloud.context.scope.refresh.RefreshScope scope = this.context
.getBean(
org.springframework.cloud.context.scope.refresh.RefreshScope.class);
.getBean(org.springframework.cloud.context.scope.refresh.RefreshScope.class);
scope.refreshAll();
}
@@ -71,12 +69,10 @@ public class RefreshScopeConfigurationTests {
@Test
public void configurationWithRefreshScope() throws Exception {
this.context = new AnnotationConfigApplicationContext(Application.class,
PropertyPlaceholderAutoConfiguration.class,
RefreshAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class, RefreshAutoConfiguration.class,
LifecycleMvcEndpointAutoConfiguration.class);
Application application = this.context.getBean(Application.class);
then(this.context.getBeanDefinition("scopedTarget.application").getScope())
.isEqualTo("refresh");
then(this.context.getBeanDefinition("scopedTarget.application").getScope()).isEqualTo("refresh");
application.hello();
refresh();
String message = application.hello();
@@ -86,8 +82,7 @@ public class RefreshScopeConfigurationTests {
@Test
public void refreshScopeOnBean() throws Exception {
this.context = new AnnotationConfigApplicationContext(ClientApp.class,
PropertyPlaceholderAutoConfiguration.class,
RefreshAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class, RefreshAutoConfiguration.class,
LifecycleMvcEndpointAutoConfiguration.class);
Controller application = this.context.getBean(Controller.class);
application.hello();
@@ -99,8 +94,7 @@ public class RefreshScopeConfigurationTests {
@Test
public void refreshScopeOnNested() throws Exception {
this.context = new AnnotationConfigApplicationContext(NestedApp.class,
PropertyPlaceholderAutoConfiguration.class,
RefreshAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class, RefreshAutoConfiguration.class,
LifecycleMvcEndpointAutoConfiguration.class);
NestedController application = this.context.getBean(NestedController.class);
application.hello();

View File

@@ -96,8 +96,7 @@ public class RefreshScopeIntegrationTests {
then(ExampleService.getDestroyCount()).isEqualTo(1);
then(id2).isNotSameAs(id1);
then(ExampleService.event).isNotNull();
then(ExampleService.event.getName())
.isEqualTo(RefreshScopeRefreshedEvent.DEFAULT_NAME);
then(ExampleService.event.getName()).isEqualTo(RefreshScopeRefreshedEvent.DEFAULT_NAME);
}
@Test
@@ -116,8 +115,7 @@ public class RefreshScopeIntegrationTests {
then(ExampleService.getDestroyCount()).isEqualTo(1);
then(id2).isNotSameAs(id1);
then(ExampleService.event).isNotNull();
then(ExampleService.event.getName())
.isEqualTo(GenericScope.SCOPED_TARGET_PREFIX + "service");
then(ExampleService.event.getName()).isEqualTo(GenericScope.SCOPED_TARGET_PREFIX + "service");
}
// see gh-349
@@ -135,8 +133,8 @@ public class RefreshScopeIntegrationTests {
}
public static class ExampleService implements Service, InitializingBean,
DisposableBean, ApplicationListener<RefreshScopeRefreshedEvent> {
public static class ExampleService
implements Service, InitializingBean, DisposableBean, ApplicationListener<RefreshScopeRefreshedEvent> {
private static Log logger = LogFactory.getLog(ExampleService.class);

View File

@@ -99,8 +99,7 @@ public class RefreshScopeLazyIntegrationTests {
then(ExampleService.getDestroyCount()).isEqualTo(1);
then(id2).isNotSameAs(id1);
then(ExampleService.event).isNotNull();
then(ExampleService.event.getName())
.isEqualTo(RefreshScopeRefreshedEvent.DEFAULT_NAME);
then(ExampleService.event.getName()).isEqualTo(RefreshScopeRefreshedEvent.DEFAULT_NAME);
}
@Test
@@ -118,8 +117,7 @@ public class RefreshScopeLazyIntegrationTests {
then(ExampleService.getDestroyCount()).isEqualTo(1);
then(id2).isNotSameAs(id1);
then(ExampleService.event).isNotNull();
then(ExampleService.event.getName())
.isEqualTo(GenericScope.SCOPED_TARGET_PREFIX + "service");
then(ExampleService.event.getName()).isEqualTo(GenericScope.SCOPED_TARGET_PREFIX + "service");
}
public interface Service {
@@ -128,8 +126,8 @@ public class RefreshScopeLazyIntegrationTests {
}
public static class ExampleService implements Service, InitializingBean,
DisposableBean, ApplicationListener<RefreshScopeRefreshedEvent> {
public static class ExampleService
implements Service, InitializingBean, DisposableBean, ApplicationListener<RefreshScopeRefreshedEvent> {
private static Log logger = LogFactory.getLog(ExampleService.class);
@@ -201,8 +199,7 @@ public class RefreshScopeLazyIntegrationTests {
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(TestProperties.class)
@ImportAutoConfiguration({ RefreshAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class })
@ImportAutoConfiguration({ RefreshAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class })
protected static class TestConfiguration {
@Autowired

View File

@@ -45,8 +45,7 @@ import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.BDDAssertions.then;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestConfiguration.class,
properties = { "test.messages[0]=one", "test.messages[1]=two" })
@SpringBootTest(classes = TestConfiguration.class, properties = { "test.messages[0]=one", "test.messages[1]=two" })
public class RefreshScopeListBindingIntegrationTests {
@Autowired
@@ -93,8 +92,7 @@ public class RefreshScopeListBindingIntegrationTests {
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties
@Import({ RefreshAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class })
@Import({ RefreshAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class })
protected static class TestConfiguration {
@Bean

View File

@@ -33,8 +33,7 @@ import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.BDDAssertions.then;
@RunWith(SpringRunner.class)
@SpringBootTest(
classes = { RefreshScopeNullBeanIntegrationTests.TestConfiguration.class })
@SpringBootTest(classes = { RefreshScopeNullBeanIntegrationTests.TestConfiguration.class })
public class RefreshScopeNullBeanIntegrationTests {
@Autowired
@@ -78,8 +77,7 @@ public class RefreshScopeNullBeanIntegrationTests {
}
@Configuration(proxyBeanMethods = false)
@Import({ RefreshAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class,
OptionalConfiguration.class })
@Import({ RefreshAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, OptionalConfiguration.class })
protected static class TestConfiguration {
@Autowired(required = false)

View File

@@ -109,8 +109,7 @@ public class RefreshScopePureScaleTests {
}
public static class ExampleService
implements Service, InitializingBean, DisposableBean {
public static class ExampleService implements Service, InitializingBean, DisposableBean {
private static Log logger = LogFactory.getLog(ExampleService.class);
@@ -124,43 +123,37 @@ public class RefreshScopePureScaleTests {
@Override
public void afterPropertiesSet() throws Exception {
logger.debug("Initializing: " + ObjectUtils.getIdentityHexString(this) + ", "
+ this.message);
logger.debug("Initializing: " + ObjectUtils.getIdentityHexString(this) + ", " + this.message);
try {
Thread.sleep(this.delay);
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
logger.debug("Initialized: " + ObjectUtils.getIdentityHexString(this) + ", "
+ this.message);
logger.debug("Initialized: " + ObjectUtils.getIdentityHexString(this) + ", " + this.message);
}
@Override
public void destroy() throws Exception {
logger.debug("Destroying message: " + ObjectUtils.getIdentityHexString(this)
+ ", " + this.message);
logger.debug("Destroying message: " + ObjectUtils.getIdentityHexString(this) + ", " + this.message);
this.message = null;
}
@Override
public String getMessage() {
logger.debug("Returning message: " + ObjectUtils.getIdentityHexString(this)
+ ", " + this.message);
logger.debug("Returning message: " + ObjectUtils.getIdentityHexString(this) + ", " + this.message);
return this.message;
}
public void setMessage(String message) {
logger.debug("Setting message: " + ObjectUtils.getIdentityHexString(this)
+ ", " + message);
logger.debug("Setting message: " + ObjectUtils.getIdentityHexString(this) + ", " + message);
this.message = message;
}
}
@Configuration(proxyBeanMethods = false)
@Import({ RefreshAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class })
@Import({ RefreshAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class })
protected static class TestConfiguration {
@Bean

View File

@@ -107,8 +107,7 @@ public class RefreshScopeScaleTests {
}
public static class ExampleService
implements Service, InitializingBean, DisposableBean {
public static class ExampleService implements Service, InitializingBean, DisposableBean {
private static Log logger = LogFactory.getLog(ExampleService.class);
@@ -155,8 +154,7 @@ public class RefreshScopeScaleTests {
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(TestProperties.class)
@Import({ RefreshAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class })
@Import({ RefreshAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class })
protected static class TestConfiguration {
@Autowired

View File

@@ -34,10 +34,8 @@ public class RefreshScopeSerializationTests {
@Test
public void defaultApplicationContextId() throws Exception {
ConfigurableApplicationContext context = new SpringApplicationBuilder(
TestConfiguration.class)
.properties("spring.config.use-legacy-processing=true")
.web(WebApplicationType.NONE).run();
ConfigurableApplicationContext context = new SpringApplicationBuilder(TestConfiguration.class)
.properties("spring.config.use-legacy-processing=true").web(WebApplicationType.NONE).run();
then(context.getId()).isEqualTo("application-1");
}
@@ -51,10 +49,9 @@ public class RefreshScopeSerializationTests {
}
private DefaultListableBeanFactory getBeanFactory() {
ConfigurableApplicationContext context = new SpringApplicationBuilder(
TestConfiguration.class).web(WebApplicationType.NONE).run();
DefaultListableBeanFactory factory = (DefaultListableBeanFactory) context
.getAutowireCapableBeanFactory();
ConfigurableApplicationContext context = new SpringApplicationBuilder(TestConfiguration.class)
.web(WebApplicationType.NONE).run();
DefaultListableBeanFactory factory = (DefaultListableBeanFactory) context.getAutowireCapableBeanFactory();
return factory;
}

View File

@@ -58,8 +58,7 @@ public class RefreshScopeWebIntegrationTests {
@Test
public void scopeOnBeanDefinition() throws Exception {
then(this.beanFactory.getBeanDefinition("scopedTarget.application").getScope())
.isEqualTo("refresh");
then(this.beanFactory.getBeanDefinition("scopedTarget.application").getScope()).isEqualTo("refresh");
}
@Test

View File

@@ -69,16 +69,12 @@ public class RefreshEndpointTests {
@Test
@Ignore // FIXME: legacy
public void keysComputedWhenAdded() throws Exception {
this.context = new SpringApplicationBuilder(Empty.class)
.web(WebApplicationType.NONE).bannerMode(Mode.OFF)
.properties("spring.config.use-legacy-processing=true",
"spring.cloud.bootstrap.name:none")
.run();
this.context = new SpringApplicationBuilder(Empty.class).web(WebApplicationType.NONE).bannerMode(Mode.OFF)
.properties("spring.config.use-legacy-processing=true", "spring.cloud.bootstrap.name:none").run();
RefreshScope scope = new RefreshScope();
scope.setApplicationContext(this.context);
this.context.getEnvironment().setActiveProfiles("local");
ContextRefresher contextRefresher = new LegacyContextRefresher(this.context,
scope);
ContextRefresher contextRefresher = new LegacyContextRefresher(this.context, scope);
RefreshEndpoint endpoint = new RefreshEndpoint(contextRefresher);
Collection<String> keys = endpoint.refresh();
then(keys.contains("added")).isTrue().as("Wrong keys: " + keys);
@@ -87,16 +83,12 @@ public class RefreshEndpointTests {
@Test
@Ignore // FIXME: legacy
public void keysComputedWhenOveridden() throws Exception {
this.context = new SpringApplicationBuilder(Empty.class)
.web(WebApplicationType.NONE).bannerMode(Mode.OFF)
.properties("spring.config.use-legacy-processing=true",
"spring.cloud.bootstrap.name:none")
.run();
this.context = new SpringApplicationBuilder(Empty.class).web(WebApplicationType.NONE).bannerMode(Mode.OFF)
.properties("spring.config.use-legacy-processing=true", "spring.cloud.bootstrap.name:none").run();
RefreshScope scope = new RefreshScope();
scope.setApplicationContext(this.context);
this.context.getEnvironment().setActiveProfiles("override");
ContextRefresher contextRefresher = new LegacyContextRefresher(this.context,
scope);
ContextRefresher contextRefresher = new LegacyContextRefresher(this.context, scope);
RefreshEndpoint endpoint = new RefreshEndpoint(contextRefresher);
Collection<String> keys = endpoint.refresh();
then(keys.contains("message")).isTrue().as("Wrong keys: " + keys);
@@ -105,19 +97,13 @@ public class RefreshEndpointTests {
@Test
@Ignore // FIXME: legacy
public void keysComputedWhenChangesInExternalProperties() throws Exception {
this.context = new SpringApplicationBuilder(Empty.class)
.web(WebApplicationType.NONE).bannerMode(Mode.OFF)
.properties("spring.cloud.bootstrap.name:none",
"spring.config.use-legacy-processing=true")
.run();
this.context = new SpringApplicationBuilder(Empty.class).web(WebApplicationType.NONE).bannerMode(Mode.OFF)
.properties("spring.cloud.bootstrap.name:none", "spring.config.use-legacy-processing=true").run();
RefreshScope scope = new RefreshScope();
scope.setApplicationContext(this.context);
TestPropertyValues
.of("spring.cloud.bootstrap.sources="
+ ExternalPropertySourceLocator.class.getName())
TestPropertyValues.of("spring.cloud.bootstrap.sources=" + ExternalPropertySourceLocator.class.getName())
.applyTo(this.context.getEnvironment(), Type.MAP, "defaultProperties");
ContextRefresher contextRefresher = new LegacyContextRefresher(this.context,
scope);
ContextRefresher contextRefresher = new LegacyContextRefresher(this.context, scope);
RefreshEndpoint endpoint = new RefreshEndpoint(contextRefresher);
Collection<String> keys = endpoint.refresh();
then(keys.contains("external.message")).isTrue().as("Wrong keys: " + keys);
@@ -125,20 +111,16 @@ public class RefreshEndpointTests {
@Test
public void springMainSourcesEmptyInRefreshCycle() throws Exception {
this.context = new SpringApplicationBuilder(Empty.class)
.web(WebApplicationType.NONE).bannerMode(Mode.OFF)
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())
TestPropertyValues.of("spring.main.sources=" + ExternalPropertySourceLocator.class.getName())
.applyTo(this.context);
ContextRefresher contextRefresher = new LegacyContextRefresher(this.context,
scope);
ContextRefresher contextRefresher = new LegacyContextRefresher(this.context, scope);
RefreshEndpoint endpoint = new RefreshEndpoint(contextRefresher);
Collection<String> keys = endpoint.refresh();
then(keys.contains("external.message")).as("Wrong keys: " + keys).isFalse();
@@ -146,12 +128,11 @@ public class RefreshEndpointTests {
@Test
public void eventsPublishedInOrder() throws Exception {
this.context = new SpringApplicationBuilder(Empty.class)
.web(WebApplicationType.NONE).bannerMode(Mode.OFF).run();
this.context = new SpringApplicationBuilder(Empty.class).web(WebApplicationType.NONE).bannerMode(Mode.OFF)
.run();
RefreshScope scope = new RefreshScope();
scope.setApplicationContext(this.context);
ContextRefresher contextRefresher = new LegacyContextRefresher(this.context,
scope);
ContextRefresher contextRefresher = new LegacyContextRefresher(this.context, scope);
RefreshEndpoint endpoint = new RefreshEndpoint(contextRefresher);
Empty empty = this.context.getBean(Empty.class);
endpoint.refresh();
@@ -162,12 +143,11 @@ public class RefreshEndpointTests {
@Test
public void shutdownHooksCleaned() {
try (ConfigurableApplicationContext context = new SpringApplicationBuilder(
Empty.class).web(WebApplicationType.NONE).bannerMode(Mode.OFF).run()) {
try (ConfigurableApplicationContext context = new SpringApplicationBuilder(Empty.class)
.web(WebApplicationType.NONE).bannerMode(Mode.OFF).run()) {
RefreshScope scope = new RefreshScope();
scope.setApplicationContext(context);
ContextRefresher contextRefresher = new LegacyContextRefresher(context,
scope);
ContextRefresher contextRefresher = new LegacyContextRefresher(context, scope);
RefreshEndpoint endpoint = new RefreshEndpoint(contextRefresher);
int count = countShutdownHooks();
endpoint.refresh();
@@ -177,8 +157,7 @@ public class RefreshEndpointTests {
}
private int countShutdownHooks() {
Class<?> type = ClassUtils.resolveClassName("java.lang.ApplicationShutdownHooks",
null);
Class<?> type = ClassUtils.resolveClassName("java.lang.ApplicationShutdownHooks", null);
Field field = ReflectionUtils.findField(type, "hooks");
ReflectionUtils.makeAccessible(field);
@SuppressWarnings("rawtypes")
@@ -199,8 +178,7 @@ public class RefreshEndpointTests {
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof EnvironmentChangeEvent
|| event instanceof RefreshScopeRefreshedEvent) {
if (event instanceof EnvironmentChangeEvent || event instanceof RefreshScopeRefreshedEvent) {
this.events.add(event);
}
}
@@ -208,13 +186,12 @@ public class RefreshEndpointTests {
}
@Component
protected static class ExternalPropertySourceLocator
implements PropertySourceLocator {
protected static class ExternalPropertySourceLocator implements PropertySourceLocator {
@Override
public PropertySource<?> locate(Environment environment) {
return new MapPropertySource("external", Collections
.<String, Object>singletonMap("external.message", "I'm External"));
return new MapPropertySource("external",
Collections.<String, Object>singletonMap("external.message", "I'm External"));
}
}

View File

@@ -39,13 +39,11 @@ public class RefreshScopeHealthIndicatorTests {
@SuppressWarnings("unchecked")
private ObjectProvider<RefreshScope> scopeProvider = mock(ObjectProvider.class);
private ConfigurationPropertiesRebinder rebinder = mock(
ConfigurationPropertiesRebinder.class);
private ConfigurationPropertiesRebinder rebinder = mock(ConfigurationPropertiesRebinder.class);
private RefreshScope scope = mock(RefreshScope.class);
private RefreshScopeHealthIndicator indicator = new RefreshScopeHealthIndicator(
this.scopeProvider, this.rebinder);
private RefreshScopeHealthIndicator indicator = new RefreshScopeHealthIndicator(this.scopeProvider, this.rebinder);
@Before
public void init() {
@@ -61,24 +59,20 @@ public class RefreshScopeHealthIndicatorTests {
@Test
public void binderError() {
when(this.rebinder.getErrors())
.thenReturn(Collections.singletonMap("foo", new RuntimeException("FOO")));
when(this.rebinder.getErrors()).thenReturn(Collections.singletonMap("foo", new RuntimeException("FOO")));
then(this.indicator.health().getStatus()).isEqualTo(Status.DOWN);
}
@Test
public void scopeError() {
when(this.scope.getErrors())
.thenReturn(Collections.singletonMap("foo", new RuntimeException("FOO")));
when(this.scope.getErrors()).thenReturn(Collections.singletonMap("foo", new RuntimeException("FOO")));
then(this.indicator.health().getStatus()).isEqualTo(Status.DOWN);
}
@Test
public void bothError() {
when(this.rebinder.getErrors())
.thenReturn(Collections.singletonMap("foo", new RuntimeException("FOO")));
when(this.scope.getErrors())
.thenReturn(Collections.singletonMap("bar", new RuntimeException("BAR")));
when(this.rebinder.getErrors()).thenReturn(Collections.singletonMap("foo", new RuntimeException("FOO")));
when(this.scope.getErrors()).thenReturn(Collections.singletonMap("bar", new RuntimeException("BAR")));
then(this.indicator.health().getStatus()).isEqualTo(Status.DOWN);
}

View File

@@ -45,16 +45,14 @@ public class LoggingRebinderTests {
@After
public void reset() {
LoggingSystem.get(getClass().getClassLoader())
.setLogLevel("org.springframework.web", LogLevel.INFO);
LoggingSystem.get(getClass().getClassLoader()).setLogLevel("org.springframework.web", LogLevel.INFO);
}
@Test
public void logLevelsChanged() {
then(this.logger.isTraceEnabled()).isFalse();
StandardEnvironment environment = new StandardEnvironment();
TestPropertyValues.of("logging.level.org.springframework.web=TRACE")
.applyTo(environment);
TestPropertyValues.of("logging.level.org.springframework.web=TRACE").applyTo(environment);
this.rebinder.setEnvironment(environment);
this.rebinder.onApplicationEvent(new EnvironmentChangeEvent(environment,
Collections.singleton("logging.level.org.springframework.web")));
@@ -65,8 +63,7 @@ public class LoggingRebinderTests {
public void logLevelsLowerCase() {
then(this.logger.isTraceEnabled()).isFalse();
StandardEnvironment environment = new StandardEnvironment();
TestPropertyValues.of("logging.level.org.springframework.web=trace")
.applyTo(environment);
TestPropertyValues.of("logging.level.org.springframework.web=trace").applyTo(environment);
this.rebinder.setEnvironment(environment);
this.rebinder.onApplicationEvent(new EnvironmentChangeEvent(environment,
Collections.singleton("logging.level.org.springframework.web")));
@@ -78,8 +75,7 @@ public class LoggingRebinderTests {
ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory
.getLogger("org.springframework.cloud");
StandardEnvironment environment = new StandardEnvironment();
TestPropertyValues.of("logging.level.org.springframework.cloud=false")
.applyTo(environment);
TestPropertyValues.of("logging.level.org.springframework.cloud=false").applyTo(environment);
rebinder.setEnvironment(environment);
rebinder.onApplicationEvent(new EnvironmentChangeEvent(environment,
Collections.singleton("logging.level.org.springframework.cloud")));

View File

@@ -67,10 +67,8 @@ public class CachedRandomPropertySourceTests {
then(cachedRandomPropertySource.getProperty("foo.app.long")).isNull();
then(cachedRandomPropertySource.getProperty("cachedrandom.app")).isNull();
then(cachedRandomPropertySource.getProperty("cachedrandom.app.long"))
.isEqualTo(1234L);
then(cachedRandomPropertySource.getProperty("cachedrandom.foo.long"))
.isEqualTo(5678L);
then(cachedRandomPropertySource.getProperty("cachedrandom.app.long")).isEqualTo(1234L);
then(cachedRandomPropertySource.getProperty("cachedrandom.foo.long")).isEqualTo(5678L);
verify(spyedCache, times(1)).computeIfAbsent(eq("app"), isA(Function.class));
verify(spyedTypeCache, times(1)).computeIfAbsent(eq("long"), isA(Function.class));
}