Checkstyle for tests

This commit is contained in:
Marcin Grzejszczak
2019-02-03 15:13:41 +01:00
parent 04d764d33a
commit 377eaad4a1
110 changed files with 1668 additions and 1043 deletions

View File

@@ -30,6 +30,8 @@
<maven-checkstyle-plugin.failsOnError>true</maven-checkstyle-plugin.failsOnError>
<maven-checkstyle-plugin.failsOnViolation>true
</maven-checkstyle-plugin.failsOnViolation>
<maven-checkstyle-plugin.includeTestSourceDirectory>true
</maven-checkstyle-plugin.includeTestSourceDirectory>
</properties>
<build>
<plugins>

View File

@@ -17,7 +17,6 @@
package org.springframework.cloud.client.hypermedia;
import org.springframework.hateoas.client.Traverson;
import org.springframework.hateoas.client.Traverson.TraversalBuilder;
/**
* Callback to define the traversal to a resource.
@@ -30,6 +29,6 @@ public interface TraversalDefinition {
* @param traverson The Traverson instance to run the traversal on.
* @return the builder for traversing
*/
TraversalBuilder buildTraversal(Traverson traverson);
Traverson.TraversalBuilder buildTraversal(Traverson traverson);
}

View File

@@ -18,4 +18,4 @@ org.springframework.boot.env.EnvironmentPostProcessor=\
org.springframework.cloud.client.HostInfoEnvironmentPostProcessor
# Failure Analyzers
org.springframework.boot.diagnostics.FailureAnalyzer=\
org.springframework.cloud.configuration.CompatibilityNotMetFailureAnalyzer
org.springframework.cloud.configuration.CompatibilityNotMetFailureAnalyzer

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.client;
import org.junit.Test;
@@ -15,12 +31,8 @@ import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import static org.hamcrest.Matchers.emptyCollectionOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.BDDAssertions.then;
/**
* @author Spencer Gibb
@@ -30,13 +42,10 @@ public class CommonsClientAutoConfigurationTests {
@Test
public void beansCreatedNormally() {
try (ConfigurableApplicationContext ctxt = init()) {
assertThat(ctxt.getBean(DiscoveryClientHealthIndicator.class),
is(notNullValue()));
assertThat(ctxt.getBean(DiscoveryCompositeHealthIndicator.class),
is(notNullValue()));
assertThat(ctxt.getBean(FeaturesEndpoint.class), is(notNullValue()));
assertThat(ctxt.getBeansOfType(HasFeatures.class).values(),
not(emptyCollectionOf(HasFeatures.class)));
then(ctxt.getBean(DiscoveryClientHealthIndicator.class)).isNotNull();
then(ctxt.getBean(DiscoveryCompositeHealthIndicator.class)).isNotNull();
then(ctxt.getBean(FeaturesEndpoint.class)).isNotNull();
then(ctxt.getBeansOfType(HasFeatures.class).values()).isNotEmpty();
}
}
@@ -46,7 +55,7 @@ public class CommonsClientAutoConfigurationTests {
"spring.cloud.discovery.enabled=false")) {
assertBeanNonExistant(ctxt, DiscoveryClientHealthIndicator.class);
assertBeanNonExistant(ctxt, DiscoveryCompositeHealthIndicator.class);
assertThat(ctxt.getBean(FeaturesEndpoint.class), is(notNullValue())); // features
then(ctxt.getBean(FeaturesEndpoint.class)).isNotNull(); // features
// actuator
// is
// independent

View File

@@ -22,7 +22,7 @@ import org.springframework.boot.SpringApplication;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.StandardEnvironment;
import static org.junit.Assert.assertNotNull;
import static org.assertj.core.api.BDDAssertions.then;
/**
* @author Dave Syer
@@ -36,14 +36,14 @@ public class HostInfoEnvironmentPostProcessorTests {
@Test
public void hostname() {
this.processor.postProcessEnvironment(this.environment, new SpringApplication());
assertNotNull(this.environment.getProperty("spring.cloud.client.hostname"));
then(this.environment.getProperty("spring.cloud.client.hostname")).isNotNull();
}
@Test
public void ipAddress() {
this.processor.postProcessEnvironment(this.environment, new SpringApplication());
String address = this.environment.getProperty("spring.cloud.client.ip-address");
assertNotNull(address);
then(address).isNotNull();
}
}

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.client.actuator;
import java.util.ArrayList;
@@ -14,7 +30,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.BDDAssertions.then;
/**
* @author Spencer Gibb
@@ -42,10 +58,10 @@ public class FeaturesEndpointTests {
public void invokeWorks() {
FeaturesEndpoint.Features features = this.context.getBean(FeaturesEndpoint.class)
.features();
assertThat(features).isNotNull();
assertThat(features.getEnabled()).hasSize(2).contains(
newFeature("foo", Foo.class), newFeature("Baz Feature", Baz.class));
assertThat(features.getDisabled()).hasSize(1).contains("Bar");
then(features).isNotNull();
then(features.getEnabled()).hasSize(2).contains(newFeature("foo", Foo.class),
newFeature("Baz Feature", Baz.class));
then(features.getDisabled()).hasSize(1).contains("Bar");
}
private FeaturesEndpoint.Feature newFeature(String name, Class<?> type) {

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.client.discovery;
import org.junit.Test;
@@ -13,8 +29,7 @@ import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationP
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.assertj.core.api.BDDAssertions.then;
/**
* @author Ryan Baxter
@@ -38,10 +53,10 @@ public class AutoRegisterPropertyFalseTests {
@Test
public void veryifyBeans() {
assertNull(this.autoConfiguration);
assertNull(this.autoServiceRegistration);
assertNull(this.autoServiceRegistrationProperties);
assertFalse(this.autoRegisterProperty);
then(this.autoConfiguration).isNull();
then(this.autoServiceRegistration).isNull();
then(this.autoServiceRegistrationProperties).isNull();
then(this.autoRegisterProperty).isFalse();
}
@EnableAutoConfiguration

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.client.discovery;
import org.junit.Test;
@@ -13,8 +29,7 @@ import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationP
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.assertj.core.api.BDDAssertions.then;
/**
* @author Ryan Baxter
@@ -37,10 +52,10 @@ public class EnableDiscoveryClientAutoRegisterFalseTests {
@Test
public void veryifyBeans() {
assertNull(this.autoConfiguration);
assertNull(this.autoServiceRegistration);
assertNull(this.autoServiceRegistrationProperties);
assertFalse(this.autoRegisterProperty);
then(this.autoConfiguration).isNull();
then(this.autoServiceRegistration).isNull();
then(this.autoServiceRegistrationProperties).isNull();
then(this.autoRegisterProperty).isFalse();
}
@EnableAutoConfiguration

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.client.discovery;
import org.junit.Before;
@@ -9,9 +25,7 @@ import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.mock.env.MockEnvironment;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.BDDAssertions.then;
import static org.mockito.BDDMockito.given;
/**
@@ -40,20 +54,20 @@ public class EnableDiscoveryClientImportSelectorTests {
public void autoRegistrationIsEnabled() {
configureAnnotation(true);
String[] imports = this.importSelector.selectImports(this.annotationMetadata);
assertTrue(this.environment.getProperty(
then(this.environment.getProperty(
"spring.cloud.service-registry.auto-registration.enabled", Boolean.class,
true));
assertThat(imports).hasSize(1);
true)).isTrue();
then(imports).hasSize(1);
}
@Test
public void autoRegistrationIsDisabled() {
configureAnnotation(false);
String[] imports = this.importSelector.selectImports(this.annotationMetadata);
assertFalse(this.environment.getProperty(
"spring.cloud.service-registry.auto-registration.enabled",
Boolean.class));
assertThat(imports).isEmpty();
then(this.environment.getProperty(
"spring.cloud.service-registry.auto-registration.enabled", Boolean.class))
.isFalse();
then(imports).isEmpty();
}
private void configureAnnotation(boolean autoRegistration) {

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.client.discovery;
import org.junit.Test;
@@ -9,7 +25,7 @@ import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.NestedRuntimeException;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.BDDAssertions.then;
/**
* Tests that if <code>@EnableDiscoveryClient</code> is used, but there is no
@@ -22,12 +38,13 @@ public class EnableDiscoveryClientMissingImplTests {
@Test
public void testContextFails() {
try (ConfigurableApplicationContext context = new SpringApplicationBuilder()
.sources(App.class).web(WebApplicationType.NONE).run(new String[0]);) {
.sources(App.class).web(WebApplicationType.NONE).run()) {
// do sth
}
catch (NestedRuntimeException e) {
Throwable rootCause = e.getRootCause();
assertTrue(rootCause instanceof IllegalStateException);
assertTrue(rootCause.getMessage().contains("no implementations"));
then(rootCause instanceof IllegalStateException).isTrue();
then(rootCause.getMessage().contains("no implementations")).isTrue();
}
}

View File

@@ -27,7 +27,7 @@ import org.springframework.cloud.test.ClassPathExclusions;
import org.springframework.cloud.test.ModifiedClassPathRunner;
import org.springframework.context.ConfigurableApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.BDDAssertions.then;
@RunWith(ModifiedClassPathRunner.class)
@ClassPathExclusions({ "spring-boot-actuator-autoconfigure-*" })
@@ -38,7 +38,7 @@ public class ManagementServerPortUtilsTests {
try (ConfigurableApplicationContext context = new SpringApplicationBuilder()
.web(WebApplicationType.NONE).sources(TestApp.class).run()) {
assertThat(ManagementServerPortUtils.hasActuator).isFalse();
then(ManagementServerPortUtils.hasActuator).isFalse();
}
}

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.client.discovery.composite;
import java.util.List;
@@ -15,7 +31,7 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.BDDAssertions.then;
/**
* Composite Discovery Client should be the one found by default.
@@ -32,19 +48,19 @@ public class CompositeDiscoveryClientAutoConfigurationTests {
@Test
public void compositeDiscoveryClientShouldBeTheDefault() {
assertThat(this.discoveryClient).isInstanceOf(CompositeDiscoveryClient.class);
then(this.discoveryClient).isInstanceOf(CompositeDiscoveryClient.class);
CompositeDiscoveryClient compositeDiscoveryClient = (CompositeDiscoveryClient) this.discoveryClient;
assertThat(compositeDiscoveryClient.getDiscoveryClients()).hasSize(2);
assertThat(compositeDiscoveryClient.getDiscoveryClients().get(0).description())
then(compositeDiscoveryClient.getDiscoveryClients()).hasSize(2);
then(compositeDiscoveryClient.getDiscoveryClients().get(0).description())
.isEqualTo("A custom discovery client");
}
@Test
public void simpleDiscoveryClientShouldBeHaveTheLowestPrecedence() {
CompositeDiscoveryClient compositeDiscoveryClient = (CompositeDiscoveryClient) this.discoveryClient;
assertThat(compositeDiscoveryClient.getDiscoveryClients().get(0).description())
then(compositeDiscoveryClient.getDiscoveryClients().get(0).description())
.isEqualTo("A custom discovery client");
assertThat(compositeDiscoveryClient.getDiscoveryClients().get(1))
then(compositeDiscoveryClient.getDiscoveryClients().get(1))
.isInstanceOf(SimpleDiscoveryClient.class);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -27,7 +27,7 @@ import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.BDDAssertions.then;
import static org.springframework.cloud.client.discovery.composite.CompositeDiscoveryClientTestsConfig.CUSTOM_DISCOVERY_CLIENT;
import static org.springframework.cloud.client.discovery.composite.CompositeDiscoveryClientTestsConfig.CUSTOM_SERVICE_ID;
import static org.springframework.cloud.client.discovery.composite.CompositeDiscoveryClientTestsConfig.DEFAULT_ORDER_DISCOVERY_CLIENT;
@@ -54,14 +54,11 @@ public class CompositeDiscoveryClientOrderTest {
.getDiscoveryClients();
// then:
assertThat(discoveryClients.get(0).description())
.isEqualTo(CUSTOM_DISCOVERY_CLIENT);
assertThat(discoveryClients.get(1).description())
then(discoveryClients.get(0).description()).isEqualTo(CUSTOM_DISCOVERY_CLIENT);
then(discoveryClients.get(1).description())
.isEqualTo(DEFAULT_ORDER_DISCOVERY_CLIENT);
assertThat(discoveryClients.get(2).description())
.isEqualTo("Simple Discovery Client");
assertThat(discoveryClients.get(3).description())
.isEqualTo(FOURTH_DISCOVERY_CLIENT);
then(discoveryClients.get(2).description()).isEqualTo("Simple Discovery Client");
then(discoveryClients.get(3).description()).isEqualTo(FOURTH_DISCOVERY_CLIENT);
}
@Test
@@ -71,8 +68,8 @@ public class CompositeDiscoveryClientOrderTest {
.getInstances(CUSTOM_SERVICE_ID);
// then:
assertThat(serviceInstances).hasSize(1);
assertThat(serviceInstances.get(0).getPort()).isEqualTo(123);
then(serviceInstances).hasSize(1);
then(serviceInstances.get(0).getPort()).isEqualTo(123);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -27,7 +27,7 @@ import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.BDDAssertions.then;
import static org.springframework.cloud.client.discovery.composite.CompositeDiscoveryClientTestsConfig.CUSTOM_SERVICE_ID;
/**
@@ -41,7 +41,7 @@ import static org.springframework.cloud.client.discovery.composite.CompositeDisc
"spring.cloud.discovery.client.simple.instances.service1[0].uri=http://s1-1:8080",
"spring.cloud.discovery.client.simple.instances.service1[1].uri=https://s1-2:8443",
"spring.cloud.discovery.client.simple.instances.service2[0].uri=https://s2-1:8080",
"spring.cloud.discovery.client.simple.instances.service2[1].uri=https://s2-2:443", }, classes = {
"spring.cloud.discovery.client.simple.instances.service2[1].uri=https://s2-2:443" }, classes = {
CompositeDiscoveryClientTestsConfig.class })
public class CompositeDiscoveryClientTests {
@@ -50,38 +50,37 @@ public class CompositeDiscoveryClientTests {
@Test
public void getInstancesByServiceIdShouldDelegateCall() {
assertThat(this.discoveryClient).isInstanceOf(CompositeDiscoveryClient.class);
then(this.discoveryClient).isInstanceOf(CompositeDiscoveryClient.class);
assertThat(this.discoveryClient.getInstances("service1")).hasSize(2);
then(this.discoveryClient.getInstances("service1")).hasSize(2);
ServiceInstance s1 = this.discoveryClient.getInstances("service1").get(0);
assertThat(s1.getHost()).isEqualTo("s1-1");
assertThat(s1.getPort()).isEqualTo(8080);
assertThat(s1.getUri()).isEqualTo(URI.create("http://s1-1:8080"));
assertThat(s1.isSecure()).isEqualTo(false);
then(s1.getHost()).isEqualTo("s1-1");
then(s1.getPort()).isEqualTo(8080);
then(s1.getUri()).isEqualTo(URI.create("http://s1-1:8080"));
then(s1.isSecure()).isEqualTo(false);
}
@Test
public void getServicesShouldAggregateAllServiceNames() {
assertThat(this.discoveryClient.getServices()).containsOnlyOnce("service1",
"service2", "custom");
then(this.discoveryClient.getServices()).containsOnlyOnce("service1", "service2",
"custom");
}
@Test
public void getDescriptionShouldBeComposite() {
assertThat(this.discoveryClient.description())
.isEqualTo("Composite Discovery Client");
then(this.discoveryClient.description()).isEqualTo("Composite Discovery Client");
}
@Test
public void getInstancesShouldRespectOrder() {
assertThat(this.discoveryClient.getInstances(CUSTOM_SERVICE_ID)).hasSize(1);
assertThat(this.discoveryClient.getInstances(CUSTOM_SERVICE_ID)).hasSize(1);
then(this.discoveryClient.getInstances(CUSTOM_SERVICE_ID)).hasSize(1);
then(this.discoveryClient.getInstances(CUSTOM_SERVICE_ID)).hasSize(1);
}
@Test
public void getInstancesByUnknownServiceIdShouldReturnAnEmptyList() {
assertThat(this.discoveryClient.getInstances("unknown")).hasSize(0);
then(this.discoveryClient.getInstances("unknown")).hasSize(0);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.

View File

@@ -18,8 +18,7 @@ package org.springframework.cloud.client.discovery.event;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.BDDAssertions.then;
/**
* @author Dave Syer
@@ -30,25 +29,25 @@ public class HeartbeatMonitorTests {
@Test
public void onAndOff() {
assertTrue(this.monitor.update("foo"));
assertFalse(this.monitor.update("foo"));
then(this.monitor.update("foo")).isTrue();
then(this.monitor.update("foo")).isFalse();
}
@Test
public void toggle() {
assertTrue(this.monitor.update("foo"));
assertTrue(this.monitor.update("bar"));
then(this.monitor.update("foo")).isTrue();
then(this.monitor.update("bar")).isTrue();
}
@Test
public void nullInitialValue() {
assertFalse(this.monitor.update(null));
then(this.monitor.update(null)).isFalse();
}
@Test
public void nullSecondValue() {
assertTrue(this.monitor.update("foo"));
assertFalse(this.monitor.update(null));
then(this.monitor.update("foo")).isTrue();
then(this.monitor.update(null)).isFalse();
}
}

View File

@@ -35,8 +35,7 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.assertj.core.api.BDDAssertions.then;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@@ -44,8 +43,10 @@ import static org.mockito.Mockito.mock;
* @author Spencer Gibb
*/
@RunWith(SpringRunner.class)
// @checkstyle:off
@SpringBootTest(classes = { DiscoveryClientHealthIndicatorTests.Config.class,
CommonsClientAutoConfiguration.class }, properties = "spring.cloud.discovery.client.health-indicator.include-description:true")
// @checkstyle:on
public class DiscoveryClientHealthIndicatorTests {
@Autowired
@@ -56,7 +57,7 @@ public class DiscoveryClientHealthIndicatorTests {
@Test
public void testHealthIndicatorDescriptionDisabled() {
assertNotNull("healthIndicator was null", this.healthIndicator);
then(this.healthIndicator).as("healthIndicator was null").isNotNull();
Health health = this.healthIndicator.health();
assertHealth(health, Status.UNKNOWN);
@@ -65,15 +66,15 @@ public class DiscoveryClientHealthIndicatorTests {
health = this.healthIndicator.health();
Status status = assertHealth(health, Status.UP);
assertEquals("status description was wrong", "TestDiscoveryClient",
status.getDescription());
then(status.getDescription()).as("status description was wrong")
.isEqualTo("TestDiscoveryClient");
}
private Status assertHealth(Health health, Status expected) {
assertNotNull("health was null", health);
then(health).as("health was null").isNotNull();
Status status = health.getStatus();
assertNotNull("status was null", status);
assertEquals("status code was wrong", expected.getCode(), status.getCode());
then(status).as("status was null").isNotNull();
then(expected.getCode()).isEqualTo(status.getCode()).as("status code was wrong");
return status;
}

View File

@@ -34,8 +34,7 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.assertj.core.api.BDDAssertions.then;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@@ -55,7 +54,7 @@ public class DiscoveryCompositeHealthIndicatorTests {
@Test
public void testHealthIndicator() {
assertNotNull("healthIndicator was null", this.healthIndicator);
then(this.healthIndicator).as("healthIndicator was null").isNotNull();
Health health = this.healthIndicator.health();
assertHealth(health, Status.UNKNOWN);
@@ -64,14 +63,14 @@ public class DiscoveryCompositeHealthIndicatorTests {
health = this.healthIndicator.health();
Status status = assertHealth(health, Status.UP);
assertEquals("status description was wrong", "", status.getDescription());
then("").isEqualTo(status.getDescription()).as("status description was wrong");
}
protected Status assertHealth(Health health, Status expected) {
assertNotNull("health was null", health);
then(health).as("health was null").isNotNull();
Status status = health.getStatus();
assertNotNull("status was null", status);
assertEquals("status code was wrong", expected.getCode(), status.getCode());
then(status).as("status was null").isNotNull();
then(expected.getCode()).isEqualTo(status.getCode()).as("status code was wrong");
return status;
}

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.client.discovery.simple;
import org.junit.Test;
@@ -11,10 +27,10 @@ import org.springframework.cloud.client.discovery.composite.CompositeDiscoveryCl
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.BDDAssertions.then;
/**
* DiscoveryClient implementation defaults to {@link CompositeDiscoveryClient}
* DiscoveryClient implementation defaults to {@link CompositeDiscoveryClient}.
*
* @author Biju Kunjummen
*/
@@ -27,7 +43,7 @@ public class DiscoveryClientAutoConfigurationDefaultTests {
@Test
public void simpleDiscoveryClientShouldBeTheDefault() {
assertThat(this.discoveryClient).isInstanceOf(CompositeDiscoveryClient.class);
then(this.discoveryClient).isInstanceOf(CompositeDiscoveryClient.class);
}
@EnableAutoConfiguration

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.client.discovery.simple;
import java.net.URI;
@@ -12,7 +28,7 @@ import org.springframework.cloud.client.ServiceInstance;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.BDDAssertions.then;
/**
* Tests for mapping properties to instances in {@link SimpleDiscoveryClient}
@@ -36,51 +52,47 @@ public class SimpleDiscoveryClientPropertiesMappingTests {
@Test
public void propsShouldGetCleanlyMapped() {
assertThat(this.props.getInstances().size()).isEqualTo(2);
assertThat(this.props.getInstances().get("service1").size()).isEqualTo(2);
assertThat(this.props.getInstances().get("service1").get(0).getHost())
then(this.props.getInstances().size()).isEqualTo(2);
then(this.props.getInstances().get("service1").size()).isEqualTo(2);
then(this.props.getInstances().get("service1").get(0).getHost())
.isEqualTo("s1-1");
assertThat(this.props.getInstances().get("service1").get(0).getPort())
.isEqualTo(8080);
assertThat(this.props.getInstances().get("service1").get(0).getUri())
then(this.props.getInstances().get("service1").get(0).getPort()).isEqualTo(8080);
then(this.props.getInstances().get("service1").get(0).getUri())
.isEqualTo(URI.create("http://s1-1:8080"));
assertThat(this.props.getInstances().get("service1").get(0).isSecure())
then(this.props.getInstances().get("service1").get(0).isSecure())
.isEqualTo(false);
assertThat(this.props.getInstances().get("service2").size()).isEqualTo(2);
assertThat(this.props.getInstances().get("service2").get(0).getHost())
then(this.props.getInstances().get("service2").size()).isEqualTo(2);
then(this.props.getInstances().get("service2").get(0).getHost())
.isEqualTo("s2-1");
assertThat(this.props.getInstances().get("service2").get(0).getPort())
.isEqualTo(8080);
assertThat(this.props.getInstances().get("service2").get(0).getUri())
then(this.props.getInstances().get("service2").get(0).getPort()).isEqualTo(8080);
then(this.props.getInstances().get("service2").get(0).getUri())
.isEqualTo(URI.create("https://s2-1:8080"));
assertThat(this.props.getInstances().get("service2").get(0).isSecure())
.isEqualTo(true);
then(this.props.getInstances().get("service2").get(0).isSecure()).isEqualTo(true);
}
@Test
public void testDiscoveryClientShouldResolveSimpleValues() {
assertThat(this.discoveryClient.description())
.isEqualTo("Simple Discovery Client");
assertThat(this.discoveryClient.getInstances("service1")).hasSize(2);
then(this.discoveryClient.description()).isEqualTo("Simple Discovery Client");
then(this.discoveryClient.getInstances("service1")).hasSize(2);
ServiceInstance s1 = this.discoveryClient.getInstances("service1").get(0);
assertThat(s1.getHost()).isEqualTo("s1-1");
assertThat(s1.getPort()).isEqualTo(8080);
assertThat(s1.getUri()).isEqualTo(URI.create("http://s1-1:8080"));
assertThat(s1.isSecure()).isEqualTo(false);
then(s1.getHost()).isEqualTo("s1-1");
then(s1.getPort()).isEqualTo(8080);
then(s1.getUri()).isEqualTo(URI.create("http://s1-1:8080"));
then(s1.isSecure()).isEqualTo(false);
}
@Test
public void testGetServices() {
assertThat(this.discoveryClient.getServices())
.containsExactlyInAnyOrder("service1", "service2");
then(this.discoveryClient.getServices()).containsExactlyInAnyOrder("service1",
"service2");
}
@Test
public void testGetANonExistentServiceShouldReturnAnEmptyList() {
assertThat(this.discoveryClient.getInstances("nonexistent")).isNotNull();
assertThat(this.discoveryClient.getInstances("nonexistent")).isEmpty();
then(this.discoveryClient.getInstances("nonexistent")).isNotNull();
then(this.discoveryClient.getInstances("nonexistent")).isEmpty();
}
@Configuration

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.client.discovery.simple;
import java.net.URI;
@@ -12,7 +28,7 @@ import org.junit.Test;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.simple.SimpleDiscoveryProperties.SimpleServiceInstance;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.BDDAssertions.then;
/**
* @author Biju Kunjummen
@@ -40,13 +56,13 @@ public class SimpleDiscoveryClientTests {
public void shouldBeAbleToRetrieveServiceDetailsByName() {
List<ServiceInstance> instances = this.simpleDiscoveryClient
.getInstances("service1");
assertThat(instances.size()).isEqualTo(2);
assertThat(instances.get(0).getServiceId()).isEqualTo("service1");
assertThat(instances.get(0).getHost()).isEqualTo("host1");
assertThat(instances.get(0).getPort()).isEqualTo(8080);
assertThat(instances.get(0).getUri()).isEqualTo(URI.create("http://host1:8080"));
assertThat(instances.get(0).isSecure()).isEqualTo(false);
assertThat(instances.get(0).getMetadata()).isNotNull();
then(instances.size()).isEqualTo(2);
then(instances.get(0).getServiceId()).isEqualTo("service1");
then(instances.get(0).getHost()).isEqualTo("host1");
then(instances.get(0).getPort()).isEqualTo(8080);
then(instances.get(0).getUri()).isEqualTo(URI.create("http://host1:8080"));
then(instances.get(0).isSecure()).isEqualTo(false);
then(instances.get(0).getMetadata()).isNotNull();
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.client.hypermedia;
import org.junit.Test;
@@ -25,11 +26,7 @@ import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import static org.hamcrest.Matchers.arrayWithSize;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
import static org.assertj.core.api.BDDAssertions.then;
/**
* Integration tests for {@link CloudHypermediaAutoConfiguration}.
@@ -54,8 +51,8 @@ public class CloudHypermediaAutoConfigurationIntegrationTests {
CloudHypermediaProperties properties = context
.getBean(CloudHypermediaProperties.class);
assertThat(properties.getRefresh().getInitialDelay(), is(50000));
assertThat(properties.getRefresh().getFixedDelay(), is(10000));
then(properties.getRefresh().getInitialDelay()).isEqualTo(50000);
then(properties.getRefresh().getFixedDelay()).isEqualTo(10000);
}
}
@@ -64,8 +61,7 @@ public class CloudHypermediaAutoConfigurationIntegrationTests {
try (ConfigurableApplicationContext context = getApplicationContext(
Config.class)) {
assertThat(context.getBeanNamesForType(CloudHypermediaProperties.class),
is(arrayWithSize(0)));
then(context.getBeanNamesForType(CloudHypermediaProperties.class)).hasSize(0);
}
}
@@ -75,9 +71,8 @@ public class CloudHypermediaAutoConfigurationIntegrationTests {
try (ConfigurableApplicationContext context = getApplicationContext(
Config.class)) {
assertThat(context.getBeansOfType(RemoteResource.class).values(), hasSize(0));
assertThat(context.getBeanNamesForType(RemoteResourceRefresher.class),
is(arrayWithSize(0)));
then(context.getBeansOfType(RemoteResource.class).values()).hasSize(0);
then(context.getBeanNamesForType(RemoteResourceRefresher.class)).hasSize(0);
}
}
@@ -87,9 +82,8 @@ public class CloudHypermediaAutoConfigurationIntegrationTests {
try (ConfigurableApplicationContext context = getApplicationContext(
ConfigWithRemoteResource.class)) {
assertThat(context.getBeansOfType(RemoteResource.class).values(), hasSize(1));
assertThat(context.getBean(RemoteResourceRefresher.class),
is(notNullValue()));
then(context.getBeansOfType(RemoteResource.class).values()).hasSize(1);
then(context.getBean(RemoteResourceRefresher.class)).isNotNull();
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.client.hypermedia;
import org.junit.Before;
@@ -25,14 +26,10 @@ import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.cloud.client.DefaultServiceInstance;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.client.Traverson;
import org.springframework.hateoas.client.Traverson.TraversalBuilder;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestOperations;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;
import static org.assertj.core.api.BDDAssertions.then;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
@@ -53,7 +50,7 @@ public class DiscoveredResourceUnitTests {
TraversalDefinition traversal;
@Mock
TraversalBuilder builder;
Traverson.TraversalBuilder builder;
@Mock
RestOperations operations;
@@ -71,7 +68,7 @@ public class DiscoveredResourceUnitTests {
@Test
public void isUndiscoveredByDefault() {
assertThat(this.resource.getLink(), is(nullValue()));
then(this.resource.getLink()).isNull();
}
@Test
@@ -85,7 +82,7 @@ public class DiscoveredResourceUnitTests {
this.resource.verifyOrDiscover();
assertThat(this.resource.getLink(), is(link));
then(this.resource.getLink()).isEqualTo(link);
verify(this.provider, times(1)).getServiceInstance();
verify(this.traversal, times(1)).buildTraversal(Matchers.any(Traverson.class));
}
@@ -97,7 +94,7 @@ public class DiscoveredResourceUnitTests {
this.resource.verifyOrDiscover();
assertThat(this.resource.getLink(), is(notNullValue()));
then(this.resource.getLink()).isNotNull();
verify(this.operations, times(1)).headForHeaders(anyString());
}
@@ -110,7 +107,7 @@ public class DiscoveredResourceUnitTests {
.headForHeaders(anyString());
this.resource.verifyOrDiscover();
assertThat(this.resource.getLink(), is(nullValue()));
then(this.resource.getLink()).isNull();
}
@Test
@@ -120,7 +117,7 @@ public class DiscoveredResourceUnitTests {
this.resource.verifyOrDiscover();
assertThat(this.resource.getLink(), is(nullValue()));
then(this.resource.getLink()).isNull();
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.client.hypermedia;
import java.util.Arrays;
@@ -25,9 +26,7 @@ import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;
import static org.assertj.core.api.BDDAssertions.then;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -43,8 +42,8 @@ public class DynamicServiceInstanceProviderUnitTests {
@Test
public void returnsNoServiceInCaseNoneIsAvailable() {
assertThat(new DynamicServiceInstanceProvider(this.client, "service")
.getServiceInstance(), is(nullValue()));
then(new DynamicServiceInstanceProvider(this.client, "service")
.getServiceInstance()).isNull();
}
@Test
@@ -56,8 +55,8 @@ public class DynamicServiceInstanceProviderUnitTests {
when(this.client.getInstances(anyString()))
.thenReturn(Arrays.asList(first, second));
assertThat(new DynamicServiceInstanceProvider(this.client, "service")
.getServiceInstance(), is(first));
then(new DynamicServiceInstanceProvider(this.client, "service")
.getServiceInstance()).isEqualTo(first);
}
}

View File

@@ -35,11 +35,7 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.web.client.RestTemplate;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.assertj.core.api.BDDAssertions.then;
/**
* @author Ryan Baxter
@@ -53,10 +49,10 @@ public abstract class AbstractLoadBalancerAutoConfigurationTests {
final Map<String, RestTemplate> restTemplates = context
.getBeansOfType(RestTemplate.class);
assertThat(restTemplates, is(notNullValue()));
assertThat(restTemplates.values(), hasSize(1));
then(restTemplates).isNotNull();
then(restTemplates.values()).hasSize(1);
RestTemplate restTemplate = restTemplates.values().iterator().next();
assertThat(restTemplate, is(notNullValue()));
then(restTemplate).isNotNull();
assertLoadBalanced(restTemplate);
}
@@ -69,17 +65,17 @@ public abstract class AbstractLoadBalancerAutoConfigurationTests {
final Map<String, RestTemplate> restTemplates = context
.getBeansOfType(RestTemplate.class);
assertThat(restTemplates, is(notNullValue()));
then(restTemplates).isNotNull();
Collection<RestTemplate> templates = restTemplates.values();
assertThat(templates, hasSize(2));
then(templates).hasSize(2);
TwoRestTemplates.Two two = context.getBean(TwoRestTemplates.Two.class);
assertThat(two.loadBalanced, is(notNullValue()));
then(two.loadBalanced).isNotNull();
assertLoadBalanced(two.loadBalanced);
assertThat(two.nonLoadBalanced, is(notNullValue()));
assertThat(two.nonLoadBalanced.getInterceptors(), is(empty()));
then(two.nonLoadBalanced).isNotNull();
then(two.nonLoadBalanced.getInterceptors()).isEmpty();
}
protected ConfigurableApplicationContext init(Class<?> config) {

View File

@@ -23,7 +23,6 @@ import java.util.List;
import java.util.Map;
import java.util.Random;
import org.hamcrest.MatcherAssert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
@@ -38,11 +37,7 @@ import org.springframework.context.annotation.Primary;
import org.springframework.http.client.AsyncClientHttpRequestInterceptor;
import org.springframework.web.client.AsyncRestTemplate;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.assertj.core.api.BDDAssertions.then;
/**
* @author Rob Worsnop
@@ -56,10 +51,10 @@ public class AsyncLoadBalancerAutoConfigurationTests {
final Map<String, AsyncRestTemplate> restTemplates = context
.getBeansOfType(AsyncRestTemplate.class);
MatcherAssert.assertThat(restTemplates, is(notNullValue()));
MatcherAssert.assertThat(restTemplates.values(), hasSize(1));
then(restTemplates).isNotNull();
then(restTemplates.values()).hasSize(1);
AsyncRestTemplate restTemplate = restTemplates.values().iterator().next();
MatcherAssert.assertThat(restTemplate, is(notNullValue()));
then(restTemplate).isNotNull();
assertLoadBalanced(restTemplate);
}
@@ -67,10 +62,9 @@ public class AsyncLoadBalancerAutoConfigurationTests {
private void assertLoadBalanced(AsyncRestTemplate restTemplate) {
List<AsyncClientHttpRequestInterceptor> interceptors = restTemplate
.getInterceptors();
MatcherAssert.assertThat(interceptors, hasSize(1));
then(interceptors).hasSize(1);
AsyncClientHttpRequestInterceptor interceptor = interceptors.get(0);
MatcherAssert.assertThat(interceptor,
is(instanceOf(AsyncLoadBalancerInterceptor.class)));
then(interceptor).isInstanceOf(AsyncLoadBalancerInterceptor.class);
}
@Test
@@ -79,17 +73,17 @@ public class AsyncLoadBalancerAutoConfigurationTests {
final Map<String, AsyncRestTemplate> restTemplates = context
.getBeansOfType(AsyncRestTemplate.class);
MatcherAssert.assertThat(restTemplates, is(notNullValue()));
then(restTemplates).isNotNull();
Collection<AsyncRestTemplate> templates = restTemplates.values();
MatcherAssert.assertThat(templates, hasSize(2));
then(templates).hasSize(2);
TwoRestTemplates.Two two = context.getBean(TwoRestTemplates.Two.class);
MatcherAssert.assertThat(two.loadBalanced, is(notNullValue()));
then(two.loadBalanced).isNotNull();
assertLoadBalanced(two.loadBalanced);
MatcherAssert.assertThat(two.nonLoadBalanced, is(notNullValue()));
MatcherAssert.assertThat(two.nonLoadBalanced.getInterceptors(), is(empty()));
then(two.nonLoadBalanced).isNotNull();
then(two.nonLoadBalanced.getInterceptors()).isEmpty();
}
protected ConfigurableApplicationContext init(Class<?> config) {

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.client.loadbalancer;
import java.io.ByteArrayInputStream;
@@ -13,8 +29,7 @@ import org.springframework.http.client.AbstractClientHttpResponse;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.util.StreamUtils;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.assertj.core.api.BDDAssertions.then;
/**
* @author Ryan Baxter
@@ -25,15 +40,15 @@ public class ClientHttpResponseStatusCodeExceptionTest {
@Test
public void testCreation() throws Exception {
MyClientHttpResponse response = new MyClientHttpResponse();
assertFalse(response.isClosed());
then(response.isClosed()).isFalse();
ClientHttpResponseStatusCodeException exp = new ClientHttpResponseStatusCodeException(
"service", response, response.getStatusText().getBytes());
ClientHttpResponse expResponse = exp.getResponse();
assertEquals(response.getRawStatusCode(), expResponse.getRawStatusCode());
assertEquals(response.getStatusText(), expResponse.getStatusText());
assertEquals(response.getHeaders(), expResponse.getHeaders());
assertEquals(response.getStatusText(),
new String(StreamUtils.copyToByteArray(expResponse.getBody())));
then(expResponse.getRawStatusCode()).isEqualTo(response.getRawStatusCode());
then(expResponse.getStatusText()).isEqualTo(response.getStatusText());
then(expResponse.getHeaders()).isEqualTo(response.getHeaders());
then(new String(StreamUtils.copyToByteArray(expResponse.getBody())))
.isEqualTo(response.getStatusText());
}
class MyClientHttpResponse extends AbstractClientHttpResponse {

View File

@@ -1,6 +1,21 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.client.loadbalancer;
import org.hamcrest.core.IsInstanceOf;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -11,8 +26,7 @@ import org.springframework.cloud.client.ServiceInstance;
import org.springframework.http.HttpRequest;
import org.springframework.retry.RetryContext;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.assertj.core.api.BDDAssertions.then;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
@@ -58,7 +72,7 @@ public class InterceptorRetryPolicyTest {
ServiceInstance serviceInstance = mock(ServiceInstance.class);
when(this.serviceInstanceChooser.choose(eq(this.serviceName)))
.thenReturn(serviceInstance);
assertThat(interceptorRetryPolicy.canRetry(context), is(true));
then(interceptorRetryPolicy.canRetry(context)).isTrue();
verify(context, times(1)).setServiceInstance(eq(serviceInstance));
}
@@ -70,7 +84,7 @@ public class InterceptorRetryPolicyTest {
LoadBalancedRetryContext context = mock(LoadBalancedRetryContext.class);
when(context.getRetryCount()).thenReturn(1);
when(this.policy.canRetryNextServer(eq(context))).thenReturn(true);
assertThat(interceptorRetryPolicy.canRetry(context), is(true));
then(interceptorRetryPolicy.canRetry(context)).isTrue();
}
@Test
@@ -79,7 +93,7 @@ public class InterceptorRetryPolicyTest {
this.request, this.policy, this.serviceInstanceChooser, this.serviceName);
LoadBalancedRetryContext context = mock(LoadBalancedRetryContext.class);
when(context.getRetryCount()).thenReturn(1);
assertThat(interceptorRetryPolicy.canRetry(context), is(false));
then(interceptorRetryPolicy.canRetry(context)).isFalse();
}
@Test
@@ -87,7 +101,7 @@ public class InterceptorRetryPolicyTest {
InterceptorRetryPolicy interceptorRetryPolicy = new InterceptorRetryPolicy(
this.request, this.policy, this.serviceInstanceChooser, this.serviceName);
RetryContext context = interceptorRetryPolicy.open(null);
assertThat(context, IsInstanceOf.instanceOf(LoadBalancedRetryContext.class));
then(context).isInstanceOf(LoadBalancedRetryContext.class);
}
@Test
@@ -114,13 +128,11 @@ public class InterceptorRetryPolicyTest {
public void equals() throws Exception {
InterceptorRetryPolicy interceptorRetryPolicy = new InterceptorRetryPolicy(
this.request, this.policy, this.serviceInstanceChooser, this.serviceName);
assertThat(interceptorRetryPolicy.equals(null), is(false));
assertThat(interceptorRetryPolicy.equals(new Object()), is(false));
assertThat(interceptorRetryPolicy.equals(interceptorRetryPolicy), is(true));
assertThat(
interceptorRetryPolicy.equals(new InterceptorRetryPolicy(this.request,
this.policy, this.serviceInstanceChooser, this.serviceName)),
is(true));
then(interceptorRetryPolicy.equals(null)).isFalse();
then(interceptorRetryPolicy.equals(new Object())).isFalse();
then(interceptorRetryPolicy.equals(interceptorRetryPolicy)).isTrue();
then(interceptorRetryPolicy.equals(new InterceptorRetryPolicy(this.request,
this.policy, this.serviceInstanceChooser, this.serviceName))).isTrue();
}
}

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.client.loadbalancer;
import org.junit.After;
@@ -10,8 +26,7 @@ import org.springframework.cloud.client.ServiceInstance;
import org.springframework.http.HttpRequest;
import org.springframework.retry.RetryContext;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.assertj.core.api.BDDAssertions.then;
import static org.mockito.Mockito.mock;
/**
@@ -40,7 +55,7 @@ public class LoadBalancedRetryContextTest {
public void getRequest() throws Exception {
LoadBalancedRetryContext lbContext = new LoadBalancedRetryContext(this.context,
this.request);
assertThat(lbContext.getRequest(), is(this.request));
then(lbContext.getRequest()).isEqualTo(this.request);
}
@Test
@@ -49,7 +64,7 @@ public class LoadBalancedRetryContextTest {
this.request);
HttpRequest newRequest = mock(HttpRequest.class);
lbContext.setRequest(newRequest);
assertThat(lbContext.getRequest(), is(newRequest));
then(lbContext.getRequest()).isEqualTo(newRequest);
}
@Test
@@ -58,7 +73,7 @@ public class LoadBalancedRetryContextTest {
this.request);
ServiceInstance serviceInstance = mock(ServiceInstance.class);
lbContext.setServiceInstance(serviceInstance);
assertThat(lbContext.getServiceInstance(), is(serviceInstance));
then(lbContext.getServiceInstance()).isEqualTo(serviceInstance);
}
}

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.client.loadbalancer;
import java.util.List;
@@ -9,10 +25,7 @@ import org.springframework.cloud.test.ModifiedClassPathRunner;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.client.RestTemplate;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.assertj.core.api.BDDAssertions.then;
/**
* @author Spencer Gibb
@@ -25,9 +38,9 @@ public class LoadBalancerAutoConfigurationTests
@Override
protected void assertLoadBalanced(RestTemplate restTemplate) {
List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
assertThat(interceptors, hasSize(1));
then(interceptors).hasSize(1);
ClientHttpRequestInterceptor interceptor = interceptors.get(0);
assertThat(interceptor, is(instanceOf(LoadBalancerInterceptor.class)));
then(interceptor).isInstanceOf(LoadBalancerInterceptor.class);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.client.loadbalancer;
import org.junit.Before;
@@ -32,7 +33,7 @@ import org.springframework.core.annotation.Order;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.BDDAssertions.then;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
@@ -94,9 +95,9 @@ public class LoadBalancerRequestFactoryConfigurationTests {
this.lbRequest.apply(this.instance);
verify(this.execution).execute(this.httpRequestCaptor.capture(), eq(this.body));
assertEquals(
"transformer should have transformed the ServiceRequestWrapper into transformedRequest",
this.transformedRequest, this.httpRequestCaptor.getValue());
then(this.httpRequestCaptor.getValue()).as(
"transformer should have transformed the ServiceRequestWrapper into transformedRequest")
.isEqualTo(this.transformedRequest);
}
@Test
@@ -106,9 +107,9 @@ public class LoadBalancerRequestFactoryConfigurationTests {
this.lbRequest.apply(this.instance);
verify(this.execution).execute(this.httpRequestCaptor.capture(), eq(this.body));
assertEquals("ServiceRequestWrapper should be executed",
ServiceRequestWrapper.class,
this.httpRequestCaptor.getValue().getClass());
then(this.httpRequestCaptor.getValue().getClass())
.as("ServiceRequestWrapper should be executed")
.isEqualTo(ServiceRequestWrapper.class);
}
@Test
@@ -127,8 +128,9 @@ public class LoadBalancerRequestFactoryConfigurationTests {
this.lbRequest.apply(this.instance);
verify(this.execution).execute(this.httpRequestCaptor.capture(), eq(this.body));
assertEquals("transformer2 should run after transformer",
this.transformedRequest2, this.httpRequestCaptor.getValue());
then(this.httpRequestCaptor.getValue())
.as("transformer2 should run after transformer")
.isEqualTo(this.transformedRequest2);
}
@Configuration

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,13 +13,13 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.client.loadbalancer;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -32,7 +32,7 @@ import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpResponse;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.BDDAssertions.then;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.verify;
@@ -79,9 +79,9 @@ public class LoadBalancerRequestFactoryTests {
executeLbRequest(null);
verify(this.execution).execute(this.httpRequestCaptor.capture(), eq(this.body));
Assert.assertEquals("request should be of type ServiceRequestWrapper",
ServiceRequestWrapper.class,
this.httpRequestCaptor.getValue().getClass());
then(this.httpRequestCaptor.getValue().getClass())
.as("request should be of type ServiceRequestWrapper")
.isEqualTo(ServiceRequestWrapper.class);
}
@Test
@@ -91,9 +91,9 @@ public class LoadBalancerRequestFactoryTests {
executeLbRequest(transformers);
verify(this.execution).execute(this.httpRequestCaptor.capture(), eq(this.body));
Assert.assertEquals("request should be of type ServiceRequestWrapper",
ServiceRequestWrapper.class,
this.httpRequestCaptor.getValue().getClass());
then(this.httpRequestCaptor.getValue().getClass())
.as("request should be of type ServiceRequestWrapper")
.isEqualTo(ServiceRequestWrapper.class);
}
@Test
@@ -106,9 +106,9 @@ public class LoadBalancerRequestFactoryTests {
executeLbRequest(transformers);
verify(this.execution).execute(this.httpRequestCaptor.capture(), eq(this.body));
assertEquals(
"transformer1 should have transformed request into transformedRequest1",
this.transformedRequest1, this.httpRequestCaptor.getValue());
then(this.httpRequestCaptor.getValue()).as(
"transformer1 should have transformed request into transformedRequest1")
.isEqualTo(this.transformedRequest1);
}
@Test
@@ -123,9 +123,9 @@ public class LoadBalancerRequestFactoryTests {
executeLbRequest(transformers);
verify(this.execution).execute(this.httpRequestCaptor.capture(), eq(this.body));
assertEquals(
"transformer2 should have transformed transformedRequest1 into transformedRequest2",
this.transformedRequest2, this.httpRequestCaptor.getValue());
then(this.httpRequestCaptor.getValue()).as(
"transformer2 should have transformed transformedRequest1 into transformedRequest2")
.isEqualTo(this.transformedRequest2);
}
private void executeLbRequest(List<LoadBalancerRequestTransformer> transformers)

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.client.loadbalancer;
import java.util.List;
@@ -9,10 +25,7 @@ import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.retry.backoff.NoBackOffPolicy;
import org.springframework.web.client.RestTemplate;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.assertj.core.api.BDDAssertions.then;
/**
* @author Ryan Baxter
@@ -23,9 +36,9 @@ public class RetryLoadBalancerAutoConfigurationTests
@Override
protected void assertLoadBalanced(RestTemplate restTemplate) {
List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
assertThat(interceptors, hasSize(1));
then(interceptors).hasSize(1);
ClientHttpRequestInterceptor interceptor = interceptors.get(0);
assertThat(interceptor, is(instanceOf(RetryLoadBalancerInterceptor.class)));
then(interceptor).isInstanceOf(RetryLoadBalancerInterceptor.class);
}
@Test
@@ -33,10 +46,9 @@ public class RetryLoadBalancerAutoConfigurationTests
ConfigurableApplicationContext context = init(OneRestTemplate.class);
LoadBalancedRetryFactory loadBalancedRetryFactory = context
.getBean(LoadBalancedRetryFactory.class);
assertThat(loadBalancedRetryFactory,
is(instanceOf(LoadBalancedRetryFactory.class)));
assertThat(loadBalancedRetryFactory.createBackOffPolicy("foo"),
is(instanceOf(NoBackOffPolicy.class)));
then(loadBalancedRetryFactory).isInstanceOf(LoadBalancedRetryFactory.class);
then(loadBalancedRetryFactory.createBackOffPolicy("foo"))
.isInstanceOf(NoBackOffPolicy.class);
}
}

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.client.loadbalancer;
import java.io.ByteArrayInputStream;
@@ -28,8 +44,7 @@ import org.springframework.retry.backoff.BackOffPolicy;
import org.springframework.retry.backoff.NoBackOffPolicy;
import org.springframework.retry.listener.RetryListenerSupport;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.assertj.core.api.BDDAssertions.then;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
@@ -145,7 +160,7 @@ public class RetryLoadBalancerInterceptorTest {
byte[] body = new byte[] {};
ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class);
ClientHttpResponse rsp = interceptor.intercept(request, body, execution);
assertThat(rsp, is(clientHttpResponse));
then(rsp).isEqualTo(clientHttpResponse);
verify(this.lbRequestFactory).createRequest(request, body, execution);
}
@@ -180,7 +195,7 @@ public class RetryLoadBalancerInterceptorTest {
verify(this.client, times(2)).execute(eq("foo"), eq(serviceInstance),
nullable(LoadBalancerRequest.class));
verify(notFoundStream, times(1)).close();
assertThat(rsp, is(clientHttpResponseOk));
then(rsp).isEqualTo(clientHttpResponseOk);
verify(this.lbRequestFactory, times(2)).createRequest(request, body, execution);
}
@@ -221,8 +236,8 @@ public class RetryLoadBalancerInterceptorTest {
// call twice in a retry attempt
byte[] content = new byte[1024];
int length = rsp.getBody().read(content);
assertThat(length, is("foo".getBytes().length));
assertThat(new String(content, 0, length), is("foo"));
then(length).isEqualTo("foo".getBytes().length);
then(new String(content, 0, length)).isEqualTo("foo");
}
@Test
@@ -251,9 +266,9 @@ public class RetryLoadBalancerInterceptorTest {
ClientHttpResponse rsp = interceptor.intercept(request, body, execution);
verify(this.client, times(2)).execute(eq("foo"), eq(serviceInstance),
any(LoadBalancerRequest.class));
assertThat(rsp, is(clientHttpResponse));
then(rsp).isEqualTo(clientHttpResponse);
verify(this.lbRequestFactory, times(2)).createRequest(request, body, execution);
assertThat(backOffPolicy.getBackoffAttempts(), is(1));
then(backOffPolicy.getBackoffAttempts()).isEqualTo(1);
}
@Test(expected = IOException.class)
@@ -310,10 +325,10 @@ public class RetryLoadBalancerInterceptorTest {
ClientHttpResponse rsp = interceptor.intercept(request, body, execution);
verify(this.client, times(2)).execute(eq("listener"), eq(serviceInstance),
any(LoadBalancerRequest.class));
assertThat(rsp, is(clientHttpResponse));
then(rsp).isEqualTo(clientHttpResponse);
verify(this.lbRequestFactory, times(2)).createRequest(request, body, execution);
assertThat(backOffPolicy.getBackoffAttempts(), is(1));
assertThat(retryListener.getOnError(), is(1));
then(backOffPolicy.getBackoffAttempts()).isEqualTo(1);
then(retryListener.getOnError()).isEqualTo(1);
}
@Test(expected = TerminatedRetryException.class)
@@ -364,9 +379,9 @@ public class RetryLoadBalancerInterceptorTest {
ClientHttpResponse rsp = interceptor.intercept(request, body, execution);
verify(this.client, times(2)).execute(eq("default"), eq(serviceInstance),
any(LoadBalancerRequest.class));
assertThat(rsp, is(clientHttpResponse));
then(rsp).isEqualTo(clientHttpResponse);
verify(this.lbRequestFactory, times(2)).createRequest(request, body, execution);
assertThat(backOffPolicy.getBackoffAttempts(), is(1));
then(backOffPolicy.getBackoffAttempts()).isEqualTo(1);
}
class MyLoadBalancedRetryFactory implements LoadBalancedRetryFactory {
@@ -377,18 +392,17 @@ public class RetryLoadBalancerInterceptorTest {
private RetryListener[] retryListeners;
public MyLoadBalancedRetryFactory(
LoadBalancedRetryPolicy loadBalancedRetryPolicy) {
MyLoadBalancedRetryFactory(LoadBalancedRetryPolicy loadBalancedRetryPolicy) {
this.loadBalancedRetryPolicy = loadBalancedRetryPolicy;
}
public MyLoadBalancedRetryFactory(LoadBalancedRetryPolicy loadBalancedRetryPolicy,
MyLoadBalancedRetryFactory(LoadBalancedRetryPolicy loadBalancedRetryPolicy,
BackOffPolicy backOffPolicy) {
this(loadBalancedRetryPolicy);
this.backOffPolicy = backOffPolicy;
}
public MyLoadBalancedRetryFactory(LoadBalancedRetryPolicy loadBalancedRetryPolicy,
MyLoadBalancedRetryFactory(LoadBalancedRetryPolicy loadBalancedRetryPolicy,
BackOffPolicy backOffPolicy, RetryListener[] retryListeners) {
this(loadBalancedRetryPolicy, backOffPolicy);
this.retryListeners = retryListeners;

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.client.loadbalancer.reactive;
import java.io.IOException;
@@ -31,7 +47,7 @@ import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.util.UriComponentsBuilder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.BDDAssertions.then;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/**
@@ -64,21 +80,21 @@ public class LoadBalancerExchangeFilterFunctionTests {
String value = WebClient.builder().baseUrl("http://testservice")
.filter(this.lbFunction).build().get().uri("/hello").retrieve()
.bodyToMono(String.class).block();
assertThat(value).isEqualTo("Hello World");
then(value).isEqualTo("Hello World");
}
@Test
public void testNoInstance() {
ClientResponse clientResponse = WebClient.builder().baseUrl("http://foobar")
.filter(this.lbFunction).build().get().exchange().block();
assertThat(clientResponse.statusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE);
then(clientResponse.statusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE);
}
@Test
public void testNoHostName() {
ClientResponse clientResponse = WebClient.builder().baseUrl("http:///foobar")
.filter(this.lbFunction).build().get().exchange().block();
assertThat(clientResponse.statusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
then(clientResponse.statusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
}
@EnableDiscoveryClient

View File

@@ -42,7 +42,7 @@ import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
import org.springframework.web.reactive.function.client.WebClient;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.BDDAssertions.then;
/**
* @author Spencer Gibb
@@ -56,18 +56,18 @@ public class ReactiveLoadBalancerAutoConfigurationTests {
final Map<String, WebClient.Builder> webClientBuilders = context
.getBeansOfType(WebClient.Builder.class);
assertThat(webClientBuilders).isNotNull().hasSize(1);
then(webClientBuilders).isNotNull().hasSize(1);
WebClient.Builder webClientBuilder = webClientBuilders.values().iterator().next();
assertThat(webClientBuilder).isNotNull();
then(webClientBuilder).isNotNull();
assertLoadBalanced(webClientBuilder);
}
private void assertLoadBalanced(WebClient.Builder webClientBuilder) {
List<ExchangeFilterFunction> filters = getFilters(webClientBuilder);
assertThat(filters).hasSize(1);
then(filters).hasSize(1);
ExchangeFilterFunction interceptor = filters.get(0);
assertThat(interceptor).isInstanceOf(LoadBalancerExchangeFilterFunction.class);
then(interceptor).isInstanceOf(LoadBalancerExchangeFilterFunction.class);
}
@SuppressWarnings("unchecked")
@@ -82,15 +82,15 @@ public class ReactiveLoadBalancerAutoConfigurationTests {
final Map<String, WebClient.Builder> webClientBuilders = context
.getBeansOfType(WebClient.Builder.class);
assertThat(webClientBuilders).hasSize(2);
then(webClientBuilders).hasSize(2);
TwoWebClientBuilders.Two two = context.getBean(TwoWebClientBuilders.Two.class);
assertThat(two.loadBalanced).isNotNull();
then(two.loadBalanced).isNotNull();
assertLoadBalanced(two.loadBalanced);
assertThat(two.nonLoadBalanced).isNotNull();
assertThat(getFilters(two.nonLoadBalanced)).isNullOrEmpty();
then(two.nonLoadBalanced).isNotNull();
then(getFilters(two.nonLoadBalanced)).isNullOrEmpty();
}
@Test
@@ -99,12 +99,12 @@ public class ReactiveLoadBalancerAutoConfigurationTests {
final Map<String, WebClient.Builder> webClientBuilders = context
.getBeansOfType(WebClient.Builder.class);
assertThat(webClientBuilders).hasSize(1);
then(webClientBuilders).hasSize(1);
WebClient.Builder builder = context.getBean(WebClient.Builder.class);
assertThat(builder).isNotNull();
assertThat(getFilters(builder)).isNullOrEmpty();
then(builder).isNotNull();
then(getFilters(builder)).isNullOrEmpty();
}
protected ConfigurableApplicationContext init(Class<?> config) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,7 +20,7 @@ import java.net.URI;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.assertj.core.api.Assertions;
import org.assertj.core.api.BDDAssertions;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -48,7 +48,7 @@ public class AbstractAutoServiceRegistrationMgmtDisabledTests {
@Test
public void portsWork() {
Assertions.assertThat(this.autoRegistration.shouldRegisterManagement()).isFalse();
BDDAssertions.then(this.autoRegistration.shouldRegisterManagement()).isFalse();
}
@EnableAutoConfiguration

View File

@@ -35,12 +35,7 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.BDDAssertions.then;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/**
@@ -48,7 +43,9 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* @author Tim Ysewyn
*/
@RunWith(SpringRunner.class)
// @checkstyle:off
@SpringBootTest(classes = AbstractAutoServiceRegistrationTests.Config.class, properties = "management.port=0", webEnvironment = RANDOM_PORT)
// @checkstyle:on
public class AbstractAutoServiceRegistrationTests {
@Autowired
@@ -68,30 +65,30 @@ public class AbstractAutoServiceRegistrationTests {
@Test
public void portsWork() {
assertNotEquals("Lifecycle port is zero", 0,
this.autoRegistration.getPort().get());
assertNotEquals("Lifecycle port is management port", this.managementPort,
this.autoRegistration.getPort().get());
assertEquals("Lifecycle port is wrong", this.port,
this.autoRegistration.getPort().get());
assertTrue("Lifecycle not running", this.autoRegistration.isRunning());
assertThat("ServiceRegistry is wrong type",
this.autoRegistration.getServiceRegistry(),
is(instanceOf(TestServiceRegistry.class)));
then(this.autoRegistration.getPort().get()).isNotEqualTo(0)
.as("Lifecycle port is zero");
then(this.managementPort).isNotEqualTo(this.autoRegistration.getPort().get())
.as("Lifecycle port is management port");
then(this.port).isEqualTo(this.autoRegistration.getPort().get())
.as("Lifecycle port is wrong");
then(this.autoRegistration.isRunning()).isTrue().as("Lifecycle not running");
then(this.autoRegistration.getServiceRegistry())
.isInstanceOf(TestServiceRegistry.class)
.as("ServiceRegistry is wrong type");
TestServiceRegistry serviceRegistry = (TestServiceRegistry) this.autoRegistration
.getServiceRegistry();
assertTrue("Lifecycle not registered", serviceRegistry.isRegistered());
assertEquals("Lifecycle appName is wrong", "application",
this.autoRegistration.getAppName());
then(serviceRegistry.isRegistered()).isTrue().as("Lifecycle not registered");
then(this.autoRegistration.getAppName()).as("Lifecycle appName is wrong")
.isEqualTo("application");
}
@Test
public void eventsFireTest() {
assertTrue(this.preEventListener.wasFired);
assertEquals("testRegistration2",
this.preEventListener.registration.getServiceId());
assertTrue(this.postEventListener.wasFired);
assertEquals("testRegistration2", this.postEventListener.config.getServiceId());
then(this.preEventListener.wasFired).isTrue();
then(this.preEventListener.registration.getServiceId())
.isEqualTo("testRegistration2");
then(this.postEventListener.wasFired).isTrue();
then(this.postEventListener.config.getServiceId()).isEqualTo("testRegistration2");
}
@EnableAutoConfiguration

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.client.serviceregistry;
import java.util.ArrayList;
@@ -16,7 +32,7 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.BDDAssertions.then;
/**
* @author Spencer Gibb
@@ -32,7 +48,7 @@ public class AutoServiceRegistrationAutoConfigurationTests {
HasAutoServiceRegistrationConfiguration.class)) {
AutoServiceRegistration autoServiceRegistration = context
.getBean(AutoServiceRegistration.class);
assertThat(autoServiceRegistration).isNotNull();
then(autoServiceRegistration).isNotNull();
}
}
@@ -57,7 +73,7 @@ public class AutoServiceRegistrationAutoConfigurationTests {
private void assertNoBean(AnnotationConfigApplicationContext context) {
Map<String, AutoServiceRegistration> beans = context
.getBeansOfType(AutoServiceRegistration.class);
assertThat(beans).isEmpty();
then(beans).isEmpty();
}
private AnnotationConfigApplicationContext setup(Class... classes) {

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.client.serviceregistry;
import org.junit.Test;

View File

@@ -63,7 +63,7 @@ public class ServiceRegistryEndpointNoRegistrationTests {
@Import({ JacksonAutoConfiguration.class,
HttpMessageConvertersAutoConfiguration.class, EndpointAutoConfiguration.class,
WebMvcAutoConfiguration.class,
WebMvcAutoConfiguration.class
// ManagementServerPropertiesAutoConfiguration.class
})
@Configuration

View File

@@ -38,7 +38,7 @@ import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.BDDAssertions.then;
import static org.hamcrest.Matchers.containsString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
@@ -50,7 +50,9 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
* @author Tim Ysewyn
*/
@RunWith(SpringRunner.class)
// @checkstyle:off
@SpringBootTest(classes = ServiceRegistryEndpointTests.TestConfiguration.class, properties = "management.endpoints.web.exposure.include=*")
// @checkstyle:on
@AutoConfigureMockMvc
public class ServiceRegistryEndpointTests {
@@ -78,8 +80,7 @@ public class ServiceRegistryEndpointTests {
this.mvc.perform(post(BASE_PATH + "/service-registry")
.content(new ObjectMapper().writeValueAsString(status))
.contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk());
assertThat(this.serviceRegistry.getUpdatedStatus().get())
.isEqualTo(UPDATED_STATUS);
then(this.serviceRegistry.getUpdatedStatus().get()).isEqualTo(UPDATED_STATUS);
}
@EnableAutoConfiguration

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.commons.httpclient;
import org.apache.http.impl.client.HttpClientBuilder;
@@ -28,7 +29,7 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.BDDAssertions.then;
/**
* @author Ryan Baxter
@@ -43,8 +44,8 @@ public class CustomHttpClientBuilderConfigurationTests {
@Test
public void testCustomBuilder() {
HttpClientBuilder builder = this.apacheHttpClientFactory.createBuilder();
assertTrue(CustomHttpClientBuilderApplication.MyHttpClientBuilder.class
.isInstance(builder));
then(CustomHttpClientBuilderApplication.MyHttpClientBuilder.class
.isInstance(builder)).isTrue();
}
}
@@ -58,7 +59,7 @@ class CustomHttpClientBuilderApplication {
}
@Configuration
@AutoConfigureBefore(value = HttpClientConfiguration.class)
@AutoConfigureBefore(HttpClientConfiguration.class)
static class MyConfig {
@Bean

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.commons.httpclient;
import java.util.concurrent.TimeUnit;
@@ -18,7 +34,7 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.BDDAssertions.then;
/**
* @author Ryan Baxter
@@ -42,32 +58,32 @@ public class CustomHttpClientConfigurationTests {
@Test
public void connManFactory() throws Exception {
assertTrue(ApacheHttpClientConnectionManagerFactory.class
.isInstance(this.connectionManagerFactory));
assertTrue(CustomApplication.MyApacheHttpClientConnectionManagerFactory.class
.isInstance(this.connectionManagerFactory));
then(ApacheHttpClientConnectionManagerFactory.class
.isInstance(this.connectionManagerFactory)).isTrue();
then(CustomApplication.MyApacheHttpClientConnectionManagerFactory.class
.isInstance(this.connectionManagerFactory)).isTrue();
}
@Test
public void apacheHttpClientFactory() throws Exception {
assertTrue(ApacheHttpClientFactory.class.isInstance(this.httpClientFactory));
assertTrue(CustomApplication.MyApacheHttpClientFactory.class
.isInstance(this.httpClientFactory));
then(ApacheHttpClientFactory.class.isInstance(this.httpClientFactory)).isTrue();
then(CustomApplication.MyApacheHttpClientFactory.class
.isInstance(this.httpClientFactory)).isTrue();
}
@Test
public void connectionPoolFactory() throws Exception {
assertTrue(OkHttpClientConnectionPoolFactory.class
.isInstance(this.okHttpClientConnectionPoolFactory));
assertTrue(CustomApplication.MyOkHttpConnectionPoolFactory.class
.isInstance(this.okHttpClientConnectionPoolFactory));
then(OkHttpClientConnectionPoolFactory.class
.isInstance(this.okHttpClientConnectionPoolFactory)).isTrue();
then(CustomApplication.MyOkHttpConnectionPoolFactory.class
.isInstance(this.okHttpClientConnectionPoolFactory)).isTrue();
}
@Test
public void okHttpClientFactory() throws Exception {
assertTrue(OkHttpClientFactory.class.isInstance(this.okHttpClientFactory));
assertTrue(CustomApplication.MyOkHttpClientFactory.class
.isInstance(this.okHttpClientFactory));
then(OkHttpClientFactory.class.isInstance(this.okHttpClientFactory)).isTrue();
then(CustomApplication.MyOkHttpClientFactory.class
.isInstance(this.okHttpClientFactory)).isTrue();
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.commons.httpclient;
import java.lang.reflect.Field;
@@ -31,7 +32,7 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.ReflectionUtils;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.BDDAssertions.then;
/**
* @author Ryan Baxter
@@ -47,7 +48,7 @@ public class CustomOkHttpClientBuilderConfigurationTests {
public void testCustomBuilder() {
OkHttpClient.Builder builder = this.okHttpClientFactory.createBuilder(false);
Integer timeout = getField(builder, "connectTimeout");
assertEquals(1, timeout.intValue());
then(timeout.intValue()).isEqualTo(1);
}
protected <T> T getField(Object target, String name) {

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.commons.httpclient;
import java.lang.reflect.Field;
@@ -16,11 +32,7 @@ import org.junit.Test;
import org.springframework.util.ReflectionUtils;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.assertj.core.api.BDDAssertions.then;
/**
* @author Ryan Baxter
@@ -32,30 +44,30 @@ public class DefaultApacheHttpClientConnectionManagerFactoryTests {
public void newConnectionManager() throws Exception {
HttpClientConnectionManager connectionManager = new DefaultApacheHttpClientConnectionManagerFactory()
.newConnectionManager(false, 2, 6);
assertEquals(6, ((PoolingHttpClientConnectionManager) connectionManager)
.getDefaultMaxPerRoute());
assertEquals(2,
((PoolingHttpClientConnectionManager) connectionManager).getMaxTotal());
then(((PoolingHttpClientConnectionManager) connectionManager)
.getDefaultMaxPerRoute()).isEqualTo(6);
then(((PoolingHttpClientConnectionManager) connectionManager).getMaxTotal())
.isEqualTo(2);
Object pool = getField(((PoolingHttpClientConnectionManager) connectionManager),
"pool");
assertEquals(new Long(-1), getField(pool, "timeToLive"));
then((Long) getField(pool, "timeToLive")).isEqualTo(new Long(-1));
TimeUnit timeUnit = getField(pool, "tunit");
assertEquals(TimeUnit.MILLISECONDS, timeUnit);
then(timeUnit).isEqualTo(TimeUnit.MILLISECONDS);
}
@Test
public void newConnectionManagerWithTTL() throws Exception {
HttpClientConnectionManager connectionManager = new DefaultApacheHttpClientConnectionManagerFactory()
.newConnectionManager(false, 2, 6, 56l, TimeUnit.DAYS, null);
assertEquals(6, ((PoolingHttpClientConnectionManager) connectionManager)
.getDefaultMaxPerRoute());
assertEquals(2,
((PoolingHttpClientConnectionManager) connectionManager).getMaxTotal());
.newConnectionManager(false, 2, 6, 56L, TimeUnit.DAYS, null);
then(((PoolingHttpClientConnectionManager) connectionManager)
.getDefaultMaxPerRoute()).isEqualTo(6);
then(((PoolingHttpClientConnectionManager) connectionManager).getMaxTotal())
.isEqualTo(2);
Object pool = getField(((PoolingHttpClientConnectionManager) connectionManager),
"pool");
assertEquals(new Long(56), getField(pool, "timeToLive"));
then((Long) getField(pool, "timeToLive")).isEqualTo(new Long(56));
TimeUnit timeUnit = getField(pool, "tunit");
assertEquals(TimeUnit.DAYS, timeUnit);
then(timeUnit).isEqualTo(TimeUnit.DAYS);
}
@Test
@@ -65,9 +77,8 @@ public class DefaultApacheHttpClientConnectionManagerFactoryTests {
Lookup<ConnectionSocketFactory> socketFactoryRegistry = getConnectionSocketFactoryLookup(
connectionManager);
assertThat(socketFactoryRegistry.lookup("https"), is(notNullValue()));
assertThat(getX509TrustManager(socketFactoryRegistry).getAcceptedIssuers(),
is(notNullValue()));
then(socketFactoryRegistry.lookup("https")).isNotNull();
then(getX509TrustManager(socketFactoryRegistry).getAcceptedIssuers()).isNotNull();
}
@Test
@@ -77,9 +88,8 @@ public class DefaultApacheHttpClientConnectionManagerFactoryTests {
Lookup<ConnectionSocketFactory> socketFactoryRegistry = getConnectionSocketFactoryLookup(
connectionManager);
assertThat(socketFactoryRegistry.lookup("https"), is(notNullValue()));
assertThat(getX509TrustManager(socketFactoryRegistry).getAcceptedIssuers(),
is(nullValue()));
then(socketFactoryRegistry.lookup("https")).isNotNull();
then(getX509TrustManager(socketFactoryRegistry).getAcceptedIssuers()).isNull();
}
private Lookup<ConnectionSocketFactory> getConnectionSocketFactoryLookup(

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.commons.httpclient;
import java.lang.reflect.Field;
@@ -8,12 +24,12 @@ import org.apache.http.client.methods.Configurable;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.assertj.core.api.Assertions;
import org.assertj.core.api.BDDAssertions;
import org.junit.Test;
import org.springframework.util.ReflectionUtils;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.BDDAssertions.then;
import static org.mockito.Mockito.mock;
/**
@@ -29,11 +45,11 @@ public class DefaultApacheHttpClientFactoryTests {
HttpClientBuilder.create()).createBuilder()
.setConnectionManager(mock(HttpClientConnectionManager.class))
.setDefaultRequestConfig(requestConfig).build();
Assertions.assertThat(httpClient).isInstanceOf(Configurable.class);
BDDAssertions.then(httpClient).isInstanceOf(Configurable.class);
RequestConfig config = ((Configurable) httpClient).getConfig();
assertEquals(100, config.getSocketTimeout());
assertEquals(200, config.getConnectTimeout());
assertEquals(CookieSpecs.IGNORE_COOKIES, config.getCookieSpec());
then(config.getSocketTimeout()).isEqualTo(100);
then(config.getConnectTimeout()).isEqualTo(200);
then(config.getCookieSpec()).isEqualTo(CookieSpecs.IGNORE_COOKIES);
}
protected <T> T getField(Object target, String name) {

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.commons.httpclient;
import org.junit.Test;
@@ -10,7 +26,7 @@ import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.BDDAssertions.then;
/**
* @author Ryan Baxter
@@ -34,31 +50,32 @@ public class DefaultHttpClientConfigurationTests {
@Test
public void connManFactory() throws Exception {
assertTrue(ApacheHttpClientConnectionManagerFactory.class
.isInstance(this.connectionManagerFactory));
assertTrue(DefaultApacheHttpClientConnectionManagerFactory.class
.isInstance(this.connectionManagerFactory));
then(ApacheHttpClientConnectionManagerFactory.class
.isInstance(this.connectionManagerFactory)).isTrue();
then(DefaultApacheHttpClientConnectionManagerFactory.class
.isInstance(this.connectionManagerFactory)).isTrue();
}
@Test
public void apacheHttpClientFactory() throws Exception {
assertTrue(ApacheHttpClientFactory.class.isInstance(this.httpClientFactory));
assertTrue(
DefaultApacheHttpClientFactory.class.isInstance(this.httpClientFactory));
then(ApacheHttpClientFactory.class.isInstance(this.httpClientFactory)).isTrue();
then(DefaultApacheHttpClientFactory.class.isInstance(this.httpClientFactory))
.isTrue();
}
@Test
public void connPoolFactory() throws Exception {
assertTrue(OkHttpClientConnectionPoolFactory.class
.isInstance(this.okHttpClientConnectionPoolFactory));
assertTrue(DefaultOkHttpClientConnectionPoolFactory.class
.isInstance(this.okHttpClientConnectionPoolFactory));
then(OkHttpClientConnectionPoolFactory.class
.isInstance(this.okHttpClientConnectionPoolFactory)).isTrue();
then(DefaultOkHttpClientConnectionPoolFactory.class
.isInstance(this.okHttpClientConnectionPoolFactory)).isTrue();
}
@Test
public void setOkHttpClientFactory() throws Exception {
assertTrue(OkHttpClientFactory.class.isInstance(this.okHttpClientFactory));
assertTrue(DefaultOkHttpClientFactory.class.isInstance(this.okHttpClientFactory));
then(OkHttpClientFactory.class.isInstance(this.okHttpClientFactory)).isTrue();
then(DefaultOkHttpClientFactory.class.isInstance(this.okHttpClientFactory))
.isTrue();
}
}

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.commons.httpclient;
import java.lang.reflect.Field;
@@ -8,7 +24,7 @@ import org.junit.Test;
import org.springframework.util.ReflectionUtils;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.BDDAssertions.then;
/**
* @author Ryan Baxter
@@ -22,8 +38,8 @@ public class DefaultOkHttpClientConnectionPoolFactoryTest {
TimeUnit.MILLISECONDS);
int idleConnections = getField(connectionPool, "maxIdleConnections");
long keepAliveDuration = getField(connectionPool, "keepAliveDurationNs");
assertEquals(2, idleConnections);
assertEquals(TimeUnit.MILLISECONDS.toNanos(3), keepAliveDuration);
then(idleConnections).isEqualTo(2);
then(keepAliveDuration).isEqualTo(TimeUnit.MILLISECONDS.toNanos(3));
}
protected <T> T getField(Object target, String name) {

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.commons.httpclient;
import java.lang.reflect.Field;
@@ -11,8 +27,7 @@ import org.junit.Test;
import org.springframework.util.ReflectionUtils;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.BDDAssertions.then;
/**
* @author Ryan Baxter
@@ -29,16 +44,16 @@ public class DefaultOkHttpClientFactoryTest {
.connectTimeout(2, TimeUnit.MILLISECONDS).readTimeout(3, TimeUnit.HOURS)
.followRedirects(true).connectionPool(pool).build();
int connectTimeout = getField(httpClient, "connectTimeout");
assertEquals(2, connectTimeout);
then(connectTimeout).isEqualTo(2);
int readTimeout = getField(httpClient, "readTimeout");
assertEquals(TimeUnit.HOURS.toMillis(3), readTimeout);
then(readTimeout).isEqualTo(TimeUnit.HOURS.toMillis(3));
boolean followRedirects = getField(httpClient, "followRedirects");
assertTrue(followRedirects);
then(followRedirects).isTrue();
ConnectionPool poolFromClient = getField(httpClient, "connectionPool");
assertEquals(pool, poolFromClient);
then(poolFromClient).isEqualTo(pool);
HostnameVerifier hostnameVerifier = getField(httpClient, "hostnameVerifier");
assertTrue(
OkHttpClientFactory.TrustAllHostnames.class.isInstance(hostnameVerifier));
then(OkHttpClientFactory.TrustAllHostnames.class.isInstance(hostnameVerifier))
.isTrue();
}
protected <T> T getField(Object target, String name) {

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.commons.util;
import org.junit.After;
@@ -6,8 +22,7 @@ import org.junit.Test;
import org.springframework.mock.env.MockEnvironment;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.assertj.core.api.BDDAssertions.then;
/**
* @author Spencer Gibb
@@ -31,28 +46,28 @@ public class IdUtilsTests {
@Test
public void emptyEnvironmentWorks() {
String instanceId = IdUtils.getDefaultInstanceId(this.env);
assertNull("instanceId was not null", instanceId);
then(instanceId).as("instanceId was not null").isNull();
}
@Test
public void vcapInstanceIdWorks() {
this.env.setProperty("vcap.application.instance_id", DEFAULT_ID);
String instanceId = IdUtils.getDefaultInstanceId(this.env);
assertEquals("instanceId was wrong", DEFAULT_ID, instanceId);
then(DEFAULT_ID).isEqualTo(instanceId).as("instanceId was wrong");
}
@Test
public void hostnameWorks() {
this.env.setProperty("spring.cloud.client.hostname", DEFAULT_ID);
String instanceId = IdUtils.getDefaultInstanceId(this.env);
assertEquals("instanceId was wrong", DEFAULT_ID, instanceId);
then(DEFAULT_ID).isEqualTo(instanceId).as("instanceId was wrong");
}
@Test
public void appNameWorks() {
this.env.setProperty("spring.application.name", DEFAULT_ID);
String instanceId = IdUtils.getDefaultInstanceId(this.env);
assertEquals("instanceId was wrong", DEFAULT_ID, instanceId);
then(DEFAULT_ID).isEqualTo(instanceId).as("instanceId was wrong");
}
@Test
@@ -60,22 +75,22 @@ public class IdUtilsTests {
this.env.setProperty("spring.application.name", DEFAULT_ID);
this.env.setProperty("spring.cloud.client.hostname", DEFAULT_ID + "2");
String instanceId = IdUtils.getDefaultInstanceId(this.env);
assertEquals("instanceId was wrong", DEFAULT_ID + "2" + ":" + DEFAULT_ID,
instanceId);
then(instanceId).as("instanceId was wrong")
.isEqualTo(DEFAULT_ID + "2" + ":" + DEFAULT_ID);
}
@Test
public void instanceIdWorks() {
this.env.setProperty("spring.cloud.client.hostname", DEFAULT_ID);
String instanceId = IdUtils.getDefaultInstanceId(this.env);
assertEquals("instanceId was wrong", DEFAULT_ID, instanceId);
then(DEFAULT_ID).isEqualTo(instanceId).as("instanceId was wrong");
}
@Test
public void portWorks() {
this.env.setProperty("spring.application.name", DEFAULT_ID);
String instanceId = IdUtils.getDefaultInstanceId(this.env);
assertEquals("instanceId was wrong", DEFAULT_ID, instanceId);
then(DEFAULT_ID).isEqualTo(instanceId).as("instanceId was wrong");
}
@Test
@@ -83,7 +98,7 @@ public class IdUtilsTests {
this.env.setProperty("spring.application.name", DEFAULT_ID);
this.env.setProperty("server.port", "80");
String instanceId = IdUtils.getDefaultInstanceId(this.env);
assertEquals("instanceId was wrong", DEFAULT_ID + ":80", instanceId);
then(DEFAULT_ID + ":80").isEqualTo(instanceId).as("instanceId was wrong");
}
@Test
@@ -92,7 +107,8 @@ public class IdUtilsTests {
this.env.setProperty("spring.application.name", DEFAULT_ID);
this.env.setProperty("server.port", "80");
String instanceId = IdUtils.getDefaultInstanceId(this.env);
assertEquals("instanceId was wrong", "myhost:" + DEFAULT_ID + ":80", instanceId);
then("myhost:" + DEFAULT_ID + ":80").isEqualTo(instanceId)
.as("instanceId was wrong");
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,9 +24,7 @@ import org.junit.Test;
import org.springframework.cloud.commons.util.InetUtils.HostInfo;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.BDDAssertions.then;
/**
* @author Dave Syer
@@ -37,21 +35,21 @@ public class InetUtilsTests {
@Test
public void testGetFirstNonLoopbackHostInfo() {
try (InetUtils utils = new InetUtils(new InetUtilsProperties())) {
assertNotNull(utils.findFirstNonLoopbackHostInfo());
then(utils.findFirstNonLoopbackHostInfo()).isNotNull();
}
}
@Test
public void testGetFirstNonLoopbackAddress() {
try (InetUtils utils = new InetUtils(new InetUtilsProperties())) {
assertNotNull(utils.findFirstNonLoopbackAddress());
then(utils.findFirstNonLoopbackAddress()).isNotNull();
}
}
@Test
public void testConvert() throws Exception {
try (InetUtils utils = new InetUtils(new InetUtilsProperties())) {
assertNotNull(utils.convertAddress(InetAddress.getByName("localhost")));
then(utils.convertAddress(InetAddress.getByName("localhost"))).isNotNull();
}
}
@@ -59,7 +57,7 @@ public class InetUtilsTests {
public void testHostInfo() {
try (InetUtils utils = new InetUtils(new InetUtilsProperties())) {
HostInfo info = utils.findFirstNonLoopbackHostInfo();
assertNotNull(info.getIpAddressAsInt());
then(info.getIpAddressAsInt()).isNotNull();
}
}
@@ -73,17 +71,17 @@ public class InetUtilsTests {
properties.setIgnoredInterfaces(Arrays.asList("docker0", "veth.*"));
try (InetUtils inetUtils = new InetUtils(properties)) {
assertTrue("docker0 not ignored", inetUtils.ignoreInterface("docker0"));
assertTrue("vethAQI2QT0 not ignored",
inetUtils.ignoreInterface("vethAQI2QT"));
assertFalse("docker1 ignored", inetUtils.ignoreInterface("docker1"));
then(inetUtils.ignoreInterface("docker0")).isTrue().as("docker0 not ignored");
then(inetUtils.ignoreInterface("vethAQI2QT")).as("vethAQI2QT0 not ignored")
.isTrue();
then(inetUtils.ignoreInterface("docker1")).as("docker1 ignored").isFalse();
}
}
@Test
public void testDefaultIgnoreInterface() {
try (InetUtils inetUtils = new InetUtils(new InetUtilsProperties())) {
assertFalse("docker0 ignored", inetUtils.ignoreInterface("docker0"));
then(inetUtils.ignoreInterface("docker0")).as("docker0 ignored").isFalse();
}
}
@@ -93,8 +91,8 @@ public class InetUtilsTests {
properties.setUseOnlySiteLocalInterfaces(true);
try (InetUtils utils = new InetUtils(properties)) {
assertTrue(utils.isPreferredAddress(InetAddress.getByName("192.168.0.1")));
assertFalse(utils.isPreferredAddress(InetAddress.getByName("5.5.8.1")));
then(utils.isPreferredAddress(InetAddress.getByName("192.168.0.1"))).isTrue();
then(utils.isPreferredAddress(InetAddress.getByName("5.5.8.1"))).isFalse();
}
}
@@ -104,10 +102,11 @@ public class InetUtilsTests {
properties.setPreferredNetworks(Arrays.asList("192.168.*", "10.0.*"));
try (InetUtils utils = new InetUtils(properties)) {
assertTrue(utils.isPreferredAddress(InetAddress.getByName("192.168.0.1")));
assertFalse(utils.isPreferredAddress(InetAddress.getByName("5.5.8.1")));
assertTrue(utils.isPreferredAddress(InetAddress.getByName("10.0.10.1")));
assertFalse(utils.isPreferredAddress(InetAddress.getByName("10.255.10.1")));
then(utils.isPreferredAddress(InetAddress.getByName("192.168.0.1"))).isTrue();
then(utils.isPreferredAddress(InetAddress.getByName("5.5.8.1"))).isFalse();
then(utils.isPreferredAddress(InetAddress.getByName("10.0.10.1"))).isTrue();
then(utils.isPreferredAddress(InetAddress.getByName("10.255.10.1")))
.isFalse();
}
}
@@ -117,10 +116,11 @@ public class InetUtilsTests {
properties.setPreferredNetworks(Arrays.asList("192", "10.0"));
try (InetUtils utils = new InetUtils(properties)) {
assertTrue(utils.isPreferredAddress(InetAddress.getByName("192.168.0.1")));
assertFalse(utils.isPreferredAddress(InetAddress.getByName("5.5.8.1")));
assertFalse(utils.isPreferredAddress(InetAddress.getByName("10.255.10.1")));
assertTrue(utils.isPreferredAddress(InetAddress.getByName("10.0.10.1")));
then(utils.isPreferredAddress(InetAddress.getByName("192.168.0.1"))).isTrue();
then(utils.isPreferredAddress(InetAddress.getByName("5.5.8.1"))).isFalse();
then(utils.isPreferredAddress(InetAddress.getByName("10.255.10.1")))
.isFalse();
then(utils.isPreferredAddress(InetAddress.getByName("10.0.10.1"))).isTrue();
}
}
@@ -129,10 +129,10 @@ public class InetUtilsTests {
InetUtilsProperties properties = new InetUtilsProperties();
properties.setPreferredNetworks(Collections.emptyList());
try (InetUtils utils = new InetUtils(properties)) {
assertTrue(utils.isPreferredAddress(InetAddress.getByName("192.168.0.1")));
assertTrue(utils.isPreferredAddress(InetAddress.getByName("5.5.8.1")));
assertTrue(utils.isPreferredAddress(InetAddress.getByName("10.255.10.1")));
assertTrue(utils.isPreferredAddress(InetAddress.getByName("10.0.10.1")));
then(utils.isPreferredAddress(InetAddress.getByName("192.168.0.1"))).isTrue();
then(utils.isPreferredAddress(InetAddress.getByName("5.5.8.1"))).isTrue();
then(utils.isPreferredAddress(InetAddress.getByName("10.255.10.1"))).isTrue();
then(utils.isPreferredAddress(InetAddress.getByName("10.0.10.1"))).isTrue();
}
}

View File

@@ -18,7 +18,7 @@ package org.springframework.cloud.commons.util;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.BDDAssertions.then;
/**
* @author Spencer Gibb
@@ -28,8 +28,8 @@ public class SpringFactoryImportSelectorTests {
@Test
public void testFindAnnotation() {
MyAnnotationImportSelector selector = new MyAnnotationImportSelector();
assertEquals("annotationClass was wrong", MyAnnotation.class,
selector.getAnnotationClass());
then(selector.getAnnotationClass()).as("annotationClass was wrong")
.isEqualTo(MyAnnotation.class);
}
public @interface MyAnnotation {

View File

@@ -1,18 +1,21 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.configuration;
import org.assertj.core.api.BDDAssertions;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -23,6 +26,8 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.BDDAssertions.then;
/**
* @author Marcin Grzejszczak
*/
@@ -35,7 +40,7 @@ public class CompatibilityVerifierAutoConfigurationTests {
@Test
public void contextLoads() {
BDDAssertions.then(this.myMismatchVerifier.called).isTrue();
then(this.myMismatchVerifier.called).isTrue();
}
@Configuration

View File

@@ -1,18 +1,21 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.configuration;
import org.assertj.core.api.BDDAssertions;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -22,6 +25,8 @@ import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.BDDAssertions.then;
/**
* @author Marcin Grzejszczak
*/
@@ -34,7 +39,7 @@ public class CompatibilityVerifierDisabledAutoConfigurationTests {
@Test
public void contextLoads() {
BDDAssertions.then(this.compositeCompatibilityVerifier).isNull();
then(this.compositeCompatibilityVerifier).isNull();
}
@Configuration

View File

@@ -1,15 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.configuration;
import org.assertj.core.api.BDDAssertions;
@@ -23,6 +27,8 @@ import org.springframework.boot.test.rule.OutputCapture;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.NestedExceptionUtils;
import static org.assertj.core.api.BDDAssertions.then;
/**
* @author Marcin Grzejszczak
*/
@@ -40,7 +46,7 @@ public class CompatibilityVerifierFailureAutoConfigurationTests {
}
catch (BeanCreationException ex) {
Throwable cause = NestedExceptionUtils.getRootCause(ex);
BDDAssertions.then(((CompatibilityNotMetException) cause).results).hasSize(1);
then(((CompatibilityNotMetException) cause).results).hasSize(1);
}
}

View File

@@ -1,15 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.configuration;
import java.util.ArrayList;
@@ -21,6 +25,8 @@ import org.junit.Test;
import org.springframework.boot.test.rule.OutputCapture;
import static org.assertj.core.api.BDDAssertions.then;
/**
* @author Marcin Grzejszczak
*/
@@ -36,7 +42,7 @@ public class CompatibilityVerifierTests {
verifier.verifyDependencies();
BDDAssertions.then(this.outputCapture.toString())
then(this.outputCapture.toString())
.doesNotContain("SPRING CLOUD VERIFICATION FAILED");
}
@@ -65,7 +71,7 @@ public class CompatibilityVerifierTests {
BDDAssertions.fail("should fail");
}
catch (CompatibilityNotMetException ex) {
BDDAssertions.then(ex.results).hasSize(2);
then(ex.results).hasSize(2);
}
}

View File

@@ -1,23 +1,28 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.1
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.configuration;
import java.util.Collections;
import java.util.List;
import org.assertj.core.api.BDDAssertions;
import org.junit.Test;
import static org.assertj.core.api.BDDAssertions.then;
/**
* @author Marcin Grzejszczak
*/
@@ -37,8 +42,8 @@ public class SpringBootDependencyTests {
VerificationResult verificationResult = versionVerifier.verify();
BDDAssertions.then(verificationResult.description).isEmpty();
BDDAssertions.then(verificationResult.action).isEmpty();
then(verificationResult.description).isEmpty();
then(verificationResult.action).isEmpty();
}
@Test
@@ -55,8 +60,8 @@ public class SpringBootDependencyTests {
VerificationResult verificationResult = versionVerifier.verify();
BDDAssertions.then(verificationResult.description).isNotEmpty();
BDDAssertions.then(verificationResult.action).isNotEmpty();
then(verificationResult.description).isNotEmpty();
then(verificationResult.action).isNotEmpty();
}
@Test
@@ -73,8 +78,8 @@ public class SpringBootDependencyTests {
VerificationResult verificationResult = versionVerifier.verify();
BDDAssertions.then(verificationResult.description).isNotEmpty();
BDDAssertions.then(verificationResult.action).isNotEmpty();
then(verificationResult.description).isNotEmpty();
then(verificationResult.action).isNotEmpty();
}
@Test
@@ -91,8 +96,8 @@ public class SpringBootDependencyTests {
VerificationResult verificationResult = versionVerifier.verify();
BDDAssertions.then(verificationResult.description).isEmpty();
BDDAssertions.then(verificationResult.action).isEmpty();
then(verificationResult.description).isEmpty();
then(verificationResult.action).isEmpty();
}
@Test
@@ -115,8 +120,8 @@ public class SpringBootDependencyTests {
VerificationResult verificationResult = versionVerifier.verify();
BDDAssertions.then(verificationResult.description).isEmpty();
BDDAssertions.then(verificationResult.action).isEmpty();
then(verificationResult.description).isEmpty();
then(verificationResult.action).isEmpty();
}
@Test
@@ -133,8 +138,8 @@ public class SpringBootDependencyTests {
VerificationResult verificationResult = versionVerifier.verify();
BDDAssertions.then(verificationResult.description).isNotEmpty();
BDDAssertions.then(verificationResult.action).isNotEmpty();
then(verificationResult.description).isNotEmpty();
then(verificationResult.action).isNotEmpty();
}
@Test
@@ -146,8 +151,8 @@ public class SpringBootDependencyTests {
VerificationResult verificationResult = versionVerifier.verify();
BDDAssertions.then(verificationResult.description).isEmpty();
BDDAssertions.then(verificationResult.action).isEmpty();
then(verificationResult.description).isEmpty();
then(verificationResult.action).isEmpty();
}
@Test
@@ -165,8 +170,8 @@ public class SpringBootDependencyTests {
VerificationResult verificationResult = versionVerifier.verify();
BDDAssertions.then(verificationResult.description).isEmpty();
BDDAssertions.then(verificationResult.action).isEmpty();
then(verificationResult.description).isEmpty();
then(verificationResult.action).isEmpty();
}
@Test
@@ -184,8 +189,8 @@ public class SpringBootDependencyTests {
VerificationResult verificationResult = versionVerifier.verify();
BDDAssertions.then(verificationResult.description).isEmpty();
BDDAssertions.then(verificationResult.action).isEmpty();
then(verificationResult.description).isEmpty();
then(verificationResult.action).isEmpty();
}
@Test
@@ -202,8 +207,8 @@ public class SpringBootDependencyTests {
VerificationResult verificationResult = versionVerifier.verify();
BDDAssertions.then(verificationResult.description).isNotEmpty();
BDDAssertions.then(verificationResult.action).isNotEmpty();
then(verificationResult.description).isNotEmpty();
then(verificationResult.action).isNotEmpty();
}
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.autoconfigure;
import org.apache.commons.logging.Log;
@@ -42,10 +43,7 @@ import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.BDDAssertions.then;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestConfiguration.class)
@@ -63,7 +61,7 @@ public class RefreshScopeIntegrationTests {
@Before
public void init() {
assertEquals(1, ExampleService.getInitCount());
then(ExampleService.getInitCount()).isEqualTo(1);
ExampleService.reset();
}
@@ -75,53 +73,53 @@ public class RefreshScopeIntegrationTests {
@Test
@DirtiesContext
public void testSimpleProperties() throws Exception {
assertEquals("Hello scope!", this.service.getMessage());
assertTrue(this.service instanceof Advised);
then(this.service.getMessage()).isEqualTo("Hello scope!");
then(this.service instanceof Advised).isTrue();
// Change the dynamic property source...
this.properties.setMessage("Foo");
// ...but don't refresh, so the bean stays the same:
assertEquals("Hello scope!", this.service.getMessage());
assertEquals(0, ExampleService.getInitCount());
assertEquals(0, ExampleService.getDestroyCount());
then(this.service.getMessage()).isEqualTo("Hello scope!");
then(ExampleService.getInitCount()).isEqualTo(0);
then(ExampleService.getDestroyCount()).isEqualTo(0);
}
@Test
@DirtiesContext
public void testRefresh() throws Exception {
assertEquals("Hello scope!", this.service.getMessage());
then(this.service.getMessage()).isEqualTo("Hello scope!");
String id1 = this.service.toString();
// Change the dynamic property source...
this.properties.setMessage("Foo");
// ...and then refresh, so the bean is re-initialized:
this.scope.refreshAll();
String id2 = this.service.toString();
assertEquals("Foo", this.service.getMessage());
assertEquals(1, ExampleService.getInitCount());
assertEquals(1, ExampleService.getDestroyCount());
assertNotSame(id1, id2);
assertNotNull(ExampleService.event);
assertEquals(RefreshScopeRefreshedEvent.DEFAULT_NAME,
ExampleService.event.getName());
then(this.service.getMessage()).isEqualTo("Foo");
then(ExampleService.getInitCount()).isEqualTo(1);
then(ExampleService.getDestroyCount()).isEqualTo(1);
then(id2).isNotSameAs(id1);
then(ExampleService.event).isNotNull();
then(ExampleService.event.getName())
.isEqualTo(RefreshScopeRefreshedEvent.DEFAULT_NAME);
}
@Test
@DirtiesContext
public void testRefreshBean() throws Exception {
assertEquals("Hello scope!", this.service.getMessage());
then(this.service.getMessage()).isEqualTo("Hello scope!");
String id1 = this.service.toString();
// Change the dynamic property source...
this.properties.setMessage("Foo");
// ...and then refresh, so the bean is re-initialized:
this.scope.refresh("service");
String id2 = this.service.toString();
assertEquals("Foo", this.service.getMessage());
assertEquals("Foo", this.service.getMessage());
assertEquals(1, ExampleService.getInitCount());
assertEquals(1, ExampleService.getDestroyCount());
assertNotSame(id1, id2);
assertNotNull(ExampleService.event);
assertEquals(GenericScope.SCOPED_TARGET_PREFIX + "service",
ExampleService.event.getName());
then(this.service.getMessage()).isEqualTo("Foo");
then(this.service.getMessage()).isEqualTo("Foo");
then(ExampleService.getInitCount()).isEqualTo(1);
then(ExampleService.getDestroyCount()).isEqualTo(1);
then(id2).isNotSameAs(id1);
then(ExampleService.event).isNotNull();
then(ExampleService.event.getName())
.isEqualTo(GenericScope.SCOPED_TARGET_PREFIX + "service");
}
// see gh-349

View File

@@ -1,4 +1,4 @@
create table if not exists foos (
id INTEGER IDENTITY PRIMARY KEY,
value VARCHAR(30)
);
);

View File

@@ -15,4 +15,4 @@ org.springframework.cloud.bootstrap.BootstrapConfiguration=\
org.springframework.cloud.bootstrap.config.PropertySourceBootstrapConfiguration,\
org.springframework.cloud.bootstrap.encrypt.EncryptionBootstrapConfiguration,\
org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration,\
org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration
org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.autoconfigure;
import java.util.List;
@@ -13,11 +29,7 @@ import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;
import static org.assertj.core.api.BDDAssertions.then;
/**
* @author Spencer Gibb
@@ -126,16 +138,16 @@ public class LifecycleMvcAutoConfigurationTests {
private void beanNotCreated(String beanName, String... contextProperties) {
try (ConfigurableApplicationContext context = getApplicationContext(Config.class,
contextProperties)) {
assertThat("bean was created", context.containsBeanDefinition(beanName),
equalTo(false));
then(context.containsBeanDefinition(beanName)).as("bean was created")
.isFalse();
}
}
private void beanCreated(String beanName, String... contextProperties) {
try (ConfigurableApplicationContext context = getApplicationContext(Config.class,
contextProperties)) {
assertThat("bean was not created", context.containsBeanDefinition(beanName),
equalTo(true));
then(context.containsBeanDefinition(beanName)).as("bean was not created")
.isTrue();
}
}
@@ -144,14 +156,13 @@ public class LifecycleMvcAutoConfigurationTests {
Function<T, Object> function, String... properties) {
try (ConfigurableApplicationContext context = getApplicationContext(Config.class,
properties)) {
assertThat("bean was not created", context.containsBeanDefinition(beanName),
equalTo(true));
then(context.containsBeanDefinition(beanName)).as("bean was not created")
.isTrue();
Object endpoint = context.getBean(beanName, type);
Object result = function.apply((T) endpoint);
assertThat("result is wrong type", result,
is(not(instanceOf(ResponseEntity.class))));
then(result).as("result is wrong type").isNotInstanceOf(ResponseEntity.class);
}
}

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.autoconfigure;
import org.junit.Test;
@@ -12,7 +28,7 @@ import org.springframework.cloud.test.ModifiedClassPathRunner;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.BDDAssertions.then;
/**
* @author Spencer Gibb
@@ -32,10 +48,10 @@ public class RefreshAutoConfigurationClassPathTests {
public void refreshEventListenerCreated() {
try (ConfigurableApplicationContext context = getApplicationContext(
Config.class)) {
assertThat(context.getBeansOfType(RefreshEventListener.class))
then(context.getBeansOfType(RefreshEventListener.class))
.as("RefreshEventListeners not created").isNotEmpty();
assertThat(context.containsBean("refreshEndpoint"))
.as("refreshEndpoint created").isFalse();
then(context.containsBean("refreshEndpoint")).as("refreshEndpoint created")
.isFalse();
}
}

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.autoconfigure;
import org.junit.Rule;
@@ -13,7 +29,7 @@ import org.springframework.cloud.test.ModifiedClassPathRunner;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.BDDAssertions.then;
/**
* @author Spencer Gibb
@@ -37,8 +53,8 @@ public class RefreshAutoConfigurationMoreClassPathTests {
try (ConfigurableApplicationContext context = getApplicationContext(Config.class,
"debug=true")) {
String output = this.outputCapture.toString();
assertThat(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

@@ -1,3 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.autoconfigure;
import org.junit.Rule;
@@ -14,7 +30,7 @@ import org.springframework.cloud.context.refresh.ContextRefresher;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.BDDAssertions.then;
/**
* @author Dave Syer
@@ -34,8 +50,8 @@ public class RefreshAutoConfigurationTests {
public void noWarnings() {
try (ConfigurableApplicationContext context = getApplicationContext(
WebApplicationType.NONE, Config.class)) {
assertThat(context.containsBean("refreshScope")).isTrue();
assertThat(this.output.toString()).doesNotContain("WARN");
then(context.containsBean("refreshScope")).isTrue();
then(this.output.toString()).doesNotContain("WARN");
}
}
@@ -44,7 +60,7 @@ public class RefreshAutoConfigurationTests {
try (ConfigurableApplicationContext context = getApplicationContext(
WebApplicationType.SERVLET, Config.class,
"spring.cloud.refresh.enabled:false")) {
assertThat(context.containsBean("refreshScope")).isFalse();
then(context.containsBean("refreshScope")).isFalse();
}
}

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.bootstrap;
import org.junit.Test;
@@ -11,7 +27,7 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertFalse;
import static org.assertj.core.api.BDDAssertions.then;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, properties = "spring.cloud.bootstrap.enabled:false")
@@ -22,7 +38,7 @@ public class BootstrapDisabledAutoConfigurationIntegrationTests {
@Test
public void noBootstrapProperties() {
assertFalse(this.environment.getPropertySources().contains("bootstrap"));
then(this.environment.getPropertySources().contains("bootstrap")).isFalse();
}
@EnableAutoConfiguration

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.bootstrap;
import org.junit.Ignore;
@@ -14,8 +30,7 @@ import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.BDDAssertions.then;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, properties = "encrypt.key:deadbeef")
@@ -28,18 +43,19 @@ public class BootstrapOrderingAutoConfigurationIntegrationTests {
@Test
@Ignore // FIXME: spring boot 2.0.0
public void bootstrapPropertiesExist() {
assertTrue(this.environment.getPropertySources().contains(
PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME));
then(this.environment.getPropertySources().contains(
PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME))
.isTrue();
}
@Test
public void normalPropertiesDecrypted() {
assertEquals("foo", this.environment.resolvePlaceholders("${foo}"));
then(this.environment.resolvePlaceholders("${foo}")).isEqualTo("foo");
}
@Test
public void bootstrapPropertiesDecrypted() {
assertEquals("bar", this.environment.resolvePlaceholders("${bar}"));
then(this.environment.resolvePlaceholders("${bar}")).isEqualTo("bar");
}
@EnableAutoConfiguration

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.bootstrap;
import java.util.Collections;
@@ -22,8 +38,7 @@ import org.springframework.core.env.PropertySource;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.BDDAssertions.then;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, properties = { "encrypt.key:deadbeef",
@@ -37,13 +52,14 @@ public class BootstrapOrderingCustomPropertySourceIntegrationTests {
@Test
@Ignore // FIXME: spring boot 2.0.0
public void bootstrapPropertiesExist() {
assertTrue(this.environment.getPropertySources().contains(
PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME));
then(this.environment.getPropertySources().contains(
PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME))
.isTrue();
}
@Test
public void customPropertiesDecrypted() {
assertEquals("bar", this.environment.resolvePlaceholders("${custom.foo}"));
then(this.environment.resolvePlaceholders("${custom.foo}")).isEqualTo("bar");
}
@EnableAutoConfiguration

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.bootstrap;
import org.junit.AfterClass;
@@ -13,8 +29,7 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.BDDAssertions.then;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, properties = "spring.cloud.bootstrap.name:json")
@@ -35,9 +50,22 @@ public class BootstrapOrderingSpringApplicationJsonIntegrationTests {
@Test
public void bootstrapPropertiesExist() {
assertTrue(this.environment.getPropertySources()
.contains("spring.application.json"));
assertEquals("From JSON", this.environment.getProperty("message"));
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use
* this file except in compliance with the License. You may obtain a copy of the
* License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
then(this.environment.getProperty("message")).isEqualTo("From JSON");
}
@EnableAutoConfiguration

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.bootstrap;
import org.junit.Test;
@@ -9,7 +25,7 @@ import org.springframework.cloud.bootstrap.BootstrapOrderingSpringApplicationJso
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.BDDAssertions.then;
import static org.springframework.cloud.bootstrap.TestHigherPriorityBootstrapConfiguration.firstToBeCreated;
@RunWith(SpringRunner.class)
@@ -19,7 +35,7 @@ public class BootstrapSourcesOrderingTests {
@Test
public void sourcesAreOrderedCorrectly() {
Class<?> firstConstructedClass = firstToBeCreated.get();
assertThat(firstConstructedClass).as("bootstrap sources not ordered correctly")
then(firstConstructedClass).as("bootstrap sources not ordered correctly")
.isEqualTo(TestHigherPriorityBootstrapConfiguration.class);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,7 +23,6 @@ package org.springframework.cloud.bootstrap;
import java.util.Locale;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -35,6 +34,8 @@ import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.BDDAssertions.then;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestApplication.class, properties = "debug=true")
public class MessageSourceConfigurationTests {
@@ -44,8 +45,8 @@ public class MessageSourceConfigurationTests {
@Test
public void loadsMessage() {
Assert.assertEquals("Hello World!", this.messageSource.getMessage("hello.message",
null, Locale.getDefault()));
then(this.messageSource.getMessage("hello.message", null, Locale.getDefault()))
.isEqualTo("Hello World!");
}
@Configuration

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.bootstrap;
import java.util.Collections;

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.bootstrap;
import java.util.concurrent.atomic.AtomicInteger;

View File

@@ -40,12 +40,7 @@ import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.StandardEnvironment;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.BDDAssertions.then;
/**
* @author Dave Syer
@@ -84,10 +79,11 @@ public class BootstrapConfigurationTests {
.sources(BareConfiguration.class)
.properties("spring.cloud.bootstrap.location=" + externalPropertiesPath)
.run();
assertEquals("externalPropertiesInfoName",
this.context.getEnvironment().getProperty("info.name"));
assertTrue(this.context.getEnvironment().getPropertySources().contains(
PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME));
then(this.context.getEnvironment().getProperty("info.name"))
.isEqualTo("externalPropertiesInfoName");
then(this.context.getEnvironment().getPropertySources().contains(
PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME))
.isTrue();
}
@Test
@@ -99,13 +95,14 @@ public class BootstrapConfigurationTests {
public void initialize(
ConfigurableApplicationContext applicationContext) {
// This property is defined in bootstrap.properties
assertEquals("child", applicationContext.getEnvironment()
.getProperty("info.name"));
then(applicationContext.getEnvironment()
.getProperty("info.name")).isEqualTo("child");
}
})
.run();
assertTrue(this.context.getEnvironment().getPropertySources().contains(
PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME));
then(this.context.getEnvironment().getPropertySources().contains(
PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME))
.isTrue();
}
/**
@@ -123,9 +120,10 @@ public class BootstrapConfigurationTests {
PropertySourceConfiguration.MAP.put("bootstrap.foo", "bar");
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
.sources(BareConfiguration.class).run();
assertEquals("bar", this.context.getEnvironment().getProperty("bootstrap.foo"));
assertTrue(this.context.getEnvironment().getPropertySources().contains(
PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME));
then(this.context.getEnvironment().getProperty("bootstrap.foo")).isEqualTo("bar");
then(this.context.getEnvironment().getPropertySources().contains(
PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME))
.isTrue();
}
@Test
@@ -142,7 +140,7 @@ public class BootstrapConfigurationTests {
System.setProperty("bootstrap.foo", "system");
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
.sources(BareConfiguration.class).run();
assertEquals("bar", this.context.getEnvironment().getProperty("bootstrap.foo"));
then(this.context.getEnvironment().getProperty("bootstrap.foo")).isEqualTo("bar");
}
@Test
@@ -153,8 +151,8 @@ public class BootstrapConfigurationTests {
System.setProperty("bootstrap.foo", "system");
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
.sources(BareConfiguration.class).run();
assertEquals("system",
this.context.getEnvironment().getProperty("bootstrap.foo"));
then(this.context.getEnvironment().getProperty("bootstrap.foo"))
.isEqualTo("system");
}
@Test
@@ -169,7 +167,7 @@ public class BootstrapConfigurationTests {
System.setProperty("bootstrap.foo", "system");
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
.sources(BareConfiguration.class).run();
assertEquals("bar", this.context.getEnvironment().getProperty("bootstrap.foo"));
then(this.context.getEnvironment().getProperty("bootstrap.foo")).isEqualTo("bar");
}
@Test
@@ -181,8 +179,8 @@ public class BootstrapConfigurationTests {
System.setProperty("bootstrap.foo", "system");
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
.sources(BareConfiguration.class).run();
assertEquals("system",
this.context.getEnvironment().getProperty("bootstrap.foo"));
then(this.context.getEnvironment().getProperty("bootstrap.foo"))
.isEqualTo("system");
}
@Test
@@ -195,7 +193,8 @@ public class BootstrapConfigurationTests {
Collections.<String, Object>singletonMap("bootstrap.foo", "splat")));
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
.environment(environment).sources(BareConfiguration.class).run();
assertEquals("splat", this.context.getEnvironment().getProperty("bootstrap.foo"));
then(this.context.getEnvironment().getProperty("bootstrap.foo"))
.isEqualTo("splat");
}
@Test
@@ -205,17 +204,18 @@ public class BootstrapConfigurationTests {
.properties("spring.cloud.bootstrap.name:other",
"spring.config.name:plain")
.sources(BareConfiguration.class).run();
assertEquals("app",
this.context.getEnvironment().getProperty("spring.application.name"));
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)
assertEquals("main", this.context.getParent().getEnvironment()
.getProperty("spring.application.name"));
then(this.context.getParent().getEnvironment()
.getProperty("spring.application.name")).isEqualTo("main");
// The bootstrap context has the same "bootstrap" property source
assertEquals(this.context.getEnvironment().getPropertySources().get("bootstrap"),
((ConfigurableEnvironment) this.context.getParent().getEnvironment())
.getPropertySources().get("bootstrap"));
assertEquals("main-1", this.context.getId());
then(((ConfigurableEnvironment) this.context.getParent().getEnvironment())
.getPropertySources().get("bootstrap"))
.isEqualTo(this.context.getEnvironment().getPropertySources()
.get("bootstrap"));
then(this.context.getId()).isEqualTo("main-1");
}
@Test
@@ -225,12 +225,12 @@ public class BootstrapConfigurationTests {
.properties("spring.cloud.bootstrap.name:application",
"spring.config.name:other")
.sources(BareConfiguration.class).run();
assertEquals("main",
this.context.getEnvironment().getProperty("spring.application.name"));
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
assertEquals(null, this.context.getParent().getEnvironment()
.getProperty("spring.application.name"));
then(this.context.getParent().getEnvironment()
.getProperty("spring.application.name")).isEqualTo(null);
}
@Test
@@ -241,13 +241,13 @@ public class BootstrapConfigurationTests {
.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)
assertEquals("main",
this.context.getEnvironment().getProperty("spring.application.name"));
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)
assertEquals("main", this.context.getParent().getEnvironment()
.getProperty("spring.application.name"));
assertEquals("main-1", this.context.getId());
then(this.context.getParent().getEnvironment()
.getProperty("spring.application.name")).isEqualTo("main");
then(this.context.getId()).isEqualTo("main-1");
}
@Test
@@ -256,15 +256,15 @@ public class BootstrapConfigurationTests {
this.context = new SpringApplicationBuilder().sources(BareConfiguration.class)
.environment(new StandardEnvironment()).child(BareConfiguration.class)
.web(WebApplicationType.NONE).run();
assertEquals("bar", this.context.getEnvironment().getProperty("bootstrap.foo"));
assertEquals(this.context.getEnvironment(),
this.context.getParent().getEnvironment());
then(this.context.getEnvironment().getProperty("bootstrap.foo")).isEqualTo("bar");
then(this.context.getParent().getEnvironment())
.isEqualTo(this.context.getEnvironment());
MutablePropertySources sources = this.context.getEnvironment()
.getPropertySources();
PropertySource<?> bootstrap = sources
.get(PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME);
assertNotNull(bootstrap);
assertEquals(0, sources.precedenceOf(bootstrap));
then(bootstrap).isNotNull();
then(sources.precedenceOf(bootstrap)).isEqualTo(0);
}
@Test
@@ -273,11 +273,11 @@ public class BootstrapConfigurationTests {
PropertySourceConfiguration.MAP.put("bootstrap.foo", "bar");
this.context = new SpringApplicationBuilder().sources(BareConfiguration.class)
.child(BareConfiguration.class).web(WebApplicationType.NONE).run();
assertEquals(1, TestHigherPriorityBootstrapConfiguration.count.get());
assertNotNull(this.context.getParent());
assertEquals("bootstrap", this.context.getParent().getParent().getId());
assertNull(this.context.getParent().getParent().getParent());
assertEquals("bar", this.context.getEnvironment().getProperty("custom.foo"));
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("bar");
}
@Test
@@ -292,19 +292,21 @@ public class BootstrapConfigurationTests {
this.context = builder.child(BareConfiguration.class)
.properties("spring.application.name=context")
.web(WebApplicationType.NONE).run();
assertEquals(1, TestHigherPriorityBootstrapConfiguration.count.get());
assertNotNull(this.context.getParent());
assertEquals("bootstrap", this.context.getParent().getParent().getId());
assertNull(this.context.getParent().getParent().getParent());
assertEquals("context", this.context.getEnvironment().getProperty("custom.foo"));
assertEquals("context",
this.context.getEnvironment().getProperty("spring.application.name"));
assertNotNull(this.sibling.getParent());
assertEquals("bootstrap", this.sibling.getParent().getParent().getId());
assertNull(this.sibling.getParent().getParent().getParent());
assertEquals("sibling", this.sibling.getEnvironment().getProperty("custom.foo"));
assertEquals("sibling",
this.sibling.getEnvironment().getProperty("spring.application.name"));
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.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");
}
@Test
@@ -312,14 +314,16 @@ public class BootstrapConfigurationTests {
PropertySourceConfiguration.MAP.put("bootstrap.foo", "bar");
this.context = new SpringApplicationBuilder().sources(BareConfiguration.class)
.child(BareConfiguration.class).web(WebApplicationType.NONE).run();
assertEquals("bar", this.context.getEnvironment().getProperty("bootstrap.foo"));
assertNotSame(this.context.getEnvironment(),
this.context.getParent().getEnvironment());
assertTrue(this.context.getEnvironment().getPropertySources().contains(
PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME));
assertTrue(((ConfigurableEnvironment) this.context.getParent().getEnvironment())
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))
.isTrue();
then(((ConfigurableEnvironment) this.context.getParent().getEnvironment())
.getPropertySources().contains(
PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME));
PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME))
.isTrue();
}
@Test
@@ -331,26 +335,29 @@ public class BootstrapConfigurationTests {
.web(WebApplicationType.NONE).run();
this.context = new SpringApplicationBuilder(BareConfiguration.class)
.profiles("child").parent(parent).web(WebApplicationType.NONE).run();
assertNotSame(this.context.getEnvironment(),
this.context.getParent().getEnvironment());
then(this.context.getParent().getEnvironment())
.isNotSameAs(this.context.getEnvironment());
// The ApplicationContext merges profiles (profiles and property sources), see
// AbstractEnvironment.merge()
assertTrue(this.context.getEnvironment().acceptsProfiles("child", "parent"));
then(this.context.getEnvironment().acceptsProfiles("child", "parent")).isTrue();
// But the parent is not a child
assertFalse(this.context.getParent().getEnvironment().acceptsProfiles("child"));
assertTrue(this.context.getParent().getEnvironment().acceptsProfiles("parent"));
assertTrue(((ConfigurableEnvironment) this.context.getParent().getEnvironment())
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));
assertEquals("bar", this.context.getEnvironment().getProperty("bootstrap.foo"));
PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME))
.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
assertEquals("bar",
this.context.getParent().getEnvironment().getProperty("bootstrap.foo"));
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)
assertEquals("parent", this.context.getEnvironment().getProperty("info.name"));
then(this.context.getEnvironment().getProperty("info.name")).isEqualTo("parent");
}
@Test
@@ -358,8 +365,8 @@ public class BootstrapConfigurationTests {
PropertySourceConfiguration.MAP.put("spring.profiles.include", "bar,baz");
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
.profiles("foo").sources(BareConfiguration.class).run();
assertTrue(this.context.getEnvironment().acceptsProfiles("baz"));
assertTrue(this.context.getEnvironment().acceptsProfiles("bar"));
then(this.context.getEnvironment().acceptsProfiles("baz")).isTrue();
then(this.context.getEnvironment().acceptsProfiles("bar")).isTrue();
}
@Test
@@ -367,8 +374,9 @@ public class BootstrapConfigurationTests {
this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
.sources(BareConfiguration.class)
.properties("spring.cloud.bootstrap.name=local").run();
assertTrue(this.context.getEnvironment().acceptsProfiles("local"));
assertEquals("Hello added!", this.context.getEnvironment().getProperty("added"));
then(this.context.getEnvironment().acceptsProfiles("local")).isTrue();
then(this.context.getEnvironment().getProperty("added"))
.isEqualTo("Hello added!");
}
@Configuration
@@ -392,8 +400,8 @@ public class BootstrapConfigurationTests {
@Override
public PropertySource<?> locate(Environment environment) {
if (this.name != null) {
assertEquals(this.name,
environment.getProperty("spring.application.name"));
then(this.name)
.isEqualTo(environment.getProperty("spring.application.name"));
}
if (this.fail) {
throw new RuntimeException("Planned");

View File

@@ -23,9 +23,7 @@ import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.assertj.core.api.BDDAssertions.then;
import static org.springframework.boot.WebApplicationType.NONE;
/**
@@ -41,7 +39,7 @@ public class BootstrapListenerHierarchyIntegrationTests {
ConfigurableApplicationContext context = new SpringApplicationBuilder()
.sources(BasicConfiguration.class).web(NONE).run();
assertNotNull(context.getParent());
then(context.getParent()).isNotNull();
}
@Test
@@ -53,16 +51,16 @@ public class BootstrapListenerHierarchyIntegrationTests {
// Should be RootConfiguration based context
ConfigurableApplicationContext parent = (ConfigurableApplicationContext) context
.getParent();
assertEquals("rootBean", parent.getBean("rootBean", String.class));
then(parent.getBean("rootBean", String.class)).isEqualTo("rootBean");
// Parent should have the bootstrap context as parent
assertNotNull(parent.getParent());
then(parent.getParent()).isNotNull();
ConfigurableApplicationContext bootstrapContext = (ConfigurableApplicationContext) parent
.getParent();
// Bootstrap should be the root, there should be no other parent
assertNull(bootstrapContext.getParent());
then(bootstrapContext.getParent()).isNull();
}
@Test
@@ -75,16 +73,16 @@ public class BootstrapListenerHierarchyIntegrationTests {
// Should be RootConfiguration based context
ConfigurableApplicationContext parent = (ConfigurableApplicationContext) context
.getParent();
assertEquals("rootBean", parent.getBean("rootBean", String.class));
then(parent.getBean("rootBean", String.class)).isEqualTo("rootBean");
// Parent should have the bootstrap context as parent
assertNotNull(parent.getParent());
then(parent.getParent()).isNotNull();
ConfigurableApplicationContext bootstrapContext = (ConfigurableApplicationContext) parent
.getParent();
// Bootstrap should be the root, there should be no other parent
assertNull(bootstrapContext.getParent());
then(bootstrapContext.getParent()).isNull();
}
@Configuration

View File

@@ -1,5 +1,3 @@
package org.springframework.cloud.bootstrap.encrypt;
/*
* Copyright 2012-2019 the original author or authors.
*
@@ -16,6 +14,8 @@ package org.springframework.cloud.bootstrap.encrypt;
* limitations under the License.
*/
package org.springframework.cloud.bootstrap.encrypt;
import org.junit.Test;
import org.springframework.boot.WebApplicationType;
@@ -24,9 +24,7 @@ import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.security.crypto.encrypt.TextEncryptor;
import org.springframework.security.rsa.crypto.RsaAlgorithm;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.BDDAssertions.then;
public class EncryptionBootstrapConfigurationTests {
@@ -36,7 +34,7 @@ public class EncryptionBootstrapConfigurationTests {
EncryptionBootstrapConfiguration.class).web(WebApplicationType.NONE)
.properties("encrypt.key:pie").run();
TextEncryptor encryptor = context.getBean(TextEncryptor.class);
assertEquals("foo", encryptor.decrypt(encryptor.encrypt("foo")));
then(encryptor.decrypt(encryptor.encrypt("foo"))).isEqualTo("foo");
context.close();
}
@@ -51,7 +49,7 @@ public class EncryptionBootstrapConfigurationTests {
"encrypt.keyStore.secret:changeme")
.run();
TextEncryptor encryptor = context.getBean(TextEncryptor.class);
assertEquals("foo", encryptor.decrypt(encryptor.encrypt("foo")));
then(encryptor.decrypt(encryptor.encrypt("foo"))).isEqualTo("foo");
context.close();
}
@@ -66,7 +64,7 @@ public class EncryptionBootstrapConfigurationTests {
"encrypt.key-store.secret:changeme")
.run();
TextEncryptor encryptor = context.getBean(TextEncryptor.class);
assertEquals("foo", encryptor.decrypt(encryptor.encrypt("foo")));
then(encryptor.decrypt(encryptor.encrypt("foo"))).isEqualTo("foo");
context.close();
}
@@ -82,9 +80,9 @@ public class EncryptionBootstrapConfigurationTests {
"encrypt.rsa.strong:true", "encrypt.rsa.salt:foobar")
.run();
RsaProperties properties = context.getBean(RsaProperties.class);
assertEquals("foobar", properties.getSalt());
assertTrue(properties.isStrong());
assertEquals(RsaAlgorithm.DEFAULT, properties.getAlgorithm());
then(properties.getSalt()).isEqualTo("foobar");
then(properties.isStrong()).isTrue();
then(properties.getAlgorithm()).isEqualTo(RsaAlgorithm.DEFAULT);
context.close();
}
@@ -98,12 +96,12 @@ public class EncryptionBootstrapConfigurationTests {
"encrypt.key-store.alias:mytestkey",
"encrypt.key-store.secret:changeme")
.run();
assertThat(false).as(
then(false).as(
"Should not create an application context with invalid keystore location")
.isTrue();
}
catch (Exception e) {
assertThat(e).hasRootCauseInstanceOf(IllegalStateException.class);
then(e).hasRootCauseInstanceOf(IllegalStateException.class);
}
}

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.bootstrap.encrypt;
import org.junit.Test;
@@ -9,7 +25,7 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.BDDAssertions.then;
public class EncryptionIntegrationTests {
@@ -20,7 +36,7 @@ public class EncryptionIntegrationTests {
"encrypt.key:pie",
"foo.password:{cipher}bf29452295df354e6153c5b31b03ef23c70e55fba24299aa85c63438f1c43c95")
.run();
assertEquals("test", context.getEnvironment().getProperty("foo.password"));
then(context.getEnvironment().getProperty("foo.password")).isEqualTo("test");
}
@Test
@@ -30,7 +46,7 @@ public class EncryptionIntegrationTests {
"encrypt.key:pie",
"foo.password:{cipher}bf29452295df354e6153c5b31b03ef23c70e55fba24299aa85c63438f1c43c95")
.run();
assertEquals("test", context.getBean(PasswordProperties.class).getPassword());
then(context.getBean(PasswordProperties.class).getPassword()).isEqualTo("test");
}
@Configuration

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.bootstrap.encrypt;
import java.nio.charset.Charset;
@@ -24,7 +25,7 @@ import org.springframework.core.io.ClassPathResource;
import org.springframework.security.crypto.encrypt.TextEncryptor;
import org.springframework.util.StreamUtils;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.BDDAssertions.then;
/**
* @author Biju Kunjummen
@@ -41,7 +42,7 @@ public class EncryptorFactoryTests {
String toEncrypt = "sample text to encrypt";
String encrypted = encryptor.encrypt(toEncrypt);
assertEquals(toEncrypt, encryptor.decrypt(encrypted));
then(encryptor.decrypt(encrypted)).isEqualTo(toEncrypt);
}
@Test(expected = RuntimeException.class)

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.bootstrap.encrypt;
import java.util.Collections;
@@ -34,9 +35,7 @@ import org.springframework.core.env.PropertySource;
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.security.crypto.encrypt.TextEncryptor;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.assertj.core.api.BDDAssertions.then;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
@@ -57,7 +56,7 @@ public class EnvironmentDecryptApplicationInitializerTests {
ConfigurableApplicationContext context = new AnnotationConfigApplicationContext();
TestPropertyValues.of("foo: {cipher}bar").applyTo(context);
this.listener.initialize(context);
assertEquals("bar", context.getEnvironment().getProperty("foo"));
then(context.getEnvironment().getProperty("foo")).isEqualTo("bar");
}
@Test
@@ -66,7 +65,7 @@ public class EnvironmentDecryptApplicationInitializerTests {
TestPropertyValues.of("FOO_TEXT: {cipher}bar").applyTo(context.getEnvironment(),
TestPropertyValues.Type.SYSTEM_ENVIRONMENT);
this.listener.initialize(context);
assertEquals("bar", context.getEnvironment().getProperty("foo.text"));
then(context.getEnvironment().getProperty("foo.text")).isEqualTo("bar");
}
@Test
@@ -77,7 +76,7 @@ public class EnvironmentDecryptApplicationInitializerTests {
.addFirst(new MapPropertySource("test_override",
Collections.<String, Object>singletonMap("foo", "{cipher}spam")));
this.listener.initialize(context);
assertEquals("spam", context.getEnvironment().getProperty("foo"));
then(context.getEnvironment().getProperty("foo")).isEqualTo("spam");
}
@Test
@@ -88,7 +87,7 @@ public class EnvironmentDecryptApplicationInitializerTests {
.addFirst(new MapPropertySource("test_override",
Collections.<String, Object>singletonMap("foo", "spam")));
this.listener.initialize(context);
assertEquals("spam", context.getEnvironment().getProperty("foo"));
then(context.getEnvironment().getProperty("foo")).isEqualTo("spam");
}
@Test(expected = IllegalStateException.class)
@@ -98,7 +97,7 @@ public class EnvironmentDecryptApplicationInitializerTests {
ConfigurableApplicationContext context = new AnnotationConfigApplicationContext();
TestPropertyValues.of("foo: {cipher}bar").applyTo(context);
this.listener.initialize(context);
assertEquals("bar", context.getEnvironment().getProperty("foo"));
then(context.getEnvironment().getProperty("foo")).isEqualTo("bar");
}
@Test
@@ -110,7 +109,7 @@ public class EnvironmentDecryptApplicationInitializerTests {
TestPropertyValues.of("foo: {cipher}bar").applyTo(context);
this.listener.initialize(context);
// Empty is safest fallback for undecryptable cipher
assertEquals("", context.getEnvironment().getProperty("foo"));
then(context.getEnvironment().getProperty("foo")).isEqualTo("");
}
@Test
@@ -131,21 +130,21 @@ public class EnvironmentDecryptApplicationInitializerTests {
.applyTo(context.getEnvironment(), Type.MAP, "combinedTest");
this.listener.initialize(context);
assertEquals("Foo", context.getEnvironment().getProperty("mine[0].someValue"));
assertEquals("Foo0", context.getEnvironment().getProperty("mine[0].someKey"));
assertEquals("Bar", context.getEnvironment().getProperty("mine[1].someValue"));
assertEquals("Bar1", context.getEnvironment().getProperty("mine[1].someKey"));
assertEquals("yourFoo",
context.getEnvironment().getProperty("yours[0].someValue"));
assertEquals("yourBar",
context.getEnvironment().getProperty("yours[1].someValue"));
then(context.getEnvironment().getProperty("mine[0].someValue")).isEqualTo("Foo");
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");
MutablePropertySources propertySources = context.getEnvironment()
.getPropertySources();
PropertySource<Map<?, ?>> decrypted = (PropertySource<Map<?, ?>>) propertySources
.get(DECRYPTED_PROPERTY_SOURCE_NAME);
assertThat("decrypted property source had wrong size",
decrypted.getSource().size(), is(4));
then(decrypted.getSource().size()).as("decrypted property source had wrong size")
.isEqualTo(4);
}
@Test
@@ -163,7 +162,7 @@ public class EnvironmentDecryptApplicationInitializerTests {
initializer.initialize(ctx);
assertEquals("value", ctx.getEnvironment().getProperty("key"));
then(ctx.getEnvironment().getProperty("key")).isEqualTo("value");
}
@Test
@@ -188,11 +187,11 @@ public class EnvironmentDecryptApplicationInitializerTests {
initializer.initialize(ctx);
// validate behaviour with encryption
assertEquals("value1b", ctx.getEnvironment().getProperty("key1"));
then(ctx.getEnvironment().getProperty("key1")).isEqualTo("value1b");
// validate behaviour without encryption
assertEquals("value2b", ctx.getEnvironment().getProperty("key2"));
then(ctx.getEnvironment().getProperty("key2")).isEqualTo("value2b");
// validate behaviour without override
assertEquals("value3", ctx.getEnvironment().getProperty("key3"));
then(ctx.getEnvironment().getProperty("key3")).isEqualTo("value3");
}
@Test
@@ -207,8 +206,8 @@ public class EnvironmentDecryptApplicationInitializerTests {
.addFirst(new MapPropertySource("test_override",
Collections.<String, Object>singletonMap("foo", "spam")));
initializer.initialize(context);
assertEquals("spam", context.getEnvironment().getProperty("foo"));
assertEquals("bar2", context.getEnvironment().getProperty("foo2"));
then(context.getEnvironment().getProperty("foo")).isEqualTo("spam");
then(context.getEnvironment().getProperty("foo2")).isEqualTo("bar2");
verify(encryptor).decrypt("bar2");
verifyNoMoreInteractions(encryptor);
}

View File

@@ -1,4 +1,3 @@
package org.springframework.cloud.bootstrap.encrypt;
/*
* Copyright 2012-2019 the original author or authors.
*
@@ -15,6 +14,8 @@ package org.springframework.cloud.bootstrap.encrypt;
* limitations under the License.
*/
package org.springframework.cloud.bootstrap.encrypt;
import java.util.Map;
import org.junit.After;
@@ -28,8 +29,7 @@ import org.springframework.cloud.test.ClassPathExclusions;
import org.springframework.cloud.test.ModifiedClassPathRunner;
import org.springframework.context.ConfigurableApplicationContext;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.assertj.core.api.BDDAssertions.then;
/**
* @author Ryan Baxter
@@ -60,7 +60,7 @@ public class RsaDisabledTests {
public void testLoadBalancedRetryFactoryBean() throws Exception {
Map<String, RsaProperties> properties = this.context
.getBeansOfType(RsaProperties.class);
assertThat(properties.values(), hasSize(0));
then(properties.values()).hasSize(0);
}
}

View File

@@ -43,9 +43,8 @@ import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.BDDAssertions.then;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
@@ -72,13 +71,13 @@ public class EnvironmentManagerIntegrationTests {
@Test
public void testRefresh() throws Exception {
assertEquals("Hello scope!", this.properties.getMessage());
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\"}"));
assertEquals("Foo", this.properties.getMessage());
then(this.properties.getMessage()).isEqualTo("Foo");
}
private String property(String name, String value) throws JsonProcessingException {
@@ -101,7 +100,7 @@ public class EnvironmentManagerIntegrationTests {
catch (ServletException e) {
// The underlying BindException is not handled by the dispatcher servlet
}
assertEquals(0, this.properties.getDelay());
then(this.properties.getDelay()).isEqualTo(0);
}
@Test
@@ -114,14 +113,14 @@ public class EnvironmentManagerIntegrationTests {
public void environmentBeansConfiguredCorrectly() {
Map<String, EnvironmentEndpoint> envbeans = this.context
.getBeansOfType(EnvironmentEndpoint.class);
assertThat(envbeans).hasSize(1).containsKey("environmentEndpoint");
assertThat(envbeans.get("environmentEndpoint"))
then(envbeans).hasSize(1).containsKey("environmentEndpoint");
then(envbeans.get("environmentEndpoint"))
.isInstanceOf(WritableEnvironmentEndpoint.class);
Map<String, EnvironmentEndpointWebExtension> extbeans = this.context
.getBeansOfType(EnvironmentEndpointWebExtension.class);
assertThat(extbeans).hasSize(1).containsKey("environmentEndpointWebExtension");
assertThat(extbeans.get("environmentEndpointWebExtension"))
then(extbeans).hasSize(1).containsKey("environmentEndpointWebExtension");
then(extbeans.get("environmentEndpointWebExtension"))
.isInstanceOf(WritableEnvironmentEndpointWebExtension.class);
}

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.context.environment;
import org.junit.Test;
@@ -7,7 +23,7 @@ import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.mock.env.MockEnvironment;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.BDDAssertions.then;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
@@ -24,22 +40,22 @@ public class EnvironmentManagerTest {
environmentManager.setProperty("foo", "bar");
assertThat(environment.getProperty("foo")).isEqualTo("bar");
then(environment.getProperty("foo")).isEqualTo("bar");
ArgumentCaptor<ApplicationEvent> eventCaptor = ArgumentCaptor
.forClass(ApplicationEvent.class);
verify(publisher, times(1)).publishEvent(eventCaptor.capture());
assertThat(eventCaptor.getValue()).isInstanceOf(EnvironmentChangeEvent.class);
then(eventCaptor.getValue()).isInstanceOf(EnvironmentChangeEvent.class);
EnvironmentChangeEvent event = (EnvironmentChangeEvent) eventCaptor.getValue();
assertThat(event.getKeys()).containsExactly("foo");
then(event.getKeys()).containsExactly("foo");
reset(publisher);
environmentManager.reset();
assertThat(environment.getProperty("foo")).isNull();
then(environment.getProperty("foo")).isNull();
verify(publisher, times(1)).publishEvent(eventCaptor.capture());
assertThat(eventCaptor.getValue()).isInstanceOf(EnvironmentChangeEvent.class);
then(eventCaptor.getValue()).isInstanceOf(EnvironmentChangeEvent.class);
event = (EnvironmentChangeEvent) eventCaptor.getValue();
assertThat(event.getKeys()).containsExactly("foo");
then(event.getKeys()).containsExactly("foo");
}
}

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.context.named;
import java.util.Arrays;
@@ -8,11 +24,7 @@ import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
import static org.assertj.core.api.BDDAssertions.then;
/**
* @author Spencer Gibb
@@ -30,24 +42,24 @@ public class NamedContextFactoryTests {
getSpec("bar", BarConfig.class)));
Foo foo = factory.getInstance("foo", Foo.class);
assertThat("foo was null", foo, is(notNullValue()));
then(foo).as("foo was null").isNotNull();
Bar bar = factory.getInstance("bar", Bar.class);
assertThat("bar was null", bar, is(notNullValue()));
then(bar).as("bar was null").isNotNull();
assertThat("context names not exposed", factory.getContextNames(),
hasItems("foo", "bar"));
then(factory.getContextNames()).as("context names not exposed").contains("foo",
"bar");
Bar foobar = factory.getInstance("foo", Bar.class);
assertThat("bar was not null", foobar, is(nullValue()));
then(foobar).as("bar was not null").isNull();
Map<String, Baz> fooBazes = factory.getInstances("foo", Baz.class);
assertThat("fooBazes was null", fooBazes, is(notNullValue()));
assertThat("fooBazes size was wrong", fooBazes.size(), is(1));
then(fooBazes).as("fooBazes was null").isNotNull();
then(fooBazes.size()).as("fooBazes size was wrong").isEqualTo(1);
Map<String, Baz> barBazes = factory.getInstances("bar", Baz.class);
assertThat("barBazes was null", barBazes, is(notNullValue()));
assertThat("barBazes size was wrong", barBazes.size(), is(2));
then(barBazes).as("barBazes was null").isNotNull();
then(barBazes.size()).as("barBazes size was wrong").isEqualTo(2);
// get the contexts before destroy() to verify these are the old ones
AnnotationConfigApplicationContext fooContext = factory.getContext("foo");
@@ -55,9 +67,9 @@ public class NamedContextFactoryTests {
factory.destroy();
assertThat("foo context wasn't closed", fooContext.isActive(), is(false));
then(fooContext.isActive()).as("foo context wasn't closed").isFalse();
assertThat("bar context wasn't closed", barContext.isActive(), is(false));
then(barContext.isActive()).as("bar context wasn't closed").isFalse();
}
private TestSpec getSpec(String name, Class<?> configClass) {
@@ -66,7 +78,7 @@ public class NamedContextFactoryTests {
static class TestClientFactory extends NamedContextFactory<TestSpec> {
public TestClientFactory() {
TestClientFactory() {
super(TestSpec.class, "testfactory", "test.client.name");
}
@@ -78,10 +90,10 @@ public class NamedContextFactoryTests {
private Class<?>[] configuration;
public TestSpec() {
TestSpec() {
}
public TestSpec(String name, Class<?>[] configuration) {
TestSpec(String name, Class<?>[] configuration) {
this.name = name;
this.configuration = configuration;
}

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.context.properties;
import javax.annotation.PostConstruct;
@@ -40,7 +41,7 @@ import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.BDDAssertions.then;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestConfiguration.class)
@@ -62,50 +63,50 @@ public class ConfigurationPropertiesRebinderIntegrationTests {
@Test
@DirtiesContext
public void testSimpleProperties() throws Exception {
assertEquals("Hello scope!", this.properties.getMessage());
assertEquals(1, this.properties.getCount());
then(this.properties.getMessage()).isEqualTo("Hello scope!");
then(this.properties.getCount()).isEqualTo(1);
// Change the dynamic property source...
TestPropertyValues.of("message:Foo").applyTo(this.environment);
// ...but don't refresh, so the bean stays the same:
assertEquals("Hello scope!", this.properties.getMessage());
assertEquals(1, this.properties.getCount());
then(this.properties.getMessage()).isEqualTo("Hello scope!");
then(this.properties.getCount()).isEqualTo(1);
}
@Test
@DirtiesContext
public void testRefreshInParent() throws Exception {
assertEquals("main", this.config.getName());
then(this.config.getName()).isEqualTo("main");
// Change the dynamic property source...
TestPropertyValues.of("config.name=foo").applyTo(this.environment);
// ...and then refresh, so the bean is re-initialized:
this.rebinder.rebind();
assertEquals("foo", this.config.getName());
then(this.config.getName()).isEqualTo("foo");
}
@Test
@DirtiesContext
public void testRefresh() throws Exception {
assertEquals(1, this.properties.getCount());
assertEquals("Hello scope!", this.properties.getMessage());
then(this.properties.getCount()).isEqualTo(1);
then(this.properties.getMessage()).isEqualTo("Hello scope!");
// Change the dynamic property source...
TestPropertyValues.of("message:Foo").applyTo(this.environment);
// ...and then refresh, so the bean is re-initialized:
this.rebinder.rebind();
assertEquals("Foo", this.properties.getMessage());
assertEquals(2, this.properties.getCount());
then(this.properties.getMessage()).isEqualTo("Foo");
then(this.properties.getCount()).isEqualTo(2);
}
@Test
@DirtiesContext
public void testRefreshByName() throws Exception {
assertEquals(1, this.properties.getCount());
assertEquals("Hello scope!", this.properties.getMessage());
then(this.properties.getCount()).isEqualTo(1);
then(this.properties.getMessage()).isEqualTo("Hello scope!");
// Change the dynamic property source...
TestPropertyValues.of("message:Foo").applyTo(this.environment);
// ...and then refresh, so the bean is re-initialized:
this.rebinder.rebind("properties");
assertEquals("Foo", this.properties.getMessage());
assertEquals(2, this.properties.getCount());
then(this.properties.getMessage()).isEqualTo("Foo");
then(this.properties.getCount()).isEqualTo(2);
}
interface SomeService {

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.context.properties;
import org.junit.Test;
@@ -36,8 +37,7 @@ import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.BDDAssertions.then;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestConfiguration.class)
@@ -55,14 +55,14 @@ public class ConfigurationPropertiesRebinderLifecycleIntegrationTests {
@Test
@DirtiesContext
public void testRefresh() throws Exception {
assertEquals(0, this.properties.getCount());
assertEquals("Hello scope!", this.properties.getMessage());
then(this.properties.getCount()).isEqualTo(0);
then(this.properties.getMessage()).isEqualTo("Hello scope!");
// Change the dynamic property source...
TestPropertyValues.of("message:Foo").applyTo(this.environment);
// ...and then refresh, so the bean is re-initialized:
this.rebinder.rebind();
assertEquals("Foo", this.properties.getMessage());
assertEquals(1, this.properties.getCount());
then(this.properties.getMessage()).isEqualTo("Foo");
then(this.properties.getCount()).isEqualTo(1);
}
@Configuration
@@ -110,7 +110,7 @@ public class ConfigurationPropertiesRebinderLifecycleIntegrationTests {
@Override
public void afterPropertiesSet() throws Exception {
assertThat(this.message).isNotEmpty();
then(this.message).isNotEmpty();
}
@Override

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.context.properties;
import java.util.List;
@@ -41,7 +42,7 @@ import org.springframework.core.env.PropertySource;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.BDDAssertions.then;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestConfiguration.class, properties = "messages=one,two")
@@ -59,22 +60,22 @@ public class ConfigurationPropertiesRebinderListIntegrationTests {
@Test
@DirtiesContext
public void testAppendProperties() throws Exception {
assertEquals("[one, two]", this.properties.getMessages().toString());
then("[one, two]").isEqualTo(this.properties.getMessages().toString());
TestPropertyValues.of("messages[0]:foo").applyTo(this.environment);
this.rebinder.rebind();
assertEquals("[foo]", this.properties.getMessages().toString());
then(this.properties.getMessages().toString()).isEqualTo("[foo]");
}
@Test
@DirtiesContext
@Ignore("Can't rebind to list and re-initialize it (need refresh scope for this to work)")
public void testReplaceProperties() throws Exception {
assertEquals("[one, two]", this.properties.getMessages().toString());
then("[one, two]").isEqualTo(this.properties.getMessages().toString());
Map<String, Object> map = findTestProperties();
map.clear();
TestPropertyValues.of("messages[0]:foo").applyTo(this.environment);
this.rebinder.rebind();
assertEquals("[foo]", this.properties.getMessages().toString());
then(this.properties.getMessages().toString()).isEqualTo("[foo]");
}
private Map<String, Object> findTestProperties() {
@@ -91,12 +92,12 @@ public class ConfigurationPropertiesRebinderListIntegrationTests {
@Test
@DirtiesContext
public void testReplacePropertiesWithCommaSeparated() throws Exception {
assertEquals("[one, two]", this.properties.getMessages().toString());
then("[one, two]").isEqualTo(this.properties.getMessages().toString());
Map<String, Object> map = findTestProperties();
map.clear();
TestPropertyValues.of("messages:foo").applyTo(this.environment);
this.rebinder.rebind();
assertEquals("[foo]", this.properties.getMessages().toString());
then(this.properties.getMessages().toString()).isEqualTo("[foo]");
}
@Configuration

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.context.properties;
import java.util.HashMap;
@@ -40,7 +41,7 @@ import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.BDDAssertions.then;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestConfiguration.class, properties = {
@@ -61,10 +62,10 @@ public class ConfigurationPropertiesRebinderProxyIntegrationTests {
public void testAppendProperties() throws Exception {
// This comes out as a String not Integer if the rebinder processes the proxy
// instead of the target
assertEquals(new Integer(168), this.properties.getExpiry().get("one"));
then(this.properties.getExpiry().get("one")).isEqualTo(new Integer(168));
TestPropertyValues.of("messages.expiry.one=56").applyTo(this.environment);
this.rebinder.rebind();
assertEquals(new Integer(56), this.properties.getExpiry().get("one"));
then(this.properties.getExpiry().get("one")).isEqualTo(new Integer(56));
}
@Configuration

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.context.properties;
import javax.annotation.PostConstruct;
@@ -37,7 +38,7 @@ import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.BDDAssertions.then;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestConfiguration.class)
@@ -58,31 +59,31 @@ public class ConfigurationPropertiesRebinderRefreshScopeIntegrationTests {
@Test
@DirtiesContext
public void testSimpleProperties() throws Exception {
assertEquals("Hello scope!", this.properties.getMessage());
then(this.properties.getMessage()).isEqualTo("Hello scope!");
// Change the dynamic property source...
TestPropertyValues.of("message:Foo").applyTo(this.environment);
// ...but don't refresh, so the bean stays the same:
assertEquals("Hello scope!", this.properties.getMessage());
assertEquals(1, this.properties.getCount());
then(this.properties.getMessage()).isEqualTo("Hello scope!");
then(this.properties.getCount()).isEqualTo(1);
}
@Test
@DirtiesContext
public void testRefresh() throws Exception {
assertEquals(1, this.properties.getCount());
assertEquals("Hello scope!", this.properties.getMessage());
assertEquals(1, this.properties.getCount());
then(this.properties.getCount()).isEqualTo(1);
then(this.properties.getMessage()).isEqualTo("Hello scope!");
then(this.properties.getCount()).isEqualTo(1);
// Change the dynamic property source...
TestPropertyValues.of("message:Foo").applyTo(this.environment);
// ...rebind, but the bean is not re-initialized:
this.rebinder.rebind();
assertEquals("Hello scope!", this.properties.getMessage());
assertEquals(1, this.properties.getCount());
then(this.properties.getMessage()).isEqualTo("Hello scope!");
then(this.properties.getCount()).isEqualTo(1);
// ...and then refresh, so the bean is re-initialized:
this.refreshScope.refreshAll();
assertEquals("Foo", this.properties.getMessage());
then(this.properties.getMessage()).isEqualTo("Foo");
// It's a new instance so the initialization count is 1
assertEquals(1, this.properties.getCount());
then(this.properties.getCount()).isEqualTo(1);
}
@Configuration

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.context.refresh;
import org.junit.Test;
@@ -32,7 +33,7 @@ import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.BDDAssertions.then;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestConfiguration.class, properties = {
@@ -51,33 +52,33 @@ public class ContextRefresherIntegrationTests {
@Test
@DirtiesContext
public void testSimpleProperties() throws Exception {
assertEquals("Hello scope!", this.properties.getMessage());
then(this.properties.getMessage()).isEqualTo("Hello scope!");
// Change the dynamic property source...
this.properties.setMessage("Foo");
// ...but don't refresh, so the bean stays the same:
assertEquals("Foo", this.properties.getMessage());
then(this.properties.getMessage()).isEqualTo("Foo");
}
@Test
@DirtiesContext
public void testRefreshBean() throws Exception {
assertEquals("Hello scope!", this.properties.getMessage());
then(this.properties.getMessage()).isEqualTo("Hello scope!");
// Change the dynamic property source...
this.properties.setMessage("Foo");
// ...and then refresh, so the bean is re-initialized:
this.refresher.refresh();
assertEquals("Hello scope!", this.properties.getMessage());
then(this.properties.getMessage()).isEqualTo("Hello scope!");
}
@Test
@DirtiesContext
public void testUpdateHikari() throws Exception {
assertEquals("Hello scope!", this.properties.getMessage());
then(this.properties.getMessage()).isEqualTo("Hello scope!");
TestPropertyValues.of("spring.datasource.hikari.read-only=true")
.applyTo(this.environment);
// ...and then refresh, so the bean is re-initialized:
this.refresher.refresh();
assertEquals("Hello scope!", this.properties.getMessage());
then(this.properties.getMessage()).isEqualTo("Hello scope!");
}
@Configuration

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.context.refresh;
import java.util.ArrayList;
@@ -24,7 +40,7 @@ import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.BDDAssertions.then;
public class ContextRefresherTests {
@@ -43,14 +59,14 @@ public class ContextRefresherTests {
"--spring.main.bannerMode=OFF")) {
context.getEnvironment().setActiveProfiles("refresh");
List<String> names = names(context.getEnvironment().getPropertySources());
assertThat(names).doesNotContain(
then(names).doesNotContain(
"applicationConfig: [classpath:/bootstrap-refresh.properties]");
ContextRefresher refresher = new ContextRefresher(context, this.scope);
refresher.refresh();
names = names(context.getEnvironment().getPropertySources());
assertThat(names).contains(
then(names).contains(
"applicationConfig: [classpath:/bootstrap-refresh.properties]");
assertThat(names).containsSequence(
then(names).containsSequence(
"applicationConfig: [classpath:/application.properties]",
"applicationConfig: [classpath:/bootstrap-refresh.properties]",
"applicationConfig: [classpath:/bootstrap.properties]");
@@ -67,14 +83,14 @@ public class ContextRefresherTests {
"--spring.cloud.bootstrap.name=refresh")) {
List<String> names = names(context.getEnvironment().getPropertySources());
System.err.println("***** " + context.getEnvironment().getPropertySources());
assertThat(names).doesNotContain("bootstrapProperties");
then(names).doesNotContain("bootstrapProperties");
ContextRefresher refresher = new ContextRefresher(context, this.scope);
TestPropertyValues.of(
"spring.cloud.bootstrap.sources: org.springframework.cloud.context.refresh.ContextRefresherTests.PropertySourceConfiguration")
TestPropertyValues.of("spring.cloud.bootstrap.sources: "
+ "org.springframework.cloud.context.refresh.ContextRefresherTests.PropertySourceConfiguration")
.applyTo(context.getEnvironment(), Type.MAP, "defaultProperties");
refresher.refresh();
names = names(context.getEnvironment().getPropertySources());
assertThat(names).first().isEqualTo("bootstrapProperties");
then(names).first().isEqualTo("bootstrapProperties");
}
}
@@ -87,16 +103,16 @@ public class ContextRefresherTests {
"--debug=false", "--spring.main.bannerMode=OFF",
"--spring.cloud.bootstrap.name=refresh")) {
ContextRefresher refresher = new ContextRefresher(context, this.scope);
TestPropertyValues.of(
"spring.cloud.bootstrap.sources: org.springframework.cloud.context.refresh.ContextRefresherTests.PropertySourceConfiguration")
TestPropertyValues.of("spring.cloud.bootstrap.sources: "
+ "org.springframework.cloud.context.refresh.ContextRefresherTests.PropertySourceConfiguration")
.applyTo(context);
ConfigurableApplicationContext refresherContext = refresher
.addConfigFilesToEnvironment();
assertThat(refresherContext.getParent()).isNotNull()
then(refresherContext.getParent()).isNotNull()
.isInstanceOf(ConfigurableApplicationContext.class);
ConfigurableApplicationContext parent = (ConfigurableApplicationContext) refresherContext
.getParent();
assertThat(parent.isActive()).isFalse();
then(parent.isActive()).isFalse();
}
}
@@ -106,15 +122,15 @@ public class ContextRefresherTests {
TestLoggingSystem.class.getName());
TestLoggingSystem system = (TestLoggingSystem) LoggingSystem
.get(getClass().getClassLoader());
assertThat(system.getCount()).isEqualTo(0);
then(system.getCount()).isEqualTo(0);
try (ConfigurableApplicationContext context = SpringApplication.run(Empty.class,
"--spring.main.web-application-type=none", "--debug=false",
"--spring.main.bannerMode=OFF",
"--spring.cloud.bootstrap.name=refresh")) {
assertThat(system.getCount()).isEqualTo(4);
then(system.getCount()).isEqualTo(4);
ContextRefresher refresher = new ContextRefresher(context, this.scope);
refresher.refresh();
assertThat(system.getCount()).isEqualTo(4);
then(system.getCount()).isEqualTo(4);
}
}
@@ -130,8 +146,7 @@ public class ContextRefresherTests {
context.getEnvironment().setActiveProfiles("refresh");
ContextRefresher refresher = new ContextRefresher(context, this.scope);
refresher.refresh();
assertThat(TestBootstrapConfiguration.fooSightings).containsExactly("bar",
"bar");
then(TestBootstrapConfiguration.fooSightings).containsExactly("bar", "bar");
}
TestBootstrapConfiguration.fooSightings = null;

View File

@@ -25,10 +25,7 @@ import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.LiveBeansView;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.assertj.core.api.BDDAssertions.then;
public class RestartIntegrationTests {
@@ -53,26 +50,26 @@ public class RestartIntegrationTests {
"--spring.liveBeansView.mbeanDomain=livebeans");
RestartEndpoint endpoint = this.context.getBean(RestartEndpoint.class);
assertNotNull(this.context.getParent());
assertNull(this.context.getParent().getParent());
then(this.context.getParent()).isNotNull();
then(this.context.getParent().getParent()).isNull();
this.context = endpoint.doRestart();
assertNotNull(this.context);
assertNotNull(this.context.getParent());
assertNull(this.context.getParent().getParent());
then(this.context).isNotNull();
then(this.context.getParent()).isNotNull();
then(this.context.getParent().getParent()).isNull();
RestartEndpoint next = this.context.getBean(RestartEndpoint.class);
assertNotSame(endpoint, next);
then(next).isNotSameAs(endpoint);
this.context = next.doRestart();
assertNotNull(this.context);
assertNotNull(this.context.getParent());
assertNull(this.context.getParent().getParent());
then(this.context).isNotNull();
then(this.context.getParent()).isNotNull();
then(this.context.getParent().getParent()).isNull();
LiveBeansView beans = new LiveBeansView();
String json = beans.getSnapshotAsJson();
assertThat(json).containsOnlyOnce("parent\": \"bootstrap");
assertThat(json).containsOnlyOnce("parent\": null");
then(json).containsOnlyOnce("parent\": \"bootstrap");
then(json).containsOnlyOnce("parent\": null");
}
@Configuration

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.context.scope.refresh;
import org.junit.Test;
@@ -28,7 +29,7 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.BDDAssertions.then;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestConfiguration.class)
@@ -45,10 +46,10 @@ public class ImportRefreshScopeIntegrationTests {
@Test
public void testSimpleProperties() throws Exception {
assertEquals("Hello scope!", this.service.getMessage());
assertEquals("refresh",
this.beanFactory.getBeanDefinition("scopedTarget.service").getScope());
assertEquals("Hello scope!", this.service.getMessage());
then(this.service.getMessage()).isEqualTo("Hello scope!");
then(this.beanFactory.getBeanDefinition("scopedTarget.service").getScope())
.isEqualTo("refresh");
then(this.service.getMessage()).isEqualTo("Hello scope!");
}
@Configuration("service")

View File

@@ -42,10 +42,8 @@ import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.BDDAssertions.then;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestConfiguration.class)
@@ -62,7 +60,7 @@ public class MoreRefreshScopeIntegrationTests {
@Before
public void init() {
assertEquals(1, TestService.getInitCount());
then(TestService.getInitCount()).isEqualTo(1);
TestService.reset();
}
@@ -74,20 +72,20 @@ public class MoreRefreshScopeIntegrationTests {
@Test
@DirtiesContext
public void testSimpleProperties() throws Exception {
assertEquals("Hello scope!", this.service.getMessage());
assertTrue(this.service instanceof Advised);
then(this.service.getMessage()).isEqualTo("Hello scope!");
then(this.service instanceof Advised).isTrue();
// Change the dynamic property source...
TestPropertyValues.of("message:Foo").applyTo(this.environment);
// ...but don't refresh, so the bean stays the same:
assertEquals("Hello scope!", this.service.getMessage());
assertEquals(0, TestService.getInitCount());
assertEquals(0, TestService.getDestroyCount());
then(this.service.getMessage()).isEqualTo("Hello scope!");
then(TestService.getInitCount()).isEqualTo(0);
then(TestService.getDestroyCount()).isEqualTo(0);
}
@Test
@DirtiesContext
public void testRefresh() throws Exception {
assertEquals("Hello scope!", this.service.getMessage());
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,
@@ -96,16 +94,16 @@ public class MoreRefreshScopeIntegrationTests {
this.scope.refreshAll();
String id2 = this.service.toString();
String message = this.service.getMessage();
assertEquals("Foo", message);
assertEquals(1, TestService.getInitCount());
assertEquals(1, TestService.getDestroyCount());
assertNotSame(id1, id2);
then(message).isEqualTo("Foo");
then(TestService.getInitCount()).isEqualTo(1);
then(TestService.getDestroyCount()).isEqualTo(1);
then(id2).isNotSameAs(id1);
}
@Test
@DirtiesContext
public void testRefreshFails() throws Exception {
assertEquals("Hello scope!", this.service.getMessage());
then(this.service.getMessage()).isEqualTo("Hello scope!");
// Change the dynamic property source...
TestPropertyValues.of("message:Foo", "delay:foo").applyTo(this.environment);
// ...and then refresh, so the bean is re-initialized:
@@ -113,7 +111,7 @@ public class MoreRefreshScopeIntegrationTests {
try {
// If a refresh fails (e.g. a binding error in this case) the application is
// basically hosed.
assertEquals("Hello scope!", this.service.getMessage());
then(this.service.getMessage()).isEqualTo("Hello scope!");
fail("expected BeanCreationException");
}
catch (BeanCreationException e) {
@@ -122,7 +120,7 @@ public class MoreRefreshScopeIntegrationTests {
TestPropertyValues.of("delay:0").applyTo(this.environment);
// ...and then refresh, so the bean is re-initialized:
this.scope.refreshAll();
assertEquals("Foo", this.service.getMessage());
then(this.service.getMessage()).isEqualTo("Foo");
}
public static class TestService implements InitializingBean, DisposableBean {

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.context.scope.refresh;
import java.net.URI;
@@ -42,7 +43,7 @@ import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.BDDAssertions.then;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/**
@@ -50,7 +51,8 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
*
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ClientApp.class, properties = "management.endpoints.web.exposure.include=*", webEnvironment = RANDOM_PORT)
@SpringBootTest(classes = ClientApp.class, properties = {
"management.endpoints.web.exposure.include=*" }, webEnvironment = RANDOM_PORT)
public class RefreshEndpointIntegrationTests {
private static final String BASE_PATH = new WebEndpointProperties().getBasePath();
@@ -69,7 +71,7 @@ public class RefreshEndpointIntegrationTests {
null, String.class);
String message = template.getForObject("http://localhost:" + this.port + "/",
String.class);
assertEquals("Hello Dave!", message);
then(message).isEqualTo("Hello Dave!");
}
private RequestEntity<?> getUrlEncodedEntity(String uri, String key, String value)

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.context.scope.refresh;
import java.util.concurrent.Callable;
@@ -46,9 +47,7 @@ import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.Repeat;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.BDDAssertions.then;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestConfiguration.class)
@@ -72,7 +71,7 @@ public class RefreshScopeConcurrencyTests {
@DirtiesContext
public void testConcurrentRefresh() throws Exception {
assertEquals("Hello scope!", this.service.getMessage());
then(this.service.getMessage()).isEqualTo("Hello scope!");
this.properties.setMessage("Foo");
this.properties.setDelay(500);
final CountDownLatch latch = new CountDownLatch(1);
@@ -89,19 +88,19 @@ public class RefreshScopeConcurrencyTests {
}
}
});
assertTrue(latch.await(1500, TimeUnit.MILLISECONDS));
then(latch.await(15000, TimeUnit.MILLISECONDS)).isTrue();
logger.info("Refreshing");
this.scope.refreshAll();
assertEquals("Foo", this.service.getMessage());
then(this.service.getMessage()).isEqualTo("Foo");
/*
* This is the most important assertion: we don't want a null value because that
* means the bean was destroyed and not re-initialized before we accessed it.
*/
assertNotNull(result.get());
assertEquals("Hello scope!", result.get());
then(result.get()).isNotNull();
then(result.get()).isEqualTo("Hello scope!");
}
public static interface Service {
public interface Service {
String getMessage();

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.context.scope.refresh;
import java.util.ArrayList;
@@ -49,11 +50,11 @@ import org.springframework.test.annotation.Repeat;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.ObjectUtils;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.BDDAssertions.then;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestConfiguration.class, properties = "logging.level.org.springframework.cloud.context.scope.refresh.RefreshScopeConfigurationScaleTests=DEBUG")
@SpringBootTest(classes = TestConfiguration.class, properties = {
"logging.level.org.springframework.cloud.context.scope.refresh.RefreshScopeConfigurationScaleTests=DEBUG" })
public class RefreshScopeConfigurationScaleTests {
private static Log logger = LogFactory
@@ -106,14 +107,14 @@ public class RefreshScopeConfigurationScaleTests {
}
});
}
assertTrue(latch.await(15000, TimeUnit.MILLISECONDS));
assertEquals("Foo", this.service.getMessage());
then(latch.await(15000, TimeUnit.MILLISECONDS)).isTrue();
then(this.service.getMessage()).isEqualTo("Foo");
for (Future<String> result : results) {
assertEquals("Foo", result.get());
then(result.get()).isEqualTo("Foo");
}
}
public static interface Service {
public interface Service {
String getMessage();

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.context.scope.refresh;
import org.junit.After;
@@ -34,7 +35,7 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.BDDAssertions.then;
/**
* @author Dave Syer
@@ -74,12 +75,12 @@ public class RefreshScopeConfigurationTests {
RefreshAutoConfiguration.class,
LifecycleMvcEndpointAutoConfiguration.class);
Application application = this.context.getBean(Application.class);
assertEquals("refresh",
this.context.getBeanDefinition("scopedTarget.application").getScope());
then(this.context.getBeanDefinition("scopedTarget.application").getScope())
.isEqualTo("refresh");
application.hello();
refresh();
String message = application.hello();
assertEquals("Hello Dave!", message);
then(message).isEqualTo("Hello Dave!");
}
@Test
@@ -92,7 +93,7 @@ public class RefreshScopeConfigurationTests {
application.hello();
refresh();
String message = application.hello();
assertEquals("Hello Dave!", message);
then(message).isEqualTo("Hello Dave!");
}
@Test
@@ -105,7 +106,7 @@ public class RefreshScopeConfigurationTests {
application.hello();
refresh();
String message = application.hello();
assertEquals("Hello Dave!", message);
then(message).isEqualTo("Hello Dave!");
}
// WTF? Maven can't compile without the FQN on this one (not the others).

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.context.scope.refresh;
import org.apache.commons.logging.Log;
@@ -41,10 +42,7 @@ import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.BDDAssertions.then;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestConfiguration.class)
@@ -61,7 +59,7 @@ public class RefreshScopeIntegrationTests {
@Before
public void init() {
assertEquals(1, ExampleService.getInitCount());
then(ExampleService.getInitCount()).isEqualTo(1);
ExampleService.reset();
}
@@ -73,53 +71,53 @@ public class RefreshScopeIntegrationTests {
@Test
@DirtiesContext
public void testSimpleProperties() throws Exception {
assertEquals("Hello scope!", this.service.getMessage());
assertTrue(this.service instanceof Advised);
then(this.service.getMessage()).isEqualTo("Hello scope!");
then(this.service instanceof Advised).isTrue();
// Change the dynamic property source...
this.properties.setMessage("Foo");
// ...but don't refresh, so the bean stays the same:
assertEquals("Hello scope!", this.service.getMessage());
assertEquals(0, ExampleService.getInitCount());
assertEquals(0, ExampleService.getDestroyCount());
then(this.service.getMessage()).isEqualTo("Hello scope!");
then(ExampleService.getInitCount()).isEqualTo(0);
then(ExampleService.getDestroyCount()).isEqualTo(0);
}
@Test
@DirtiesContext
public void testRefresh() throws Exception {
assertEquals("Hello scope!", this.service.getMessage());
then(this.service.getMessage()).isEqualTo("Hello scope!");
String id1 = this.service.toString();
// Change the dynamic property source...
this.properties.setMessage("Foo");
// ...and then refresh, so the bean is re-initialized:
this.scope.refreshAll();
String id2 = this.service.toString();
assertEquals("Foo", this.service.getMessage());
assertEquals(1, ExampleService.getInitCount());
assertEquals(1, ExampleService.getDestroyCount());
assertNotSame(id1, id2);
assertNotNull(ExampleService.event);
assertEquals(RefreshScopeRefreshedEvent.DEFAULT_NAME,
ExampleService.event.getName());
then(this.service.getMessage()).isEqualTo("Foo");
then(ExampleService.getInitCount()).isEqualTo(1);
then(ExampleService.getDestroyCount()).isEqualTo(1);
then(id2).isNotSameAs(id1);
then(ExampleService.event).isNotNull();
then(ExampleService.event.getName())
.isEqualTo(RefreshScopeRefreshedEvent.DEFAULT_NAME);
}
@Test
@DirtiesContext
public void testRefreshBean() throws Exception {
assertEquals("Hello scope!", this.service.getMessage());
then(this.service.getMessage()).isEqualTo("Hello scope!");
String id1 = this.service.toString();
// Change the dynamic property source...
this.properties.setMessage("Foo");
// ...and then refresh, so the bean is re-initialized:
this.scope.refresh("service");
String id2 = this.service.toString();
assertEquals("Foo", this.service.getMessage());
assertEquals("Foo", this.service.getMessage());
assertEquals(1, ExampleService.getInitCount());
assertEquals(1, ExampleService.getDestroyCount());
assertNotSame(id1, id2);
assertNotNull(ExampleService.event);
assertEquals(GenericScope.SCOPED_TARGET_PREFIX + "service",
ExampleService.event.getName());
then(this.service.getMessage()).isEqualTo("Foo");
then(this.service.getMessage()).isEqualTo("Foo");
then(ExampleService.getInitCount()).isEqualTo(1);
then(ExampleService.getDestroyCount()).isEqualTo(1);
then(id2).isNotSameAs(id1);
then(ExampleService.event).isNotNull();
then(ExampleService.event.getName())
.isEqualTo(GenericScope.SCOPED_TARGET_PREFIX + "service");
}
// see gh-349

View File

@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.context.scope.refresh;
import org.apache.commons.logging.Log;
@@ -43,10 +44,7 @@ import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.BDDAssertions.then;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestConfiguration.class)
@@ -64,7 +62,7 @@ public class RefreshScopeLazyIntegrationTests {
@Before
public void init() {
// The RefreshScope is lazy (eager=false) so it won't have been instantiated yet
assertEquals(0, ExampleService.getInitCount());
then(ExampleService.getInitCount()).isEqualTo(0);
ExampleService.reset();
}
@@ -76,55 +74,55 @@ public class RefreshScopeLazyIntegrationTests {
@Test
@DirtiesContext
public void testSimpleProperties() throws Exception {
assertEquals("Hello scope!", this.service.getMessage());
assertTrue(this.service instanceof Advised);
then(this.service.getMessage()).isEqualTo("Hello scope!");
then(this.service instanceof Advised).isTrue();
// Change the dynamic property source...
this.properties.setMessage("Foo");
// ...but don't refresh, so the bean stays the same:
assertEquals("Hello scope!", this.service.getMessage());
assertEquals(1, ExampleService.getInitCount());
assertEquals(0, ExampleService.getDestroyCount());
then(this.service.getMessage()).isEqualTo("Hello scope!");
then(ExampleService.getInitCount()).isEqualTo(1);
then(ExampleService.getDestroyCount()).isEqualTo(0);
}
@Test
@DirtiesContext
public void testRefresh() throws Exception {
assertEquals("Hello scope!", this.service.getMessage());
then(this.service.getMessage()).isEqualTo("Hello scope!");
String id1 = this.service.toString();
// Change the dynamic property source...
this.properties.setMessage("Foo");
// ...and then refresh, so the bean is re-initialized:
this.scope.refreshAll();
String id2 = this.service.toString();
assertEquals("Foo", this.service.getMessage());
assertEquals(2, ExampleService.getInitCount());
assertEquals(1, ExampleService.getDestroyCount());
assertNotSame(id1, id2);
assertNotNull(ExampleService.event);
assertEquals(RefreshScopeRefreshedEvent.DEFAULT_NAME,
ExampleService.event.getName());
then(this.service.getMessage()).isEqualTo("Foo");
then(ExampleService.getInitCount()).isEqualTo(2);
then(ExampleService.getDestroyCount()).isEqualTo(1);
then(id2).isNotSameAs(id1);
then(ExampleService.event).isNotNull();
then(ExampleService.event.getName())
.isEqualTo(RefreshScopeRefreshedEvent.DEFAULT_NAME);
}
@Test
@DirtiesContext
public void testRefreshBean() throws Exception {
assertEquals("Hello scope!", this.service.getMessage());
then(this.service.getMessage()).isEqualTo("Hello scope!");
String id1 = this.service.toString();
// Change the dynamic property source...
this.properties.setMessage("Foo");
// ...and then refresh, so the bean is re-initialized:
this.scope.refresh("service");
String id2 = this.service.toString();
assertEquals("Foo", this.service.getMessage());
assertEquals(2, ExampleService.getInitCount());
assertEquals(1, ExampleService.getDestroyCount());
assertNotSame(id1, id2);
assertNotNull(ExampleService.event);
assertEquals(GenericScope.SCOPED_TARGET_PREFIX + "service",
ExampleService.event.getName());
then(this.service.getMessage()).isEqualTo("Foo");
then(ExampleService.getInitCount()).isEqualTo(2);
then(ExampleService.getDestroyCount()).isEqualTo(1);
then(id2).isNotSameAs(id1);
then(ExampleService.event).isNotNull();
then(ExampleService.event.getName())
.isEqualTo(GenericScope.SCOPED_TARGET_PREFIX + "service");
}
public static interface Service {
public interface Service {
String getMessage();
@@ -212,7 +210,8 @@ public class RefreshScopeLazyIntegrationTests {
@Bean
public static org.springframework.cloud.context.scope.refresh.RefreshScope refreshScope() {
org.springframework.cloud.context.scope.refresh.RefreshScope scope = new org.springframework.cloud.context.scope.refresh.RefreshScope();
org.springframework.cloud.context.scope.refresh.RefreshScope scope = null;
scope = new org.springframework.cloud.context.scope.refresh.RefreshScope();
scope.setEager(false);
return scope;
}

View File

@@ -42,8 +42,7 @@ import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.BDDAssertions.then;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestConfiguration.class, properties = { "test.messages[0]=one",
@@ -62,23 +61,23 @@ public class RefreshScopeListBindingIntegrationTests {
@Test
@DirtiesContext
public void testAppendProperties() throws Exception {
assertEquals("[one, two]", this.properties.getMessages().toString());
assertTrue(this.properties instanceof Advised);
then("[one, two]").isEqualTo(this.properties.getMessages().toString());
then(this.properties instanceof Advised).isTrue();
TestPropertyValues.of("test.messages[0]:foo").applyTo(this.environment);
this.scope.refreshAll();
assertEquals("[foo]", this.properties.getMessages().toString());
then(this.properties.getMessages().toString()).isEqualTo("[foo]");
}
@Test
@DirtiesContext
public void testReplaceProperties() throws Exception {
assertEquals("[one, two]", this.properties.getMessages().toString());
assertTrue(this.properties instanceof Advised);
then("[one, two]").isEqualTo(this.properties.getMessages().toString());
then(this.properties instanceof Advised).isTrue();
Map<String, Object> map = findTestProperties();
map.clear();
TestPropertyValues.of("test.messages[0]:foo").applyTo(this.environment);
this.scope.refreshAll();
assertEquals("[foo]", this.properties.getMessages().toString());
then(this.properties.getMessages().toString()).isEqualTo("[foo]");
}
private Map<String, Object> findTestProperties() {

Some files were not shown because too many files have changed in this diff Show More