Move tests to JUnit 5 wherever possible

This commit is contained in:
Andy Wilkinson 2019-05-24 11:24:29 +01:00
parent 36f56d034a
commit b18fffaf14
1320 changed files with 13424 additions and 14185 deletions

View File

@ -41,7 +41,7 @@ import org.springframework.context.ConfigurableApplicationContext;
* *
* @author Dave Syer * @author Dave Syer
*/ */
public class SpringApplicationHierarchyTests { class SpringApplicationHierarchyTests {
private ConfigurableApplicationContext context; private ConfigurableApplicationContext context;
@ -51,14 +51,14 @@ public class SpringApplicationHierarchyTests {
} }
@Test @Test
public void testParent() { void testParent() {
SpringApplicationBuilder builder = new SpringApplicationBuilder(Child.class); SpringApplicationBuilder builder = new SpringApplicationBuilder(Child.class);
builder.parent(Parent.class); builder.parent(Parent.class);
this.context = builder.run("--server.port=0", "--management.metrics.use-global-registry=false"); this.context = builder.run("--server.port=0", "--management.metrics.use-global-registry=false");
} }
@Test @Test
public void testChild() { void testChild() {
SpringApplicationBuilder builder = new SpringApplicationBuilder(Parent.class); SpringApplicationBuilder builder = new SpringApplicationBuilder(Parent.class);
builder.child(Child.class); builder.child(Child.class);
this.context = builder.run("--server.port=0", "--management.metrics.use-global-registry=false"); this.context = builder.run("--server.port=0", "--management.metrics.use-global-registry=false");

View File

@ -32,20 +32,20 @@ import static org.assertj.core.api.Assertions.assertThat;
* *
* @author Phillip Webb * @author Phillip Webb
*/ */
public class RabbitHealthIndicatorAutoConfigurationTests { class RabbitHealthIndicatorAutoConfigurationTests {
private ApplicationContextRunner contextRunner = new ApplicationContextRunner() private ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(RabbitAutoConfiguration.class, .withConfiguration(AutoConfigurations.of(RabbitAutoConfiguration.class,
RabbitHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class)); RabbitHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class));
@Test @Test
public void runShouldCreateIndicator() { void runShouldCreateIndicator() {
this.contextRunner.run((context) -> assertThat(context).hasSingleBean(RabbitHealthIndicator.class) this.contextRunner.run((context) -> assertThat(context).hasSingleBean(RabbitHealthIndicator.class)
.doesNotHaveBean(ApplicationHealthIndicator.class)); .doesNotHaveBean(ApplicationHealthIndicator.class));
} }
@Test @Test
public void runWhenDisabledShouldNotCreateIndicator() { void runWhenDisabledShouldNotCreateIndicator() {
this.contextRunner.withPropertyValues("management.health.rabbit.enabled:false") this.contextRunner.withPropertyValues("management.health.rabbit.enabled:false")
.run((context) -> assertThat(context).doesNotHaveBean(RabbitHealthIndicator.class) .run((context) -> assertThat(context).doesNotHaveBean(RabbitHealthIndicator.class)
.hasSingleBean(ApplicationHealthIndicator.class)); .hasSingleBean(ApplicationHealthIndicator.class));

View File

@ -44,18 +44,18 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Vedran Pavic * @author Vedran Pavic
* @author Madhura Bhave * @author Madhura Bhave
*/ */
public class AuditAutoConfigurationTests { class AuditAutoConfigurationTests {
private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(AuditAutoConfiguration.class)); .withConfiguration(AutoConfigurations.of(AuditAutoConfiguration.class));
@Test @Test
public void autoConfigurationIsDisabledByDefault() { void autoConfigurationIsDisabledByDefault() {
this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(AuditAutoConfiguration.class)); this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(AuditAutoConfiguration.class));
} }
@Test @Test
public void autoConfigurationIsEnabledWhenAuditEventRepositoryBeanPresent() { void autoConfigurationIsEnabledWhenAuditEventRepositoryBeanPresent() {
this.contextRunner.withUserConfiguration(CustomAuditEventRepositoryConfiguration.class).run((context) -> { this.contextRunner.withUserConfiguration(CustomAuditEventRepositoryConfiguration.class).run((context) -> {
assertThat(context.getBean(AuditEventRepository.class)).isNotNull(); assertThat(context.getBean(AuditEventRepository.class)).isNotNull();
assertThat(context.getBean(AuthenticationAuditListener.class)).isNotNull(); assertThat(context.getBean(AuthenticationAuditListener.class)).isNotNull();
@ -64,7 +64,7 @@ public class AuditAutoConfigurationTests {
} }
@Test @Test
public void ownAuthenticationAuditListener() { void ownAuthenticationAuditListener() {
this.contextRunner.withUserConfiguration(CustomAuditEventRepositoryConfiguration.class) this.contextRunner.withUserConfiguration(CustomAuditEventRepositoryConfiguration.class)
.withUserConfiguration(CustomAuthenticationAuditListenerConfiguration.class) .withUserConfiguration(CustomAuthenticationAuditListenerConfiguration.class)
.run((context) -> assertThat(context.getBean(AbstractAuthenticationAuditListener.class)) .run((context) -> assertThat(context.getBean(AbstractAuthenticationAuditListener.class))
@ -72,7 +72,7 @@ public class AuditAutoConfigurationTests {
} }
@Test @Test
public void ownAuthorizationAuditListener() { void ownAuthorizationAuditListener() {
this.contextRunner.withUserConfiguration(CustomAuditEventRepositoryConfiguration.class) this.contextRunner.withUserConfiguration(CustomAuditEventRepositoryConfiguration.class)
.withUserConfiguration(CustomAuthorizationAuditListenerConfiguration.class) .withUserConfiguration(CustomAuthorizationAuditListenerConfiguration.class)
.run((context) -> assertThat(context.getBean(AbstractAuthorizationAuditListener.class)) .run((context) -> assertThat(context.getBean(AbstractAuthorizationAuditListener.class))
@ -80,7 +80,7 @@ public class AuditAutoConfigurationTests {
} }
@Test @Test
public void ownAuditListener() { void ownAuditListener() {
this.contextRunner.withUserConfiguration(CustomAuditEventRepositoryConfiguration.class) this.contextRunner.withUserConfiguration(CustomAuditEventRepositoryConfiguration.class)
.withUserConfiguration(CustomAuditListenerConfiguration.class) .withUserConfiguration(CustomAuditListenerConfiguration.class)
.run((context) -> assertThat(context.getBean(AbstractAuditListener.class)) .run((context) -> assertThat(context.getBean(AbstractAuditListener.class))
@ -88,7 +88,7 @@ public class AuditAutoConfigurationTests {
} }
@Test @Test
public void backsOffWhenDisabled() { void backsOffWhenDisabled() {
this.contextRunner.withUserConfiguration(CustomAuditEventRepositoryConfiguration.class) this.contextRunner.withUserConfiguration(CustomAuditEventRepositoryConfiguration.class)
.withPropertyValues("management.auditevents.enabled=false") .withPropertyValues("management.auditevents.enabled=false")
.run((context) -> assertThat(context).doesNotHaveBean(AuditListener.class) .run((context) -> assertThat(context).doesNotHaveBean(AuditListener.class)

View File

@ -34,31 +34,31 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Phillip Webb * @author Phillip Webb
* @author Vedran Pavic * @author Vedran Pavic
*/ */
public class AuditEventsEndpointAutoConfigurationTests { class AuditEventsEndpointAutoConfigurationTests {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration( private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration(
AutoConfigurations.of(AuditAutoConfiguration.class, AuditEventsEndpointAutoConfiguration.class)); AutoConfigurations.of(AuditAutoConfiguration.class, AuditEventsEndpointAutoConfiguration.class));
@Test @Test
public void runWhenRepositoryBeanAvailableShouldHaveEndpointBean() { void runWhenRepositoryBeanAvailableShouldHaveEndpointBean() {
this.contextRunner.withUserConfiguration(CustomAuditEventRepositoryConfiguration.class) this.contextRunner.withUserConfiguration(CustomAuditEventRepositoryConfiguration.class)
.withPropertyValues("management.endpoints.web.exposure.include=auditevents") .withPropertyValues("management.endpoints.web.exposure.include=auditevents")
.run((context) -> assertThat(context).hasSingleBean(AuditEventsEndpoint.class)); .run((context) -> assertThat(context).hasSingleBean(AuditEventsEndpoint.class));
} }
@Test @Test
public void endpointBacksOffWhenRepositoryNotAvailable() { void endpointBacksOffWhenRepositoryNotAvailable() {
this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=auditevents") this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=auditevents")
.run((context) -> assertThat(context).doesNotHaveBean(AuditEventsEndpoint.class)); .run((context) -> assertThat(context).doesNotHaveBean(AuditEventsEndpoint.class));
} }
@Test @Test
public void runWhenNotExposedShouldNotHaveEndpointBean() { void runWhenNotExposedShouldNotHaveEndpointBean() {
this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(AuditEventsEndpoint.class)); this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(AuditEventsEndpoint.class));
} }
@Test @Test
public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpoint() { void runWhenEnabledPropertyIsFalseShouldNotHaveEndpoint() {
this.contextRunner.withUserConfiguration(CustomAuditEventRepositoryConfiguration.class) this.contextRunner.withUserConfiguration(CustomAuditEventRepositoryConfiguration.class)
.withPropertyValues("management.endpoint.auditevents.enabled:false") .withPropertyValues("management.endpoint.auditevents.enabled:false")
.withPropertyValues("management.endpoints.web.exposure.include=*") .withPropertyValues("management.endpoints.web.exposure.include=*")

View File

@ -29,24 +29,24 @@ import static org.assertj.core.api.Assertions.assertThat;
* *
* @author Phillip Webb * @author Phillip Webb
*/ */
public class BeansEndpointAutoConfigurationTests { class BeansEndpointAutoConfigurationTests {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(BeansEndpointAutoConfiguration.class)); .withConfiguration(AutoConfigurations.of(BeansEndpointAutoConfiguration.class));
@Test @Test
public void runShouldHaveEndpointBean() { void runShouldHaveEndpointBean() {
this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=beans") this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=beans")
.run((context) -> assertThat(context).hasSingleBean(BeansEndpoint.class)); .run((context) -> assertThat(context).hasSingleBean(BeansEndpoint.class));
} }
@Test @Test
public void runWhenNotExposedShouldNotHaveEndpointBean() { void runWhenNotExposedShouldNotHaveEndpointBean() {
this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(BeansEndpoint.class)); this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(BeansEndpoint.class));
} }
@Test @Test
public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() {
this.contextRunner.withPropertyValues("management.endpoint.beans.enabled:false") this.contextRunner.withPropertyValues("management.endpoint.beans.enabled:false")
.withPropertyValues("management.endpoints.web.exposure.include=*") .withPropertyValues("management.endpoints.web.exposure.include=*")
.run((context) -> assertThat(context).doesNotHaveBean(BeansEndpoint.class)); .run((context) -> assertThat(context).doesNotHaveBean(BeansEndpoint.class));

View File

@ -32,32 +32,32 @@ import static org.mockito.Mockito.mock;
* @author Johannes Edmeier * @author Johannes Edmeier
* @author Stephane Nicoll * @author Stephane Nicoll
*/ */
public class CachesEndpointAutoConfigurationTests { class CachesEndpointAutoConfigurationTests {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(CachesEndpointAutoConfiguration.class)); .withConfiguration(AutoConfigurations.of(CachesEndpointAutoConfiguration.class));
@Test @Test
public void runShouldHaveEndpointBean() { void runShouldHaveEndpointBean() {
this.contextRunner.withBean(CacheManager.class, () -> mock(CacheManager.class)) this.contextRunner.withBean(CacheManager.class, () -> mock(CacheManager.class))
.withPropertyValues("management.endpoints.web.exposure.include=caches") .withPropertyValues("management.endpoints.web.exposure.include=caches")
.run((context) -> assertThat(context).hasSingleBean(CachesEndpoint.class)); .run((context) -> assertThat(context).hasSingleBean(CachesEndpoint.class));
} }
@Test @Test
public void runWithoutCacheManagerShouldHaveEndpointBean() { void runWithoutCacheManagerShouldHaveEndpointBean() {
this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=caches") this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=caches")
.run((context) -> assertThat(context).hasSingleBean(CachesEndpoint.class)); .run((context) -> assertThat(context).hasSingleBean(CachesEndpoint.class));
} }
@Test @Test
public void runWhenNotExposedShouldNotHaveEndpointBean() { void runWhenNotExposedShouldNotHaveEndpointBean() {
this.contextRunner.withBean(CacheManager.class, () -> mock(CacheManager.class)) this.contextRunner.withBean(CacheManager.class, () -> mock(CacheManager.class))
.run((context) -> assertThat(context).doesNotHaveBean(CachesEndpoint.class)); .run((context) -> assertThat(context).doesNotHaveBean(CachesEndpoint.class));
} }
@Test @Test
public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() {
this.contextRunner.withPropertyValues("management.endpoint.caches.enabled:false") this.contextRunner.withPropertyValues("management.endpoint.caches.enabled:false")
.withPropertyValues("management.endpoints.web.exposure.include=*") .withPropertyValues("management.endpoints.web.exposure.include=*")
.withBean(CacheManager.class, () -> mock(CacheManager.class)) .withBean(CacheManager.class, () -> mock(CacheManager.class))

View File

@ -36,20 +36,20 @@ import static org.mockito.Mockito.mock;
* *
* @author Phillip Webb * @author Phillip Webb
*/ */
public class CassandraHealthIndicatorAutoConfigurationTests { class CassandraHealthIndicatorAutoConfigurationTests {
private ApplicationContextRunner contextRunner = new ApplicationContextRunner() private ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(CassandraConfiguration.class, .withConfiguration(AutoConfigurations.of(CassandraConfiguration.class,
CassandraHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class)); CassandraHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class));
@Test @Test
public void runShouldCreateIndicator() { void runShouldCreateIndicator() {
this.contextRunner.run((context) -> assertThat(context).hasSingleBean(CassandraHealthIndicator.class) this.contextRunner.run((context) -> assertThat(context).hasSingleBean(CassandraHealthIndicator.class)
.doesNotHaveBean(ApplicationHealthIndicator.class)); .doesNotHaveBean(ApplicationHealthIndicator.class));
} }
@Test @Test
public void runWhenDisabledShouldNotCreateIndicator() { void runWhenDisabledShouldNotCreateIndicator() {
this.contextRunner.withPropertyValues("management.health.cassandra.enabled:false") this.contextRunner.withPropertyValues("management.health.cassandra.enabled:false")
.run((context) -> assertThat(context).doesNotHaveBean(CassandraHealthIndicator.class) .run((context) -> assertThat(context).doesNotHaveBean(CassandraHealthIndicator.class)
.hasSingleBean(ApplicationHealthIndicator.class)); .hasSingleBean(ApplicationHealthIndicator.class));

View File

@ -35,7 +35,7 @@ import static org.mockito.Mockito.mock;
* @author Artsiom Yudovin * @author Artsiom Yudovin
* @author Stephane Nicoll * @author Stephane Nicoll
*/ */
public class CassandraReactiveHealthIndicatorAutoConfigurationTests { class CassandraReactiveHealthIndicatorAutoConfigurationTests {
private ApplicationContextRunner contextRunner = new ApplicationContextRunner() private ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withBean(ReactiveCassandraOperations.class, () -> mock(ReactiveCassandraOperations.class)) .withBean(ReactiveCassandraOperations.class, () -> mock(ReactiveCassandraOperations.class))
@ -43,13 +43,13 @@ public class CassandraReactiveHealthIndicatorAutoConfigurationTests {
HealthIndicatorAutoConfiguration.class)); HealthIndicatorAutoConfiguration.class));
@Test @Test
public void runShouldCreateIndicator() { void runShouldCreateIndicator() {
this.contextRunner.run((context) -> assertThat(context).hasSingleBean(CassandraReactiveHealthIndicator.class) this.contextRunner.run((context) -> assertThat(context).hasSingleBean(CassandraReactiveHealthIndicator.class)
.doesNotHaveBean(CassandraHealthIndicator.class).doesNotHaveBean(ApplicationHealthIndicator.class)); .doesNotHaveBean(CassandraHealthIndicator.class).doesNotHaveBean(ApplicationHealthIndicator.class));
} }
@Test @Test
public void runWhenDisabledShouldNotCreateIndicator() { void runWhenDisabledShouldNotCreateIndicator() {
this.contextRunner.withPropertyValues("management.health.cassandra.enabled:false") this.contextRunner.withPropertyValues("management.health.cassandra.enabled:false")
.run((context) -> assertThat(context).doesNotHaveBean(CassandraReactiveHealthIndicator.class) .run((context) -> assertThat(context).doesNotHaveBean(CassandraReactiveHealthIndicator.class)
.hasSingleBean(ApplicationHealthIndicator.class)); .hasSingleBean(ApplicationHealthIndicator.class));

View File

@ -25,28 +25,28 @@ import static org.assertj.core.api.Assertions.assertThat;
* *
* @author Madhura Bhave * @author Madhura Bhave
*/ */
public class AccessLevelTests { class AccessLevelTests {
@Test @Test
public void accessToHealthEndpointShouldNotBeRestricted() { void accessToHealthEndpointShouldNotBeRestricted() {
assertThat(AccessLevel.RESTRICTED.isAccessAllowed("health")).isTrue(); assertThat(AccessLevel.RESTRICTED.isAccessAllowed("health")).isTrue();
assertThat(AccessLevel.FULL.isAccessAllowed("health")).isTrue(); assertThat(AccessLevel.FULL.isAccessAllowed("health")).isTrue();
} }
@Test @Test
public void accessToInfoEndpointShouldNotBeRestricted() { void accessToInfoEndpointShouldNotBeRestricted() {
assertThat(AccessLevel.RESTRICTED.isAccessAllowed("info")).isTrue(); assertThat(AccessLevel.RESTRICTED.isAccessAllowed("info")).isTrue();
assertThat(AccessLevel.FULL.isAccessAllowed("info")).isTrue(); assertThat(AccessLevel.FULL.isAccessAllowed("info")).isTrue();
} }
@Test @Test
public void accessToDiscoveryEndpointShouldNotBeRestricted() { void accessToDiscoveryEndpointShouldNotBeRestricted() {
assertThat(AccessLevel.RESTRICTED.isAccessAllowed("")).isTrue(); assertThat(AccessLevel.RESTRICTED.isAccessAllowed("")).isTrue();
assertThat(AccessLevel.FULL.isAccessAllowed("")).isTrue(); assertThat(AccessLevel.FULL.isAccessAllowed("")).isTrue();
} }
@Test @Test
public void accessToAnyOtherEndpointShouldBeRestricted() { void accessToAnyOtherEndpointShouldBeRestricted() {
assertThat(AccessLevel.RESTRICTED.isAccessAllowed("env")).isFalse(); assertThat(AccessLevel.RESTRICTED.isAccessAllowed("env")).isFalse();
assertThat(AccessLevel.FULL.isAccessAllowed("")).isTrue(); assertThat(AccessLevel.FULL.isAccessAllowed("")).isTrue();
} }

View File

@ -28,51 +28,51 @@ import static org.assertj.core.api.Assertions.assertThat;
* *
* @author Madhura Bhave * @author Madhura Bhave
*/ */
public class CloudFoundryAuthorizationExceptionTests { class CloudFoundryAuthorizationExceptionTests {
@Test @Test
public void statusCodeForInvalidTokenReasonShouldBe401() { void statusCodeForInvalidTokenReasonShouldBe401() {
assertThat(createException(Reason.INVALID_TOKEN).getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); assertThat(createException(Reason.INVALID_TOKEN).getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
} }
@Test @Test
public void statusCodeForInvalidIssuerReasonShouldBe401() { void statusCodeForInvalidIssuerReasonShouldBe401() {
assertThat(createException(Reason.INVALID_ISSUER).getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); assertThat(createException(Reason.INVALID_ISSUER).getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
} }
@Test @Test
public void statusCodeForInvalidAudienceReasonShouldBe401() { void statusCodeForInvalidAudienceReasonShouldBe401() {
assertThat(createException(Reason.INVALID_AUDIENCE).getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); assertThat(createException(Reason.INVALID_AUDIENCE).getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
} }
@Test @Test
public void statusCodeForInvalidSignatureReasonShouldBe401() { void statusCodeForInvalidSignatureReasonShouldBe401() {
assertThat(createException(Reason.INVALID_SIGNATURE).getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); assertThat(createException(Reason.INVALID_SIGNATURE).getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
} }
@Test @Test
public void statusCodeForMissingAuthorizationReasonShouldBe401() { void statusCodeForMissingAuthorizationReasonShouldBe401() {
assertThat(createException(Reason.MISSING_AUTHORIZATION).getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); assertThat(createException(Reason.MISSING_AUTHORIZATION).getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
} }
@Test @Test
public void statusCodeForUnsupportedSignatureAlgorithmReasonShouldBe401() { void statusCodeForUnsupportedSignatureAlgorithmReasonShouldBe401() {
assertThat(createException(Reason.UNSUPPORTED_TOKEN_SIGNING_ALGORITHM).getStatusCode()) assertThat(createException(Reason.UNSUPPORTED_TOKEN_SIGNING_ALGORITHM).getStatusCode())
.isEqualTo(HttpStatus.UNAUTHORIZED); .isEqualTo(HttpStatus.UNAUTHORIZED);
} }
@Test @Test
public void statusCodeForTokenExpiredReasonShouldBe401() { void statusCodeForTokenExpiredReasonShouldBe401() {
assertThat(createException(Reason.TOKEN_EXPIRED).getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); assertThat(createException(Reason.TOKEN_EXPIRED).getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
} }
@Test @Test
public void statusCodeForAccessDeniedReasonShouldBe403() { void statusCodeForAccessDeniedReasonShouldBe403() {
assertThat(createException(Reason.ACCESS_DENIED).getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); assertThat(createException(Reason.ACCESS_DENIED).getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
} }
@Test @Test
public void statusCodeForServiceUnavailableReasonShouldBe503() { void statusCodeForServiceUnavailableReasonShouldBe503() {
assertThat(createException(Reason.SERVICE_UNAVAILABLE).getStatusCode()) assertThat(createException(Reason.SERVICE_UNAVAILABLE).getStatusCode())
.isEqualTo(HttpStatus.SERVICE_UNAVAILABLE); .isEqualTo(HttpStatus.SERVICE_UNAVAILABLE);
} }

View File

@ -29,19 +29,19 @@ import static org.mockito.Mockito.mock;
* *
* @author Madhura Bhave * @author Madhura Bhave
*/ */
public class CloudFoundryEndpointFilterTests { class CloudFoundryEndpointFilterTests {
private CloudFoundryEndpointFilter filter = new CloudFoundryEndpointFilter(); private CloudFoundryEndpointFilter filter = new CloudFoundryEndpointFilter();
@Test @Test
public void matchIfDiscovererCloudFoundryShouldReturnFalse() { void matchIfDiscovererCloudFoundryShouldReturnFalse() {
DiscoveredEndpoint<?> endpoint = mock(DiscoveredEndpoint.class); DiscoveredEndpoint<?> endpoint = mock(DiscoveredEndpoint.class);
given(endpoint.wasDiscoveredBy(CloudFoundryWebEndpointDiscoverer.class)).willReturn(true); given(endpoint.wasDiscoveredBy(CloudFoundryWebEndpointDiscoverer.class)).willReturn(true);
assertThat(this.filter.match(endpoint)).isTrue(); assertThat(this.filter.match(endpoint)).isTrue();
} }
@Test @Test
public void matchIfDiscovererNotCloudFoundryShouldReturnFalse() { void matchIfDiscovererNotCloudFoundryShouldReturnFalse() {
DiscoveredEndpoint<?> endpoint = mock(DiscoveredEndpoint.class); DiscoveredEndpoint<?> endpoint = mock(DiscoveredEndpoint.class);
given(endpoint.wasDiscoveredBy(CloudFoundryWebEndpointDiscoverer.class)).willReturn(false); given(endpoint.wasDiscoveredBy(CloudFoundryWebEndpointDiscoverer.class)).willReturn(false);
assertThat(this.filter.match(endpoint)).isFalse(); assertThat(this.filter.match(endpoint)).isFalse();

View File

@ -50,10 +50,10 @@ import static org.mockito.Mockito.mock;
* *
* @author Madhura Bhave * @author Madhura Bhave
*/ */
public class CloudFoundryWebEndpointDiscovererTests { class CloudFoundryWebEndpointDiscovererTests {
@Test @Test
public void getEndpointsShouldAddCloudFoundryHealthExtension() { void getEndpointsShouldAddCloudFoundryHealthExtension() {
load(TestConfiguration.class, (discoverer) -> { load(TestConfiguration.class, (discoverer) -> {
Collection<ExposableWebEndpoint> endpoints = discoverer.getEndpoints(); Collection<ExposableWebEndpoint> endpoints = discoverer.getEndpoints();
assertThat(endpoints.size()).isEqualTo(2); assertThat(endpoints.size()).isEqualTo(2);

View File

@ -31,16 +31,16 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
* *
* @author Madhura Bhave * @author Madhura Bhave
*/ */
public class TokenTests { class TokenTests {
@Test @Test
public void invalidJwtShouldThrowException() { void invalidJwtShouldThrowException() {
assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy(() -> new Token("invalid-token")) assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy(() -> new Token("invalid-token"))
.satisfies(reasonRequirement(Reason.INVALID_TOKEN)); .satisfies(reasonRequirement(Reason.INVALID_TOKEN));
} }
@Test @Test
public void invalidJwtClaimsShouldThrowException() { void invalidJwtClaimsShouldThrowException() {
String header = "{\"alg\": \"RS256\", \"kid\": \"key-id\", \"typ\": \"JWT\"}"; String header = "{\"alg\": \"RS256\", \"kid\": \"key-id\", \"typ\": \"JWT\"}";
String claims = "invalid-claims"; String claims = "invalid-claims";
assertThatExceptionOfType(CloudFoundryAuthorizationException.class) assertThatExceptionOfType(CloudFoundryAuthorizationException.class)
@ -50,7 +50,7 @@ public class TokenTests {
} }
@Test @Test
public void invalidJwtHeaderShouldThrowException() { void invalidJwtHeaderShouldThrowException() {
String header = "invalid-header"; String header = "invalid-header";
String claims = "{\"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\"}"; String claims = "{\"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\"}";
assertThatExceptionOfType(CloudFoundryAuthorizationException.class) assertThatExceptionOfType(CloudFoundryAuthorizationException.class)
@ -60,7 +60,7 @@ public class TokenTests {
} }
@Test @Test
public void emptyJwtSignatureShouldThrowException() { void emptyJwtSignatureShouldThrowException() {
String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ0b3B0YWwu" String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ0b3B0YWwu"
+ "Y29tIiwiZXhwIjoxNDI2NDIwODAwLCJhd2Vzb21lIjp0cnVlfQ."; + "Y29tIiwiZXhwIjoxNDI2NDIwODAwLCJhd2Vzb21lIjp0cnVlfQ.";
assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy(() -> new Token(token)) assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy(() -> new Token(token))
@ -68,7 +68,7 @@ public class TokenTests {
} }
@Test @Test
public void validJwt() { void validJwt() {
String header = "{\"alg\": \"RS256\", \"kid\": \"key-id\", \"typ\": \"JWT\"}"; String header = "{\"alg\": \"RS256\", \"kid\": \"key-id\", \"typ\": \"JWT\"}";
String claims = "{\"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\"}"; String claims = "{\"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\"}";
String content = Base64Utils.encodeToString(header.getBytes()) + "." String content = Base64Utils.encodeToString(header.getBytes()) + "."
@ -84,7 +84,7 @@ public class TokenTests {
} }
@Test @Test
public void getSignatureAlgorithmWhenAlgIsNullShouldThrowException() { void getSignatureAlgorithmWhenAlgIsNullShouldThrowException() {
String header = "{\"kid\": \"key-id\", \"typ\": \"JWT\"}"; String header = "{\"kid\": \"key-id\", \"typ\": \"JWT\"}";
String claims = "{\"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\"}"; String claims = "{\"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\"}";
Token token = createToken(header, claims); Token token = createToken(header, claims);
@ -93,7 +93,7 @@ public class TokenTests {
} }
@Test @Test
public void getIssuerWhenIssIsNullShouldThrowException() { void getIssuerWhenIssIsNullShouldThrowException() {
String header = "{\"alg\": \"RS256\", \"kid\": \"key-id\", \"typ\": \"JWT\"}"; String header = "{\"alg\": \"RS256\", \"kid\": \"key-id\", \"typ\": \"JWT\"}";
String claims = "{\"exp\": 2147483647}"; String claims = "{\"exp\": 2147483647}";
Token token = createToken(header, claims); Token token = createToken(header, claims);
@ -102,7 +102,7 @@ public class TokenTests {
} }
@Test @Test
public void getKidWhenKidIsNullShouldThrowException() { void getKidWhenKidIsNullShouldThrowException() {
String header = "{\"alg\": \"RS256\", \"typ\": \"JWT\"}"; String header = "{\"alg\": \"RS256\", \"typ\": \"JWT\"}";
String claims = "{\"exp\": 2147483647}"; String claims = "{\"exp\": 2147483647}";
Token token = createToken(header, claims); Token token = createToken(header, claims);
@ -111,7 +111,7 @@ public class TokenTests {
} }
@Test @Test
public void getExpiryWhenExpIsNullShouldThrowException() { void getExpiryWhenExpIsNullShouldThrowException() {
String header = "{\"alg\": \"RS256\", \"kid\": \"key-id\", \"typ\": \"JWT\"}"; String header = "{\"alg\": \"RS256\", \"kid\": \"key-id\", \"typ\": \"JWT\"}";
String claims = "{\"iss\": \"http://localhost:8080/uaa/oauth/token\"" + "}"; String claims = "{\"iss\": \"http://localhost:8080/uaa/oauth/token\"" + "}";
Token token = createToken(header, claims); Token token = createToken(header, claims);

View File

@ -42,7 +42,7 @@ import static org.assertj.core.api.Assertions.assertThat;
* *
* @author Madhura Bhave * @author Madhura Bhave
*/ */
public class CloudFoundryReactiveHealthEndpointWebExtensionTests { class CloudFoundryReactiveHealthEndpointWebExtensionTests {
private ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() private ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner()
.withPropertyValues("VCAP_APPLICATION={}") .withPropertyValues("VCAP_APPLICATION={}")
@ -57,7 +57,7 @@ public class CloudFoundryReactiveHealthEndpointWebExtensionTests {
ReactiveCloudFoundryActuatorAutoConfiguration.class)); ReactiveCloudFoundryActuatorAutoConfiguration.class));
@Test @Test
public void healthDetailsAlwaysPresent() { void healthDetailsAlwaysPresent() {
this.contextRunner.run((context) -> { this.contextRunner.run((context) -> {
CloudFoundryReactiveHealthEndpointWebExtension extension = context CloudFoundryReactiveHealthEndpointWebExtension extension = context
.getBean(CloudFoundryReactiveHealthEndpointWebExtension.class); .getBean(CloudFoundryReactiveHealthEndpointWebExtension.class);

View File

@ -68,7 +68,7 @@ import static org.mockito.Mockito.mock;
* @author Madhura Bhave * @author Madhura Bhave
* @author Stephane Nicoll * @author Stephane Nicoll
*/ */
public class CloudFoundryWebFluxEndpointIntegrationTests { class CloudFoundryWebFluxEndpointIntegrationTests {
private static ReactiveTokenValidator tokenValidator = mock(ReactiveTokenValidator.class); private static ReactiveTokenValidator tokenValidator = mock(ReactiveTokenValidator.class);
@ -82,7 +82,7 @@ public class CloudFoundryWebFluxEndpointIntegrationTests {
.withUserConfiguration(TestEndpointConfiguration.class).withPropertyValues("server.port=0"); .withUserConfiguration(TestEndpointConfiguration.class).withPropertyValues("server.port=0");
@Test @Test
public void operationWithSecurityInterceptorForbidden() { void operationWithSecurityInterceptorForbidden() {
given(tokenValidator.validate(any())).willReturn(Mono.empty()); given(tokenValidator.validate(any())).willReturn(Mono.empty());
given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(Mono.just(AccessLevel.RESTRICTED)); given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(Mono.just(AccessLevel.RESTRICTED));
this.contextRunner.run(withWebTestClient((client) -> client.get().uri("/cfApplication/test") this.contextRunner.run(withWebTestClient((client) -> client.get().uri("/cfApplication/test")
@ -91,7 +91,7 @@ public class CloudFoundryWebFluxEndpointIntegrationTests {
} }
@Test @Test
public void operationWithSecurityInterceptorSuccess() { void operationWithSecurityInterceptorSuccess() {
given(tokenValidator.validate(any())).willReturn(Mono.empty()); given(tokenValidator.validate(any())).willReturn(Mono.empty());
given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(Mono.just(AccessLevel.FULL)); given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(Mono.just(AccessLevel.FULL));
this.contextRunner.run(withWebTestClient((client) -> client.get().uri("/cfApplication/test") this.contextRunner.run(withWebTestClient((client) -> client.get().uri("/cfApplication/test")
@ -100,7 +100,7 @@ public class CloudFoundryWebFluxEndpointIntegrationTests {
} }
@Test @Test
public void responseToOptionsRequestIncludesCorsHeaders() { void responseToOptionsRequestIncludesCorsHeaders() {
this.contextRunner.run(withWebTestClient((client) -> client.options().uri("/cfApplication/test") this.contextRunner.run(withWebTestClient((client) -> client.options().uri("/cfApplication/test")
.accept(MediaType.APPLICATION_JSON).header("Access-Control-Request-Method", "POST") .accept(MediaType.APPLICATION_JSON).header("Access-Control-Request-Method", "POST")
.header("Origin", "https://example.com").exchange().expectStatus().isOk().expectHeader() .header("Origin", "https://example.com").exchange().expectStatus().isOk().expectHeader()
@ -109,7 +109,7 @@ public class CloudFoundryWebFluxEndpointIntegrationTests {
} }
@Test @Test
public void linksToOtherEndpointsWithFullAccess() { void linksToOtherEndpointsWithFullAccess() {
given(tokenValidator.validate(any())).willReturn(Mono.empty()); given(tokenValidator.validate(any())).willReturn(Mono.empty());
given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(Mono.just(AccessLevel.FULL)); given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(Mono.just(AccessLevel.FULL));
this.contextRunner this.contextRunner
@ -124,7 +124,7 @@ public class CloudFoundryWebFluxEndpointIntegrationTests {
} }
@Test @Test
public void linksToOtherEndpointsForbidden() { void linksToOtherEndpointsForbidden() {
CloudFoundryAuthorizationException exception = new CloudFoundryAuthorizationException(Reason.INVALID_TOKEN, CloudFoundryAuthorizationException exception = new CloudFoundryAuthorizationException(Reason.INVALID_TOKEN,
"invalid-token"); "invalid-token");
willThrow(exception).given(tokenValidator).validate(any()); willThrow(exception).given(tokenValidator).validate(any());
@ -134,7 +134,7 @@ public class CloudFoundryWebFluxEndpointIntegrationTests {
} }
@Test @Test
public void linksToOtherEndpointsWithRestrictedAccess() { void linksToOtherEndpointsWithRestrictedAccess() {
given(tokenValidator.validate(any())).willReturn(Mono.empty()); given(tokenValidator.validate(any())).willReturn(Mono.empty());
given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(Mono.just(AccessLevel.RESTRICTED)); given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(Mono.just(AccessLevel.RESTRICTED));
this.contextRunner this.contextRunner

View File

@ -78,7 +78,7 @@ import static org.mockito.Mockito.mock;
* *
* @author Madhura Bhave * @author Madhura Bhave
*/ */
public class ReactiveCloudFoundryActuatorAutoConfigurationTests { class ReactiveCloudFoundryActuatorAutoConfigurationTests {
private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class, .withConfiguration(AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class,
@ -97,7 +97,7 @@ public class ReactiveCloudFoundryActuatorAutoConfigurationTests {
} }
@Test @Test
public void cloudFoundryPlatformActive() { void cloudFoundryPlatformActive() {
this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id",
"vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> {
CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context);
@ -115,7 +115,7 @@ public class ReactiveCloudFoundryActuatorAutoConfigurationTests {
} }
@Test @Test
public void cloudfoundryapplicationProducesActuatorMediaType() { void cloudfoundryapplicationProducesActuatorMediaType() {
this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id",
"vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> {
WebTestClient webTestClient = WebTestClient.bindToApplicationContext(context).build(); WebTestClient webTestClient = WebTestClient.bindToApplicationContext(context).build();
@ -125,7 +125,7 @@ public class ReactiveCloudFoundryActuatorAutoConfigurationTests {
} }
@Test @Test
public void cloudFoundryPlatformActiveSetsApplicationId() { void cloudFoundryPlatformActiveSetsApplicationId() {
this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id",
"vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> {
CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context);
@ -136,7 +136,7 @@ public class ReactiveCloudFoundryActuatorAutoConfigurationTests {
} }
@Test @Test
public void cloudFoundryPlatformActiveSetsCloudControllerUrl() { void cloudFoundryPlatformActiveSetsCloudControllerUrl() {
this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id",
"vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> {
CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context);
@ -150,7 +150,7 @@ public class ReactiveCloudFoundryActuatorAutoConfigurationTests {
} }
@Test @Test
public void cloudFoundryPlatformActiveAndCloudControllerUrlNotPresent() { void cloudFoundryPlatformActiveAndCloudControllerUrlNotPresent() {
this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id") this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id")
.run((context) -> { .run((context) -> {
CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = context.getBean( CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = context.getBean(
@ -165,7 +165,7 @@ public class ReactiveCloudFoundryActuatorAutoConfigurationTests {
@Test @Test
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void cloudFoundryPathsIgnoredBySpringSecurity() { void cloudFoundryPathsIgnoredBySpringSecurity() {
this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id",
"vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> {
WebFilterChainProxy chainProxy = context.getBean(WebFilterChainProxy.class); WebFilterChainProxy chainProxy = context.getBean(WebFilterChainProxy.class);
@ -189,19 +189,19 @@ public class ReactiveCloudFoundryActuatorAutoConfigurationTests {
} }
@Test @Test
public void cloudFoundryPlatformInactive() { void cloudFoundryPlatformInactive() {
this.contextRunner.run( this.contextRunner.run(
(context) -> assertThat(context.containsBean("cloudFoundryWebFluxEndpointHandlerMapping")).isFalse()); (context) -> assertThat(context.containsBean("cloudFoundryWebFluxEndpointHandlerMapping")).isFalse());
} }
@Test @Test
public void cloudFoundryManagementEndpointsDisabled() { void cloudFoundryManagementEndpointsDisabled() {
this.contextRunner.withPropertyValues("VCAP_APPLICATION=---", "management.cloudfoundry.enabled:false").run( this.contextRunner.withPropertyValues("VCAP_APPLICATION=---", "management.cloudfoundry.enabled:false").run(
(context) -> assertThat(context.containsBean("cloudFoundryWebFluxEndpointHandlerMapping")).isFalse()); (context) -> assertThat(context.containsBean("cloudFoundryWebFluxEndpointHandlerMapping")).isFalse());
} }
@Test @Test
public void allEndpointsAvailableUnderCloudFoundryWithoutEnablingWebIncludes() { void allEndpointsAvailableUnderCloudFoundryWithoutEnablingWebIncludes() {
this.contextRunner.withBean(TestEndpoint.class, TestEndpoint::new).withPropertyValues("VCAP_APPLICATION:---", this.contextRunner.withBean(TestEndpoint.class, TestEndpoint::new).withPropertyValues("VCAP_APPLICATION:---",
"vcap.application.application_id:my-app-id", "vcap.application.cf_api:https://my-cloud-controller.com") "vcap.application.application_id:my-app-id", "vcap.application.cf_api:https://my-cloud-controller.com")
.run((context) -> { .run((context) -> {
@ -214,7 +214,7 @@ public class ReactiveCloudFoundryActuatorAutoConfigurationTests {
} }
@Test @Test
public void endpointPathCustomizationIsNotApplied() { void endpointPathCustomizationIsNotApplied() {
this.contextRunner.withBean(TestEndpoint.class, TestEndpoint::new).withPropertyValues("VCAP_APPLICATION:---", this.contextRunner.withBean(TestEndpoint.class, TestEndpoint::new).withPropertyValues("VCAP_APPLICATION:---",
"vcap.application.application_id:my-app-id", "vcap.application.cf_api:https://my-cloud-controller.com") "vcap.application.application_id:my-app-id", "vcap.application.cf_api:https://my-cloud-controller.com")
.run((context) -> { .run((context) -> {
@ -230,7 +230,7 @@ public class ReactiveCloudFoundryActuatorAutoConfigurationTests {
} }
@Test @Test
public void healthEndpointInvokerShouldBeCloudFoundryWebExtension() { void healthEndpointInvokerShouldBeCloudFoundryWebExtension() {
this.contextRunner.withConfiguration(AutoConfigurations.of(HealthEndpointAutoConfiguration.class)) this.contextRunner.withConfiguration(AutoConfigurations.of(HealthEndpointAutoConfiguration.class))
.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id",
"vcap.application.cf_api:https://my-cloud-controller.com") "vcap.application.cf_api:https://my-cloud-controller.com")
@ -247,7 +247,7 @@ public class ReactiveCloudFoundryActuatorAutoConfigurationTests {
@Test @Test
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void gitFullDetailsAlwaysPresent() { void gitFullDetailsAlwaysPresent() {
this.contextRunner.withPropertyValues("VCAP_APPLICATION:---").run((context) -> { this.contextRunner.withPropertyValues("VCAP_APPLICATION:---").run((context) -> {
CloudFoundryInfoEndpointWebExtension extension = context CloudFoundryInfoEndpointWebExtension extension = context
.getBean(CloudFoundryInfoEndpointWebExtension.class); .getBean(CloudFoundryInfoEndpointWebExtension.class);
@ -258,7 +258,7 @@ public class ReactiveCloudFoundryActuatorAutoConfigurationTests {
} }
@Test @Test
public void skipSslValidation() { void skipSslValidation() {
this.contextRunner.withConfiguration(AutoConfigurations.of(HealthEndpointAutoConfiguration.class)) this.contextRunner.withConfiguration(AutoConfigurations.of(HealthEndpointAutoConfiguration.class))
.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id",
"vcap.application.cf_api:https://my-cloud-controller.com", "vcap.application.cf_api:https://my-cloud-controller.com",
@ -275,7 +275,7 @@ public class ReactiveCloudFoundryActuatorAutoConfigurationTests {
} }
@Test @Test
public void sslValidationNotSkippedByDefault() { void sslValidationNotSkippedByDefault() {
this.contextRunner.withConfiguration(AutoConfigurations.of(HealthEndpointAutoConfiguration.class)) this.contextRunner.withConfiguration(AutoConfigurations.of(HealthEndpointAutoConfiguration.class))
.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id",
"vcap.application.cf_api:https://my-cloud-controller.com") "vcap.application.cf_api:https://my-cloud-controller.com")

View File

@ -41,7 +41,7 @@ import static org.mockito.BDDMockito.given;
* *
* @author Madhura Bhave * @author Madhura Bhave
*/ */
public class ReactiveCloudFoundrySecurityInterceptorTests { class ReactiveCloudFoundrySecurityInterceptorTests {
@Mock @Mock
private ReactiveTokenValidator tokenValidator; private ReactiveTokenValidator tokenValidator;
@ -58,7 +58,7 @@ public class ReactiveCloudFoundrySecurityInterceptorTests {
} }
@Test @Test
public void preHandleWhenRequestIsPreFlightShouldBeOk() { void preHandleWhenRequestIsPreFlightShouldBeOk() {
MockServerWebExchange request = MockServerWebExchange MockServerWebExchange request = MockServerWebExchange
.from(MockServerHttpRequest.options("/a").header(HttpHeaders.ORIGIN, "https://example.com") .from(MockServerHttpRequest.options("/a").header(HttpHeaders.ORIGIN, "https://example.com")
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET").build()); .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET").build());
@ -68,7 +68,7 @@ public class ReactiveCloudFoundrySecurityInterceptorTests {
} }
@Test @Test
public void preHandleWhenTokenIsMissingShouldReturnMissingAuthorization() { void preHandleWhenTokenIsMissingShouldReturnMissingAuthorization() {
MockServerWebExchange request = MockServerWebExchange.from(MockServerHttpRequest.get("/a").build()); MockServerWebExchange request = MockServerWebExchange.from(MockServerHttpRequest.get("/a").build());
StepVerifier.create(this.interceptor.preHandle(request, "/a")).consumeNextWith( StepVerifier.create(this.interceptor.preHandle(request, "/a")).consumeNextWith(
(response) -> assertThat(response.getStatus()).isEqualTo(Reason.MISSING_AUTHORIZATION.getStatus())) (response) -> assertThat(response.getStatus()).isEqualTo(Reason.MISSING_AUTHORIZATION.getStatus()))
@ -76,7 +76,7 @@ public class ReactiveCloudFoundrySecurityInterceptorTests {
} }
@Test @Test
public void preHandleWhenTokenIsNotBearerShouldReturnMissingAuthorization() { void preHandleWhenTokenIsNotBearerShouldReturnMissingAuthorization() {
MockServerWebExchange request = MockServerWebExchange MockServerWebExchange request = MockServerWebExchange
.from(MockServerHttpRequest.get("/a").header(HttpHeaders.AUTHORIZATION, mockAccessToken()).build()); .from(MockServerHttpRequest.get("/a").header(HttpHeaders.AUTHORIZATION, mockAccessToken()).build());
StepVerifier.create(this.interceptor.preHandle(request, "/a")).consumeNextWith( StepVerifier.create(this.interceptor.preHandle(request, "/a")).consumeNextWith(
@ -85,7 +85,7 @@ public class ReactiveCloudFoundrySecurityInterceptorTests {
} }
@Test @Test
public void preHandleWhenApplicationIdIsNullShouldReturnError() { void preHandleWhenApplicationIdIsNullShouldReturnError() {
this.interceptor = new CloudFoundrySecurityInterceptor(this.tokenValidator, this.securityService, null); this.interceptor = new CloudFoundrySecurityInterceptor(this.tokenValidator, this.securityService, null);
MockServerWebExchange request = MockServerWebExchange.from(MockServerHttpRequest.get("/a") MockServerWebExchange request = MockServerWebExchange.from(MockServerHttpRequest.get("/a")
.header(HttpHeaders.AUTHORIZATION, "bearer " + mockAccessToken()).build()); .header(HttpHeaders.AUTHORIZATION, "bearer " + mockAccessToken()).build());
@ -96,7 +96,7 @@ public class ReactiveCloudFoundrySecurityInterceptorTests {
} }
@Test @Test
public void preHandleWhenCloudFoundrySecurityServiceIsNullShouldReturnError() { void preHandleWhenCloudFoundrySecurityServiceIsNullShouldReturnError() {
this.interceptor = new CloudFoundrySecurityInterceptor(this.tokenValidator, null, "my-app-id"); this.interceptor = new CloudFoundrySecurityInterceptor(this.tokenValidator, null, "my-app-id");
MockServerWebExchange request = MockServerWebExchange MockServerWebExchange request = MockServerWebExchange
.from(MockServerHttpRequest.get("/a").header(HttpHeaders.AUTHORIZATION, mockAccessToken()).build()); .from(MockServerHttpRequest.get("/a").header(HttpHeaders.AUTHORIZATION, mockAccessToken()).build());
@ -107,7 +107,7 @@ public class ReactiveCloudFoundrySecurityInterceptorTests {
} }
@Test @Test
public void preHandleWhenAccessIsNotAllowedShouldReturnAccessDenied() { void preHandleWhenAccessIsNotAllowedShouldReturnAccessDenied() {
given(this.securityService.getAccessLevel(mockAccessToken(), "my-app-id")) given(this.securityService.getAccessLevel(mockAccessToken(), "my-app-id"))
.willReturn(Mono.just(AccessLevel.RESTRICTED)); .willReturn(Mono.just(AccessLevel.RESTRICTED));
given(this.tokenValidator.validate(any())).willReturn(Mono.empty()); given(this.tokenValidator.validate(any())).willReturn(Mono.empty());
@ -120,7 +120,7 @@ public class ReactiveCloudFoundrySecurityInterceptorTests {
} }
@Test @Test
public void preHandleSuccessfulWithFullAccess() { void preHandleSuccessfulWithFullAccess() {
String accessToken = mockAccessToken(); String accessToken = mockAccessToken();
given(this.securityService.getAccessLevel(accessToken, "my-app-id")).willReturn(Mono.just(AccessLevel.FULL)); given(this.securityService.getAccessLevel(accessToken, "my-app-id")).willReturn(Mono.just(AccessLevel.FULL));
given(this.tokenValidator.validate(any())).willReturn(Mono.empty()); given(this.tokenValidator.validate(any())).willReturn(Mono.empty());
@ -133,7 +133,7 @@ public class ReactiveCloudFoundrySecurityInterceptorTests {
} }
@Test @Test
public void preHandleSuccessfulWithRestrictedAccess() { void preHandleSuccessfulWithRestrictedAccess() {
String accessToken = mockAccessToken(); String accessToken = mockAccessToken();
given(this.securityService.getAccessLevel(accessToken, "my-app-id")) given(this.securityService.getAccessLevel(accessToken, "my-app-id"))
.willReturn(Mono.just(AccessLevel.RESTRICTED)); .willReturn(Mono.just(AccessLevel.RESTRICTED));

View File

@ -39,7 +39,7 @@ import static org.assertj.core.api.Assertions.assertThat;
* *
* @author Madhura Bhave * @author Madhura Bhave
*/ */
public class ReactiveCloudFoundrySecurityServiceTests { class ReactiveCloudFoundrySecurityServiceTests {
private static final String CLOUD_CONTROLLER = "/my-cloud-controller.com"; private static final String CLOUD_CONTROLLER = "/my-cloud-controller.com";
@ -66,7 +66,7 @@ public class ReactiveCloudFoundrySecurityServiceTests {
} }
@Test @Test
public void getAccessLevelWhenSpaceDeveloperShouldReturnFull() throws Exception { void getAccessLevelWhenSpaceDeveloperShouldReturnFull() throws Exception {
String responseBody = "{\"read_sensitive_data\": true,\"read_basic_data\": true}"; String responseBody = "{\"read_sensitive_data\": true,\"read_basic_data\": true}";
prepareResponse((response) -> response.setBody(responseBody).setHeader("Content-Type", "application/json")); prepareResponse((response) -> response.setBody(responseBody).setHeader("Content-Type", "application/json"));
StepVerifier.create(this.securityService.getAccessLevel("my-access-token", "my-app-id")) StepVerifier.create(this.securityService.getAccessLevel("my-access-token", "my-app-id"))
@ -79,7 +79,7 @@ public class ReactiveCloudFoundrySecurityServiceTests {
} }
@Test @Test
public void getAccessLevelWhenNotSpaceDeveloperShouldReturnRestricted() throws Exception { void getAccessLevelWhenNotSpaceDeveloperShouldReturnRestricted() throws Exception {
String responseBody = "{\"read_sensitive_data\": false,\"read_basic_data\": true}"; String responseBody = "{\"read_sensitive_data\": false,\"read_basic_data\": true}";
prepareResponse((response) -> response.setBody(responseBody).setHeader("Content-Type", "application/json")); prepareResponse((response) -> response.setBody(responseBody).setHeader("Content-Type", "application/json"));
StepVerifier.create(this.securityService.getAccessLevel("my-access-token", "my-app-id")) StepVerifier.create(this.securityService.getAccessLevel("my-access-token", "my-app-id"))
@ -92,7 +92,7 @@ public class ReactiveCloudFoundrySecurityServiceTests {
} }
@Test @Test
public void getAccessLevelWhenTokenIsNotValidShouldThrowException() throws Exception { void getAccessLevelWhenTokenIsNotValidShouldThrowException() throws Exception {
prepareResponse((response) -> response.setResponseCode(401)); prepareResponse((response) -> response.setResponseCode(401));
StepVerifier.create(this.securityService.getAccessLevel("my-access-token", "my-app-id")) StepVerifier.create(this.securityService.getAccessLevel("my-access-token", "my-app-id"))
.consumeErrorWith((throwable) -> { .consumeErrorWith((throwable) -> {
@ -107,7 +107,7 @@ public class ReactiveCloudFoundrySecurityServiceTests {
} }
@Test @Test
public void getAccessLevelWhenForbiddenShouldThrowException() throws Exception { void getAccessLevelWhenForbiddenShouldThrowException() throws Exception {
prepareResponse((response) -> response.setResponseCode(403)); prepareResponse((response) -> response.setResponseCode(403));
StepVerifier.create(this.securityService.getAccessLevel("my-access-token", "my-app-id")) StepVerifier.create(this.securityService.getAccessLevel("my-access-token", "my-app-id"))
.consumeErrorWith((throwable) -> { .consumeErrorWith((throwable) -> {
@ -122,7 +122,7 @@ public class ReactiveCloudFoundrySecurityServiceTests {
} }
@Test @Test
public void getAccessLevelWhenCloudControllerIsNotReachableThrowsException() throws Exception { void getAccessLevelWhenCloudControllerIsNotReachableThrowsException() throws Exception {
prepareResponse((response) -> response.setResponseCode(500)); prepareResponse((response) -> response.setResponseCode(500));
StepVerifier.create(this.securityService.getAccessLevel("my-access-token", "my-app-id")) StepVerifier.create(this.securityService.getAccessLevel("my-access-token", "my-app-id"))
.consumeErrorWith((throwable) -> { .consumeErrorWith((throwable) -> {
@ -137,7 +137,7 @@ public class ReactiveCloudFoundrySecurityServiceTests {
} }
@Test @Test
public void fetchTokenKeysWhenSuccessfulShouldReturnListOfKeysFromUAA() throws Exception { void fetchTokenKeysWhenSuccessfulShouldReturnListOfKeysFromUAA() throws Exception {
String tokenKeyValue = "-----BEGIN PUBLIC KEY-----\n" String tokenKeyValue = "-----BEGIN PUBLIC KEY-----\n"
+ "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0m59l2u9iDnMbrXHfqkO\n" + "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0m59l2u9iDnMbrXHfqkO\n"
+ "rn2dVQ3vfBJqcDuFUK03d+1PZGbVlNCqnkpIJ8syFppW8ljnWweP7+LiWpRoz0I7\n" + "rn2dVQ3vfBJqcDuFUK03d+1PZGbVlNCqnkpIJ8syFppW8ljnWweP7+LiWpRoz0I7\n"
@ -164,7 +164,7 @@ public class ReactiveCloudFoundrySecurityServiceTests {
} }
@Test @Test
public void fetchTokenKeysWhenNoKeysReturnedFromUAA() throws Exception { void fetchTokenKeysWhenNoKeysReturnedFromUAA() throws Exception {
prepareResponse((response) -> { prepareResponse((response) -> {
response.setBody("{\"token_endpoint\":\"/my-uaa.com\"}"); response.setBody("{\"token_endpoint\":\"/my-uaa.com\"}");
response.setHeader("Content-Type", "application/json"); response.setHeader("Content-Type", "application/json");
@ -181,7 +181,7 @@ public class ReactiveCloudFoundrySecurityServiceTests {
} }
@Test @Test
public void fetchTokenKeysWhenUnsuccessfulShouldThrowException() throws Exception { void fetchTokenKeysWhenUnsuccessfulShouldThrowException() throws Exception {
prepareResponse((response) -> { prepareResponse((response) -> {
response.setBody("{\"token_endpoint\":\"/my-uaa.com\"}"); response.setBody("{\"token_endpoint\":\"/my-uaa.com\"}");
response.setHeader("Content-Type", "application/json"); response.setHeader("Content-Type", "application/json");
@ -197,7 +197,7 @@ public class ReactiveCloudFoundrySecurityServiceTests {
} }
@Test @Test
public void getUaaUrlShouldCallCloudControllerInfoOnlyOnce() throws Exception { void getUaaUrlShouldCallCloudControllerInfoOnlyOnce() throws Exception {
prepareResponse((response) -> { prepareResponse((response) -> {
response.setBody("{\"token_endpoint\":\"" + UAA_URL + "\"}"); response.setBody("{\"token_endpoint\":\"" + UAA_URL + "\"}");
response.setHeader("Content-Type", "application/json"); response.setHeader("Content-Type", "application/json");
@ -211,7 +211,7 @@ public class ReactiveCloudFoundrySecurityServiceTests {
} }
@Test @Test
public void getUaaUrlWhenCloudControllerUrlIsNotReachableShouldThrowException() throws Exception { void getUaaUrlWhenCloudControllerUrlIsNotReachableShouldThrowException() throws Exception {
prepareResponse((response) -> response.setResponseCode(500)); prepareResponse((response) -> response.setResponseCode(500));
StepVerifier.create(this.securityService.getUaaUrl()).consumeErrorWith((throwable) -> { StepVerifier.create(this.securityService.getUaaUrl()).consumeErrorWith((throwable) -> {
assertThat(throwable).isInstanceOf(CloudFoundryAuthorizationException.class); assertThat(throwable).isInstanceOf(CloudFoundryAuthorizationException.class);

View File

@ -52,7 +52,7 @@ import static org.mockito.BDDMockito.given;
* *
* @author Madhura Bhave * @author Madhura Bhave
*/ */
public class ReactiveTokenValidatorTests { class ReactiveTokenValidatorTests {
private static final byte[] DOT = ".".getBytes(); private static final byte[] DOT = ".".getBytes();
@ -92,7 +92,7 @@ public class ReactiveTokenValidatorTests {
} }
@Test @Test
public void validateTokenWhenKidValidationFailsTwiceShouldThrowException() throws Exception { void validateTokenWhenKidValidationFailsTwiceShouldThrowException() throws Exception {
PublisherProbe<Map<String, String>> fetchTokenKeys = PublisherProbe.of(Mono.just(VALID_KEYS)); PublisherProbe<Map<String, String>> fetchTokenKeys = PublisherProbe.of(Mono.just(VALID_KEYS));
ReflectionTestUtils.setField(this.tokenValidator, "cachedTokenKeys", VALID_KEYS); ReflectionTestUtils.setField(this.tokenValidator, "cachedTokenKeys", VALID_KEYS);
given(this.securityService.fetchTokenKeys()).willReturn(fetchTokenKeys.mono()); given(this.securityService.fetchTokenKeys()).willReturn(fetchTokenKeys.mono());
@ -110,7 +110,7 @@ public class ReactiveTokenValidatorTests {
} }
@Test @Test
public void validateTokenWhenKidValidationSucceedsInTheSecondAttempt() throws Exception { void validateTokenWhenKidValidationSucceedsInTheSecondAttempt() throws Exception {
PublisherProbe<Map<String, String>> fetchTokenKeys = PublisherProbe.of(Mono.just(VALID_KEYS)); PublisherProbe<Map<String, String>> fetchTokenKeys = PublisherProbe.of(Mono.just(VALID_KEYS));
ReflectionTestUtils.setField(this.tokenValidator, "cachedTokenKeys", INVALID_KEYS); ReflectionTestUtils.setField(this.tokenValidator, "cachedTokenKeys", INVALID_KEYS);
given(this.securityService.fetchTokenKeys()).willReturn(fetchTokenKeys.mono()); given(this.securityService.fetchTokenKeys()).willReturn(fetchTokenKeys.mono());
@ -125,7 +125,7 @@ public class ReactiveTokenValidatorTests {
} }
@Test @Test
public void validateTokenWhenCacheIsEmptyShouldFetchTokenKeys() throws Exception { void validateTokenWhenCacheIsEmptyShouldFetchTokenKeys() throws Exception {
PublisherProbe<Map<String, String>> fetchTokenKeys = PublisherProbe.of(Mono.just(VALID_KEYS)); PublisherProbe<Map<String, String>> fetchTokenKeys = PublisherProbe.of(Mono.just(VALID_KEYS));
given(this.securityService.fetchTokenKeys()).willReturn(fetchTokenKeys.mono()); given(this.securityService.fetchTokenKeys()).willReturn(fetchTokenKeys.mono());
given(this.securityService.getUaaUrl()).willReturn(Mono.just("http://localhost:8080/uaa")); given(this.securityService.getUaaUrl()).willReturn(Mono.just("http://localhost:8080/uaa"));
@ -139,7 +139,7 @@ public class ReactiveTokenValidatorTests {
} }
@Test @Test
public void validateTokenWhenCacheEmptyAndInvalidKeyShouldThrowException() throws Exception { void validateTokenWhenCacheEmptyAndInvalidKeyShouldThrowException() throws Exception {
PublisherProbe<Map<String, String>> fetchTokenKeys = PublisherProbe.of(Mono.just(VALID_KEYS)); PublisherProbe<Map<String, String>> fetchTokenKeys = PublisherProbe.of(Mono.just(VALID_KEYS));
given(this.securityService.fetchTokenKeys()).willReturn(fetchTokenKeys.mono()); given(this.securityService.fetchTokenKeys()).willReturn(fetchTokenKeys.mono());
given(this.securityService.getUaaUrl()).willReturn(Mono.just("http://localhost:8080/uaa")); given(this.securityService.getUaaUrl()).willReturn(Mono.just("http://localhost:8080/uaa"));
@ -156,7 +156,7 @@ public class ReactiveTokenValidatorTests {
} }
@Test @Test
public void validateTokenWhenCacheValidShouldNotFetchTokenKeys() throws Exception { void validateTokenWhenCacheValidShouldNotFetchTokenKeys() throws Exception {
PublisherProbe<Map<String, String>> fetchTokenKeys = PublisherProbe.empty(); PublisherProbe<Map<String, String>> fetchTokenKeys = PublisherProbe.empty();
ReflectionTestUtils.setField(this.tokenValidator, "cachedTokenKeys", VALID_KEYS); ReflectionTestUtils.setField(this.tokenValidator, "cachedTokenKeys", VALID_KEYS);
given(this.securityService.fetchTokenKeys()).willReturn(fetchTokenKeys.mono()); given(this.securityService.fetchTokenKeys()).willReturn(fetchTokenKeys.mono());
@ -170,7 +170,7 @@ public class ReactiveTokenValidatorTests {
} }
@Test @Test
public void validateTokenWhenSignatureInvalidShouldThrowException() throws Exception { void validateTokenWhenSignatureInvalidShouldThrowException() throws Exception {
Map<String, String> KEYS = Collections.singletonMap("valid-key", INVALID_KEY); Map<String, String> KEYS = Collections.singletonMap("valid-key", INVALID_KEY);
given(this.securityService.fetchTokenKeys()).willReturn(Mono.just(KEYS)); given(this.securityService.fetchTokenKeys()).willReturn(Mono.just(KEYS));
given(this.securityService.getUaaUrl()).willReturn(Mono.just("http://localhost:8080/uaa")); given(this.securityService.getUaaUrl()).willReturn(Mono.just("http://localhost:8080/uaa"));
@ -186,7 +186,7 @@ public class ReactiveTokenValidatorTests {
} }
@Test @Test
public void validateTokenWhenTokenAlgorithmIsNotRS256ShouldThrowException() throws Exception { void validateTokenWhenTokenAlgorithmIsNotRS256ShouldThrowException() throws Exception {
given(this.securityService.fetchTokenKeys()).willReturn(Mono.just(VALID_KEYS)); given(this.securityService.fetchTokenKeys()).willReturn(Mono.just(VALID_KEYS));
given(this.securityService.getUaaUrl()).willReturn(Mono.just("http://localhost:8080/uaa")); given(this.securityService.getUaaUrl()).willReturn(Mono.just("http://localhost:8080/uaa"));
String header = "{ \"alg\": \"HS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\"}"; String header = "{ \"alg\": \"HS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\"}";
@ -201,7 +201,7 @@ public class ReactiveTokenValidatorTests {
} }
@Test @Test
public void validateTokenWhenExpiredShouldThrowException() throws Exception { void validateTokenWhenExpiredShouldThrowException() throws Exception {
given(this.securityService.fetchTokenKeys()).willReturn(Mono.just(VALID_KEYS)); given(this.securityService.fetchTokenKeys()).willReturn(Mono.just(VALID_KEYS));
given(this.securityService.getUaaUrl()).willReturn(Mono.just("http://localhost:8080/uaa")); given(this.securityService.getUaaUrl()).willReturn(Mono.just("http://localhost:8080/uaa"));
String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\"}"; String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\"}";
@ -215,7 +215,7 @@ public class ReactiveTokenValidatorTests {
} }
@Test @Test
public void validateTokenWhenIssuerIsNotValidShouldThrowException() throws Exception { void validateTokenWhenIssuerIsNotValidShouldThrowException() throws Exception {
given(this.securityService.fetchTokenKeys()).willReturn(Mono.just(VALID_KEYS)); given(this.securityService.fetchTokenKeys()).willReturn(Mono.just(VALID_KEYS));
given(this.securityService.getUaaUrl()).willReturn(Mono.just("https://other-uaa.com")); given(this.securityService.getUaaUrl()).willReturn(Mono.just("https://other-uaa.com"));
String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\", \"scope\": [\"actuator.read\"]}"; String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\", \"scope\": [\"actuator.read\"]}";
@ -229,7 +229,7 @@ public class ReactiveTokenValidatorTests {
} }
@Test @Test
public void validateTokenWhenAudienceIsNotValidShouldThrowException() throws Exception { void validateTokenWhenAudienceIsNotValidShouldThrowException() throws Exception {
given(this.securityService.fetchTokenKeys()).willReturn(Mono.just(VALID_KEYS)); given(this.securityService.fetchTokenKeys()).willReturn(Mono.just(VALID_KEYS));
given(this.securityService.getUaaUrl()).willReturn(Mono.just("http://localhost:8080/uaa")); given(this.securityService.getUaaUrl()).willReturn(Mono.just("http://localhost:8080/uaa"));
String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\"}"; String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\"}";

View File

@ -64,7 +64,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
* *
* @author Madhura Bhave * @author Madhura Bhave
*/ */
public class CloudFoundryActuatorAutoConfigurationTests { class CloudFoundryActuatorAutoConfigurationTests {
private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(SecurityAutoConfiguration.class, WebMvcAutoConfiguration.class, .withConfiguration(AutoConfigurations.of(SecurityAutoConfiguration.class, WebMvcAutoConfiguration.class,
@ -75,7 +75,7 @@ public class CloudFoundryActuatorAutoConfigurationTests {
WebEndpointAutoConfiguration.class, CloudFoundryActuatorAutoConfiguration.class)); WebEndpointAutoConfiguration.class, CloudFoundryActuatorAutoConfiguration.class));
@Test @Test
public void cloudFoundryPlatformActive() { void cloudFoundryPlatformActive() {
this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id",
"vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> {
CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context);
@ -93,7 +93,7 @@ public class CloudFoundryActuatorAutoConfigurationTests {
} }
@Test @Test
public void cloudfoundryapplicationProducesActuatorMediaType() throws Exception { void cloudfoundryapplicationProducesActuatorMediaType() throws Exception {
this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id",
"vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> {
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
@ -103,7 +103,7 @@ public class CloudFoundryActuatorAutoConfigurationTests {
} }
@Test @Test
public void cloudFoundryPlatformActiveSetsApplicationId() { void cloudFoundryPlatformActiveSetsApplicationId() {
this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id",
"vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> {
CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context);
@ -114,7 +114,7 @@ public class CloudFoundryActuatorAutoConfigurationTests {
} }
@Test @Test
public void cloudFoundryPlatformActiveSetsCloudControllerUrl() { void cloudFoundryPlatformActiveSetsCloudControllerUrl() {
this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id",
"vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> {
CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context);
@ -128,7 +128,7 @@ public class CloudFoundryActuatorAutoConfigurationTests {
} }
@Test @Test
public void skipSslValidation() { void skipSslValidation() {
this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id",
"vcap.application.cf_api:https://my-cloud-controller.com", "vcap.application.cf_api:https://my-cloud-controller.com",
"management.cloudfoundry.skip-ssl-validation:true").run((context) -> { "management.cloudfoundry.skip-ssl-validation:true").run((context) -> {
@ -144,7 +144,7 @@ public class CloudFoundryActuatorAutoConfigurationTests {
} }
@Test @Test
public void cloudFoundryPlatformActiveAndCloudControllerUrlNotPresent() { void cloudFoundryPlatformActiveAndCloudControllerUrlNotPresent() {
this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id") this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id")
.run((context) -> { .run((context) -> {
CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context);
@ -156,7 +156,7 @@ public class CloudFoundryActuatorAutoConfigurationTests {
} }
@Test @Test
public void cloudFoundryPathsIgnoredBySpringSecurity() { void cloudFoundryPathsIgnoredBySpringSecurity() {
this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id") this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id")
.run((context) -> { .run((context) -> {
FilterChainProxy securityFilterChain = (FilterChainProxy) context FilterChainProxy securityFilterChain = (FilterChainProxy) context
@ -172,20 +172,20 @@ public class CloudFoundryActuatorAutoConfigurationTests {
} }
@Test @Test
public void cloudFoundryPlatformInactive() { void cloudFoundryPlatformInactive() {
this.contextRunner.withPropertyValues() this.contextRunner.withPropertyValues()
.run((context) -> assertThat(context.containsBean("cloudFoundryWebEndpointServletHandlerMapping")) .run((context) -> assertThat(context.containsBean("cloudFoundryWebEndpointServletHandlerMapping"))
.isFalse()); .isFalse());
} }
@Test @Test
public void cloudFoundryManagementEndpointsDisabled() { void cloudFoundryManagementEndpointsDisabled() {
this.contextRunner.withPropertyValues("VCAP_APPLICATION=---", "management.cloudfoundry.enabled:false") this.contextRunner.withPropertyValues("VCAP_APPLICATION=---", "management.cloudfoundry.enabled:false")
.run((context) -> assertThat(context.containsBean("cloudFoundryEndpointHandlerMapping")).isFalse()); .run((context) -> assertThat(context.containsBean("cloudFoundryEndpointHandlerMapping")).isFalse());
} }
@Test @Test
public void allEndpointsAvailableUnderCloudFoundryWithoutExposeAllOnWeb() { void allEndpointsAvailableUnderCloudFoundryWithoutExposeAllOnWeb() {
this.contextRunner.withBean(TestEndpoint.class, TestEndpoint::new).withPropertyValues("VCAP_APPLICATION:---", this.contextRunner.withBean(TestEndpoint.class, TestEndpoint::new).withPropertyValues("VCAP_APPLICATION:---",
"vcap.application.application_id:my-app-id", "vcap.application.cf_api:https://my-cloud-controller.com") "vcap.application.application_id:my-app-id", "vcap.application.cf_api:https://my-cloud-controller.com")
.run((context) -> { .run((context) -> {
@ -198,7 +198,7 @@ public class CloudFoundryActuatorAutoConfigurationTests {
} }
@Test @Test
public void endpointPathCustomizationIsNotApplied() { void endpointPathCustomizationIsNotApplied() {
this.contextRunner this.contextRunner
.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id",
"vcap.application.cf_api:https://my-cloud-controller.com", "vcap.application.cf_api:https://my-cloud-controller.com",
@ -216,7 +216,7 @@ public class CloudFoundryActuatorAutoConfigurationTests {
} }
@Test @Test
public void healthEndpointInvokerShouldBeCloudFoundryWebExtension() { void healthEndpointInvokerShouldBeCloudFoundryWebExtension() {
this.contextRunner this.contextRunner
.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id",
"vcap.application.cf_api:https://my-cloud-controller.com") "vcap.application.cf_api:https://my-cloud-controller.com")

View File

@ -41,7 +41,7 @@ import static org.assertj.core.api.Assertions.assertThat;
* *
* @author Madhura Bhave * @author Madhura Bhave
*/ */
public class CloudFoundryHealthEndpointWebExtensionTests { class CloudFoundryHealthEndpointWebExtensionTests {
private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withPropertyValues("VCAP_APPLICATION={}") .withPropertyValues("VCAP_APPLICATION={}")
@ -54,7 +54,7 @@ public class CloudFoundryHealthEndpointWebExtensionTests {
HealthEndpointAutoConfiguration.class, CloudFoundryActuatorAutoConfiguration.class)); HealthEndpointAutoConfiguration.class, CloudFoundryActuatorAutoConfiguration.class));
@Test @Test
public void healthDetailsAlwaysPresent() { void healthDetailsAlwaysPresent() {
this.contextRunner.run((context) -> { this.contextRunner.run((context) -> {
CloudFoundryHealthEndpointWebExtension extension = context CloudFoundryHealthEndpointWebExtension extension = context
.getBean(CloudFoundryHealthEndpointWebExtension.class); .getBean(CloudFoundryHealthEndpointWebExtension.class);

View File

@ -17,7 +17,7 @@ package org.springframework.boot.actuate.autoconfigure.cloudfoundry.servlet;
import java.util.Map; import java.util.Map;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.actuate.autoconfigure.endpoint.EndpointAutoConfiguration; import org.springframework.boot.actuate.autoconfigure.endpoint.EndpointAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointAutoConfiguration; import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointAutoConfiguration;
@ -46,7 +46,7 @@ import static org.assertj.core.api.Assertions.assertThat;
* *
* @author Madhura Bhave * @author Madhura Bhave
*/ */
public class CloudFoundryInfoEndpointWebExtensionTests { class CloudFoundryInfoEndpointWebExtensionTests {
private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withPropertyValues("VCAP_APPLICATION={}") .withPropertyValues("VCAP_APPLICATION={}")
@ -61,7 +61,7 @@ public class CloudFoundryInfoEndpointWebExtensionTests {
@Test @Test
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void gitFullDetailsAlwaysPresent() { void gitFullDetailsAlwaysPresent() {
this.contextRunner.withInitializer(new ConditionEvaluationReportLoggingListener(LogLevel.INFO)) this.contextRunner.withInitializer(new ConditionEvaluationReportLoggingListener(LogLevel.INFO))
.run((context) -> { .run((context) -> {
CloudFoundryInfoEndpointWebExtension extension = context CloudFoundryInfoEndpointWebExtension extension = context

View File

@ -63,14 +63,14 @@ import static org.mockito.Mockito.mock;
* *
* @author Madhura Bhave * @author Madhura Bhave
*/ */
public class CloudFoundryMvcWebEndpointIntegrationTests { class CloudFoundryMvcWebEndpointIntegrationTests {
private static TokenValidator tokenValidator = mock(TokenValidator.class); private static TokenValidator tokenValidator = mock(TokenValidator.class);
private static CloudFoundrySecurityService securityService = mock(CloudFoundrySecurityService.class); private static CloudFoundrySecurityService securityService = mock(CloudFoundrySecurityService.class);
@Test @Test
public void operationWithSecurityInterceptorForbidden() { void operationWithSecurityInterceptorForbidden() {
given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(AccessLevel.RESTRICTED); given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(AccessLevel.RESTRICTED);
load(TestEndpointConfiguration.class, load(TestEndpointConfiguration.class,
(client) -> client.get().uri("/cfApplication/test").accept(MediaType.APPLICATION_JSON) (client) -> client.get().uri("/cfApplication/test").accept(MediaType.APPLICATION_JSON)
@ -79,7 +79,7 @@ public class CloudFoundryMvcWebEndpointIntegrationTests {
} }
@Test @Test
public void operationWithSecurityInterceptorSuccess() { void operationWithSecurityInterceptorSuccess() {
given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(AccessLevel.FULL); given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(AccessLevel.FULL);
load(TestEndpointConfiguration.class, load(TestEndpointConfiguration.class,
(client) -> client.get().uri("/cfApplication/test").accept(MediaType.APPLICATION_JSON) (client) -> client.get().uri("/cfApplication/test").accept(MediaType.APPLICATION_JSON)
@ -88,7 +88,7 @@ public class CloudFoundryMvcWebEndpointIntegrationTests {
} }
@Test @Test
public void responseToOptionsRequestIncludesCorsHeaders() { void responseToOptionsRequestIncludesCorsHeaders() {
load(TestEndpointConfiguration.class, load(TestEndpointConfiguration.class,
(client) -> client.options().uri("/cfApplication/test").accept(MediaType.APPLICATION_JSON) (client) -> client.options().uri("/cfApplication/test").accept(MediaType.APPLICATION_JSON)
.header("Access-Control-Request-Method", "POST").header("Origin", "https://example.com") .header("Access-Control-Request-Method", "POST").header("Origin", "https://example.com")
@ -98,7 +98,7 @@ public class CloudFoundryMvcWebEndpointIntegrationTests {
} }
@Test @Test
public void linksToOtherEndpointsWithFullAccess() { void linksToOtherEndpointsWithFullAccess() {
given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(AccessLevel.FULL); given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(AccessLevel.FULL);
load(TestEndpointConfiguration.class, load(TestEndpointConfiguration.class,
(client) -> client.get().uri("/cfApplication").accept(MediaType.APPLICATION_JSON) (client) -> client.get().uri("/cfApplication").accept(MediaType.APPLICATION_JSON)
@ -112,7 +112,7 @@ public class CloudFoundryMvcWebEndpointIntegrationTests {
} }
@Test @Test
public void linksToOtherEndpointsForbidden() { void linksToOtherEndpointsForbidden() {
CloudFoundryAuthorizationException exception = new CloudFoundryAuthorizationException(Reason.INVALID_TOKEN, CloudFoundryAuthorizationException exception = new CloudFoundryAuthorizationException(Reason.INVALID_TOKEN,
"invalid-token"); "invalid-token");
willThrow(exception).given(tokenValidator).validate(any()); willThrow(exception).given(tokenValidator).validate(any());
@ -123,7 +123,7 @@ public class CloudFoundryMvcWebEndpointIntegrationTests {
} }
@Test @Test
public void linksToOtherEndpointsWithRestrictedAccess() { void linksToOtherEndpointsWithRestrictedAccess() {
given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(AccessLevel.RESTRICTED); given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(AccessLevel.RESTRICTED);
load(TestEndpointConfiguration.class, load(TestEndpointConfiguration.class,
(client) -> client.get().uri("/cfApplication").accept(MediaType.APPLICATION_JSON) (client) -> client.get().uri("/cfApplication").accept(MediaType.APPLICATION_JSON)

View File

@ -41,7 +41,7 @@ import static org.mockito.Mockito.verify;
* *
* @author Madhura Bhave * @author Madhura Bhave
*/ */
public class CloudFoundrySecurityInterceptorTests { class CloudFoundrySecurityInterceptorTests {
@Mock @Mock
private TokenValidator tokenValidator; private TokenValidator tokenValidator;
@ -61,7 +61,7 @@ public class CloudFoundrySecurityInterceptorTests {
} }
@Test @Test
public void preHandleWhenRequestIsPreFlightShouldReturnTrue() { void preHandleWhenRequestIsPreFlightShouldReturnTrue() {
this.request.setMethod("OPTIONS"); this.request.setMethod("OPTIONS");
this.request.addHeader(HttpHeaders.ORIGIN, "https://example.com"); this.request.addHeader(HttpHeaders.ORIGIN, "https://example.com");
this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET"); this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
@ -70,20 +70,20 @@ public class CloudFoundrySecurityInterceptorTests {
} }
@Test @Test
public void preHandleWhenTokenIsMissingShouldReturnFalse() { void preHandleWhenTokenIsMissingShouldReturnFalse() {
SecurityResponse response = this.interceptor.preHandle(this.request, EndpointId.of("test")); SecurityResponse response = this.interceptor.preHandle(this.request, EndpointId.of("test"));
assertThat(response.getStatus()).isEqualTo(Reason.MISSING_AUTHORIZATION.getStatus()); assertThat(response.getStatus()).isEqualTo(Reason.MISSING_AUTHORIZATION.getStatus());
} }
@Test @Test
public void preHandleWhenTokenIsNotBearerShouldReturnFalse() { void preHandleWhenTokenIsNotBearerShouldReturnFalse() {
this.request.addHeader("Authorization", mockAccessToken()); this.request.addHeader("Authorization", mockAccessToken());
SecurityResponse response = this.interceptor.preHandle(this.request, EndpointId.of("test")); SecurityResponse response = this.interceptor.preHandle(this.request, EndpointId.of("test"));
assertThat(response.getStatus()).isEqualTo(Reason.MISSING_AUTHORIZATION.getStatus()); assertThat(response.getStatus()).isEqualTo(Reason.MISSING_AUTHORIZATION.getStatus());
} }
@Test @Test
public void preHandleWhenApplicationIdIsNullShouldReturnFalse() { void preHandleWhenApplicationIdIsNullShouldReturnFalse() {
this.interceptor = new CloudFoundrySecurityInterceptor(this.tokenValidator, this.securityService, null); this.interceptor = new CloudFoundrySecurityInterceptor(this.tokenValidator, this.securityService, null);
this.request.addHeader("Authorization", "bearer " + mockAccessToken()); this.request.addHeader("Authorization", "bearer " + mockAccessToken());
SecurityResponse response = this.interceptor.preHandle(this.request, EndpointId.of("test")); SecurityResponse response = this.interceptor.preHandle(this.request, EndpointId.of("test"));
@ -91,7 +91,7 @@ public class CloudFoundrySecurityInterceptorTests {
} }
@Test @Test
public void preHandleWhenCloudFoundrySecurityServiceIsNullShouldReturnFalse() { void preHandleWhenCloudFoundrySecurityServiceIsNullShouldReturnFalse() {
this.interceptor = new CloudFoundrySecurityInterceptor(this.tokenValidator, null, "my-app-id"); this.interceptor = new CloudFoundrySecurityInterceptor(this.tokenValidator, null, "my-app-id");
this.request.addHeader("Authorization", "bearer " + mockAccessToken()); this.request.addHeader("Authorization", "bearer " + mockAccessToken());
SecurityResponse response = this.interceptor.preHandle(this.request, EndpointId.of("test")); SecurityResponse response = this.interceptor.preHandle(this.request, EndpointId.of("test"));
@ -99,7 +99,7 @@ public class CloudFoundrySecurityInterceptorTests {
} }
@Test @Test
public void preHandleWhenAccessIsNotAllowedShouldReturnFalse() { void preHandleWhenAccessIsNotAllowedShouldReturnFalse() {
String accessToken = mockAccessToken(); String accessToken = mockAccessToken();
this.request.addHeader("Authorization", "bearer " + accessToken); this.request.addHeader("Authorization", "bearer " + accessToken);
given(this.securityService.getAccessLevel(accessToken, "my-app-id")).willReturn(AccessLevel.RESTRICTED); given(this.securityService.getAccessLevel(accessToken, "my-app-id")).willReturn(AccessLevel.RESTRICTED);
@ -108,7 +108,7 @@ public class CloudFoundrySecurityInterceptorTests {
} }
@Test @Test
public void preHandleSuccessfulWithFullAccess() { void preHandleSuccessfulWithFullAccess() {
String accessToken = mockAccessToken(); String accessToken = mockAccessToken();
this.request.addHeader("Authorization", "Bearer " + accessToken); this.request.addHeader("Authorization", "Bearer " + accessToken);
given(this.securityService.getAccessLevel(accessToken, "my-app-id")).willReturn(AccessLevel.FULL); given(this.securityService.getAccessLevel(accessToken, "my-app-id")).willReturn(AccessLevel.FULL);
@ -122,7 +122,7 @@ public class CloudFoundrySecurityInterceptorTests {
} }
@Test @Test
public void preHandleSuccessfulWithRestrictedAccess() { void preHandleSuccessfulWithRestrictedAccess() {
String accessToken = mockAccessToken(); String accessToken = mockAccessToken();
this.request.addHeader("Authorization", "Bearer " + accessToken); this.request.addHeader("Authorization", "Bearer " + accessToken);
given(this.securityService.getAccessLevel(accessToken, "my-app-id")).willReturn(AccessLevel.RESTRICTED); given(this.securityService.getAccessLevel(accessToken, "my-app-id")).willReturn(AccessLevel.RESTRICTED);

View File

@ -47,7 +47,7 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat
* *
* @author Madhura Bhave * @author Madhura Bhave
*/ */
public class CloudFoundrySecurityServiceTests { class CloudFoundrySecurityServiceTests {
private static final String CLOUD_CONTROLLER = "https://my-cloud-controller.com"; private static final String CLOUD_CONTROLLER = "https://my-cloud-controller.com";
@ -68,7 +68,7 @@ public class CloudFoundrySecurityServiceTests {
} }
@Test @Test
public void skipSslValidationWhenTrue() { void skipSslValidationWhenTrue() {
RestTemplateBuilder builder = new RestTemplateBuilder(); RestTemplateBuilder builder = new RestTemplateBuilder();
this.securityService = new CloudFoundrySecurityService(builder, CLOUD_CONTROLLER, true); this.securityService = new CloudFoundrySecurityService(builder, CLOUD_CONTROLLER, true);
RestTemplate restTemplate = (RestTemplate) ReflectionTestUtils.getField(this.securityService, "restTemplate"); RestTemplate restTemplate = (RestTemplate) ReflectionTestUtils.getField(this.securityService, "restTemplate");
@ -76,7 +76,7 @@ public class CloudFoundrySecurityServiceTests {
} }
@Test @Test
public void doNotskipSslValidationWhenFalse() { void doNotskipSslValidationWhenFalse() {
RestTemplateBuilder builder = new RestTemplateBuilder(); RestTemplateBuilder builder = new RestTemplateBuilder();
this.securityService = new CloudFoundrySecurityService(builder, CLOUD_CONTROLLER, false); this.securityService = new CloudFoundrySecurityService(builder, CLOUD_CONTROLLER, false);
RestTemplate restTemplate = (RestTemplate) ReflectionTestUtils.getField(this.securityService, "restTemplate"); RestTemplate restTemplate = (RestTemplate) ReflectionTestUtils.getField(this.securityService, "restTemplate");
@ -84,7 +84,7 @@ public class CloudFoundrySecurityServiceTests {
} }
@Test @Test
public void getAccessLevelWhenSpaceDeveloperShouldReturnFull() { void getAccessLevelWhenSpaceDeveloperShouldReturnFull() {
String responseBody = "{\"read_sensitive_data\": true,\"read_basic_data\": true}"; String responseBody = "{\"read_sensitive_data\": true,\"read_basic_data\": true}";
this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS)) this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS))
.andExpect(header("Authorization", "bearer my-access-token")) .andExpect(header("Authorization", "bearer my-access-token"))
@ -95,7 +95,7 @@ public class CloudFoundrySecurityServiceTests {
} }
@Test @Test
public void getAccessLevelWhenNotSpaceDeveloperShouldReturnRestricted() { void getAccessLevelWhenNotSpaceDeveloperShouldReturnRestricted() {
String responseBody = "{\"read_sensitive_data\": false,\"read_basic_data\": true}"; String responseBody = "{\"read_sensitive_data\": false,\"read_basic_data\": true}";
this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS)) this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS))
.andExpect(header("Authorization", "bearer my-access-token")) .andExpect(header("Authorization", "bearer my-access-token"))
@ -106,7 +106,7 @@ public class CloudFoundrySecurityServiceTests {
} }
@Test @Test
public void getAccessLevelWhenTokenIsNotValidShouldThrowException() { void getAccessLevelWhenTokenIsNotValidShouldThrowException() {
this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS)) this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS))
.andExpect(header("Authorization", "bearer my-access-token")).andRespond(withUnauthorizedRequest()); .andExpect(header("Authorization", "bearer my-access-token")).andRespond(withUnauthorizedRequest());
assertThatExceptionOfType(CloudFoundryAuthorizationException.class) assertThatExceptionOfType(CloudFoundryAuthorizationException.class)
@ -115,7 +115,7 @@ public class CloudFoundrySecurityServiceTests {
} }
@Test @Test
public void getAccessLevelWhenForbiddenShouldThrowException() { void getAccessLevelWhenForbiddenShouldThrowException() {
this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS)) this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS))
.andExpect(header("Authorization", "bearer my-access-token")) .andExpect(header("Authorization", "bearer my-access-token"))
.andRespond(withStatus(HttpStatus.FORBIDDEN)); .andRespond(withStatus(HttpStatus.FORBIDDEN));
@ -125,7 +125,7 @@ public class CloudFoundrySecurityServiceTests {
} }
@Test @Test
public void getAccessLevelWhenCloudControllerIsNotReachableThrowsException() { void getAccessLevelWhenCloudControllerIsNotReachableThrowsException() {
this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS)) this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS))
.andExpect(header("Authorization", "bearer my-access-token")).andRespond(withServerError()); .andExpect(header("Authorization", "bearer my-access-token")).andRespond(withServerError());
assertThatExceptionOfType(CloudFoundryAuthorizationException.class) assertThatExceptionOfType(CloudFoundryAuthorizationException.class)
@ -134,7 +134,7 @@ public class CloudFoundrySecurityServiceTests {
} }
@Test @Test
public void fetchTokenKeysWhenSuccessfulShouldReturnListOfKeysFromUAA() { void fetchTokenKeysWhenSuccessfulShouldReturnListOfKeysFromUAA() {
this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")) this.server.expect(requestTo(CLOUD_CONTROLLER + "/info"))
.andRespond(withSuccess("{\"token_endpoint\":\"https://my-uaa.com\"}", MediaType.APPLICATION_JSON)); .andRespond(withSuccess("{\"token_endpoint\":\"https://my-uaa.com\"}", MediaType.APPLICATION_JSON));
String tokenKeyValue = "-----BEGIN PUBLIC KEY-----\n" String tokenKeyValue = "-----BEGIN PUBLIC KEY-----\n"
@ -155,7 +155,7 @@ public class CloudFoundrySecurityServiceTests {
} }
@Test @Test
public void fetchTokenKeysWhenNoKeysReturnedFromUAA() { void fetchTokenKeysWhenNoKeysReturnedFromUAA() {
this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")) this.server.expect(requestTo(CLOUD_CONTROLLER + "/info"))
.andRespond(withSuccess("{\"token_endpoint\":\"" + UAA_URL + "\"}", MediaType.APPLICATION_JSON)); .andRespond(withSuccess("{\"token_endpoint\":\"" + UAA_URL + "\"}", MediaType.APPLICATION_JSON));
String responseBody = "{\"keys\": []}"; String responseBody = "{\"keys\": []}";
@ -167,7 +167,7 @@ public class CloudFoundrySecurityServiceTests {
} }
@Test @Test
public void fetchTokenKeysWhenUnsuccessfulShouldThrowException() { void fetchTokenKeysWhenUnsuccessfulShouldThrowException() {
this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")) this.server.expect(requestTo(CLOUD_CONTROLLER + "/info"))
.andRespond(withSuccess("{\"token_endpoint\":\"" + UAA_URL + "\"}", MediaType.APPLICATION_JSON)); .andRespond(withSuccess("{\"token_endpoint\":\"" + UAA_URL + "\"}", MediaType.APPLICATION_JSON));
this.server.expect(requestTo(UAA_URL + "/token_keys")).andRespond(withServerError()); this.server.expect(requestTo(UAA_URL + "/token_keys")).andRespond(withServerError());
@ -177,7 +177,7 @@ public class CloudFoundrySecurityServiceTests {
} }
@Test @Test
public void getUaaUrlShouldCallCloudControllerInfoOnlyOnce() { void getUaaUrlShouldCallCloudControllerInfoOnlyOnce() {
this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")) this.server.expect(requestTo(CLOUD_CONTROLLER + "/info"))
.andRespond(withSuccess("{\"token_endpoint\":\"" + UAA_URL + "\"}", MediaType.APPLICATION_JSON)); .andRespond(withSuccess("{\"token_endpoint\":\"" + UAA_URL + "\"}", MediaType.APPLICATION_JSON));
String uaaUrl = this.securityService.getUaaUrl(); String uaaUrl = this.securityService.getUaaUrl();
@ -189,7 +189,7 @@ public class CloudFoundrySecurityServiceTests {
} }
@Test @Test
public void getUaaUrlWhenCloudControllerUrlIsNotReachableShouldThrowException() { void getUaaUrlWhenCloudControllerUrlIsNotReachableShouldThrowException() {
this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")).andRespond(withServerError()); this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")).andRespond(withServerError());
assertThatExceptionOfType(CloudFoundryAuthorizationException.class) assertThatExceptionOfType(CloudFoundryAuthorizationException.class)
.isThrownBy(() -> this.securityService.getUaaUrl()) .isThrownBy(() -> this.securityService.getUaaUrl())

View File

@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* Test for {@link SkipSslVerificationHttpRequestFactory}. * Test for {@link SkipSslVerificationHttpRequestFactory}.
*/ */
public class SkipSslVerificationHttpRequestFactoryTests { class SkipSslVerificationHttpRequestFactoryTests {
private WebServer webServer; private WebServer webServer;
@ -49,7 +49,7 @@ public class SkipSslVerificationHttpRequestFactoryTests {
} }
@Test @Test
public void restCallToSelfSignedServerShouldNotThrowSslException() { void restCallToSelfSignedServerShouldNotThrowSslException() {
String httpsUrl = getHttpsUrl(); String httpsUrl = getHttpsUrl();
SkipSslVerificationHttpRequestFactory requestFactory = new SkipSslVerificationHttpRequestFactory(); SkipSslVerificationHttpRequestFactory requestFactory = new SkipSslVerificationHttpRequestFactory();
RestTemplate restTemplate = new RestTemplate(requestFactory); RestTemplate restTemplate = new RestTemplate(requestFactory);

View File

@ -52,7 +52,7 @@ import static org.mockito.Mockito.verify;
* *
* @author Madhura Bhave * @author Madhura Bhave
*/ */
public class TokenValidatorTests { class TokenValidatorTests {
private static final byte[] DOT = ".".getBytes(); private static final byte[] DOT = ".".getBytes();
@ -90,7 +90,7 @@ public class TokenValidatorTests {
} }
@Test @Test
public void validateTokenWhenKidValidationFailsTwiceShouldThrowException() throws Exception { void validateTokenWhenKidValidationFailsTwiceShouldThrowException() throws Exception {
ReflectionTestUtils.setField(this.tokenValidator, "tokenKeys", INVALID_KEYS); ReflectionTestUtils.setField(this.tokenValidator, "tokenKeys", INVALID_KEYS);
given(this.securityService.fetchTokenKeys()).willReturn(INVALID_KEYS); given(this.securityService.fetchTokenKeys()).willReturn(INVALID_KEYS);
String header = "{\"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}"; String header = "{\"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}";
@ -101,7 +101,7 @@ public class TokenValidatorTests {
} }
@Test @Test
public void validateTokenWhenKidValidationSucceedsInTheSecondAttempt() throws Exception { void validateTokenWhenKidValidationSucceedsInTheSecondAttempt() throws Exception {
ReflectionTestUtils.setField(this.tokenValidator, "tokenKeys", INVALID_KEYS); ReflectionTestUtils.setField(this.tokenValidator, "tokenKeys", INVALID_KEYS);
given(this.securityService.fetchTokenKeys()).willReturn(VALID_KEYS); given(this.securityService.fetchTokenKeys()).willReturn(VALID_KEYS);
given(this.securityService.getUaaUrl()).willReturn("http://localhost:8080/uaa"); given(this.securityService.getUaaUrl()).willReturn("http://localhost:8080/uaa");
@ -112,7 +112,7 @@ public class TokenValidatorTests {
} }
@Test @Test
public void validateTokenShouldFetchTokenKeysIfNull() throws Exception { void validateTokenShouldFetchTokenKeysIfNull() throws Exception {
given(this.securityService.fetchTokenKeys()).willReturn(VALID_KEYS); given(this.securityService.fetchTokenKeys()).willReturn(VALID_KEYS);
given(this.securityService.getUaaUrl()).willReturn("http://localhost:8080/uaa"); given(this.securityService.getUaaUrl()).willReturn("http://localhost:8080/uaa");
String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}"; String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}";
@ -122,7 +122,7 @@ public class TokenValidatorTests {
} }
@Test @Test
public void validateTokenWhenValidShouldNotFetchTokenKeys() throws Exception { void validateTokenWhenValidShouldNotFetchTokenKeys() throws Exception {
ReflectionTestUtils.setField(this.tokenValidator, "tokenKeys", VALID_KEYS); ReflectionTestUtils.setField(this.tokenValidator, "tokenKeys", VALID_KEYS);
given(this.securityService.getUaaUrl()).willReturn("http://localhost:8080/uaa"); given(this.securityService.getUaaUrl()).willReturn("http://localhost:8080/uaa");
String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}"; String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}";
@ -132,7 +132,7 @@ public class TokenValidatorTests {
} }
@Test @Test
public void validateTokenWhenSignatureInvalidShouldThrowException() throws Exception { void validateTokenWhenSignatureInvalidShouldThrowException() throws Exception {
ReflectionTestUtils.setField(this.tokenValidator, "tokenKeys", ReflectionTestUtils.setField(this.tokenValidator, "tokenKeys",
Collections.singletonMap("valid-key", INVALID_KEY)); Collections.singletonMap("valid-key", INVALID_KEY));
given(this.securityService.getUaaUrl()).willReturn("http://localhost:8080/uaa"); given(this.securityService.getUaaUrl()).willReturn("http://localhost:8080/uaa");
@ -144,7 +144,7 @@ public class TokenValidatorTests {
} }
@Test @Test
public void validateTokenWhenTokenAlgorithmIsNotRS256ShouldThrowException() throws Exception { void validateTokenWhenTokenAlgorithmIsNotRS256ShouldThrowException() throws Exception {
given(this.securityService.fetchTokenKeys()).willReturn(VALID_KEYS); given(this.securityService.fetchTokenKeys()).willReturn(VALID_KEYS);
String header = "{ \"alg\": \"HS256\", \"typ\": \"JWT\"}"; String header = "{ \"alg\": \"HS256\", \"typ\": \"JWT\"}";
String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}";
@ -154,7 +154,7 @@ public class TokenValidatorTests {
} }
@Test @Test
public void validateTokenWhenExpiredShouldThrowException() throws Exception { void validateTokenWhenExpiredShouldThrowException() throws Exception {
given(this.securityService.fetchTokenKeys()).willReturn(VALID_KEYS); given(this.securityService.fetchTokenKeys()).willReturn(VALID_KEYS);
given(this.securityService.fetchTokenKeys()).willReturn(VALID_KEYS); given(this.securityService.fetchTokenKeys()).willReturn(VALID_KEYS);
String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\"}"; String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\"}";
@ -165,7 +165,7 @@ public class TokenValidatorTests {
} }
@Test @Test
public void validateTokenWhenIssuerIsNotValidShouldThrowException() throws Exception { void validateTokenWhenIssuerIsNotValidShouldThrowException() throws Exception {
given(this.securityService.fetchTokenKeys()).willReturn(VALID_KEYS); given(this.securityService.fetchTokenKeys()).willReturn(VALID_KEYS);
given(this.securityService.getUaaUrl()).willReturn("https://other-uaa.com"); given(this.securityService.getUaaUrl()).willReturn("https://other-uaa.com");
String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\", \"scope\": [\"actuator.read\"]}"; String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\", \"scope\": [\"actuator.read\"]}";
@ -176,7 +176,7 @@ public class TokenValidatorTests {
} }
@Test @Test
public void validateTokenWhenAudienceIsNotValidShouldThrowException() throws Exception { void validateTokenWhenAudienceIsNotValidShouldThrowException() throws Exception {
given(this.securityService.fetchTokenKeys()).willReturn(VALID_KEYS); given(this.securityService.fetchTokenKeys()).willReturn(VALID_KEYS);
given(this.securityService.getUaaUrl()).willReturn("http://localhost:8080/uaa"); given(this.securityService.getUaaUrl()).willReturn("http://localhost:8080/uaa");
String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\"}"; String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\"}";

View File

@ -28,24 +28,24 @@ import static org.assertj.core.api.Assertions.assertThat;
* *
* @author Phillip Webb * @author Phillip Webb
*/ */
public class ConditionsReportEndpointAutoConfigurationTests { class ConditionsReportEndpointAutoConfigurationTests {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(ConditionsReportEndpointAutoConfiguration.class)); .withConfiguration(AutoConfigurations.of(ConditionsReportEndpointAutoConfiguration.class));
@Test @Test
public void runShouldHaveEndpointBean() { void runShouldHaveEndpointBean() {
this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=conditions") this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=conditions")
.run((context) -> assertThat(context).hasSingleBean(ConditionsReportEndpoint.class)); .run((context) -> assertThat(context).hasSingleBean(ConditionsReportEndpoint.class));
} }
@Test @Test
public void runWhenNotExposedShouldNotHaveEndpointBean() { void runWhenNotExposedShouldNotHaveEndpointBean() {
this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(ConditionsReportEndpoint.class)); this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(ConditionsReportEndpoint.class));
} }
@Test @Test
public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() {
this.contextRunner.withPropertyValues("management.endpoint.conditions.enabled:false") this.contextRunner.withPropertyValues("management.endpoint.conditions.enabled:false")
.run((context) -> assertThat(context).doesNotHaveBean(ConditionsReportEndpoint.class)); .run((context) -> assertThat(context).doesNotHaveBean(ConditionsReportEndpoint.class));
} }

View File

@ -43,10 +43,10 @@ import static org.mockito.Mockito.mock;
* @author Phillip Webb * @author Phillip Webb
* @author Andy Wilkinson * @author Andy Wilkinson
*/ */
public class ConditionsReportEndpointTests { class ConditionsReportEndpointTests {
@Test @Test
public void invoke() { void invoke() {
new ApplicationContextRunner().withUserConfiguration(Config.class).run((context) -> { new ApplicationContextRunner().withUserConfiguration(Config.class).run((context) -> {
ContextConditionEvaluation report = context.getBean(ConditionsReportEndpoint.class) ContextConditionEvaluation report = context.getBean(ConditionsReportEndpoint.class)
.applicationConditionEvaluation().getContexts().get(context.getId()); .applicationConditionEvaluation().getContexts().get(context.getId());

View File

@ -29,26 +29,26 @@ import static org.assertj.core.api.Assertions.assertThat;
* *
* @author Phillip Webb * @author Phillip Webb
*/ */
public class ShutdownEndpointAutoConfigurationTests { class ShutdownEndpointAutoConfigurationTests {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(ShutdownEndpointAutoConfiguration.class)); .withConfiguration(AutoConfigurations.of(ShutdownEndpointAutoConfiguration.class));
@Test @Test
public void runShouldHaveEndpointBean() { void runShouldHaveEndpointBean() {
this.contextRunner.withPropertyValues("management.endpoint.shutdown.enabled:true") this.contextRunner.withPropertyValues("management.endpoint.shutdown.enabled:true")
.withPropertyValues("management.endpoints.web.exposure.include=shutdown") .withPropertyValues("management.endpoints.web.exposure.include=shutdown")
.run((context) -> assertThat(context).hasSingleBean(ShutdownEndpoint.class)); .run((context) -> assertThat(context).hasSingleBean(ShutdownEndpoint.class));
} }
@Test @Test
public void runWhenNotExposedShouldNotHaveEndpointBean() { void runWhenNotExposedShouldNotHaveEndpointBean() {
this.contextRunner.withPropertyValues("management.endpoint.shutdown.enabled:true") this.contextRunner.withPropertyValues("management.endpoint.shutdown.enabled:true")
.run((context) -> assertThat(context).doesNotHaveBean(ShutdownEndpoint.class)); .run((context) -> assertThat(context).doesNotHaveBean(ShutdownEndpoint.class));
} }
@Test @Test
public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() {
this.contextRunner.withPropertyValues("management.endpoint.shutdown.enabled:false") this.contextRunner.withPropertyValues("management.endpoint.shutdown.enabled:false")
.run((context) -> assertThat(context).doesNotHaveBean(ShutdownEndpoint.class)); .run((context) -> assertThat(context).doesNotHaveBean(ShutdownEndpoint.class));
} }

View File

@ -38,26 +38,26 @@ import static org.assertj.core.api.Assertions.assertThat;
* *
* @author Phillip Webb * @author Phillip Webb
*/ */
public class ConfigurationPropertiesReportEndpointAutoConfigurationTests { class ConfigurationPropertiesReportEndpointAutoConfigurationTests {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(ConfigurationPropertiesReportEndpointAutoConfiguration.class)); .withConfiguration(AutoConfigurations.of(ConfigurationPropertiesReportEndpointAutoConfiguration.class));
@Test @Test
public void runShouldHaveEndpointBean() { void runShouldHaveEndpointBean() {
this.contextRunner.withUserConfiguration(Config.class) this.contextRunner.withUserConfiguration(Config.class)
.withPropertyValues("management.endpoints.web.exposure.include=configprops") .withPropertyValues("management.endpoints.web.exposure.include=configprops")
.run(validateTestProperties("******", "654321")); .run(validateTestProperties("******", "654321"));
} }
@Test @Test
public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() {
this.contextRunner.withPropertyValues("management.endpoint.configprops.enabled:false") this.contextRunner.withPropertyValues("management.endpoint.configprops.enabled:false")
.run((context) -> assertThat(context).doesNotHaveBean(ConfigurationPropertiesReportEndpoint.class)); .run((context) -> assertThat(context).doesNotHaveBean(ConfigurationPropertiesReportEndpoint.class));
} }
@Test @Test
public void keysToSanitizeCanBeConfiguredViaTheEnvironment() { void keysToSanitizeCanBeConfiguredViaTheEnvironment() {
this.contextRunner.withUserConfiguration(Config.class) this.contextRunner.withUserConfiguration(Config.class)
.withPropertyValues("management.endpoint.configprops.keys-to-sanitize: .*pass.*, property") .withPropertyValues("management.endpoint.configprops.keys-to-sanitize: .*pass.*, property")
.withPropertyValues("management.endpoints.web.exposure.include=configprops") .withPropertyValues("management.endpoints.web.exposure.include=configprops")
@ -65,7 +65,7 @@ public class ConfigurationPropertiesReportEndpointAutoConfigurationTests {
} }
@Test @Test
public void runWhenNotExposedShouldNotHaveEndpointBean() { void runWhenNotExposedShouldNotHaveEndpointBean() {
this.contextRunner this.contextRunner
.run((context) -> assertThat(context).doesNotHaveBean(ConfigurationPropertiesReportEndpoint.class)); .run((context) -> assertThat(context).doesNotHaveBean(ConfigurationPropertiesReportEndpoint.class));
} }

View File

@ -34,21 +34,21 @@ import static org.mockito.Mockito.mock;
* @author Phillip Webb * @author Phillip Webb
* @author Stephane Nicoll * @author Stephane Nicoll
*/ */
public class CouchbaseHealthIndicatorAutoConfigurationTests { class CouchbaseHealthIndicatorAutoConfigurationTests {
private ApplicationContextRunner contextRunner = new ApplicationContextRunner() private ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withBean(Cluster.class, () -> mock(Cluster.class)).withConfiguration(AutoConfigurations .withBean(Cluster.class, () -> mock(Cluster.class)).withConfiguration(AutoConfigurations
.of(CouchbaseHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class)); .of(CouchbaseHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class));
@Test @Test
public void runShouldCreateIndicator() { void runShouldCreateIndicator() {
this.contextRunner.run((context) -> assertThat(context).hasSingleBean(CouchbaseHealthIndicator.class) this.contextRunner.run((context) -> assertThat(context).hasSingleBean(CouchbaseHealthIndicator.class)
.doesNotHaveBean(CouchbaseReactiveHealthIndicator.class) .doesNotHaveBean(CouchbaseReactiveHealthIndicator.class)
.doesNotHaveBean(ApplicationHealthIndicator.class)); .doesNotHaveBean(ApplicationHealthIndicator.class));
} }
@Test @Test
public void runWhenDisabledShouldNotCreateIndicator() { void runWhenDisabledShouldNotCreateIndicator() {
this.contextRunner.withPropertyValues("management.health.couchbase.enabled:false") this.contextRunner.withPropertyValues("management.health.couchbase.enabled:false")
.run((context) -> assertThat(context).doesNotHaveBean(CouchbaseHealthIndicator.class) .run((context) -> assertThat(context).doesNotHaveBean(CouchbaseHealthIndicator.class)
.hasSingleBean(ApplicationHealthIndicator.class)); .hasSingleBean(ApplicationHealthIndicator.class));

View File

@ -33,20 +33,20 @@ import static org.mockito.Mockito.mock;
* *
* @author Mikalai Lushchytski * @author Mikalai Lushchytski
*/ */
public class CouchbaseReactiveHealthIndicatorAutoConfigurationTests { class CouchbaseReactiveHealthIndicatorAutoConfigurationTests {
private ApplicationContextRunner contextRunner = new ApplicationContextRunner() private ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withBean(Cluster.class, () -> mock(Cluster.class)).withConfiguration(AutoConfigurations.of( .withBean(Cluster.class, () -> mock(Cluster.class)).withConfiguration(AutoConfigurations.of(
CouchbaseReactiveHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class)); CouchbaseReactiveHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class));
@Test @Test
public void runShouldCreateIndicator() { void runShouldCreateIndicator() {
this.contextRunner.run((context) -> assertThat(context).hasSingleBean(CouchbaseReactiveHealthIndicator.class) this.contextRunner.run((context) -> assertThat(context).hasSingleBean(CouchbaseReactiveHealthIndicator.class)
.doesNotHaveBean(CouchbaseHealthIndicator.class).doesNotHaveBean(ApplicationHealthIndicator.class)); .doesNotHaveBean(CouchbaseHealthIndicator.class).doesNotHaveBean(ApplicationHealthIndicator.class));
} }
@Test @Test
public void runWhenDisabledShouldNotCreateIndicator() { void runWhenDisabledShouldNotCreateIndicator() {
this.contextRunner.withPropertyValues("management.health.couchbase.enabled:false") this.contextRunner.withPropertyValues("management.health.couchbase.enabled:false")
.run((context) -> assertThat(context).doesNotHaveBean(CouchbaseReactiveHealthIndicator.class) .run((context) -> assertThat(context).doesNotHaveBean(CouchbaseReactiveHealthIndicator.class)
.hasSingleBean(ApplicationHealthIndicator.class)); .hasSingleBean(ApplicationHealthIndicator.class));

View File

@ -37,14 +37,14 @@ import static org.mockito.Mockito.mock;
* @author Phillip Webb * @author Phillip Webb
*/ */
@Deprecated @Deprecated
public class ElasticsearchHealthIndicatorAutoConfigurationTests { class ElasticsearchHealthIndicatorAutoConfigurationTests {
private ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration(AutoConfigurations private ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration(AutoConfigurations
.of(ElasticsearchAutoConfiguration.class, ElasticSearchClientHealthIndicatorAutoConfiguration.class, .of(ElasticsearchAutoConfiguration.class, ElasticSearchClientHealthIndicatorAutoConfiguration.class,
ElasticSearchJestHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class)); ElasticSearchJestHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class));
@Test @Test
public void runShouldCreateIndicator() { void runShouldCreateIndicator() {
this.contextRunner.withPropertyValues("spring.data.elasticsearch.cluster-nodes:localhost:0") this.contextRunner.withPropertyValues("spring.data.elasticsearch.cluster-nodes:localhost:0")
.withSystemProperties("es.set.netty.runtime.available.processors=false") .withSystemProperties("es.set.netty.runtime.available.processors=false")
.run((context) -> assertThat(context).hasSingleBean(ElasticsearchHealthIndicator.class) .run((context) -> assertThat(context).hasSingleBean(ElasticsearchHealthIndicator.class)
@ -53,7 +53,7 @@ public class ElasticsearchHealthIndicatorAutoConfigurationTests {
} }
@Test @Test
public void runWhenUsingJestClientShouldCreateIndicator() { void runWhenUsingJestClientShouldCreateIndicator() {
this.contextRunner.withBean(JestClient.class, () -> mock(JestClient.class)) this.contextRunner.withBean(JestClient.class, () -> mock(JestClient.class))
.withSystemProperties("es.set.netty.runtime.available.processors=false") .withSystemProperties("es.set.netty.runtime.available.processors=false")
.run((context) -> assertThat(context).hasSingleBean(ElasticsearchJestHealthIndicator.class) .run((context) -> assertThat(context).hasSingleBean(ElasticsearchJestHealthIndicator.class)
@ -62,7 +62,7 @@ public class ElasticsearchHealthIndicatorAutoConfigurationTests {
} }
@Test @Test
public void runWhenDisabledShouldNotCreateIndicator() { void runWhenDisabledShouldNotCreateIndicator() {
this.contextRunner.withPropertyValues("management.health.elasticsearch.enabled:false") this.contextRunner.withPropertyValues("management.health.elasticsearch.enabled:false")
.run((context) -> assertThat(context).doesNotHaveBean(ElasticsearchHealthIndicator.class) .run((context) -> assertThat(context).doesNotHaveBean(ElasticsearchHealthIndicator.class)
.doesNotHaveBean(ElasticsearchJestHealthIndicator.class) .doesNotHaveBean(ElasticsearchJestHealthIndicator.class)

View File

@ -31,27 +31,27 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Phillip Webb * @author Phillip Webb
*/ */
public class EndpointIdTimeToLivePropertyFunctionTests { class EndpointIdTimeToLivePropertyFunctionTests {
private final MockEnvironment environment = new MockEnvironment(); private final MockEnvironment environment = new MockEnvironment();
private final Function<EndpointId, Long> timeToLive = new EndpointIdTimeToLivePropertyFunction(this.environment); private final Function<EndpointId, Long> timeToLive = new EndpointIdTimeToLivePropertyFunction(this.environment);
@Test @Test
public void defaultConfiguration() { void defaultConfiguration() {
Long result = this.timeToLive.apply(EndpointId.of("test")); Long result = this.timeToLive.apply(EndpointId.of("test"));
assertThat(result).isNull(); assertThat(result).isNull();
} }
@Test @Test
public void userConfiguration() { void userConfiguration() {
this.environment.setProperty("management.endpoint.test.cache.time-to-live", "500"); this.environment.setProperty("management.endpoint.test.cache.time-to-live", "500");
Long result = this.timeToLive.apply(EndpointId.of("test")); Long result = this.timeToLive.apply(EndpointId.of("test"));
assertThat(result).isEqualTo(500L); assertThat(result).isEqualTo(500L);
} }
@Test @Test
public void mixedCaseUserConfiguration() { void mixedCaseUserConfiguration() {
this.environment.setProperty("management.endpoint.another-test.cache.time-to-live", "500"); this.environment.setProperty("management.endpoint.another-test.cache.time-to-live", "500");
Long result = this.timeToLive.apply(EndpointId.of("anotherTest")); Long result = this.timeToLive.apply(EndpointId.of("anotherTest"));
assertThat(result).isEqualTo(500L); assertThat(result).isEqualTo(500L);

View File

@ -36,7 +36,7 @@ import static org.mockito.Mockito.mock;
* *
* @author Phillip Webb * @author Phillip Webb
*/ */
public class ExposeExcludePropertyEndpointFilterTests { class ExposeExcludePropertyEndpointFilterTests {
private ExposeExcludePropertyEndpointFilter<?> filter; private ExposeExcludePropertyEndpointFilter<?> filter;
@ -46,77 +46,77 @@ public class ExposeExcludePropertyEndpointFilterTests {
} }
@Test @Test
public void createWhenEndpointTypeIsNullShouldThrowException() { void createWhenEndpointTypeIsNullShouldThrowException() {
assertThatIllegalArgumentException() assertThatIllegalArgumentException()
.isThrownBy(() -> new ExposeExcludePropertyEndpointFilter<>(null, new MockEnvironment(), "foo")) .isThrownBy(() -> new ExposeExcludePropertyEndpointFilter<>(null, new MockEnvironment(), "foo"))
.withMessageContaining("EndpointType must not be null"); .withMessageContaining("EndpointType must not be null");
} }
@Test @Test
public void createWhenEnvironmentIsNullShouldThrowException() { void createWhenEnvironmentIsNullShouldThrowException() {
assertThatIllegalArgumentException() assertThatIllegalArgumentException()
.isThrownBy(() -> new ExposeExcludePropertyEndpointFilter<>(ExposableEndpoint.class, null, "foo")) .isThrownBy(() -> new ExposeExcludePropertyEndpointFilter<>(ExposableEndpoint.class, null, "foo"))
.withMessageContaining("Environment must not be null"); .withMessageContaining("Environment must not be null");
} }
@Test @Test
public void createWhenPrefixIsNullShouldThrowException() { void createWhenPrefixIsNullShouldThrowException() {
assertThatIllegalArgumentException().isThrownBy( assertThatIllegalArgumentException().isThrownBy(
() -> new ExposeExcludePropertyEndpointFilter<>(ExposableEndpoint.class, new MockEnvironment(), null)) () -> new ExposeExcludePropertyEndpointFilter<>(ExposableEndpoint.class, new MockEnvironment(), null))
.withMessageContaining("Prefix must not be empty"); .withMessageContaining("Prefix must not be empty");
} }
@Test @Test
public void createWhenPrefixIsEmptyShouldThrowException() { void createWhenPrefixIsEmptyShouldThrowException() {
assertThatIllegalArgumentException().isThrownBy( assertThatIllegalArgumentException().isThrownBy(
() -> new ExposeExcludePropertyEndpointFilter<>(ExposableEndpoint.class, new MockEnvironment(), "")) () -> new ExposeExcludePropertyEndpointFilter<>(ExposableEndpoint.class, new MockEnvironment(), ""))
.withMessageContaining("Prefix must not be empty"); .withMessageContaining("Prefix must not be empty");
} }
@Test @Test
public void matchWhenExposeIsEmptyAndExcludeIsEmptyAndInDefaultShouldMatch() { void matchWhenExposeIsEmptyAndExcludeIsEmptyAndInDefaultShouldMatch() {
setupFilter("", ""); setupFilter("", "");
assertThat(match(EndpointId.of("def"))).isTrue(); assertThat(match(EndpointId.of("def"))).isTrue();
} }
@Test @Test
public void matchWhenExposeIsEmptyAndExcludeIsEmptyAndNotInDefaultShouldNotMatch() { void matchWhenExposeIsEmptyAndExcludeIsEmptyAndNotInDefaultShouldNotMatch() {
setupFilter("", ""); setupFilter("", "");
assertThat(match(EndpointId.of("bar"))).isFalse(); assertThat(match(EndpointId.of("bar"))).isFalse();
} }
@Test @Test
public void matchWhenExposeMatchesAndExcludeIsEmptyShouldMatch() { void matchWhenExposeMatchesAndExcludeIsEmptyShouldMatch() {
setupFilter("bar", ""); setupFilter("bar", "");
assertThat(match(EndpointId.of("bar"))).isTrue(); assertThat(match(EndpointId.of("bar"))).isTrue();
} }
@Test @Test
public void matchWhenExposeDoesNotMatchAndExcludeIsEmptyShouldNotMatch() { void matchWhenExposeDoesNotMatchAndExcludeIsEmptyShouldNotMatch() {
setupFilter("bar", ""); setupFilter("bar", "");
assertThat(match(EndpointId.of("baz"))).isFalse(); assertThat(match(EndpointId.of("baz"))).isFalse();
} }
@Test @Test
public void matchWhenExposeMatchesAndExcludeMatchesShouldNotMatch() { void matchWhenExposeMatchesAndExcludeMatchesShouldNotMatch() {
setupFilter("bar,baz", "baz"); setupFilter("bar,baz", "baz");
assertThat(match(EndpointId.of("baz"))).isFalse(); assertThat(match(EndpointId.of("baz"))).isFalse();
} }
@Test @Test
public void matchWhenExposeMatchesAndExcludeDoesNotMatchShouldMatch() { void matchWhenExposeMatchesAndExcludeDoesNotMatchShouldMatch() {
setupFilter("bar,baz", "buz"); setupFilter("bar,baz", "buz");
assertThat(match(EndpointId.of("baz"))).isTrue(); assertThat(match(EndpointId.of("baz"))).isTrue();
} }
@Test @Test
public void matchWhenExposeMatchesWithDifferentCaseShouldMatch() { void matchWhenExposeMatchesWithDifferentCaseShouldMatch() {
setupFilter("bar", ""); setupFilter("bar", "");
assertThat(match(EndpointId.of("bAr"))).isTrue(); assertThat(match(EndpointId.of("bAr"))).isTrue();
} }
@Test @Test
public void matchWhenDiscovererDoesNotMatchShouldMatch() { void matchWhenDiscovererDoesNotMatchShouldMatch() {
MockEnvironment environment = new MockEnvironment(); MockEnvironment environment = new MockEnvironment();
environment.setProperty("foo.include", "bar"); environment.setProperty("foo.include", "bar");
environment.setProperty("foo.exclude", ""); environment.setProperty("foo.exclude", "");
@ -126,7 +126,7 @@ public class ExposeExcludePropertyEndpointFilterTests {
} }
@Test @Test
public void matchWhenIncludeIsAsteriskShouldMatchAll() { void matchWhenIncludeIsAsteriskShouldMatchAll() {
setupFilter("*", "buz"); setupFilter("*", "buz");
assertThat(match(EndpointId.of("bar"))).isTrue(); assertThat(match(EndpointId.of("bar"))).isTrue();
assertThat(match(EndpointId.of("baz"))).isTrue(); assertThat(match(EndpointId.of("baz"))).isTrue();
@ -134,7 +134,7 @@ public class ExposeExcludePropertyEndpointFilterTests {
} }
@Test @Test
public void matchWhenExcludeIsAsteriskShouldMatchNone() { void matchWhenExcludeIsAsteriskShouldMatchNone() {
setupFilter("bar,baz,buz", "*"); setupFilter("bar,baz,buz", "*");
assertThat(match(EndpointId.of("bar"))).isFalse(); assertThat(match(EndpointId.of("bar"))).isFalse();
assertThat(match(EndpointId.of("baz"))).isFalse(); assertThat(match(EndpointId.of("baz"))).isFalse();
@ -142,7 +142,7 @@ public class ExposeExcludePropertyEndpointFilterTests {
} }
@Test @Test
public void matchWhenMixedCaseShouldMatch() { void matchWhenMixedCaseShouldMatch() {
setupFilter("foo-bar", ""); setupFilter("foo-bar", "");
assertThat(match(EndpointId.of("fooBar"))).isTrue(); assertThat(match(EndpointId.of("fooBar"))).isTrue();
} }

View File

@ -16,7 +16,7 @@
package org.springframework.boot.actuate.autoconfigure.endpoint.condition; package org.springframework.boot.actuate.autoconfigure.endpoint.condition;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.actuate.endpoint.EndpointFilter; import org.springframework.boot.actuate.endpoint.EndpointFilter;
import org.springframework.boot.actuate.endpoint.ExposableEndpoint; import org.springframework.boot.actuate.endpoint.ExposableEndpoint;
@ -33,33 +33,33 @@ import static org.assertj.core.api.Assertions.assertThat;
* *
* @author Brian Clozel * @author Brian Clozel
*/ */
public class ConditionalOnAvailableEndpointTests { class ConditionalOnAvailableEndpointTests {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withUserConfiguration(AllEndpointsConfiguration.class); .withUserConfiguration(AllEndpointsConfiguration.class);
@Test @Test
public void outcomeShouldMatchDefaults() { void outcomeShouldMatchDefaults() {
this.contextRunner.run((context) -> assertThat(context).hasBean("info").hasBean("health") this.contextRunner.run((context) -> assertThat(context).hasBean("info").hasBean("health")
.doesNotHaveBean("spring").doesNotHaveBean("test").doesNotHaveBean("shutdown")); .doesNotHaveBean("spring").doesNotHaveBean("test").doesNotHaveBean("shutdown"));
} }
@Test @Test
public void outcomeWithEnabledByDefaultSetToFalseShouldNotMatchAnything() { void outcomeWithEnabledByDefaultSetToFalseShouldNotMatchAnything() {
this.contextRunner.withPropertyValues("management.endpoints.enabled-by-default=false") this.contextRunner.withPropertyValues("management.endpoints.enabled-by-default=false")
.run((context) -> assertThat(context).doesNotHaveBean("info").doesNotHaveBean("health") .run((context) -> assertThat(context).doesNotHaveBean("info").doesNotHaveBean("health")
.doesNotHaveBean("spring").doesNotHaveBean("test").doesNotHaveBean("shutdown")); .doesNotHaveBean("spring").doesNotHaveBean("test").doesNotHaveBean("shutdown"));
} }
@Test @Test
public void outcomeWhenIncludeAllWebShouldMatchEnabledEndpoints() { void outcomeWhenIncludeAllWebShouldMatchEnabledEndpoints() {
this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=*") this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=*")
.run((context) -> assertThat(context).hasBean("info").hasBean("health").hasBean("test") .run((context) -> assertThat(context).hasBean("info").hasBean("health").hasBean("test")
.hasBean("spring").doesNotHaveBean("shutdown")); .hasBean("spring").doesNotHaveBean("shutdown"));
} }
@Test @Test
public void outcomeWhenIncludeAllWebAndDisablingEndpointShouldMatchEnabledEndpoints() { void outcomeWhenIncludeAllWebAndDisablingEndpointShouldMatchEnabledEndpoints() {
this.contextRunner this.contextRunner
.withPropertyValues("management.endpoints.web.exposure.include=*", .withPropertyValues("management.endpoints.web.exposure.include=*",
"management.endpoint.test.enabled=false", "management.endpoint.health.enabled=false") "management.endpoint.test.enabled=false", "management.endpoint.health.enabled=false")
@ -68,7 +68,7 @@ public class ConditionalOnAvailableEndpointTests {
} }
@Test @Test
public void outcomeWhenIncludeAllWebAndEnablingEndpointDisabledByDefaultShouldMatchAll() { void outcomeWhenIncludeAllWebAndEnablingEndpointDisabledByDefaultShouldMatchAll() {
this.contextRunner this.contextRunner
.withPropertyValues("management.endpoints.web.exposure.include=*", .withPropertyValues("management.endpoints.web.exposure.include=*",
"management.endpoint.shutdown.enabled=true") "management.endpoint.shutdown.enabled=true")
@ -77,21 +77,21 @@ public class ConditionalOnAvailableEndpointTests {
} }
@Test @Test
public void outcomeWhenIncludeAllJmxButJmxDisabledShouldMatchDefaults() { void outcomeWhenIncludeAllJmxButJmxDisabledShouldMatchDefaults() {
this.contextRunner.withPropertyValues("management.endpoints.jmx.exposure.include=*") this.contextRunner.withPropertyValues("management.endpoints.jmx.exposure.include=*")
.run((context) -> assertThat(context).hasBean("info").hasBean("health").doesNotHaveBean("spring") .run((context) -> assertThat(context).hasBean("info").hasBean("health").doesNotHaveBean("spring")
.doesNotHaveBean("test").doesNotHaveBean("shutdown")); .doesNotHaveBean("test").doesNotHaveBean("shutdown"));
} }
@Test @Test
public void outcomeWhenIncludeAllJmxAndJmxEnabledShouldMatchEnabledEndpoints() { void outcomeWhenIncludeAllJmxAndJmxEnabledShouldMatchEnabledEndpoints() {
this.contextRunner.withPropertyValues("management.endpoints.jmx.exposure.include=*", "spring.jmx.enabled=true") this.contextRunner.withPropertyValues("management.endpoints.jmx.exposure.include=*", "spring.jmx.enabled=true")
.run((context) -> assertThat(context).hasBean("info").hasBean("health").hasBean("test") .run((context) -> assertThat(context).hasBean("info").hasBean("health").hasBean("test")
.hasBean("spring").doesNotHaveBean("shutdown")); .hasBean("spring").doesNotHaveBean("shutdown"));
} }
@Test @Test
public void outcomeWhenIncludeAllJmxAndJmxEnabledAndEnablingEndpointDisabledByDefaultShouldMatchAll() { void outcomeWhenIncludeAllJmxAndJmxEnabledAndEnablingEndpointDisabledByDefaultShouldMatchAll() {
this.contextRunner this.contextRunner
.withPropertyValues("management.endpoints.jmx.exposure.include=*", "spring.jmx.enabled=true", .withPropertyValues("management.endpoints.jmx.exposure.include=*", "spring.jmx.enabled=true",
"management.endpoint.shutdown.enabled=true") "management.endpoint.shutdown.enabled=true")
@ -100,7 +100,7 @@ public class ConditionalOnAvailableEndpointTests {
} }
@Test @Test
public void outcomeWhenIncludeAllWebAndExcludeMatchesShouldNotMatch() { void outcomeWhenIncludeAllWebAndExcludeMatchesShouldNotMatch() {
this.contextRunner this.contextRunner
.withPropertyValues("management.endpoints.web.exposure.include=*", .withPropertyValues("management.endpoints.web.exposure.include=*",
"management.endpoints.web.exposure.exclude=spring,info") "management.endpoints.web.exposure.exclude=spring,info")
@ -109,7 +109,7 @@ public class ConditionalOnAvailableEndpointTests {
} }
@Test @Test
public void outcomeWhenIncludeMatchesAndExcludeMatchesShouldNotMatch() { void outcomeWhenIncludeMatchesAndExcludeMatchesShouldNotMatch() {
this.contextRunner this.contextRunner
.withPropertyValues("management.endpoints.web.exposure.include=info,health,spring,test", .withPropertyValues("management.endpoints.web.exposure.include=info,health,spring,test",
"management.endpoints.web.exposure.exclude=spring,info") "management.endpoints.web.exposure.exclude=spring,info")
@ -118,21 +118,21 @@ public class ConditionalOnAvailableEndpointTests {
} }
@Test @Test
public void outcomeWhenIncludeMatchesShouldMatchEnabledEndpoints() { void outcomeWhenIncludeMatchesShouldMatchEnabledEndpoints() {
this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=spring") this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=spring")
.run((context) -> assertThat(context).hasBean("spring").doesNotHaveBean("health") .run((context) -> assertThat(context).hasBean("spring").doesNotHaveBean("health")
.doesNotHaveBean("info").doesNotHaveBean("test").doesNotHaveBean("shutdown")); .doesNotHaveBean("info").doesNotHaveBean("test").doesNotHaveBean("shutdown"));
} }
@Test @Test
public void outcomeWhenIncludeMatchOnDisabledEndpointShouldNotMatch() { void outcomeWhenIncludeMatchOnDisabledEndpointShouldNotMatch() {
this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=shutdown") this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=shutdown")
.run((context) -> assertThat(context).doesNotHaveBean("spring").doesNotHaveBean("health") .run((context) -> assertThat(context).doesNotHaveBean("spring").doesNotHaveBean("health")
.doesNotHaveBean("info").doesNotHaveBean("test").doesNotHaveBean("shutdown")); .doesNotHaveBean("info").doesNotHaveBean("test").doesNotHaveBean("shutdown"));
} }
@Test @Test
public void outcomeWhenIncludeMatchOnEnabledEndpointShouldNotMatch() { void outcomeWhenIncludeMatchOnEnabledEndpointShouldNotMatch() {
this.contextRunner this.contextRunner
.withPropertyValues("management.endpoints.web.exposure.include=shutdown", .withPropertyValues("management.endpoints.web.exposure.include=shutdown",
"management.endpoint.shutdown.enabled=true") "management.endpoint.shutdown.enabled=true")
@ -141,14 +141,14 @@ public class ConditionalOnAvailableEndpointTests {
} }
@Test @Test
public void outcomeWhenIncludeMatchesWithCaseShouldMatch() { void outcomeWhenIncludeMatchesWithCaseShouldMatch() {
this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=sPRing") this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=sPRing")
.run((context) -> assertThat(context).hasBean("spring").doesNotHaveBean("health") .run((context) -> assertThat(context).hasBean("spring").doesNotHaveBean("health")
.doesNotHaveBean("info").doesNotHaveBean("test").doesNotHaveBean("shutdown")); .doesNotHaveBean("info").doesNotHaveBean("test").doesNotHaveBean("shutdown"));
} }
@Test @Test
public void outcomeWhenIncludeMatchesAndExcludeAllShouldNotMatch() { void outcomeWhenIncludeMatchesAndExcludeAllShouldNotMatch() {
this.contextRunner this.contextRunner
.withPropertyValues("management.endpoints.web.exposure.include=info,health,spring,test", .withPropertyValues("management.endpoints.web.exposure.include=info,health,spring,test",
"management.endpoints.web.exposure.exclude=*") "management.endpoints.web.exposure.exclude=*")
@ -157,7 +157,7 @@ public class ConditionalOnAvailableEndpointTests {
} }
@Test @Test
public void outcomeWhenIncludeMatchesShouldMatchWithExtensionsAndComponents() { void outcomeWhenIncludeMatchesShouldMatchWithExtensionsAndComponents() {
this.contextRunner.withUserConfiguration(ComponentEnabledIfEndpointIsExposedConfiguration.class) this.contextRunner.withUserConfiguration(ComponentEnabledIfEndpointIsExposedConfiguration.class)
.withPropertyValues("management.endpoints.web.exposure.include=spring") .withPropertyValues("management.endpoints.web.exposure.include=spring")
.run((context) -> assertThat(context).hasBean("spring").hasBean("springComponent") .run((context) -> assertThat(context).hasBean("spring").hasBean("springComponent")
@ -166,7 +166,7 @@ public class ConditionalOnAvailableEndpointTests {
} }
@Test @Test
public void outcomeWithNoEndpointReferenceShouldFail() { void outcomeWithNoEndpointReferenceShouldFail() {
this.contextRunner.withUserConfiguration(ComponentWithNoEndpointReferenceConfiguration.class) this.contextRunner.withUserConfiguration(ComponentWithNoEndpointReferenceConfiguration.class)
.withPropertyValues("management.endpoints.web.exposure.include=*").run((context) -> { .withPropertyValues("management.endpoints.web.exposure.include=*").run((context) -> {
assertThat(context).hasFailed(); assertThat(context).hasFailed();
@ -177,7 +177,7 @@ public class ConditionalOnAvailableEndpointTests {
} }
@Test @Test
public void outcomeOnCloudFoundryShouldMatchAll() { void outcomeOnCloudFoundryShouldMatchAll() {
this.contextRunner.withPropertyValues("VCAP_APPLICATION:---").run( this.contextRunner.withPropertyValues("VCAP_APPLICATION:---").run(
(context) -> assertThat(context).hasBean("info").hasBean("health").hasBean("spring").hasBean("test")); (context) -> assertThat(context).hasBean("info").hasBean("health").hasBean("spring").hasBean("test"));
} }

View File

@ -36,64 +36,64 @@ import static org.assertj.core.api.Assertions.assertThat;
*/ */
@Deprecated @Deprecated
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public class ConditionalOnEnabledEndpointTests { class ConditionalOnEnabledEndpointTests {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner(); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner();
@Test @Test
public void outcomeWhenEndpointEnabledPropertyIsTrueShouldMatch() { void outcomeWhenEndpointEnabledPropertyIsTrueShouldMatch() {
this.contextRunner.withPropertyValues("management.endpoint.foo.enabled=true") this.contextRunner.withPropertyValues("management.endpoint.foo.enabled=true")
.withUserConfiguration(FooEndpointEnabledByDefaultFalseConfiguration.class) .withUserConfiguration(FooEndpointEnabledByDefaultFalseConfiguration.class)
.run((context) -> assertThat(context).hasBean("foo")); .run((context) -> assertThat(context).hasBean("foo"));
} }
@Test @Test
public void outcomeWhenEndpointEnabledPropertyIsFalseShouldNotMatch() { void outcomeWhenEndpointEnabledPropertyIsFalseShouldNotMatch() {
this.contextRunner.withPropertyValues("management.endpoint.foo.enabled=false") this.contextRunner.withPropertyValues("management.endpoint.foo.enabled=false")
.withUserConfiguration(FooEndpointEnabledByDefaultTrueConfiguration.class) .withUserConfiguration(FooEndpointEnabledByDefaultTrueConfiguration.class)
.run((context) -> assertThat(context).doesNotHaveBean("foo")); .run((context) -> assertThat(context).doesNotHaveBean("foo"));
} }
@Test @Test
public void outcomeWhenNoEndpointPropertyAndUserDefinedDefaultIsTrueShouldMatch() { void outcomeWhenNoEndpointPropertyAndUserDefinedDefaultIsTrueShouldMatch() {
this.contextRunner.withPropertyValues("management.endpoints.enabled-by-default=true") this.contextRunner.withPropertyValues("management.endpoints.enabled-by-default=true")
.withUserConfiguration(FooEndpointEnabledByDefaultFalseConfiguration.class) .withUserConfiguration(FooEndpointEnabledByDefaultFalseConfiguration.class)
.run((context) -> assertThat(context).hasBean("foo")); .run((context) -> assertThat(context).hasBean("foo"));
} }
@Test @Test
public void outcomeWhenNoEndpointPropertyAndUserDefinedDefaultIsFalseShouldNotMatch() { void outcomeWhenNoEndpointPropertyAndUserDefinedDefaultIsFalseShouldNotMatch() {
this.contextRunner.withPropertyValues("management.endpoints.enabled-by-default=false") this.contextRunner.withPropertyValues("management.endpoints.enabled-by-default=false")
.withUserConfiguration(FooEndpointEnabledByDefaultTrueConfiguration.class) .withUserConfiguration(FooEndpointEnabledByDefaultTrueConfiguration.class)
.run((context) -> assertThat(context).doesNotHaveBean("foo")); .run((context) -> assertThat(context).doesNotHaveBean("foo"));
} }
@Test @Test
public void outcomeWhenNoPropertiesAndAnnotationIsEnabledByDefaultShouldMatch() { void outcomeWhenNoPropertiesAndAnnotationIsEnabledByDefaultShouldMatch() {
this.contextRunner.withUserConfiguration(FooEndpointEnabledByDefaultTrueConfiguration.class) this.contextRunner.withUserConfiguration(FooEndpointEnabledByDefaultTrueConfiguration.class)
.run((context) -> assertThat(context).hasBean("foo")); .run((context) -> assertThat(context).hasBean("foo"));
} }
@Test @Test
public void outcomeWhenNoPropertiesAndAnnotationIsNotEnabledByDefaultShouldNotMatch() { void outcomeWhenNoPropertiesAndAnnotationIsNotEnabledByDefaultShouldNotMatch() {
this.contextRunner.withUserConfiguration(FooEndpointEnabledByDefaultFalseConfiguration.class) this.contextRunner.withUserConfiguration(FooEndpointEnabledByDefaultFalseConfiguration.class)
.run((context) -> assertThat(context).doesNotHaveBean("foo")); .run((context) -> assertThat(context).doesNotHaveBean("foo"));
} }
@Test @Test
public void outcomeWhenNoPropertiesAndExtensionAnnotationIsEnabledByDefaultShouldMatch() { void outcomeWhenNoPropertiesAndExtensionAnnotationIsEnabledByDefaultShouldMatch() {
this.contextRunner.withUserConfiguration(FooEndpointAndExtensionEnabledByDefaultTrueConfiguration.class) this.contextRunner.withUserConfiguration(FooEndpointAndExtensionEnabledByDefaultTrueConfiguration.class)
.run((context) -> assertThat(context).hasBean("foo").hasBean("fooExt")); .run((context) -> assertThat(context).hasBean("foo").hasBean("fooExt"));
} }
@Test @Test
public void outcomeWhenNoPropertiesAndExtensionAnnotationIsNotEnabledByDefaultShouldNotMatch() { void outcomeWhenNoPropertiesAndExtensionAnnotationIsNotEnabledByDefaultShouldNotMatch() {
this.contextRunner.withUserConfiguration(FooEndpointAndExtensionEnabledByDefaultFalseConfiguration.class) this.contextRunner.withUserConfiguration(FooEndpointAndExtensionEnabledByDefaultFalseConfiguration.class)
.run((context) -> assertThat(context).doesNotHaveBean("foo").doesNotHaveBean("fooExt")); .run((context) -> assertThat(context).doesNotHaveBean("foo").doesNotHaveBean("fooExt"));
} }
@Test @Test
public void outcomeWithReferenceWhenNoPropertiesShouldMatch() { void outcomeWithReferenceWhenNoPropertiesShouldMatch() {
this.contextRunner this.contextRunner
.withUserConfiguration(FooEndpointEnabledByDefaultTrue.class, .withUserConfiguration(FooEndpointEnabledByDefaultTrue.class,
ComponentEnabledIfEndpointIsEnabledConfiguration.class) ComponentEnabledIfEndpointIsEnabledConfiguration.class)
@ -101,7 +101,7 @@ public class ConditionalOnEnabledEndpointTests {
} }
@Test @Test
public void outcomeWithReferenceWhenEndpointEnabledPropertyIsTrueShouldMatch() { void outcomeWithReferenceWhenEndpointEnabledPropertyIsTrueShouldMatch() {
this.contextRunner.withPropertyValues("management.endpoint.foo.enabled=true") this.contextRunner.withPropertyValues("management.endpoint.foo.enabled=true")
.withUserConfiguration(FooEndpointEnabledByDefaultTrue.class, .withUserConfiguration(FooEndpointEnabledByDefaultTrue.class,
ComponentEnabledIfEndpointIsEnabledConfiguration.class) ComponentEnabledIfEndpointIsEnabledConfiguration.class)
@ -109,7 +109,7 @@ public class ConditionalOnEnabledEndpointTests {
} }
@Test @Test
public void outcomeWithReferenceWhenEndpointEnabledPropertyIsFalseShouldNotMatch() { void outcomeWithReferenceWhenEndpointEnabledPropertyIsFalseShouldNotMatch() {
this.contextRunner.withPropertyValues("management.endpoint.foo.enabled=false") this.contextRunner.withPropertyValues("management.endpoint.foo.enabled=false")
.withUserConfiguration(FooEndpointEnabledByDefaultTrue.class, .withUserConfiguration(FooEndpointEnabledByDefaultTrue.class,
ComponentEnabledIfEndpointIsEnabledConfiguration.class) ComponentEnabledIfEndpointIsEnabledConfiguration.class)
@ -117,7 +117,7 @@ public class ConditionalOnEnabledEndpointTests {
} }
@Test @Test
public void outcomeWithNoReferenceShouldFail() { void outcomeWithNoReferenceShouldFail() {
this.contextRunner.withUserConfiguration(ComponentWithNoEndpointReferenceConfiguration.class).run((context) -> { this.contextRunner.withUserConfiguration(ComponentWithNoEndpointReferenceConfiguration.class).run((context) -> {
assertThat(context).hasFailed(); assertThat(context).hasFailed();
assertThat(context.getStartupFailure().getCause().getMessage()) assertThat(context.getStartupFailure().getCause().getMessage())
@ -127,14 +127,14 @@ public class ConditionalOnEnabledEndpointTests {
} }
@Test @Test
public void outcomeWhenEndpointEnabledPropertyIsTrueAndMixedCaseShouldMatch() { void outcomeWhenEndpointEnabledPropertyIsTrueAndMixedCaseShouldMatch() {
this.contextRunner.withPropertyValues("management.endpoint.foo-bar.enabled=true") this.contextRunner.withPropertyValues("management.endpoint.foo-bar.enabled=true")
.withUserConfiguration(FooBarEndpointEnabledByDefaultFalseConfiguration.class) .withUserConfiguration(FooBarEndpointEnabledByDefaultFalseConfiguration.class)
.run((context) -> assertThat(context).hasBean("fooBar")); .run((context) -> assertThat(context).hasBean("fooBar"));
} }
@Test @Test
public void outcomeWhenEndpointEnabledPropertyIsFalseOnClassShouldNotMatch() { void outcomeWhenEndpointEnabledPropertyIsFalseOnClassShouldNotMatch() {
this.contextRunner.withPropertyValues("management.endpoint.foo.enabled=false") this.contextRunner.withPropertyValues("management.endpoint.foo.enabled=false")
.withUserConfiguration(FooEndpointEnabledByDefaultTrueOnConfigurationConfiguration.class) .withUserConfiguration(FooEndpointEnabledByDefaultTrueOnConfigurationConfiguration.class)
.run((context) -> assertThat(context).doesNotHaveBean("foo")); .run((context) -> assertThat(context).doesNotHaveBean("foo"));

View File

@ -38,7 +38,7 @@ import static org.mockito.Mockito.mock;
* *
* @author Stephane Nicoll * @author Stephane Nicoll
*/ */
public class DefaultEndpointObjectNameFactoryTests { class DefaultEndpointObjectNameFactoryTests {
private final MockEnvironment environment = new MockEnvironment(); private final MockEnvironment environment = new MockEnvironment();
@ -49,26 +49,26 @@ public class DefaultEndpointObjectNameFactoryTests {
private String contextId; private String contextId;
@Test @Test
public void generateObjectName() { void generateObjectName() {
ObjectName objectName = generateObjectName(endpoint(EndpointId.of("test"))); ObjectName objectName = generateObjectName(endpoint(EndpointId.of("test")));
assertThat(objectName.toString()).isEqualTo("org.springframework.boot:type=Endpoint,name=Test"); assertThat(objectName.toString()).isEqualTo("org.springframework.boot:type=Endpoint,name=Test");
} }
@Test @Test
public void generateObjectNameWithCapitalizedId() { void generateObjectNameWithCapitalizedId() {
ObjectName objectName = generateObjectName(endpoint(EndpointId.of("testEndpoint"))); ObjectName objectName = generateObjectName(endpoint(EndpointId.of("testEndpoint")));
assertThat(objectName.toString()).isEqualTo("org.springframework.boot:type=Endpoint,name=TestEndpoint"); assertThat(objectName.toString()).isEqualTo("org.springframework.boot:type=Endpoint,name=TestEndpoint");
} }
@Test @Test
public void generateObjectNameWithCustomDomain() { void generateObjectNameWithCustomDomain() {
this.properties.setDomain("com.example.acme"); this.properties.setDomain("com.example.acme");
ObjectName objectName = generateObjectName(endpoint(EndpointId.of("test"))); ObjectName objectName = generateObjectName(endpoint(EndpointId.of("test")));
assertThat(objectName.toString()).isEqualTo("com.example.acme:type=Endpoint,name=Test"); assertThat(objectName.toString()).isEqualTo("com.example.acme:type=Endpoint,name=Test");
} }
@Test @Test
public void generateObjectNameWithUniqueNames() { void generateObjectNameWithUniqueNames() {
this.environment.setProperty("spring.jmx.unique-names", "true"); this.environment.setProperty("spring.jmx.unique-names", "true");
assertUniqueObjectName(); assertUniqueObjectName();
} }
@ -81,7 +81,7 @@ public class DefaultEndpointObjectNameFactoryTests {
} }
@Test @Test
public void generateObjectNameWithStaticNames() { void generateObjectNameWithStaticNames() {
this.properties.getStaticNames().setProperty("counter", "42"); this.properties.getStaticNames().setProperty("counter", "42");
this.properties.getStaticNames().setProperty("foo", "bar"); this.properties.getStaticNames().setProperty("foo", "bar");
ObjectName objectName = generateObjectName(endpoint(EndpointId.of("test"))); ObjectName objectName = generateObjectName(endpoint(EndpointId.of("test")));
@ -91,7 +91,7 @@ public class DefaultEndpointObjectNameFactoryTests {
} }
@Test @Test
public void generateObjectNameWithDuplicate() throws MalformedObjectNameException { void generateObjectNameWithDuplicate() throws MalformedObjectNameException {
this.contextId = "testContext"; this.contextId = "testContext";
given(this.mBeanServer.queryNames(new ObjectName("org.springframework.boot:type=Endpoint,name=Test,*"), null)) given(this.mBeanServer.queryNames(new ObjectName("org.springframework.boot:type=Endpoint,name=Test,*"), null))
.willReturn(Collections.singleton(new ObjectName("org.springframework.boot:type=Endpoint,name=Test"))); .willReturn(Collections.singleton(new ObjectName("org.springframework.boot:type=Endpoint,name=Test")));

View File

@ -30,16 +30,16 @@ import static org.assertj.core.api.Assertions.assertThat;
* *
* @author Stephane Nicoll * @author Stephane Nicoll
*/ */
public class MappingWebEndpointPathMapperTests { class MappingWebEndpointPathMapperTests {
@Test @Test
public void defaultConfiguration() { void defaultConfiguration() {
MappingWebEndpointPathMapper mapper = new MappingWebEndpointPathMapper(Collections.emptyMap()); MappingWebEndpointPathMapper mapper = new MappingWebEndpointPathMapper(Collections.emptyMap());
assertThat(PathMapper.getRootPath(Collections.singletonList(mapper), EndpointId.of("test"))).isEqualTo("test"); assertThat(PathMapper.getRootPath(Collections.singletonList(mapper), EndpointId.of("test"))).isEqualTo("test");
} }
@Test @Test
public void userConfiguration() { void userConfiguration() {
MappingWebEndpointPathMapper mapper = new MappingWebEndpointPathMapper( MappingWebEndpointPathMapper mapper = new MappingWebEndpointPathMapper(
Collections.singletonMap("test", "custom")); Collections.singletonMap("test", "custom"));
assertThat(PathMapper.getRootPath(Collections.singletonList(mapper), EndpointId.of("test"))) assertThat(PathMapper.getRootPath(Collections.singletonList(mapper), EndpointId.of("test")))
@ -47,14 +47,14 @@ public class MappingWebEndpointPathMapperTests {
} }
@Test @Test
public void mixedCaseDefaultConfiguration() { void mixedCaseDefaultConfiguration() {
MappingWebEndpointPathMapper mapper = new MappingWebEndpointPathMapper(Collections.emptyMap()); MappingWebEndpointPathMapper mapper = new MappingWebEndpointPathMapper(Collections.emptyMap());
assertThat(PathMapper.getRootPath(Collections.singletonList(mapper), EndpointId.of("testEndpoint"))) assertThat(PathMapper.getRootPath(Collections.singletonList(mapper), EndpointId.of("testEndpoint")))
.isEqualTo("testEndpoint"); .isEqualTo("testEndpoint");
} }
@Test @Test
public void mixedCaseUserConfiguration() { void mixedCaseUserConfiguration() {
MappingWebEndpointPathMapper mapper = new MappingWebEndpointPathMapper( MappingWebEndpointPathMapper mapper = new MappingWebEndpointPathMapper(
Collections.singletonMap("test-endpoint", "custom")); Collections.singletonMap("test-endpoint", "custom"));
assertThat(PathMapper.getRootPath(Collections.singletonList(mapper), EndpointId.of("testEndpoint"))) assertThat(PathMapper.getRootPath(Collections.singletonList(mapper), EndpointId.of("testEndpoint")))

View File

@ -42,13 +42,13 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Phillip Webb * @author Phillip Webb
* @author Madhura Bhave * @author Madhura Bhave
*/ */
public class ServletEndpointManagementContextConfigurationTests { class ServletEndpointManagementContextConfigurationTests {
private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withUserConfiguration(TestConfig.class); .withUserConfiguration(TestConfig.class);
@Test @Test
public void contextShouldContainServletEndpointRegistrar() { void contextShouldContainServletEndpointRegistrar() {
FilteredClassLoader classLoader = new FilteredClassLoader(ResourceConfig.class); FilteredClassLoader classLoader = new FilteredClassLoader(ResourceConfig.class);
this.contextRunner.withClassLoader(classLoader).run((context) -> { this.contextRunner.withClassLoader(classLoader).run((context) -> {
assertThat(context).hasSingleBean(ServletEndpointRegistrar.class); assertThat(context).hasSingleBean(ServletEndpointRegistrar.class);
@ -58,7 +58,7 @@ public class ServletEndpointManagementContextConfigurationTests {
} }
@Test @Test
public void contextWhenJerseyShouldContainServletEndpointRegistrar() { void contextWhenJerseyShouldContainServletEndpointRegistrar() {
FilteredClassLoader classLoader = new FilteredClassLoader(DispatcherServlet.class); FilteredClassLoader classLoader = new FilteredClassLoader(DispatcherServlet.class);
this.contextRunner.withClassLoader(classLoader).run((context) -> { this.contextRunner.withClassLoader(classLoader).run((context) -> {
assertThat(context).hasSingleBean(ServletEndpointRegistrar.class); assertThat(context).hasSingleBean(ServletEndpointRegistrar.class);
@ -68,7 +68,7 @@ public class ServletEndpointManagementContextConfigurationTests {
} }
@Test @Test
public void contextWhenNoServletBasedShouldNotContainServletEndpointRegistrar() { void contextWhenNoServletBasedShouldNotContainServletEndpointRegistrar() {
new ApplicationContextRunner().withUserConfiguration(TestConfig.class) new ApplicationContextRunner().withUserConfiguration(TestConfig.class)
.run((context) -> assertThat(context).doesNotHaveBean(ServletEndpointRegistrar.class)); .run((context) -> assertThat(context).doesNotHaveBean(ServletEndpointRegistrar.class));
} }

View File

@ -49,7 +49,7 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Yunkun Huang * @author Yunkun Huang
* @author Phillip Webb * @author Phillip Webb
*/ */
public class WebEndpointAutoConfigurationTests { class WebEndpointAutoConfigurationTests {
private static final AutoConfigurations CONFIGURATIONS = AutoConfigurations.of(EndpointAutoConfiguration.class, private static final AutoConfigurations CONFIGURATIONS = AutoConfigurations.of(EndpointAutoConfiguration.class,
WebEndpointAutoConfiguration.class); WebEndpointAutoConfiguration.class);
@ -58,7 +58,7 @@ public class WebEndpointAutoConfigurationTests {
.withConfiguration(CONFIGURATIONS); .withConfiguration(CONFIGURATIONS);
@Test @Test
public void webApplicationConfiguresEndpointMediaTypes() { void webApplicationConfiguresEndpointMediaTypes() {
this.contextRunner.run((context) -> { this.contextRunner.run((context) -> {
EndpointMediaTypes endpointMediaTypes = context.getBean(EndpointMediaTypes.class); EndpointMediaTypes endpointMediaTypes = context.getBean(EndpointMediaTypes.class);
assertThat(endpointMediaTypes.getConsumed()).containsExactly(ActuatorMediaType.V2_JSON, "application/json"); assertThat(endpointMediaTypes.getConsumed()).containsExactly(ActuatorMediaType.V2_JSON, "application/json");
@ -66,7 +66,7 @@ public class WebEndpointAutoConfigurationTests {
} }
@Test @Test
public void webApplicationConfiguresPathMapper() { void webApplicationConfiguresPathMapper() {
this.contextRunner.withPropertyValues("management.endpoints.web.path-mapping.health=healthcheck") this.contextRunner.withPropertyValues("management.endpoints.web.path-mapping.health=healthcheck")
.run((context) -> { .run((context) -> {
assertThat(context).hasSingleBean(PathMapper.class); assertThat(context).hasSingleBean(PathMapper.class);
@ -76,7 +76,7 @@ public class WebEndpointAutoConfigurationTests {
} }
@Test @Test
public void webApplicationSupportCustomPathMatcher() { void webApplicationSupportCustomPathMatcher() {
this.contextRunner this.contextRunner
.withPropertyValues("management.endpoints.web.exposure.include=*", .withPropertyValues("management.endpoints.web.exposure.include=*",
"management.endpoints.web.path-mapping.testanotherone=foo") "management.endpoints.web.path-mapping.testanotherone=foo")
@ -93,7 +93,7 @@ public class WebEndpointAutoConfigurationTests {
} }
@Test @Test
public void webApplicationConfiguresEndpointDiscoverer() { void webApplicationConfiguresEndpointDiscoverer() {
this.contextRunner.run((context) -> { this.contextRunner.run((context) -> {
assertThat(context).hasSingleBean(ControllerEndpointDiscoverer.class); assertThat(context).hasSingleBean(ControllerEndpointDiscoverer.class);
assertThat(context).hasSingleBean(WebEndpointDiscoverer.class); assertThat(context).hasSingleBean(WebEndpointDiscoverer.class);
@ -101,19 +101,19 @@ public class WebEndpointAutoConfigurationTests {
} }
@Test @Test
public void webApplicationConfiguresExposeExcludePropertyEndpointFilter() { void webApplicationConfiguresExposeExcludePropertyEndpointFilter() {
this.contextRunner this.contextRunner
.run((context) -> assertThat(context).getBeans(ExposeExcludePropertyEndpointFilter.class).containsKeys( .run((context) -> assertThat(context).getBeans(ExposeExcludePropertyEndpointFilter.class).containsKeys(
"webExposeExcludePropertyEndpointFilter", "controllerExposeExcludePropertyEndpointFilter")); "webExposeExcludePropertyEndpointFilter", "controllerExposeExcludePropertyEndpointFilter"));
} }
@Test @Test
public void contextShouldConfigureServletEndpointDiscoverer() { void contextShouldConfigureServletEndpointDiscoverer() {
this.contextRunner.run((context) -> assertThat(context).hasSingleBean(ServletEndpointDiscoverer.class)); this.contextRunner.run((context) -> assertThat(context).hasSingleBean(ServletEndpointDiscoverer.class));
} }
@Test @Test
public void contextWhenNotServletShouldNotConfigureServletEndpointDiscoverer() { void contextWhenNotServletShouldNotConfigureServletEndpointDiscoverer() {
new ApplicationContextRunner().withConfiguration(CONFIGURATIONS) new ApplicationContextRunner().withConfiguration(CONFIGURATIONS)
.run((context) -> assertThat(context).doesNotHaveBean(ServletEndpointDiscoverer.class)); .run((context) -> assertThat(context).doesNotHaveBean(ServletEndpointDiscoverer.class));
} }

View File

@ -26,16 +26,16 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
* *
* @author Madhura Bhave * @author Madhura Bhave
*/ */
public class WebEndpointPropertiesTests { class WebEndpointPropertiesTests {
@Test @Test
public void defaultBasePathShouldBeApplication() { void defaultBasePathShouldBeApplication() {
WebEndpointProperties properties = new WebEndpointProperties(); WebEndpointProperties properties = new WebEndpointProperties();
assertThat(properties.getBasePath()).isEqualTo("/actuator"); assertThat(properties.getBasePath()).isEqualTo("/actuator");
} }
@Test @Test
public void basePathShouldBeCleaned() { void basePathShouldBeCleaned() {
WebEndpointProperties properties = new WebEndpointProperties(); WebEndpointProperties properties = new WebEndpointProperties();
properties.setBasePath("/"); properties.setBasePath("/");
assertThat(properties.getBasePath()).isEqualTo(""); assertThat(properties.getBasePath()).isEqualTo("");
@ -44,14 +44,14 @@ public class WebEndpointPropertiesTests {
} }
@Test @Test
public void basePathMustStartWithSlash() { void basePathMustStartWithSlash() {
WebEndpointProperties properties = new WebEndpointProperties(); WebEndpointProperties properties = new WebEndpointProperties();
assertThatIllegalArgumentException().isThrownBy(() -> properties.setBasePath("admin")) assertThatIllegalArgumentException().isThrownBy(() -> properties.setBasePath("admin"))
.withMessageContaining("Base path must start with '/' or be empty"); .withMessageContaining("Base path must start with '/' or be empty");
} }
@Test @Test
public void basePathCanBeEmpty() { void basePathCanBeEmpty() {
WebEndpointProperties properties = new WebEndpointProperties(); WebEndpointProperties properties = new WebEndpointProperties();
properties.setBasePath(""); properties.setBasePath("");
assertThat(properties.getBasePath()).isEqualTo(""); assertThat(properties.getBasePath()).isEqualTo("");

View File

@ -47,13 +47,13 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
* *
* @author Andy Wilkinson * @author Andy Wilkinson
*/ */
public class AuditEventsEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { class AuditEventsEndpointDocumentationTests extends MockMvcEndpointDocumentationTests {
@MockBean @MockBean
private AuditEventRepository repository; private AuditEventRepository repository;
@Test @Test
public void allAuditEvents() throws Exception { void allAuditEvents() throws Exception {
String queryTimestamp = "2017-11-07T09:37Z"; String queryTimestamp = "2017-11-07T09:37Z";
given(this.repository.find(any(), any(), any())) given(this.repository.find(any(), any(), any()))
.willReturn(Arrays.asList(new AuditEvent("alice", "logout", Collections.emptyMap()))); .willReturn(Arrays.asList(new AuditEvent("alice", "logout", Collections.emptyMap())));
@ -66,7 +66,7 @@ public class AuditEventsEndpointDocumentationTests extends MockMvcEndpointDocume
} }
@Test @Test
public void filteredAuditEvents() throws Exception { void filteredAuditEvents() throws Exception {
OffsetDateTime now = OffsetDateTime.now(); OffsetDateTime now = OffsetDateTime.now();
String queryTimestamp = DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(now); String queryTimestamp = DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(now);
given(this.repository.find("alice", now.toInstant(), "logout")) given(this.repository.find("alice", now.toInstant(), "logout"))

View File

@ -45,10 +45,10 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
* *
* @author Andy Wilkinson * @author Andy Wilkinson
*/ */
public class BeansEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { class BeansEndpointDocumentationTests extends MockMvcEndpointDocumentationTests {
@Test @Test
public void beans() throws Exception { void beans() throws Exception {
List<FieldDescriptor> beanFields = Arrays.asList(fieldWithPath("aliases").description("Names of any aliases."), List<FieldDescriptor> beanFields = Arrays.asList(fieldWithPath("aliases").description("Names of any aliases."),
fieldWithPath("scope").description("Scope of the bean."), fieldWithPath("scope").description("Scope of the bean."),
fieldWithPath("type").description("Fully qualified type of the bean."), fieldWithPath("type").description("Fully qualified type of the bean."),

View File

@ -48,7 +48,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
* *
* @author Stephane Nicoll * @author Stephane Nicoll
*/ */
public class CachesEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { class CachesEndpointDocumentationTests extends MockMvcEndpointDocumentationTests {
private static final List<FieldDescriptor> levelFields = Arrays.asList( private static final List<FieldDescriptor> levelFields = Arrays.asList(
fieldWithPath("name").description("Cache name."), fieldWithPath("name").description("Cache name."),
@ -61,7 +61,7 @@ public class CachesEndpointDocumentationTests extends MockMvcEndpointDocumentati
.optional()); .optional());
@Test @Test
public void allCaches() throws Exception { void allCaches() throws Exception {
this.mockMvc.perform(get("/actuator/caches")).andExpect(status().isOk()) this.mockMvc.perform(get("/actuator/caches")).andExpect(status().isOk())
.andDo(MockMvcRestDocumentation.document("caches/all", .andDo(MockMvcRestDocumentation.document("caches/all",
responseFields(fieldWithPath("cacheManagers").description("Cache managers keyed by id."), responseFields(fieldWithPath("cacheManagers").description("Cache managers keyed by id."),
@ -72,19 +72,19 @@ public class CachesEndpointDocumentationTests extends MockMvcEndpointDocumentati
} }
@Test @Test
public void namedCache() throws Exception { void namedCache() throws Exception {
this.mockMvc.perform(get("/actuator/caches/cities")).andExpect(status().isOk()).andDo(MockMvcRestDocumentation this.mockMvc.perform(get("/actuator/caches/cities")).andExpect(status().isOk()).andDo(MockMvcRestDocumentation
.document("caches/named", requestParameters(requestParameters), responseFields(levelFields))); .document("caches/named", requestParameters(requestParameters), responseFields(levelFields)));
} }
@Test @Test
public void evictAllCaches() throws Exception { void evictAllCaches() throws Exception {
this.mockMvc.perform(delete("/actuator/caches")).andExpect(status().isNoContent()) this.mockMvc.perform(delete("/actuator/caches")).andExpect(status().isNoContent())
.andDo(MockMvcRestDocumentation.document("caches/evict-all")); .andDo(MockMvcRestDocumentation.document("caches/evict-all"));
} }
@Test @Test
public void evictNamedCache() throws Exception { void evictNamedCache() throws Exception {
this.mockMvc.perform(delete("/actuator/caches/countries?cacheManager=anotherCacheManager")) this.mockMvc.perform(delete("/actuator/caches/countries?cacheManager=anotherCacheManager"))
.andExpect(status().isNoContent()) .andExpect(status().isNoContent())
.andDo(MockMvcRestDocumentation.document("caches/evict-named", requestParameters(requestParameters))); .andDo(MockMvcRestDocumentation.document("caches/evict-named", requestParameters(requestParameters)));

View File

@ -49,7 +49,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
* *
* @author Andy Wilkinson * @author Andy Wilkinson
*/ */
public class ConditionsReportEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { class ConditionsReportEndpointDocumentationTests extends MockMvcEndpointDocumentationTests {
private MockMvc mockMvc; private MockMvc mockMvc;
@ -64,7 +64,7 @@ public class ConditionsReportEndpointDocumentationTests extends MockMvcEndpointD
} }
@Test @Test
public void conditions() throws Exception { void conditions() throws Exception {
List<FieldDescriptor> positiveMatchFields = Arrays.asList( List<FieldDescriptor> positiveMatchFields = Arrays.asList(
fieldWithPath("").description("Classes and methods with conditions that were " + "matched."), fieldWithPath("").description("Classes and methods with conditions that were " + "matched."),
fieldWithPath(".*.[].condition").description("Name of the condition."), fieldWithPath(".*.[].condition").description("Name of the condition."),

View File

@ -37,10 +37,10 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
* *
* @author Andy Wilkinson * @author Andy Wilkinson
*/ */
public class ConfigurationPropertiesReportEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { class ConfigurationPropertiesReportEndpointDocumentationTests extends MockMvcEndpointDocumentationTests {
@Test @Test
public void configProps() throws Exception { void configProps() throws Exception {
this.mockMvc.perform(get("/actuator/configprops")).andExpect(status().isOk()) this.mockMvc.perform(get("/actuator/configprops")).andExpect(status().isOk())
.andDo(MockMvcRestDocumentation.document("configprops", .andDo(MockMvcRestDocumentation.document("configprops",
preprocessResponse(limit("contexts", getApplicationContext().getId(), "beans")), preprocessResponse(limit("contexts", getApplicationContext().getId(), "beans")),

View File

@ -57,7 +57,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
*/ */
@TestPropertySource( @TestPropertySource(
properties = "spring.config.location=classpath:/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/") properties = "spring.config.location=classpath:/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/")
public class EnvironmentEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { class EnvironmentEndpointDocumentationTests extends MockMvcEndpointDocumentationTests {
private static final FieldDescriptor activeProfiles = fieldWithPath("activeProfiles") private static final FieldDescriptor activeProfiles = fieldWithPath("activeProfiles")
.description("Names of the active profiles, if any."); .description("Names of the active profiles, if any.");
@ -69,7 +69,7 @@ public class EnvironmentEndpointDocumentationTests extends MockMvcEndpointDocume
.description("Name of the property source."); .description("Name of the property source.");
@Test @Test
public void env() throws Exception { void env() throws Exception {
this.mockMvc.perform(get("/actuator/env")).andExpect(status().isOk()) this.mockMvc.perform(get("/actuator/env")).andExpect(status().isOk())
.andDo(document("env/all", preprocessResponse(replacePattern( .andDo(document("env/all", preprocessResponse(replacePattern(
Pattern.compile("org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/"), Pattern.compile("org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/"),
@ -84,7 +84,7 @@ public class EnvironmentEndpointDocumentationTests extends MockMvcEndpointDocume
} }
@Test @Test
public void singlePropertyFromEnv() throws Exception { void singlePropertyFromEnv() throws Exception {
this.mockMvc.perform(get("/actuator/env/com.example.cache.max-size")).andExpect(status().isOk()).andDo(document( this.mockMvc.perform(get("/actuator/env/com.example.cache.max-size")).andExpect(status().isOk()).andDo(document(
"env/single", "env/single",
preprocessResponse(replacePattern( preprocessResponse(replacePattern(

View File

@ -47,10 +47,10 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
* *
* @author Andy Wilkinson * @author Andy Wilkinson
*/ */
public class FlywayEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { class FlywayEndpointDocumentationTests extends MockMvcEndpointDocumentationTests {
@Test @Test
public void flyway() throws Exception { void flyway() throws Exception {
this.mockMvc.perform(get("/actuator/flyway")).andExpect(status().isOk()) this.mockMvc.perform(get("/actuator/flyway")).andExpect(status().isOk())
.andDo(MockMvcRestDocumentation.document("flyway", .andDo(MockMvcRestDocumentation.document("flyway",
responseFields(fieldWithPath("contexts").description("Application contexts keyed by id"), responseFields(fieldWithPath("contexts").description("Application contexts keyed by id"),

View File

@ -55,7 +55,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
* @author Andy Wilkinson * @author Andy Wilkinson
* @author Stephane Nicoll * @author Stephane Nicoll
*/ */
public class HealthEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { class HealthEndpointDocumentationTests extends MockMvcEndpointDocumentationTests {
private static final List<FieldDescriptor> componentFields = Arrays.asList( private static final List<FieldDescriptor> componentFields = Arrays.asList(
fieldWithPath("status").description("Status of a specific part of the application"), fieldWithPath("status").description("Status of a specific part of the application"),
@ -63,7 +63,7 @@ public class HealthEndpointDocumentationTests extends MockMvcEndpointDocumentati
.description("Details of the health of a specific part of the" + " application.")); .description("Details of the health of a specific part of the" + " application."));
@Test @Test
public void health() throws Exception { void health() throws Exception {
this.mockMvc.perform(get("/actuator/health")).andExpect(status().isOk()).andDo(document("health", this.mockMvc.perform(get("/actuator/health")).andExpect(status().isOk()).andDo(document("health",
responseFields(fieldWithPath("status").description("Overall status of the application."), responseFields(fieldWithPath("status").description("Overall status of the application."),
fieldWithPath("details") fieldWithPath("details")
@ -75,13 +75,13 @@ public class HealthEndpointDocumentationTests extends MockMvcEndpointDocumentati
} }
@Test @Test
public void healthComponent() throws Exception { void healthComponent() throws Exception {
this.mockMvc.perform(get("/actuator/health/db")).andExpect(status().isOk()) this.mockMvc.perform(get("/actuator/health/db")).andExpect(status().isOk())
.andDo(document("health/component", responseFields(componentFields))); .andDo(document("health/component", responseFields(componentFields)));
} }
@Test @Test
public void healthComponentInstance() throws Exception { void healthComponentInstance() throws Exception {
this.mockMvc.perform(get("/actuator/health/broker/us1")).andExpect(status().isOk()) this.mockMvc.perform(get("/actuator/health/broker/us1")).andExpect(status().isOk())
.andDo(document("health/instance", responseFields(componentFields))); .andDo(document("health/instance", responseFields(componentFields)));
} }

View File

@ -39,10 +39,10 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
* *
* @author Andy Wilkinson * @author Andy Wilkinson
*/ */
public class HeapDumpWebEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { class HeapDumpWebEndpointDocumentationTests extends MockMvcEndpointDocumentationTests {
@Test @Test
public void heapDump() throws Exception { void heapDump() throws Exception {
this.mockMvc.perform(get("/actuator/heapdump")).andExpect(status().isOk()) this.mockMvc.perform(get("/actuator/heapdump")).andExpect(status().isOk())
.andDo(document("heapdump", new CurlRequestSnippet(CliDocumentation.multiLineFormat()) { .andDo(document("heapdump", new CurlRequestSnippet(CliDocumentation.multiLineFormat()) {

View File

@ -52,13 +52,13 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
* *
* @author Andy Wilkinson * @author Andy Wilkinson
*/ */
public class HttpTraceEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { class HttpTraceEndpointDocumentationTests extends MockMvcEndpointDocumentationTests {
@MockBean @MockBean
private HttpTraceRepository repository; private HttpTraceRepository repository;
@Test @Test
public void traces() throws Exception { void traces() throws Exception {
TraceableRequest request = mock(TraceableRequest.class); TraceableRequest request = mock(TraceableRequest.class);
given(request.getUri()).willReturn(URI.create("https://api.example.com")); given(request.getUri()).willReturn(URI.create("https://api.example.com"));
given(request.getMethod()).willReturn("GET"); given(request.getMethod()).willReturn("GET");

View File

@ -44,10 +44,10 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
* *
* @author Andy Wilkinson * @author Andy Wilkinson
*/ */
public class InfoEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { class InfoEndpointDocumentationTests extends MockMvcEndpointDocumentationTests {
@Test @Test
public void info() throws Exception { void info() throws Exception {
this.mockMvc.perform(get("/actuator/info")).andExpect(status().isOk()) this.mockMvc.perform(get("/actuator/info")).andExpect(status().isOk())
.andDo(MockMvcRestDocumentation.document("info", .andDo(MockMvcRestDocumentation.document("info",
responseFields(beneathPath("git"), responseFields(beneathPath("git"),

View File

@ -35,16 +35,16 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
* *
* @author Tim Ysewyn * @author Tim Ysewyn
*/ */
public class IntegrationGraphEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { class IntegrationGraphEndpointDocumentationTests extends MockMvcEndpointDocumentationTests {
@Test @Test
public void graph() throws Exception { void graph() throws Exception {
this.mockMvc.perform(get("/actuator/integrationgraph")).andExpect(status().isOk()) this.mockMvc.perform(get("/actuator/integrationgraph")).andExpect(status().isOk())
.andDo(MockMvcRestDocumentation.document("integrationgraph/graph")); .andDo(MockMvcRestDocumentation.document("integrationgraph/graph"));
} }
@Test @Test
public void rebuild() throws Exception { void rebuild() throws Exception {
this.mockMvc.perform(post("/actuator/integrationgraph")).andExpect(status().isNoContent()) this.mockMvc.perform(post("/actuator/integrationgraph")).andExpect(status().isNoContent())
.andDo(MockMvcRestDocumentation.document("integrationgraph/rebuild")); .andDo(MockMvcRestDocumentation.document("integrationgraph/rebuild"));
} }

View File

@ -43,10 +43,10 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
* *
* @author Andy Wilkinson * @author Andy Wilkinson
*/ */
public class LiquibaseEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { class LiquibaseEndpointDocumentationTests extends MockMvcEndpointDocumentationTests {
@Test @Test
public void liquibase() throws Exception { void liquibase() throws Exception {
FieldDescriptor changeSetsField = fieldWithPath("contexts.*.liquibaseBeans.*.changeSets") FieldDescriptor changeSetsField = fieldWithPath("contexts.*.liquibaseBeans.*.changeSets")
.description("Change sets made by the Liquibase beans, keyed by " + "bean name."); .description("Change sets made by the Liquibase beans, keyed by " + "bean name.");
this.mockMvc.perform(get("/actuator/liquibase")).andExpect(status().isOk()) this.mockMvc.perform(get("/actuator/liquibase")).andExpect(status().isOk())

View File

@ -36,16 +36,16 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
*/ */
@TestPropertySource( @TestPropertySource(
properties = "logging.file.name=src/test/resources/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/sample.log") properties = "logging.file.name=src/test/resources/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/sample.log")
public class LogFileWebEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { class LogFileWebEndpointDocumentationTests extends MockMvcEndpointDocumentationTests {
@Test @Test
public void logFile() throws Exception { void logFile() throws Exception {
this.mockMvc.perform(get("/actuator/logfile")).andExpect(status().isOk()) this.mockMvc.perform(get("/actuator/logfile")).andExpect(status().isOk())
.andDo(MockMvcRestDocumentation.document("logfile/entire")); .andDo(MockMvcRestDocumentation.document("logfile/entire"));
} }
@Test @Test
public void logFileRange() throws Exception { void logFileRange() throws Exception {
this.mockMvc.perform(get("/actuator/logfile").header("Range", "bytes=0-1023")) this.mockMvc.perform(get("/actuator/logfile").header("Range", "bytes=0-1023"))
.andExpect(status().isPartialContent()).andDo(MockMvcRestDocumentation.document("logfile/range")); .andExpect(status().isPartialContent()).andDo(MockMvcRestDocumentation.document("logfile/range"));
} }

View File

@ -48,7 +48,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
* *
* @author Andy Wilkinson * @author Andy Wilkinson
*/ */
public class LoggersEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { class LoggersEndpointDocumentationTests extends MockMvcEndpointDocumentationTests {
private static final List<FieldDescriptor> levelFields = Arrays.asList( private static final List<FieldDescriptor> levelFields = Arrays.asList(
fieldWithPath("configuredLevel").description("Configured level of the logger, if any.").optional(), fieldWithPath("configuredLevel").description("Configured level of the logger, if any.").optional(),
@ -58,7 +58,7 @@ public class LoggersEndpointDocumentationTests extends MockMvcEndpointDocumentat
private LoggingSystem loggingSystem; private LoggingSystem loggingSystem;
@Test @Test
public void allLoggers() throws Exception { void allLoggers() throws Exception {
given(this.loggingSystem.getSupportedLogLevels()).willReturn(EnumSet.allOf(LogLevel.class)); given(this.loggingSystem.getSupportedLogLevels()).willReturn(EnumSet.allOf(LogLevel.class));
given(this.loggingSystem.getLoggerConfigurations()) given(this.loggingSystem.getLoggerConfigurations())
.willReturn(Arrays.asList(new LoggerConfiguration("ROOT", LogLevel.INFO, LogLevel.INFO), .willReturn(Arrays.asList(new LoggerConfiguration("ROOT", LogLevel.INFO, LogLevel.INFO),
@ -71,7 +71,7 @@ public class LoggersEndpointDocumentationTests extends MockMvcEndpointDocumentat
} }
@Test @Test
public void logger() throws Exception { void logger() throws Exception {
given(this.loggingSystem.getLoggerConfiguration("com.example")) given(this.loggingSystem.getLoggerConfiguration("com.example"))
.willReturn(new LoggerConfiguration("com.example", LogLevel.INFO, LogLevel.INFO)); .willReturn(new LoggerConfiguration("com.example", LogLevel.INFO, LogLevel.INFO));
this.mockMvc.perform(get("/actuator/loggers/com.example")).andExpect(status().isOk()) this.mockMvc.perform(get("/actuator/loggers/com.example")).andExpect(status().isOk())
@ -79,7 +79,7 @@ public class LoggersEndpointDocumentationTests extends MockMvcEndpointDocumentat
} }
@Test @Test
public void setLogLevel() throws Exception { void setLogLevel() throws Exception {
this.mockMvc this.mockMvc
.perform(post("/actuator/loggers/com.example").content("{\"configuredLevel\":\"debug\"}") .perform(post("/actuator/loggers/com.example").content("{\"configuredLevel\":\"debug\"}")
.contentType(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON))
@ -90,7 +90,7 @@ public class LoggersEndpointDocumentationTests extends MockMvcEndpointDocumentat
} }
@Test @Test
public void clearLogLevel() throws Exception { void clearLogLevel() throws Exception {
this.mockMvc this.mockMvc
.perform(post("/actuator/loggers/com.example").content("{}").contentType(MediaType.APPLICATION_JSON)) .perform(post("/actuator/loggers/com.example").content("{}").contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent()).andDo(MockMvcRestDocumentation.document("loggers/clear")); .andExpect(status().isNoContent()).andDo(MockMvcRestDocumentation.document("loggers/clear"));

View File

@ -62,7 +62,7 @@ import static org.springframework.web.reactive.function.server.RouterFunctions.r
*/ */
@ExtendWith(RestDocumentationExtension.class) @ExtendWith(RestDocumentationExtension.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "spring.main.web-application-type=reactive") @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "spring.main.web-application-type=reactive")
public class MappingsEndpointReactiveDocumentationTests extends AbstractEndpointDocumentationTests { class MappingsEndpointReactiveDocumentationTests extends AbstractEndpointDocumentationTests {
@LocalServerPort @LocalServerPort
private int port; private int port;
@ -77,7 +77,7 @@ public class MappingsEndpointReactiveDocumentationTests extends AbstractEndpoint
} }
@Test @Test
public void mappings() throws Exception { void mappings() throws Exception {
List<FieldDescriptor> requestMappingConditions = Arrays.asList( List<FieldDescriptor> requestMappingConditions = Arrays.asList(
requestMappingConditionField("").description("Details of the request mapping conditions.").optional(), requestMappingConditionField("").description("Details of the request mapping conditions.").optional(),
requestMappingConditionField(".consumes").description("Details of the consumes condition"), requestMappingConditionField(".consumes").description("Details of the consumes condition"),

View File

@ -62,7 +62,7 @@ import static org.springframework.restdocs.webtestclient.WebTestClientRestDocume
*/ */
@ExtendWith(RestDocumentationExtension.class) @ExtendWith(RestDocumentationExtension.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class MappingsEndpointServletDocumentationTests extends AbstractEndpointDocumentationTests { class MappingsEndpointServletDocumentationTests extends AbstractEndpointDocumentationTests {
@LocalServerPort @LocalServerPort
private int port; private int port;
@ -76,7 +76,7 @@ public class MappingsEndpointServletDocumentationTests extends AbstractEndpointD
} }
@Test @Test
public void mappings() throws Exception { void mappings() throws Exception {
ResponseFieldsSnippet commonResponseFields = responseFields( ResponseFieldsSnippet commonResponseFields = responseFields(
fieldWithPath("contexts").description("Application contexts keyed by id."), fieldWithPath("contexts").description("Application contexts keyed by id."),
fieldWithPath("contexts.*.mappings").description("Mappings in the context, keyed by mapping type."), fieldWithPath("contexts.*.mappings").description("Mappings in the context, keyed by mapping type."),

View File

@ -39,16 +39,16 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
* *
* @author Andy Wilkinson * @author Andy Wilkinson
*/ */
public class MetricsEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { class MetricsEndpointDocumentationTests extends MockMvcEndpointDocumentationTests {
@Test @Test
public void metricNames() throws Exception { void metricNames() throws Exception {
this.mockMvc.perform(get("/actuator/metrics")).andExpect(status().isOk()).andDo(document("metrics/names", this.mockMvc.perform(get("/actuator/metrics")).andExpect(status().isOk()).andDo(document("metrics/names",
responseFields(fieldWithPath("names").description("Names of the known metrics.")))); responseFields(fieldWithPath("names").description("Names of the known metrics."))));
} }
@Test @Test
public void metric() throws Exception { void metric() throws Exception {
this.mockMvc.perform(get("/actuator/metrics/jvm.memory.max")).andExpect(status().isOk()) this.mockMvc.perform(get("/actuator/metrics/jvm.memory.max")).andExpect(status().isOk())
.andDo(document("metrics/metric", .andDo(document("metrics/metric",
responseFields(fieldWithPath("name").description("Name of the metric"), responseFields(fieldWithPath("name").description("Name of the metric"),
@ -64,7 +64,7 @@ public class MetricsEndpointDocumentationTests extends MockMvcEndpointDocumentat
} }
@Test @Test
public void metricWithTags() throws Exception { void metricWithTags() throws Exception {
this.mockMvc this.mockMvc
.perform(get("/actuator/metrics/jvm.memory.max").param("tag", "area:nonheap").param("tag", .perform(get("/actuator/metrics/jvm.memory.max").param("tag", "area:nonheap").param("tag",
"id:Compressed Class Space")) "id:Compressed Class Space"))

View File

@ -36,10 +36,10 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
* *
* @author Andy Wilkinson * @author Andy Wilkinson
*/ */
public class PrometheusScrapeEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { class PrometheusScrapeEndpointDocumentationTests extends MockMvcEndpointDocumentationTests {
@Test @Test
public void prometheus() throws Exception { void prometheus() throws Exception {
this.mockMvc.perform(get("/actuator/prometheus")).andExpect(status().isOk()).andDo(document("prometheus")); this.mockMvc.perform(get("/actuator/prometheus")).andExpect(status().isOk()).andDo(document("prometheus"));
} }

View File

@ -48,10 +48,10 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
* *
* @author Andy Wilkinson * @author Andy Wilkinson
*/ */
public class ScheduledTasksEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { class ScheduledTasksEndpointDocumentationTests extends MockMvcEndpointDocumentationTests {
@Test @Test
public void scheduledTasks() throws Exception { void scheduledTasks() throws Exception {
this.mockMvc.perform(get("/actuator/scheduledtasks")).andExpect(status().isOk()).andDo(document( this.mockMvc.perform(get("/actuator/scheduledtasks")).andExpect(status().isOk()).andDo(document(
"scheduled-tasks", "scheduled-tasks",
preprocessResponse(replacePattern( preprocessResponse(replacePattern(

View File

@ -54,7 +54,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
* @author Andy Wilkinson * @author Andy Wilkinson
*/ */
@TestPropertySource(properties = "spring.jackson.serialization.write-dates-as-timestamps=false") @TestPropertySource(properties = "spring.jackson.serialization.write-dates-as-timestamps=false")
public class SessionsEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { class SessionsEndpointDocumentationTests extends MockMvcEndpointDocumentationTests {
private static final Session sessionOne = createSession(Instant.now().minusSeconds(60 * 60 * 12), private static final Session sessionOne = createSession(Instant.now().minusSeconds(60 * 60 * 12),
Instant.now().minusSeconds(45)); Instant.now().minusSeconds(45));
@ -78,7 +78,7 @@ public class SessionsEndpointDocumentationTests extends MockMvcEndpointDocumenta
private FindByIndexNameSessionRepository<Session> sessionRepository; private FindByIndexNameSessionRepository<Session> sessionRepository;
@Test @Test
public void sessionsForUsername() throws Exception { void sessionsForUsername() throws Exception {
Map<String, Session> sessions = new HashMap<>(); Map<String, Session> sessions = new HashMap<>();
sessions.put(sessionOne.getId(), sessionOne); sessions.put(sessionOne.getId(), sessionOne);
sessions.put(sessionTwo.getId(), sessionTwo); sessions.put(sessionTwo.getId(), sessionTwo);
@ -92,7 +92,7 @@ public class SessionsEndpointDocumentationTests extends MockMvcEndpointDocumenta
} }
@Test @Test
public void sessionWithId() throws Exception { void sessionWithId() throws Exception {
Map<String, Session> sessions = new HashMap<>(); Map<String, Session> sessions = new HashMap<>();
sessions.put(sessionOne.getId(), sessionOne); sessions.put(sessionOne.getId(), sessionOne);
sessions.put(sessionTwo.getId(), sessionTwo); sessions.put(sessionTwo.getId(), sessionTwo);
@ -103,7 +103,7 @@ public class SessionsEndpointDocumentationTests extends MockMvcEndpointDocumenta
} }
@Test @Test
public void deleteASession() throws Exception { void deleteASession() throws Exception {
this.mockMvc.perform(delete("/actuator/sessions/{id}", sessionTwo.getId())).andExpect(status().isNoContent()) this.mockMvc.perform(delete("/actuator/sessions/{id}", sessionTwo.getId())).andExpect(status().isNoContent())
.andDo(document("sessions/delete")); .andDo(document("sessions/delete"));
verify(this.sessionRepository).deleteById(sessionTwo.getId()); verify(this.sessionRepository).deleteById(sessionTwo.getId());

View File

@ -36,10 +36,10 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
* *
* @author Andy Wilkinson * @author Andy Wilkinson
*/ */
public class ShutdownEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { class ShutdownEndpointDocumentationTests extends MockMvcEndpointDocumentationTests {
@Test @Test
public void shutdown() throws Exception { void shutdown() throws Exception {
this.mockMvc.perform(post("/actuator/shutdown")).andExpect(status().isOk()) this.mockMvc.perform(post("/actuator/shutdown")).andExpect(status().isOk())
.andDo(MockMvcRestDocumentation.document("shutdown", responseFields( .andDo(MockMvcRestDocumentation.document("shutdown", responseFields(
fieldWithPath("message").description("Message describing the result of the request.")))); fieldWithPath("message").description("Message describing the result of the request."))));

View File

@ -40,10 +40,10 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
* *
* @author Andy Wilkinson * @author Andy Wilkinson
*/ */
public class ThreadDumpEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { class ThreadDumpEndpointDocumentationTests extends MockMvcEndpointDocumentationTests {
@Test @Test
public void threadDump() throws Exception { void threadDump() throws Exception {
ReentrantLock lock = new ReentrantLock(); ReentrantLock lock = new ReentrantLock();
CountDownLatch latch = new CountDownLatch(1); CountDownLatch latch = new CountDownLatch(1);
new Thread(() -> { new Thread(() -> {

View File

@ -38,7 +38,7 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Michael Simons * @author Michael Simons
* @author Madhura Bhave * @author Madhura Bhave
*/ */
public class JerseyWebEndpointManagementContextConfigurationTests { class JerseyWebEndpointManagementContextConfigurationTests {
private final WebApplicationContextRunner runner = new WebApplicationContextRunner() private final WebApplicationContextRunner runner = new WebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(WebEndpointAutoConfiguration.class, .withConfiguration(AutoConfigurations.of(WebEndpointAutoConfiguration.class,
@ -46,12 +46,12 @@ public class JerseyWebEndpointManagementContextConfigurationTests {
.withBean(WebEndpointsSupplier.class, () -> Collections::emptyList); .withBean(WebEndpointsSupplier.class, () -> Collections::emptyList);
@Test @Test
public void resourceConfigCustomizerForEndpointsIsAutoConfigured() { void resourceConfigCustomizerForEndpointsIsAutoConfigured() {
this.runner.run((context) -> assertThat(context).hasSingleBean(ResourceConfigCustomizer.class)); this.runner.run((context) -> assertThat(context).hasSingleBean(ResourceConfigCustomizer.class));
} }
@Test @Test
public void autoConfigurationIsConditionalOnServletWebApplication() { void autoConfigurationIsConditionalOnServletWebApplication() {
ApplicationContextRunner contextRunner = new ApplicationContextRunner() ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(JerseySameManagementContextConfiguration.class)); .withConfiguration(AutoConfigurations.of(JerseySameManagementContextConfiguration.class));
contextRunner contextRunner
@ -59,7 +59,7 @@ public class JerseyWebEndpointManagementContextConfigurationTests {
} }
@Test @Test
public void autoConfigurationIsConditionalOnClassResourceConfig() { void autoConfigurationIsConditionalOnClassResourceConfig() {
this.runner.withClassLoader(new FilteredClassLoader(ResourceConfig.class)) this.runner.withClassLoader(new FilteredClassLoader(ResourceConfig.class))
.run((context) -> assertThat(context).doesNotHaveBean(JerseySameManagementContextConfiguration.class)); .run((context) -> assertThat(context).doesNotHaveBean(JerseySameManagementContextConfiguration.class));
} }

View File

@ -36,31 +36,31 @@ import static org.assertj.core.api.Assertions.assertThat;
* *
* @author Phillip Webb * @author Phillip Webb
*/ */
public class EnvironmentEndpointAutoConfigurationTests { class EnvironmentEndpointAutoConfigurationTests {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(EnvironmentEndpointAutoConfiguration.class)); .withConfiguration(AutoConfigurations.of(EnvironmentEndpointAutoConfiguration.class));
@Test @Test
public void runShouldHaveEndpointBean() { void runShouldHaveEndpointBean() {
this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=env") this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=env")
.withSystemProperties("dbPassword=123456", "apiKey=123456") .withSystemProperties("dbPassword=123456", "apiKey=123456")
.run(validateSystemProperties("******", "******")); .run(validateSystemProperties("******", "******"));
} }
@Test @Test
public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() {
this.contextRunner.withPropertyValues("management.endpoint.env.enabled:false") this.contextRunner.withPropertyValues("management.endpoint.env.enabled:false")
.run((context) -> assertThat(context).doesNotHaveBean(EnvironmentEndpoint.class)); .run((context) -> assertThat(context).doesNotHaveBean(EnvironmentEndpoint.class));
} }
@Test @Test
public void runWhenNotExposedShouldNotHaveEndpointBean() { void runWhenNotExposedShouldNotHaveEndpointBean() {
this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(EnvironmentEndpoint.class)); this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(EnvironmentEndpoint.class));
} }
@Test @Test
public void keysToSanitizeCanBeConfiguredViaTheEnvironment() { void keysToSanitizeCanBeConfiguredViaTheEnvironment() {
this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=env") this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=env")
.withSystemProperties("dbPassword=123456", "apiKey=123456") .withSystemProperties("dbPassword=123456", "apiKey=123456")
.withPropertyValues("management.endpoint.env.keys-to-sanitize=.*pass.*") .withPropertyValues("management.endpoint.env.keys-to-sanitize=.*pass.*")

View File

@ -31,26 +31,26 @@ import static org.mockito.Mockito.mock;
* *
* @author Phillip Webb * @author Phillip Webb
*/ */
public class FlywayEndpointAutoConfigurationTests { class FlywayEndpointAutoConfigurationTests {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(FlywayEndpointAutoConfiguration.class)) .withConfiguration(AutoConfigurations.of(FlywayEndpointAutoConfiguration.class))
.withBean(Flyway.class, () -> mock(Flyway.class)); .withBean(Flyway.class, () -> mock(Flyway.class));
@Test @Test
public void runShouldHaveEndpointBean() { void runShouldHaveEndpointBean() {
this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=flyway") this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=flyway")
.run((context) -> assertThat(context).hasSingleBean(FlywayEndpoint.class)); .run((context) -> assertThat(context).hasSingleBean(FlywayEndpoint.class));
} }
@Test @Test
public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() {
this.contextRunner.withPropertyValues("management.endpoint.flyway.enabled:false") this.contextRunner.withPropertyValues("management.endpoint.flyway.enabled:false")
.run((context) -> assertThat(context).doesNotHaveBean(FlywayEndpoint.class)); .run((context) -> assertThat(context).doesNotHaveBean(FlywayEndpoint.class));
} }
@Test @Test
public void runWhenNotExposedShouldNotHaveEndpointBean() { void runWhenNotExposedShouldNotHaveEndpointBean() {
this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(FlywayEndpoint.class)); this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(FlywayEndpoint.class));
} }

View File

@ -40,13 +40,13 @@ import static org.mockito.Mockito.verify;
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Phillip Webb * @author Phillip Webb
*/ */
public class HealthEndpointAutoConfigurationTests { class HealthEndpointAutoConfigurationTests {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration( private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration(
AutoConfigurations.of(HealthIndicatorAutoConfiguration.class, HealthEndpointAutoConfiguration.class)); AutoConfigurations.of(HealthIndicatorAutoConfiguration.class, HealthEndpointAutoConfiguration.class));
@Test @Test
public void healthEndpointShowDetailsDefault() { void healthEndpointShowDetailsDefault() {
this.contextRunner.withBean(ReactiveHealthIndicator.class, this::reactiveHealthIndicator).run((context) -> { this.contextRunner.withBean(ReactiveHealthIndicator.class, this::reactiveHealthIndicator).run((context) -> {
ReactiveHealthIndicator indicator = context.getBean("reactiveHealthIndicator", ReactiveHealthIndicator indicator = context.getBean("reactiveHealthIndicator",
ReactiveHealthIndicator.class); ReactiveHealthIndicator.class);
@ -59,7 +59,7 @@ public class HealthEndpointAutoConfigurationTests {
} }
@Test @Test
public void healthEndpointAdaptReactiveHealthIndicator() { void healthEndpointAdaptReactiveHealthIndicator() {
this.contextRunner.withPropertyValues("management.endpoint.health.show-details=always") this.contextRunner.withPropertyValues("management.endpoint.health.show-details=always")
.withBean(ReactiveHealthIndicator.class, this::reactiveHealthIndicator).run((context) -> { .withBean(ReactiveHealthIndicator.class, this::reactiveHealthIndicator).run((context) -> {
ReactiveHealthIndicator indicator = context.getBean("reactiveHealthIndicator", ReactiveHealthIndicator indicator = context.getBean("reactiveHealthIndicator",
@ -73,7 +73,7 @@ public class HealthEndpointAutoConfigurationTests {
} }
@Test @Test
public void healthEndpointMergeRegularAndReactive() { void healthEndpointMergeRegularAndReactive() {
this.contextRunner.withPropertyValues("management.endpoint.health.show-details=always") this.contextRunner.withPropertyValues("management.endpoint.health.show-details=always")
.withBean("simpleHealthIndicator", HealthIndicator.class, this::simpleHealthIndicator) .withBean("simpleHealthIndicator", HealthIndicator.class, this::simpleHealthIndicator)
.withBean("reactiveHealthIndicator", ReactiveHealthIndicator.class, this::reactiveHealthIndicator) .withBean("reactiveHealthIndicator", ReactiveHealthIndicator.class, this::reactiveHealthIndicator)

View File

@ -49,25 +49,25 @@ import static org.mockito.Mockito.mock;
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Phillip Webb * @author Phillip Webb
*/ */
public class HealthEndpointWebExtensionTests { class HealthEndpointWebExtensionTests {
private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withUserConfiguration(HealthIndicatorsConfiguration.class).withConfiguration(AutoConfigurations .withUserConfiguration(HealthIndicatorsConfiguration.class).withConfiguration(AutoConfigurations
.of(HealthIndicatorAutoConfiguration.class, HealthEndpointAutoConfiguration.class)); .of(HealthIndicatorAutoConfiguration.class, HealthEndpointAutoConfiguration.class));
@Test @Test
public void runShouldCreateExtensionBeans() { void runShouldCreateExtensionBeans() {
this.contextRunner.run((context) -> assertThat(context).hasSingleBean(HealthEndpointWebExtension.class)); this.contextRunner.run((context) -> assertThat(context).hasSingleBean(HealthEndpointWebExtension.class));
} }
@Test @Test
public void runWhenHealthEndpointIsDisabledShouldNotCreateExtensionBeans() { void runWhenHealthEndpointIsDisabledShouldNotCreateExtensionBeans() {
this.contextRunner.withPropertyValues("management.endpoint.health.enabled:false") this.contextRunner.withPropertyValues("management.endpoint.health.enabled:false")
.run((context) -> assertThat(context).doesNotHaveBean(HealthEndpointWebExtension.class)); .run((context) -> assertThat(context).doesNotHaveBean(HealthEndpointWebExtension.class));
} }
@Test @Test
public void runWithCustomHealthMappingShouldMapStatusCode() { void runWithCustomHealthMappingShouldMapStatusCode() {
this.contextRunner.withPropertyValues("management.health.status.http-mapping.CUSTOM=500").run((context) -> { this.contextRunner.withPropertyValues("management.health.status.http-mapping.CUSTOM=500").run((context) -> {
Object extension = context.getBean(HealthEndpointWebExtension.class); Object extension = context.getBean(HealthEndpointWebExtension.class);
HealthWebEndpointResponseMapper responseMapper = (HealthWebEndpointResponseMapper) ReflectionTestUtils HealthWebEndpointResponseMapper responseMapper = (HealthWebEndpointResponseMapper) ReflectionTestUtils
@ -82,7 +82,7 @@ public class HealthEndpointWebExtensionTests {
} }
@Test @Test
public void unauthenticatedUsersAreNotShownDetailsByDefault() { void unauthenticatedUsersAreNotShownDetailsByDefault() {
this.contextRunner.run((context) -> { this.contextRunner.run((context) -> {
HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class);
assertThat(extension.health(mock(SecurityContext.class)).getBody().getDetails()).isEmpty(); assertThat(extension.health(mock(SecurityContext.class)).getBody().getDetails()).isEmpty();
@ -90,7 +90,7 @@ public class HealthEndpointWebExtensionTests {
} }
@Test @Test
public void authenticatedUsersAreNotShownDetailsByDefault() { void authenticatedUsersAreNotShownDetailsByDefault() {
this.contextRunner.run((context) -> { this.contextRunner.run((context) -> {
HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class);
SecurityContext securityContext = mock(SecurityContext.class); SecurityContext securityContext = mock(SecurityContext.class);
@ -100,7 +100,7 @@ public class HealthEndpointWebExtensionTests {
} }
@Test @Test
public void authenticatedUsersWhenAuthorizedCanBeShownDetails() { void authenticatedUsersWhenAuthorizedCanBeShownDetails() {
this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized") this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized")
.run((context) -> { .run((context) -> {
HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class);
@ -111,7 +111,7 @@ public class HealthEndpointWebExtensionTests {
} }
@Test @Test
public void unauthenticatedUsersCanBeShownDetails() { void unauthenticatedUsersCanBeShownDetails() {
this.contextRunner.withPropertyValues("management.endpoint.health.show-details=always").run((context) -> { this.contextRunner.withPropertyValues("management.endpoint.health.show-details=always").run((context) -> {
HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class);
assertThat(extension.health(null).getBody().getDetails()).isNotEmpty(); assertThat(extension.health(null).getBody().getDetails()).isNotEmpty();
@ -119,7 +119,7 @@ public class HealthEndpointWebExtensionTests {
} }
@Test @Test
public void detailsCanBeHiddenFromAuthenticatedUsers() { void detailsCanBeHiddenFromAuthenticatedUsers() {
this.contextRunner.withPropertyValues("management.endpoint.health.show-details=never").run((context) -> { this.contextRunner.withPropertyValues("management.endpoint.health.show-details=never").run((context) -> {
HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class);
assertThat(extension.health(mock(SecurityContext.class)).getBody().getDetails()).isEmpty(); assertThat(extension.health(mock(SecurityContext.class)).getBody().getDetails()).isEmpty();
@ -127,7 +127,7 @@ public class HealthEndpointWebExtensionTests {
} }
@Test @Test
public void detailsCanBeHiddenFromUnauthorizedUsers() { void detailsCanBeHiddenFromUnauthorizedUsers() {
this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized", this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized",
"management.endpoint.health.roles=ACTUATOR").run((context) -> { "management.endpoint.health.roles=ACTUATOR").run((context) -> {
HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class);
@ -139,7 +139,7 @@ public class HealthEndpointWebExtensionTests {
} }
@Test @Test
public void detailsCanBeShownToAuthorizedUsers() { void detailsCanBeShownToAuthorizedUsers() {
this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized", this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized",
"management.endpoint.health.roles=ACTUATOR").run((context) -> { "management.endpoint.health.roles=ACTUATOR").run((context) -> {
HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class);
@ -151,7 +151,7 @@ public class HealthEndpointWebExtensionTests {
} }
@Test @Test
public void unauthenticatedUsersAreNotShownComponentByDefault() { void unauthenticatedUsersAreNotShownComponentByDefault() {
this.contextRunner.run((context) -> { this.contextRunner.run((context) -> {
HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class);
assertDetailsNotFound(extension.healthForComponent(mock(SecurityContext.class), "simple")); assertDetailsNotFound(extension.healthForComponent(mock(SecurityContext.class), "simple"));
@ -159,7 +159,7 @@ public class HealthEndpointWebExtensionTests {
} }
@Test @Test
public void authenticatedUsersAreNotShownComponentByDefault() { void authenticatedUsersAreNotShownComponentByDefault() {
this.contextRunner.run((context) -> { this.contextRunner.run((context) -> {
HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class);
SecurityContext securityContext = mock(SecurityContext.class); SecurityContext securityContext = mock(SecurityContext.class);
@ -169,7 +169,7 @@ public class HealthEndpointWebExtensionTests {
} }
@Test @Test
public void authenticatedUsersWhenAuthorizedCanBeShownComponent() { void authenticatedUsersWhenAuthorizedCanBeShownComponent() {
this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized") this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized")
.run((context) -> { .run((context) -> {
HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class);
@ -180,7 +180,7 @@ public class HealthEndpointWebExtensionTests {
} }
@Test @Test
public void unauthenticatedUsersCanBeShownComponent() { void unauthenticatedUsersCanBeShownComponent() {
this.contextRunner.withPropertyValues("management.endpoint.health.show-details=always").run((context) -> { this.contextRunner.withPropertyValues("management.endpoint.health.show-details=always").run((context) -> {
HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class);
assertSimpleComponent(extension.healthForComponent(null, "simple")); assertSimpleComponent(extension.healthForComponent(null, "simple"));
@ -188,7 +188,7 @@ public class HealthEndpointWebExtensionTests {
} }
@Test @Test
public void componentCanBeHiddenFromAuthenticatedUsers() { void componentCanBeHiddenFromAuthenticatedUsers() {
this.contextRunner.withPropertyValues("management.endpoint.health.show-details=never").run((context) -> { this.contextRunner.withPropertyValues("management.endpoint.health.show-details=never").run((context) -> {
HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class);
assertDetailsNotFound(extension.healthForComponent(mock(SecurityContext.class), "simple")); assertDetailsNotFound(extension.healthForComponent(mock(SecurityContext.class), "simple"));
@ -196,7 +196,7 @@ public class HealthEndpointWebExtensionTests {
} }
@Test @Test
public void componentCanBeHiddenFromUnauthorizedUsers() { void componentCanBeHiddenFromUnauthorizedUsers() {
this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized", this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized",
"management.endpoint.health.roles=ACTUATOR").run((context) -> { "management.endpoint.health.roles=ACTUATOR").run((context) -> {
HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class);
@ -208,7 +208,7 @@ public class HealthEndpointWebExtensionTests {
} }
@Test @Test
public void componentCanBeShownToAuthorizedUsers() { void componentCanBeShownToAuthorizedUsers() {
this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized", this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized",
"management.endpoint.health.roles=ACTUATOR").run((context) -> { "management.endpoint.health.roles=ACTUATOR").run((context) -> {
HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class);
@ -220,7 +220,7 @@ public class HealthEndpointWebExtensionTests {
} }
@Test @Test
public void componentThatDoesNotExistMapTo404() { void componentThatDoesNotExistMapTo404() {
this.contextRunner.withPropertyValues("management.endpoint.health.show-details=always").run((context) -> { this.contextRunner.withPropertyValues("management.endpoint.health.show-details=always").run((context) -> {
HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class);
assertDetailsNotFound(extension.healthForComponent(null, "does-not-exist")); assertDetailsNotFound(extension.healthForComponent(null, "does-not-exist"));
@ -228,7 +228,7 @@ public class HealthEndpointWebExtensionTests {
} }
@Test @Test
public void unauthenticatedUsersAreNotShownComponentInstanceByDefault() { void unauthenticatedUsersAreNotShownComponentInstanceByDefault() {
this.contextRunner.run((context) -> { this.contextRunner.run((context) -> {
HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class);
assertDetailsNotFound( assertDetailsNotFound(
@ -237,7 +237,7 @@ public class HealthEndpointWebExtensionTests {
} }
@Test @Test
public void authenticatedUsersAreNotShownComponentInstanceByDefault() { void authenticatedUsersAreNotShownComponentInstanceByDefault() {
this.contextRunner.run((context) -> { this.contextRunner.run((context) -> {
HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class);
SecurityContext securityContext = mock(SecurityContext.class); SecurityContext securityContext = mock(SecurityContext.class);
@ -247,7 +247,7 @@ public class HealthEndpointWebExtensionTests {
} }
@Test @Test
public void authenticatedUsersWhenAuthorizedCanBeShownComponentInstance() { void authenticatedUsersWhenAuthorizedCanBeShownComponentInstance() {
this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized") this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized")
.run((context) -> { .run((context) -> {
HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class);
@ -258,7 +258,7 @@ public class HealthEndpointWebExtensionTests {
} }
@Test @Test
public void unauthenticatedUsersCanBeShownComponentInstance() { void unauthenticatedUsersCanBeShownComponentInstance() {
this.contextRunner.withPropertyValues("management.endpoint.health.show-details=always").run((context) -> { this.contextRunner.withPropertyValues("management.endpoint.health.show-details=always").run((context) -> {
HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class);
assertSimpleComponent(extension.healthForComponentInstance(null, "composite", "one")); assertSimpleComponent(extension.healthForComponentInstance(null, "composite", "one"));
@ -266,7 +266,7 @@ public class HealthEndpointWebExtensionTests {
} }
@Test @Test
public void componentInstanceCanBeHiddenFromAuthenticatedUsers() { void componentInstanceCanBeHiddenFromAuthenticatedUsers() {
this.contextRunner.withPropertyValues("management.endpoint.health.show-details=never").run((context) -> { this.contextRunner.withPropertyValues("management.endpoint.health.show-details=never").run((context) -> {
HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class);
assertDetailsNotFound( assertDetailsNotFound(
@ -275,7 +275,7 @@ public class HealthEndpointWebExtensionTests {
} }
@Test @Test
public void componentInstanceCanBeHiddenFromUnauthorizedUsers() { void componentInstanceCanBeHiddenFromUnauthorizedUsers() {
this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized", this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized",
"management.endpoint.health.roles=ACTUATOR").run((context) -> { "management.endpoint.health.roles=ACTUATOR").run((context) -> {
HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class);
@ -287,7 +287,7 @@ public class HealthEndpointWebExtensionTests {
} }
@Test @Test
public void componentInstanceCanBeShownToAuthorizedUsers() { void componentInstanceCanBeShownToAuthorizedUsers() {
this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized", this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized",
"management.endpoint.health.roles=ACTUATOR").run((context) -> { "management.endpoint.health.roles=ACTUATOR").run((context) -> {
HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class);
@ -299,7 +299,7 @@ public class HealthEndpointWebExtensionTests {
} }
@Test @Test
public void componentInstanceThatDoesNotExistMapTo404() { void componentInstanceThatDoesNotExistMapTo404() {
this.contextRunner.withPropertyValues("management.endpoint.health.show-details=always").run((context) -> { this.contextRunner.withPropertyValues("management.endpoint.health.show-details=always").run((context) -> {
HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class);
assertDetailsNotFound(extension.healthForComponentInstance(null, "composite", "does-not-exist")); assertDetailsNotFound(extension.healthForComponentInstance(null, "composite", "does-not-exist"));
@ -317,7 +317,7 @@ public class HealthEndpointWebExtensionTests {
} }
@Test @Test
public void roleCanBeCustomized() { void roleCanBeCustomized() {
this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized", this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized",
"management.endpoint.health.roles=ADMIN").run((context) -> { "management.endpoint.health.roles=ADMIN").run((context) -> {
HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class);

View File

@ -40,26 +40,26 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Phillip Webb * @author Phillip Webb
* @author Stephane Nicoll * @author Stephane Nicoll
*/ */
public class HealthIndicatorAutoConfigurationTests { class HealthIndicatorAutoConfigurationTests {
private ApplicationContextRunner contextRunner = new ApplicationContextRunner() private ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(HealthIndicatorAutoConfiguration.class)); .withConfiguration(AutoConfigurations.of(HealthIndicatorAutoConfiguration.class));
@Test @Test
public void runWhenNoOtherIndicatorsShouldCreateDefaultApplicationHealthIndicator() { void runWhenNoOtherIndicatorsShouldCreateDefaultApplicationHealthIndicator() {
this.contextRunner.run((context) -> assertThat(context).getBean(HealthIndicator.class) this.contextRunner.run((context) -> assertThat(context).getBean(HealthIndicator.class)
.isInstanceOf(ApplicationHealthIndicator.class)); .isInstanceOf(ApplicationHealthIndicator.class));
} }
@Test @Test
public void runWhenHasDefinedIndicatorShouldNotCreateDefaultApplicationHealthIndicator() { void runWhenHasDefinedIndicatorShouldNotCreateDefaultApplicationHealthIndicator() {
this.contextRunner.withUserConfiguration(CustomHealthIndicatorConfiguration.class) this.contextRunner.withUserConfiguration(CustomHealthIndicatorConfiguration.class)
.run((context) -> assertThat(context).getBean(HealthIndicator.class) .run((context) -> assertThat(context).getBean(HealthIndicator.class)
.isInstanceOf(CustomHealthIndicator.class)); .isInstanceOf(CustomHealthIndicator.class));
} }
@Test @Test
public void runWhenHasDefaultsDisabledAndNoSingleIndicatorEnabledShouldCreateDefaultApplicationHealthIndicator() { void runWhenHasDefaultsDisabledAndNoSingleIndicatorEnabledShouldCreateDefaultApplicationHealthIndicator() {
this.contextRunner.withUserConfiguration(CustomHealthIndicatorConfiguration.class) this.contextRunner.withUserConfiguration(CustomHealthIndicatorConfiguration.class)
.withPropertyValues("management.health.defaults.enabled:false").run((context) -> assertThat(context) .withPropertyValues("management.health.defaults.enabled:false").run((context) -> assertThat(context)
.getBean(HealthIndicator.class).isInstanceOf(ApplicationHealthIndicator.class)); .getBean(HealthIndicator.class).isInstanceOf(ApplicationHealthIndicator.class));
@ -67,7 +67,7 @@ public class HealthIndicatorAutoConfigurationTests {
} }
@Test @Test
public void runWhenHasDefaultsDisabledAndSingleIndicatorEnabledShouldCreateEnabledIndicator() { void runWhenHasDefaultsDisabledAndSingleIndicatorEnabledShouldCreateEnabledIndicator() {
this.contextRunner.withUserConfiguration(CustomHealthIndicatorConfiguration.class) this.contextRunner.withUserConfiguration(CustomHealthIndicatorConfiguration.class)
.withPropertyValues("management.health.defaults.enabled:false", "management.health.custom.enabled:true") .withPropertyValues("management.health.defaults.enabled:false", "management.health.custom.enabled:true")
.run((context) -> assertThat(context).getBean(HealthIndicator.class) .run((context) -> assertThat(context).getBean(HealthIndicator.class)
@ -76,13 +76,13 @@ public class HealthIndicatorAutoConfigurationTests {
} }
@Test @Test
public void runShouldCreateOrderedHealthAggregator() { void runShouldCreateOrderedHealthAggregator() {
this.contextRunner.run((context) -> assertThat(context).getBean(HealthAggregator.class) this.contextRunner.run((context) -> assertThat(context).getBean(HealthAggregator.class)
.isInstanceOf(OrderedHealthAggregator.class)); .isInstanceOf(OrderedHealthAggregator.class));
} }
@Test @Test
public void runWhenHasCustomOrderPropertyShouldCreateOrderedHealthAggregator() { void runWhenHasCustomOrderPropertyShouldCreateOrderedHealthAggregator() {
this.contextRunner.withPropertyValues("management.health.status.order:UP,DOWN").run((context) -> { this.contextRunner.withPropertyValues("management.health.status.order:UP,DOWN").run((context) -> {
OrderedHealthAggregator aggregator = context.getBean(OrderedHealthAggregator.class); OrderedHealthAggregator aggregator = context.getBean(OrderedHealthAggregator.class);
Map<String, Health> healths = new LinkedHashMap<>(); Map<String, Health> healths = new LinkedHashMap<>();
@ -94,7 +94,7 @@ public class HealthIndicatorAutoConfigurationTests {
} }
@Test @Test
public void runWhenHasCustomHealthAggregatorShouldNotCreateOrderedHealthAggregator() { void runWhenHasCustomHealthAggregatorShouldNotCreateOrderedHealthAggregator() {
this.contextRunner.withUserConfiguration(CustomHealthAggregatorConfiguration.class) this.contextRunner.withUserConfiguration(CustomHealthAggregatorConfiguration.class)
.run((context) -> assertThat(context).getBean(HealthAggregator.class) .run((context) -> assertThat(context).getBean(HealthAggregator.class)
.isNotInstanceOf(OrderedHealthAggregator.class)); .isNotInstanceOf(OrderedHealthAggregator.class));

View File

@ -46,25 +46,25 @@ import static org.mockito.Mockito.mock;
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Phillip Webb * @author Phillip Webb
*/ */
public class ReactiveHealthEndpointWebExtensionTests { class ReactiveHealthEndpointWebExtensionTests {
private ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() private ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner()
.withUserConfiguration(HealthIndicatorAutoConfiguration.class, HealthEndpointAutoConfiguration.class); .withUserConfiguration(HealthIndicatorAutoConfiguration.class, HealthEndpointAutoConfiguration.class);
@Test @Test
public void runShouldCreateExtensionBeans() { void runShouldCreateExtensionBeans() {
this.contextRunner this.contextRunner
.run((context) -> assertThat(context).hasSingleBean(ReactiveHealthEndpointWebExtension.class)); .run((context) -> assertThat(context).hasSingleBean(ReactiveHealthEndpointWebExtension.class));
} }
@Test @Test
public void runWhenHealthEndpointIsDisabledShouldNotCreateExtensionBeans() { void runWhenHealthEndpointIsDisabledShouldNotCreateExtensionBeans() {
this.contextRunner.withPropertyValues("management.endpoint.health.enabled:false") this.contextRunner.withPropertyValues("management.endpoint.health.enabled:false")
.run((context) -> assertThat(context).doesNotHaveBean(ReactiveHealthEndpointWebExtension.class)); .run((context) -> assertThat(context).doesNotHaveBean(ReactiveHealthEndpointWebExtension.class));
} }
@Test @Test
public void runWithCustomHealthMappingShouldMapStatusCode() { void runWithCustomHealthMappingShouldMapStatusCode() {
this.contextRunner.withPropertyValues("management.health.status.http-mapping.CUSTOM=500").run((context) -> { this.contextRunner.withPropertyValues("management.health.status.http-mapping.CUSTOM=500").run((context) -> {
Object extension = context.getBean(ReactiveHealthEndpointWebExtension.class); Object extension = context.getBean(ReactiveHealthEndpointWebExtension.class);
HealthWebEndpointResponseMapper responseMapper = (HealthWebEndpointResponseMapper) ReflectionTestUtils HealthWebEndpointResponseMapper responseMapper = (HealthWebEndpointResponseMapper) ReflectionTestUtils
@ -79,7 +79,7 @@ public class ReactiveHealthEndpointWebExtensionTests {
} }
@Test @Test
public void regularAndReactiveHealthIndicatorsMatch() { void regularAndReactiveHealthIndicatorsMatch() {
this.contextRunner.withPropertyValues("management.endpoint.health.show-details=always") this.contextRunner.withPropertyValues("management.endpoint.health.show-details=always")
.withUserConfiguration(HealthIndicatorsConfiguration.class).run((context) -> { .withUserConfiguration(HealthIndicatorsConfiguration.class).run((context) -> {
HealthEndpoint endpoint = context.getBean(HealthEndpoint.class); HealthEndpoint endpoint = context.getBean(HealthEndpoint.class);
@ -95,7 +95,7 @@ public class ReactiveHealthEndpointWebExtensionTests {
} }
@Test @Test
public void unauthenticatedUsersAreNotShownDetailsByDefault() { void unauthenticatedUsersAreNotShownDetailsByDefault() {
this.contextRunner.run((context) -> { this.contextRunner.run((context) -> {
ReactiveHealthEndpointWebExtension extension = context.getBean(ReactiveHealthEndpointWebExtension.class); ReactiveHealthEndpointWebExtension extension = context.getBean(ReactiveHealthEndpointWebExtension.class);
assertThat( assertThat(
@ -105,7 +105,7 @@ public class ReactiveHealthEndpointWebExtensionTests {
} }
@Test @Test
public void authenticatedUsersAreNotShownDetailsByDefault() { void authenticatedUsersAreNotShownDetailsByDefault() {
this.contextRunner.run((context) -> { this.contextRunner.run((context) -> {
ReactiveHealthEndpointWebExtension extension = context.getBean(ReactiveHealthEndpointWebExtension.class); ReactiveHealthEndpointWebExtension extension = context.getBean(ReactiveHealthEndpointWebExtension.class);
SecurityContext securityContext = mock(SecurityContext.class); SecurityContext securityContext = mock(SecurityContext.class);
@ -116,7 +116,7 @@ public class ReactiveHealthEndpointWebExtensionTests {
} }
@Test @Test
public void authenticatedUsersWhenAuthorizedCanBeShownDetails() { void authenticatedUsersWhenAuthorizedCanBeShownDetails() {
this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized") this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized")
.run((context) -> { .run((context) -> {
ReactiveHealthEndpointWebExtension extension = context ReactiveHealthEndpointWebExtension extension = context
@ -129,7 +129,7 @@ public class ReactiveHealthEndpointWebExtensionTests {
} }
@Test @Test
public void unauthenticatedUsersCanBeShownDetails() { void unauthenticatedUsersCanBeShownDetails() {
this.contextRunner.withPropertyValues("management.endpoint.health.show-details=always").run((context) -> { this.contextRunner.withPropertyValues("management.endpoint.health.show-details=always").run((context) -> {
ReactiveHealthEndpointWebExtension extension = context.getBean(ReactiveHealthEndpointWebExtension.class); ReactiveHealthEndpointWebExtension extension = context.getBean(ReactiveHealthEndpointWebExtension.class);
assertThat(extension.health(null).block(Duration.ofSeconds(30)).getBody().getDetails()).isNotEmpty(); assertThat(extension.health(null).block(Duration.ofSeconds(30)).getBody().getDetails()).isNotEmpty();
@ -137,7 +137,7 @@ public class ReactiveHealthEndpointWebExtensionTests {
} }
@Test @Test
public void detailsCanBeHiddenFromAuthenticatedUsers() { void detailsCanBeHiddenFromAuthenticatedUsers() {
this.contextRunner.withPropertyValues("management.endpoint.health.show-details=never").run((context) -> { this.contextRunner.withPropertyValues("management.endpoint.health.show-details=never").run((context) -> {
ReactiveHealthEndpointWebExtension extension = context.getBean(ReactiveHealthEndpointWebExtension.class); ReactiveHealthEndpointWebExtension extension = context.getBean(ReactiveHealthEndpointWebExtension.class);
SecurityContext securityContext = mock(SecurityContext.class); SecurityContext securityContext = mock(SecurityContext.class);
@ -147,7 +147,7 @@ public class ReactiveHealthEndpointWebExtensionTests {
} }
@Test @Test
public void detailsCanBeHiddenFromUnauthorizedUsers() { void detailsCanBeHiddenFromUnauthorizedUsers() {
this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized", this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized",
"management.endpoint.health.roles=ACTUATOR").run((context) -> { "management.endpoint.health.roles=ACTUATOR").run((context) -> {
ReactiveHealthEndpointWebExtension extension = context ReactiveHealthEndpointWebExtension extension = context
@ -161,7 +161,7 @@ public class ReactiveHealthEndpointWebExtensionTests {
} }
@Test @Test
public void detailsCanBeShownToAuthorizedUsers() { void detailsCanBeShownToAuthorizedUsers() {
this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized", this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized",
"management.endpoint.health.roles=ACTUATOR").run((context) -> { "management.endpoint.health.roles=ACTUATOR").run((context) -> {
ReactiveHealthEndpointWebExtension extension = context ReactiveHealthEndpointWebExtension extension = context
@ -175,7 +175,7 @@ public class ReactiveHealthEndpointWebExtensionTests {
} }
@Test @Test
public void roleCanBeCustomized() { void roleCanBeCustomized() {
this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized", this.contextRunner.withPropertyValues("management.endpoint.health.show-details=when-authorized",
"management.endpoint.health.roles=ADMIN").run((context) -> { "management.endpoint.health.roles=ADMIN").run((context) -> {
ReactiveHealthEndpointWebExtension extension = context ReactiveHealthEndpointWebExtension extension = context
@ -189,7 +189,7 @@ public class ReactiveHealthEndpointWebExtensionTests {
} }
@Test @Test
public void registryCanBeAltered() { void registryCanBeAltered() {
this.contextRunner.withUserConfiguration(HealthIndicatorsConfiguration.class) this.contextRunner.withUserConfiguration(HealthIndicatorsConfiguration.class)
.withPropertyValues("management.endpoint.health.show-details=always").run((context) -> { .withPropertyValues("management.endpoint.health.show-details=always").run((context) -> {
ReactiveHealthIndicatorRegistry registry = context.getBean(ReactiveHealthIndicatorRegistry.class); ReactiveHealthIndicatorRegistry registry = context.getBean(ReactiveHealthIndicatorRegistry.class);

View File

@ -33,20 +33,20 @@ import static org.mockito.Mockito.mock;
* *
* @author Eddú Meléndez * @author Eddú Meléndez
*/ */
public class InfluxDbHealthIndicatorAutoConfigurationTests { class InfluxDbHealthIndicatorAutoConfigurationTests {
private ApplicationContextRunner contextRunner = new ApplicationContextRunner() private ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withBean(InfluxDB.class, () -> mock(InfluxDB.class)).withConfiguration(AutoConfigurations .withBean(InfluxDB.class, () -> mock(InfluxDB.class)).withConfiguration(AutoConfigurations
.of(InfluxDbHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class)); .of(InfluxDbHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class));
@Test @Test
public void runShouldCreateIndicator() { void runShouldCreateIndicator() {
this.contextRunner.run((context) -> assertThat(context).hasSingleBean(InfluxDbHealthIndicator.class) this.contextRunner.run((context) -> assertThat(context).hasSingleBean(InfluxDbHealthIndicator.class)
.doesNotHaveBean(ApplicationHealthIndicator.class)); .doesNotHaveBean(ApplicationHealthIndicator.class));
} }
@Test @Test
public void runWhenDisabledShouldNotCreateIndicator() { void runWhenDisabledShouldNotCreateIndicator() {
this.contextRunner.withPropertyValues("management.health.influxdb.enabled:false") this.contextRunner.withPropertyValues("management.health.influxdb.enabled:false")
.run((context) -> assertThat(context).doesNotHaveBean(InfluxDbHealthIndicator.class) .run((context) -> assertThat(context).doesNotHaveBean(InfluxDbHealthIndicator.class)
.hasSingleBean(ApplicationHealthIndicator.class)); .hasSingleBean(ApplicationHealthIndicator.class));

View File

@ -40,7 +40,7 @@ import static org.assertj.core.api.Assertions.assertThat;
* *
* @author Stephane Nicoll * @author Stephane Nicoll
*/ */
public class InfoContributorAutoConfigurationTests { class InfoContributorAutoConfigurationTests {
private AnnotationConfigApplicationContext context; private AnnotationConfigApplicationContext context;
@ -52,21 +52,21 @@ public class InfoContributorAutoConfigurationTests {
} }
@Test @Test
public void disableEnvContributor() { void disableEnvContributor() {
load("management.info.env.enabled:false"); load("management.info.env.enabled:false");
Map<String, InfoContributor> beans = this.context.getBeansOfType(InfoContributor.class); Map<String, InfoContributor> beans = this.context.getBeansOfType(InfoContributor.class);
assertThat(beans).hasSize(0); assertThat(beans).hasSize(0);
} }
@Test @Test
public void defaultInfoContributorsDisabled() { void defaultInfoContributorsDisabled() {
load("management.info.defaults.enabled:false"); load("management.info.defaults.enabled:false");
Map<String, InfoContributor> beans = this.context.getBeansOfType(InfoContributor.class); Map<String, InfoContributor> beans = this.context.getBeansOfType(InfoContributor.class);
assertThat(beans).hasSize(0); assertThat(beans).hasSize(0);
} }
@Test @Test
public void defaultInfoContributorsDisabledWithCustomOne() { void defaultInfoContributorsDisabledWithCustomOne() {
load(CustomInfoContributorConfiguration.class, "management.info.defaults.enabled:false"); load(CustomInfoContributorConfiguration.class, "management.info.defaults.enabled:false");
Map<String, InfoContributor> beans = this.context.getBeansOfType(InfoContributor.class); Map<String, InfoContributor> beans = this.context.getBeansOfType(InfoContributor.class);
assertThat(beans).hasSize(1); assertThat(beans).hasSize(1);
@ -75,7 +75,7 @@ public class InfoContributorAutoConfigurationTests {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Test @Test
public void gitPropertiesDefaultMode() { void gitPropertiesDefaultMode() {
load(GitPropertiesConfiguration.class); load(GitPropertiesConfiguration.class);
Map<String, InfoContributor> beans = this.context.getBeansOfType(InfoContributor.class); Map<String, InfoContributor> beans = this.context.getBeansOfType(InfoContributor.class);
assertThat(beans).containsKeys("gitInfoContributor"); assertThat(beans).containsKeys("gitInfoContributor");
@ -89,7 +89,7 @@ public class InfoContributorAutoConfigurationTests {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Test @Test
public void gitPropertiesFullMode() { void gitPropertiesFullMode() {
load(GitPropertiesConfiguration.class, "management.info.git.mode=full"); load(GitPropertiesConfiguration.class, "management.info.git.mode=full");
Map<String, Object> content = invokeContributor( Map<String, Object> content = invokeContributor(
this.context.getBean("gitInfoContributor", InfoContributor.class)); this.context.getBean("gitInfoContributor", InfoContributor.class));
@ -101,7 +101,7 @@ public class InfoContributorAutoConfigurationTests {
} }
@Test @Test
public void customGitInfoContributor() { void customGitInfoContributor() {
load(CustomGitInfoContributorConfiguration.class); load(CustomGitInfoContributorConfiguration.class);
assertThat(this.context.getBean(GitInfoContributor.class)) assertThat(this.context.getBean(GitInfoContributor.class))
.isSameAs(this.context.getBean("customGitInfoContributor")); .isSameAs(this.context.getBean("customGitInfoContributor"));
@ -109,7 +109,7 @@ public class InfoContributorAutoConfigurationTests {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Test @Test
public void buildProperties() { void buildProperties() {
load(BuildPropertiesConfiguration.class); load(BuildPropertiesConfiguration.class);
Map<String, InfoContributor> beans = this.context.getBeansOfType(InfoContributor.class); Map<String, InfoContributor> beans = this.context.getBeansOfType(InfoContributor.class);
assertThat(beans).containsKeys("buildInfoContributor"); assertThat(beans).containsKeys("buildInfoContributor");
@ -123,7 +123,7 @@ public class InfoContributorAutoConfigurationTests {
} }
@Test @Test
public void customBuildInfoContributor() { void customBuildInfoContributor() {
load(CustomBuildInfoContributorConfiguration.class); load(CustomBuildInfoContributorConfiguration.class);
assertThat(this.context.getBean(BuildInfoContributor.class)) assertThat(this.context.getBean(BuildInfoContributor.class))
.isSameAs(this.context.getBean("customBuildInfoContributor")); .isSameAs(this.context.getBean("customBuildInfoContributor"));

View File

@ -29,26 +29,26 @@ import static org.assertj.core.api.Assertions.assertThat;
* *
* @author Phillip Webb * @author Phillip Webb
*/ */
public class InfoEndpointAutoConfigurationTests { class InfoEndpointAutoConfigurationTests {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(InfoEndpointAutoConfiguration.class)); .withConfiguration(AutoConfigurations.of(InfoEndpointAutoConfiguration.class));
@Test @Test
public void runShouldHaveEndpointBean() { void runShouldHaveEndpointBean() {
this.contextRunner.withPropertyValues("management.endpoint.shutdown.enabled:true") this.contextRunner.withPropertyValues("management.endpoint.shutdown.enabled:true")
.run((context) -> assertThat(context).hasSingleBean(InfoEndpoint.class)); .run((context) -> assertThat(context).hasSingleBean(InfoEndpoint.class));
} }
@Test @Test
public void runShouldHaveEndpointBeanEvenIfDefaultIsDisabled() { void runShouldHaveEndpointBeanEvenIfDefaultIsDisabled() {
// FIXME // FIXME
this.contextRunner.withPropertyValues("management.endpoint.default.enabled:false") this.contextRunner.withPropertyValues("management.endpoint.default.enabled:false")
.run((context) -> assertThat(context).hasSingleBean(InfoEndpoint.class)); .run((context) -> assertThat(context).hasSingleBean(InfoEndpoint.class));
} }
@Test @Test
public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() {
this.contextRunner.withPropertyValues("management.endpoint.info.enabled:false") this.contextRunner.withPropertyValues("management.endpoint.info.enabled:false")
.run((context) -> assertThat(context).doesNotHaveBean(InfoEndpoint.class)); .run((context) -> assertThat(context).doesNotHaveBean(InfoEndpoint.class));
} }

View File

@ -33,20 +33,20 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Tim Ysewyn * @author Tim Ysewyn
* @author Stephane Nicoll * @author Stephane Nicoll
*/ */
public class IntegrationGraphEndpointAutoConfigurationTests { class IntegrationGraphEndpointAutoConfigurationTests {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class, IntegrationAutoConfiguration.class, .withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class, IntegrationAutoConfiguration.class,
IntegrationGraphEndpointAutoConfiguration.class)); IntegrationGraphEndpointAutoConfiguration.class));
@Test @Test
public void runShouldHaveEndpointBean() { void runShouldHaveEndpointBean() {
this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=integrationgraph") this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=integrationgraph")
.run((context) -> assertThat(context).hasSingleBean(IntegrationGraphEndpoint.class)); .run((context) -> assertThat(context).hasSingleBean(IntegrationGraphEndpoint.class));
} }
@Test @Test
public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() {
this.contextRunner.withPropertyValues("management.endpoint.integrationgraph.enabled:false").run((context) -> { this.contextRunner.withPropertyValues("management.endpoint.integrationgraph.enabled:false").run((context) -> {
assertThat(context).doesNotHaveBean(IntegrationGraphEndpoint.class); assertThat(context).doesNotHaveBean(IntegrationGraphEndpoint.class);
assertThat(context).doesNotHaveBean(IntegrationGraphServer.class); assertThat(context).doesNotHaveBean(IntegrationGraphServer.class);
@ -54,7 +54,7 @@ public class IntegrationGraphEndpointAutoConfigurationTests {
} }
@Test @Test
public void runWhenNotExposedShouldNotHaveEndpointBean() { void runWhenNotExposedShouldNotHaveEndpointBean() {
this.contextRunner.run((context) -> { this.contextRunner.run((context) -> {
assertThat(context).doesNotHaveBean(IntegrationGraphEndpoint.class); assertThat(context).doesNotHaveBean(IntegrationGraphEndpoint.class);
assertThat(context).doesNotHaveBean(IntegrationGraphServer.class); assertThat(context).doesNotHaveBean(IntegrationGraphServer.class);
@ -62,7 +62,7 @@ public class IntegrationGraphEndpointAutoConfigurationTests {
} }
@Test @Test
public void runWhenSpringIntegrationIsNotEnabledShouldNotHaveEndpointBean() { void runWhenSpringIntegrationIsNotEnabledShouldNotHaveEndpointBean() {
ApplicationContextRunner noSpringIntegrationRunner = new ApplicationContextRunner() ApplicationContextRunner noSpringIntegrationRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(IntegrationGraphEndpointAutoConfiguration.class)); .withConfiguration(AutoConfigurations.of(IntegrationGraphEndpointAutoConfiguration.class));
noSpringIntegrationRunner.run((context) -> { noSpringIntegrationRunner.run((context) -> {

View File

@ -45,7 +45,7 @@ import org.springframework.web.bind.annotation.GetMapping;
* *
* @author Phillip Webb * @author Phillip Webb
*/ */
public class ControllerEndpointWebFluxIntegrationTests { class ControllerEndpointWebFluxIntegrationTests {
private AnnotationConfigReactiveWebApplicationContext context; private AnnotationConfigReactiveWebApplicationContext context;
@ -56,7 +56,7 @@ public class ControllerEndpointWebFluxIntegrationTests {
} }
@Test @Test
public void endpointsCanBeAccessed() throws Exception { void endpointsCanBeAccessed() throws Exception {
TestSecurityContextHolder.getContext() TestSecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("user", "N/A", "ROLE_ACTUATOR")); .setAuthentication(new TestingAuthenticationToken("user", "N/A", "ROLE_ACTUATOR"));
this.context = new AnnotationConfigReactiveWebApplicationContext(); this.context = new AnnotationConfigReactiveWebApplicationContext();

View File

@ -58,7 +58,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
* @author Phillip Webb * @author Phillip Webb
* @author Andy Wilkinson * @author Andy Wilkinson
*/ */
public class ControllerEndpointWebMvcIntegrationTests { class ControllerEndpointWebMvcIntegrationTests {
private AnnotationConfigServletWebApplicationContext context; private AnnotationConfigServletWebApplicationContext context;
@ -69,7 +69,7 @@ public class ControllerEndpointWebMvcIntegrationTests {
} }
@Test @Test
public void endpointsAreSecureByDefault() throws Exception { void endpointsAreSecureByDefault() throws Exception {
this.context = new AnnotationConfigServletWebApplicationContext(); this.context = new AnnotationConfigServletWebApplicationContext();
this.context.register(SecureConfiguration.class, ExampleController.class); this.context.register(SecureConfiguration.class, ExampleController.class);
MockMvc mockMvc = createSecureMockMvc(); MockMvc mockMvc = createSecureMockMvc();
@ -78,7 +78,7 @@ public class ControllerEndpointWebMvcIntegrationTests {
} }
@Test @Test
public void endpointsCanBeAccessed() throws Exception { void endpointsCanBeAccessed() throws Exception {
TestSecurityContextHolder.getContext() TestSecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("user", "N/A", "ROLE_ACTUATOR")); .setAuthentication(new TestingAuthenticationToken("user", "N/A", "ROLE_ACTUATOR"));
this.context = new AnnotationConfigServletWebApplicationContext(); this.context = new AnnotationConfigServletWebApplicationContext();

View File

@ -43,15 +43,15 @@ import org.springframework.web.servlet.DispatcherServlet;
* @author Andy Wilkinson * @author Andy Wilkinson
* @author Madhura Bhave * @author Madhura Bhave
*/ */
public class JerseyEndpointIntegrationTests { class JerseyEndpointIntegrationTests {
@Test @Test
public void linksAreProvidedToAllEndpointTypes() { void linksAreProvidedToAllEndpointTypes() {
testJerseyEndpoints(new Class[] { EndpointsConfiguration.class, ResourceConfigConfiguration.class }); testJerseyEndpoints(new Class[] { EndpointsConfiguration.class, ResourceConfigConfiguration.class });
} }
@Test @Test
public void actuatorEndpointsWhenUserProvidedResourceConfigBeanNotAvailable() { void actuatorEndpointsWhenUserProvidedResourceConfigBeanNotAvailable() {
testJerseyEndpoints(new Class[] { EndpointsConfiguration.class }); testJerseyEndpoints(new Class[] { EndpointsConfiguration.class });
} }

View File

@ -47,7 +47,7 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Andy Wilkinson * @author Andy Wilkinson
*/ */
public class JmxEndpointIntegrationTests { class JmxEndpointIntegrationTests {
private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class, EndpointAutoConfiguration.class, .withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class, EndpointAutoConfiguration.class,
@ -58,7 +58,7 @@ public class JmxEndpointIntegrationTests {
.withConfiguration(AutoConfigurations.of(EndpointAutoConfigurationClasses.ALL)); .withConfiguration(AutoConfigurations.of(EndpointAutoConfigurationClasses.ALL));
@Test @Test
public void jmxEndpointsAreExposed() { void jmxEndpointsAreExposed() {
this.contextRunner.run((context) -> { this.contextRunner.run((context) -> {
MBeanServer mBeanServer = context.getBean(MBeanServer.class); MBeanServer mBeanServer = context.getBean(MBeanServer.class);
checkEndpointMBeans(mBeanServer, new String[] { "beans", "conditions", "configprops", "env", "health", checkEndpointMBeans(mBeanServer, new String[] { "beans", "conditions", "configprops", "env", "health",
@ -67,7 +67,7 @@ public class JmxEndpointIntegrationTests {
} }
@Test @Test
public void jmxEndpointsCanBeExcluded() { void jmxEndpointsCanBeExcluded() {
this.contextRunner.withPropertyValues("management.endpoints.jmx.exposure.exclude:*").run((context) -> { this.contextRunner.withPropertyValues("management.endpoints.jmx.exposure.exclude:*").run((context) -> {
MBeanServer mBeanServer = context.getBean(MBeanServer.class); MBeanServer mBeanServer = context.getBean(MBeanServer.class);
checkEndpointMBeans(mBeanServer, new String[0], new String[] { "beans", "conditions", "configprops", "env", checkEndpointMBeans(mBeanServer, new String[0], new String[] { "beans", "conditions", "configprops", "env",
@ -77,7 +77,7 @@ public class JmxEndpointIntegrationTests {
} }
@Test @Test
public void singleJmxEndpointCanBeExposed() { void singleJmxEndpointCanBeExposed() {
this.contextRunner.withPropertyValues("management.endpoints.jmx.exposure.include=beans").run((context) -> { this.contextRunner.withPropertyValues("management.endpoints.jmx.exposure.include=beans").run((context) -> {
MBeanServer mBeanServer = context.getBean(MBeanServer.class); MBeanServer mBeanServer = context.getBean(MBeanServer.class);
checkEndpointMBeans(mBeanServer, new String[] { "beans" }, new String[] { "conditions", "configprops", checkEndpointMBeans(mBeanServer, new String[] { "beans" }, new String[] { "conditions", "configprops",

View File

@ -58,13 +58,13 @@ import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT,
properties = "management.endpoints.web.exposure.include=jolokia") properties = "management.endpoints.web.exposure.include=jolokia")
@DirtiesContext @DirtiesContext
public class JolokiaEndpointAutoConfigurationIntegrationTests { class JolokiaEndpointAutoConfigurationIntegrationTests {
@Autowired @Autowired
private TestRestTemplate restTemplate; private TestRestTemplate restTemplate;
@Test @Test
public void jolokiaIsExposed() { void jolokiaIsExposed() {
ResponseEntity<String> response = this.restTemplate.getForEntity("/actuator/jolokia", String.class); ResponseEntity<String> response = this.restTemplate.getForEntity("/actuator/jolokia", String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(response.getBody()).contains("\"agent\""); assertThat(response.getBody()).contains("\"agent\"");
@ -72,7 +72,7 @@ public class JolokiaEndpointAutoConfigurationIntegrationTests {
} }
@Test @Test
public void search() { void search() {
ResponseEntity<String> response = this.restTemplate.getForEntity("/actuator/jolokia/search/java.lang:*", ResponseEntity<String> response = this.restTemplate.getForEntity("/actuator/jolokia/search/java.lang:*",
String.class); String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
@ -80,7 +80,7 @@ public class JolokiaEndpointAutoConfigurationIntegrationTests {
} }
@Test @Test
public void read() { void read() {
ResponseEntity<String> response = this.restTemplate.getForEntity("/actuator/jolokia/read/java.lang:type=Memory", ResponseEntity<String> response = this.restTemplate.getForEntity("/actuator/jolokia/read/java.lang:type=Memory",
String.class); String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
@ -88,7 +88,7 @@ public class JolokiaEndpointAutoConfigurationIntegrationTests {
} }
@Test @Test
public void list() { void list() {
ResponseEntity<String> response = this.restTemplate ResponseEntity<String> response = this.restTemplate
.getForEntity("/actuator/jolokia/list/java.lang/type=Memory/attr", String.class); .getForEntity("/actuator/jolokia/list/java.lang/type=Memory/attr", String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);

View File

@ -51,16 +51,16 @@ import static org.assertj.core.api.Assertions.assertThat;
* *
* @author Andy Wilkinson * @author Andy Wilkinson
*/ */
public class WebEndpointsAutoConfigurationIntegrationTests { class WebEndpointsAutoConfigurationIntegrationTests {
@Test @Test
public void healthEndpointWebExtensionIsAutoConfigured() { void healthEndpointWebExtensionIsAutoConfigured() {
servletWebRunner().run((context) -> context.getBean(WebEndpointTestApplication.class)); servletWebRunner().run((context) -> context.getBean(WebEndpointTestApplication.class));
servletWebRunner().run((context) -> assertThat(context).hasSingleBean(HealthEndpointWebExtension.class)); servletWebRunner().run((context) -> assertThat(context).hasSingleBean(HealthEndpointWebExtension.class));
} }
@Test @Test
public void healthEndpointReactiveWebExtensionIsAutoConfigured() { void healthEndpointReactiveWebExtensionIsAutoConfigured() {
reactiveWebRunner() reactiveWebRunner()
.run((context) -> assertThat(context).hasSingleBean(ReactiveHealthEndpointWebExtension.class)); .run((context) -> assertThat(context).hasSingleBean(ReactiveHealthEndpointWebExtension.class));
} }

View File

@ -44,7 +44,7 @@ import org.springframework.test.web.reactive.server.WebTestClient;
* @author Stephane Nicoll * @author Stephane Nicoll
* @see WebFluxEndpointManagementContextConfiguration * @see WebFluxEndpointManagementContextConfiguration
*/ */
public class WebFluxEndpointCorsIntegrationTests { class WebFluxEndpointCorsIntegrationTests {
private ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() private ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, CodecsAutoConfiguration.class, .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, CodecsAutoConfiguration.class,
@ -54,14 +54,14 @@ public class WebFluxEndpointCorsIntegrationTests {
.withPropertyValues("management.endpoints.web.exposure.include:*"); .withPropertyValues("management.endpoints.web.exposure.include:*");
@Test @Test
public void corsIsDisabledByDefault() { void corsIsDisabledByDefault() {
this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.options().uri("/actuator/beans") this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.options().uri("/actuator/beans")
.header("Origin", "spring.example.org").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") .header("Origin", "spring.example.org").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")
.exchange().expectHeader().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN))); .exchange().expectHeader().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)));
} }
@Test @Test
public void settingAllowedOriginsEnablesCors() { void settingAllowedOriginsEnablesCors() {
this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org") this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org")
.run(withWebTestClient((webTestClient) -> { .run(withWebTestClient((webTestClient) -> {
webTestClient.options().uri("/actuator/beans").header("Origin", "test.example.org") webTestClient.options().uri("/actuator/beans").header("Origin", "test.example.org")
@ -72,14 +72,14 @@ public class WebFluxEndpointCorsIntegrationTests {
} }
@Test @Test
public void maxAgeDefaultsTo30Minutes() { void maxAgeDefaultsTo30Minutes() {
this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org") this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org")
.run(withWebTestClient((webTestClient) -> performAcceptedCorsRequest(webTestClient, "/actuator/beans") .run(withWebTestClient((webTestClient) -> performAcceptedCorsRequest(webTestClient, "/actuator/beans")
.expectHeader().valueEquals(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"))); .expectHeader().valueEquals(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800")));
} }
@Test @Test
public void maxAgeCanBeConfigured() { void maxAgeCanBeConfigured() {
this.contextRunner this.contextRunner
.withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org", .withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org",
"management.endpoints.web.cors.max-age: 2400") "management.endpoints.web.cors.max-age: 2400")
@ -88,7 +88,7 @@ public class WebFluxEndpointCorsIntegrationTests {
} }
@Test @Test
public void requestsWithDisallowedHeadersAreRejected() { void requestsWithDisallowedHeadersAreRejected() {
this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org") this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org")
.run(withWebTestClient((webTestClient) -> webTestClient.options().uri("/actuator/beans") .run(withWebTestClient((webTestClient) -> webTestClient.options().uri("/actuator/beans")
.header("Origin", "spring.example.org").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") .header("Origin", "spring.example.org").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")
@ -97,7 +97,7 @@ public class WebFluxEndpointCorsIntegrationTests {
} }
@Test @Test
public void allowedHeadersCanBeConfigured() { void allowedHeadersCanBeConfigured() {
this.contextRunner this.contextRunner
.withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org", .withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org",
"management.endpoints.web.cors.allowed-headers:Alpha,Bravo") "management.endpoints.web.cors.allowed-headers:Alpha,Bravo")
@ -108,7 +108,7 @@ public class WebFluxEndpointCorsIntegrationTests {
} }
@Test @Test
public void requestsWithDisallowedMethodsAreRejected() { void requestsWithDisallowedMethodsAreRejected() {
this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org") this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org")
.run(withWebTestClient((webTestClient) -> webTestClient.options().uri("/actuator/beans") .run(withWebTestClient((webTestClient) -> webTestClient.options().uri("/actuator/beans")
.header("Origin", "spring.example.org") .header("Origin", "spring.example.org")
@ -117,7 +117,7 @@ public class WebFluxEndpointCorsIntegrationTests {
} }
@Test @Test
public void allowedMethodsCanBeConfigured() { void allowedMethodsCanBeConfigured() {
this.contextRunner this.contextRunner
.withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org", .withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org",
"management.endpoints.web.cors.allowed-methods:GET,HEAD") "management.endpoints.web.cors.allowed-methods:GET,HEAD")
@ -128,7 +128,7 @@ public class WebFluxEndpointCorsIntegrationTests {
} }
@Test @Test
public void credentialsCanBeAllowed() { void credentialsCanBeAllowed() {
this.contextRunner this.contextRunner
.withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org", .withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org",
"management.endpoints.web.cors.allow-credentials:true") "management.endpoints.web.cors.allow-credentials:true")
@ -137,7 +137,7 @@ public class WebFluxEndpointCorsIntegrationTests {
} }
@Test @Test
public void credentialsCanBeDisabled() { void credentialsCanBeDisabled() {
this.contextRunner this.contextRunner
.withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org", .withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org",
"management.endpoints.web.cors.allow-credentials:false") "management.endpoints.web.cors.allow-credentials:false")

View File

@ -41,10 +41,10 @@ import org.springframework.test.web.reactive.server.WebTestClient;
* *
* @author Andy Wilkinson * @author Andy Wilkinson
*/ */
public class WebFluxEndpointIntegrationTests { class WebFluxEndpointIntegrationTests {
@Test @Test
public void linksAreProvidedToAllEndpointTypes() throws Exception { void linksAreProvidedToAllEndpointTypes() throws Exception {
new ReactiveWebApplicationContextRunner() new ReactiveWebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, CodecsAutoConfiguration.class, .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, CodecsAutoConfiguration.class,
WebFluxAutoConfiguration.class, HttpHandlerAutoConfiguration.class, WebFluxAutoConfiguration.class, HttpHandlerAutoConfiguration.class,

View File

@ -48,7 +48,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
* @author Stephane Nicoll * @author Stephane Nicoll
* @see WebMvcEndpointManagementContextConfiguration * @see WebMvcEndpointManagementContextConfiguration
*/ */
public class WebMvcEndpointCorsIntegrationTests { class WebMvcEndpointCorsIntegrationTests {
private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class,
@ -59,7 +59,7 @@ public class WebMvcEndpointCorsIntegrationTests {
.withPropertyValues("management.endpoints.web.exposure.include:*"); .withPropertyValues("management.endpoints.web.exposure.include:*");
@Test @Test
public void corsIsDisabledByDefault() { void corsIsDisabledByDefault() {
this.contextRunner.run(withMockMvc((mockMvc) -> mockMvc this.contextRunner.run(withMockMvc((mockMvc) -> mockMvc
.perform(options("/actuator/beans").header("Origin", "foo.example.com") .perform(options("/actuator/beans").header("Origin", "foo.example.com")
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")) .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET"))
@ -67,7 +67,7 @@ public class WebMvcEndpointCorsIntegrationTests {
} }
@Test @Test
public void settingAllowedOriginsEnablesCors() { void settingAllowedOriginsEnablesCors() {
this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com") this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com")
.run(withMockMvc((mockMvc) -> { .run(withMockMvc((mockMvc) -> {
mockMvc.perform(options("/actuator/beans").header("Origin", "bar.example.com") mockMvc.perform(options("/actuator/beans").header("Origin", "bar.example.com")
@ -78,14 +78,14 @@ public class WebMvcEndpointCorsIntegrationTests {
} }
@Test @Test
public void maxAgeDefaultsTo30Minutes() { void maxAgeDefaultsTo30Minutes() {
this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com") this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com")
.run(withMockMvc((mockMvc) -> performAcceptedCorsRequest(mockMvc) .run(withMockMvc((mockMvc) -> performAcceptedCorsRequest(mockMvc)
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800")))); .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"))));
} }
@Test @Test
public void maxAgeCanBeConfigured() { void maxAgeCanBeConfigured() {
this.contextRunner this.contextRunner
.withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com", .withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com",
"management.endpoints.web.cors.max-age: 2400") "management.endpoints.web.cors.max-age: 2400")
@ -94,7 +94,7 @@ public class WebMvcEndpointCorsIntegrationTests {
} }
@Test @Test
public void requestsWithDisallowedHeadersAreRejected() { void requestsWithDisallowedHeadersAreRejected() {
this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com") this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com")
.run(withMockMvc((mockMvc) -> .run(withMockMvc((mockMvc) ->
@ -105,7 +105,7 @@ public class WebMvcEndpointCorsIntegrationTests {
} }
@Test @Test
public void allowedHeadersCanBeConfigured() { void allowedHeadersCanBeConfigured() {
this.contextRunner this.contextRunner
.withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com", .withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com",
"management.endpoints.web.cors.allowed-headers:Alpha,Bravo") "management.endpoints.web.cors.allowed-headers:Alpha,Bravo")
@ -118,7 +118,7 @@ public class WebMvcEndpointCorsIntegrationTests {
} }
@Test @Test
public void requestsWithDisallowedMethodsAreRejected() { void requestsWithDisallowedMethodsAreRejected() {
this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com") this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com")
.run(withMockMvc((mockMvc) -> mockMvc .run(withMockMvc((mockMvc) -> mockMvc
.perform(options("/actuator/beans").header(HttpHeaders.ORIGIN, "foo.example.com") .perform(options("/actuator/beans").header(HttpHeaders.ORIGIN, "foo.example.com")
@ -127,7 +127,7 @@ public class WebMvcEndpointCorsIntegrationTests {
} }
@Test @Test
public void allowedMethodsCanBeConfigured() { void allowedMethodsCanBeConfigured() {
this.contextRunner this.contextRunner
.withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com", .withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com",
"management.endpoints.web.cors.allowed-methods:GET,HEAD") "management.endpoints.web.cors.allowed-methods:GET,HEAD")
@ -139,7 +139,7 @@ public class WebMvcEndpointCorsIntegrationTests {
} }
@Test @Test
public void credentialsCanBeAllowed() { void credentialsCanBeAllowed() {
this.contextRunner this.contextRunner
.withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com", .withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com",
"management.endpoints.web.cors.allow-credentials:true") "management.endpoints.web.cors.allow-credentials:true")
@ -148,7 +148,7 @@ public class WebMvcEndpointCorsIntegrationTests {
} }
@Test @Test
public void credentialsCanBeDisabled() { void credentialsCanBeDisabled() {
this.contextRunner this.contextRunner
.withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com", .withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com",
"management.endpoints.web.cors.allow-credentials:false") "management.endpoints.web.cors.allow-credentials:false")

View File

@ -63,7 +63,7 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Phillip Webb * @author Phillip Webb
*/ */
public class WebMvcEndpointExposureIntegrationTests { class WebMvcEndpointExposureIntegrationTests {
private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner( private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner(
AnnotationConfigServletWebServerApplicationContext::new) AnnotationConfigServletWebServerApplicationContext::new)
@ -80,7 +80,7 @@ public class WebMvcEndpointExposureIntegrationTests {
.withPropertyValues("server.port:0"); .withPropertyValues("server.port:0");
@Test @Test
public void webEndpointsAreDisabledByDefault() { void webEndpointsAreDisabledByDefault() {
this.contextRunner.run((context) -> { this.contextRunner.run((context) -> {
WebTestClient client = createClient(context); WebTestClient client = createClient(context);
assertThat(isExposed(client, HttpMethod.GET, "beans")).isFalse(); assertThat(isExposed(client, HttpMethod.GET, "beans")).isFalse();
@ -99,7 +99,7 @@ public class WebMvcEndpointExposureIntegrationTests {
} }
@Test @Test
public void webEndpointsCanBeExposed() { void webEndpointsCanBeExposed() {
WebApplicationContextRunner contextRunner = this.contextRunner WebApplicationContextRunner contextRunner = this.contextRunner
.withPropertyValues("management.endpoints.web.exposure.include=*"); .withPropertyValues("management.endpoints.web.exposure.include=*");
contextRunner.run((context) -> { contextRunner.run((context) -> {
@ -120,7 +120,7 @@ public class WebMvcEndpointExposureIntegrationTests {
} }
@Test @Test
public void singleWebEndpointCanBeExposed() { void singleWebEndpointCanBeExposed() {
WebApplicationContextRunner contextRunner = this.contextRunner WebApplicationContextRunner contextRunner = this.contextRunner
.withPropertyValues("management.endpoints.web.exposure.include=beans"); .withPropertyValues("management.endpoints.web.exposure.include=beans");
contextRunner.run((context) -> { contextRunner.run((context) -> {
@ -141,7 +141,7 @@ public class WebMvcEndpointExposureIntegrationTests {
} }
@Test @Test
public void singleWebEndpointCanBeExcluded() { void singleWebEndpointCanBeExcluded() {
WebApplicationContextRunner contextRunner = this.contextRunner.withPropertyValues( WebApplicationContextRunner contextRunner = this.contextRunner.withPropertyValues(
"management.endpoints.web.exposure.include=*", "management.endpoints.web.exposure.exclude=shutdown"); "management.endpoints.web.exposure.include=*", "management.endpoints.web.exposure.exclude=shutdown");
contextRunner.run((context) -> { contextRunner.run((context) -> {

View File

@ -68,7 +68,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
* *
* @author Andy Wilkinson * @author Andy Wilkinson
*/ */
public class WebMvcEndpointIntegrationTests { class WebMvcEndpointIntegrationTests {
private AnnotationConfigServletWebApplicationContext context; private AnnotationConfigServletWebApplicationContext context;
@ -79,7 +79,7 @@ public class WebMvcEndpointIntegrationTests {
} }
@Test @Test
public void endpointsAreSecureByDefault() throws Exception { void endpointsAreSecureByDefault() throws Exception {
this.context = new AnnotationConfigServletWebApplicationContext(); this.context = new AnnotationConfigServletWebApplicationContext();
this.context.register(SecureConfiguration.class); this.context.register(SecureConfiguration.class);
MockMvc mockMvc = createSecureMockMvc(); MockMvc mockMvc = createSecureMockMvc();
@ -87,7 +87,7 @@ public class WebMvcEndpointIntegrationTests {
} }
@Test @Test
public void endpointsAreSecureByDefaultWithCustomBasePath() throws Exception { void endpointsAreSecureByDefaultWithCustomBasePath() throws Exception {
this.context = new AnnotationConfigServletWebApplicationContext(); this.context = new AnnotationConfigServletWebApplicationContext();
this.context.register(SecureConfiguration.class); this.context.register(SecureConfiguration.class);
TestPropertyValues.of("management.endpoints.web.base-path:/management").applyTo(this.context); TestPropertyValues.of("management.endpoints.web.base-path:/management").applyTo(this.context);
@ -97,7 +97,7 @@ public class WebMvcEndpointIntegrationTests {
} }
@Test @Test
public void endpointsAreSecureWithActuatorRoleWithCustomBasePath() throws Exception { void endpointsAreSecureWithActuatorRoleWithCustomBasePath() throws Exception {
TestSecurityContextHolder.getContext() TestSecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("user", "N/A", "ROLE_ACTUATOR")); .setAuthentication(new TestingAuthenticationToken("user", "N/A", "ROLE_ACTUATOR"));
this.context = new AnnotationConfigServletWebApplicationContext(); this.context = new AnnotationConfigServletWebApplicationContext();
@ -110,7 +110,7 @@ public class WebMvcEndpointIntegrationTests {
} }
@Test @Test
public void linksAreProvidedToAllEndpointTypes() throws Exception { void linksAreProvidedToAllEndpointTypes() throws Exception {
this.context = new AnnotationConfigServletWebApplicationContext(); this.context = new AnnotationConfigServletWebApplicationContext();
this.context.register(DefaultConfiguration.class, EndpointsConfiguration.class); this.context.register(DefaultConfiguration.class, EndpointsConfiguration.class);
TestPropertyValues.of("management.endpoints.web.exposure.include=*").applyTo(this.context); TestPropertyValues.of("management.endpoints.web.exposure.include=*").applyTo(this.context);

View File

@ -45,7 +45,7 @@ import static org.mockito.Mockito.mock;
* *
* @author Phillip Webb * @author Phillip Webb
*/ */
public class DataSourceHealthIndicatorAutoConfigurationTests { class DataSourceHealthIndicatorAutoConfigurationTests {
private ApplicationContextRunner contextRunner = new ApplicationContextRunner() private ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class,
@ -53,7 +53,7 @@ public class DataSourceHealthIndicatorAutoConfigurationTests {
.withPropertyValues("spring.datasource.initialization-mode=never"); .withPropertyValues("spring.datasource.initialization-mode=never");
@Test @Test
public void runShouldCreateIndicator() { void runShouldCreateIndicator() {
this.contextRunner.run((context) -> { this.contextRunner.run((context) -> {
context.getBean(DataSourceHealthIndicator.class); context.getBean(DataSourceHealthIndicator.class);
assertThat(context).hasSingleBean(DataSourceHealthIndicator.class) assertThat(context).hasSingleBean(DataSourceHealthIndicator.class)
@ -62,7 +62,7 @@ public class DataSourceHealthIndicatorAutoConfigurationTests {
} }
@Test @Test
public void runWhenMultipleDataSourceBeansShouldCreateCompositeIndicator() { void runWhenMultipleDataSourceBeansShouldCreateCompositeIndicator() {
this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, DataSourceConfig.class) this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, DataSourceConfig.class)
.run((context) -> { .run((context) -> {
assertThat(context).hasSingleBean(HealthIndicator.class); assertThat(context).hasSingleBean(HealthIndicator.class);
@ -72,14 +72,14 @@ public class DataSourceHealthIndicatorAutoConfigurationTests {
} }
@Test @Test
public void runShouldFilterRoutingDataSource() { void runShouldFilterRoutingDataSource() {
this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, RoutingDatasourceConfig.class) this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, RoutingDatasourceConfig.class)
.run((context) -> assertThat(context).hasSingleBean(DataSourceHealthIndicator.class) .run((context) -> assertThat(context).hasSingleBean(DataSourceHealthIndicator.class)
.doesNotHaveBean(CompositeHealthIndicator.class)); .doesNotHaveBean(CompositeHealthIndicator.class));
} }
@Test @Test
public void runWithValidationQueryPropertyShouldUseCustomQuery() { void runWithValidationQueryPropertyShouldUseCustomQuery() {
this.contextRunner this.contextRunner
.withUserConfiguration(DataSourceConfig.class, DataSourcePoolMetadataProvidersConfiguration.class) .withUserConfiguration(DataSourceConfig.class, DataSourcePoolMetadataProvidersConfiguration.class)
.withPropertyValues("spring.datasource.test.validation-query:SELECT from FOOBAR").run((context) -> { .withPropertyValues("spring.datasource.test.validation-query:SELECT from FOOBAR").run((context) -> {
@ -90,7 +90,7 @@ public class DataSourceHealthIndicatorAutoConfigurationTests {
} }
@Test @Test
public void runWhenDisabledShouldNotCreateIndicator() { void runWhenDisabledShouldNotCreateIndicator() {
this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class)
.withPropertyValues("management.health.db.enabled:false") .withPropertyValues("management.health.db.enabled:false")
.run((context) -> assertThat(context).doesNotHaveBean(DataSourceHealthIndicator.class) .run((context) -> assertThat(context).doesNotHaveBean(DataSourceHealthIndicator.class)

View File

@ -33,20 +33,20 @@ import static org.assertj.core.api.Assertions.assertThat;
* *
* @author Phillip Webb * @author Phillip Webb
*/ */
public class JmsHealthIndicatorAutoConfigurationTests { class JmsHealthIndicatorAutoConfigurationTests {
private ApplicationContextRunner contextRunner = new ApplicationContextRunner() private ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(ActiveMQAutoConfiguration.class, .withConfiguration(AutoConfigurations.of(ActiveMQAutoConfiguration.class,
JmsHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class)); JmsHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class));
@Test @Test
public void runShouldCreateIndicator() { void runShouldCreateIndicator() {
this.contextRunner.run((context) -> assertThat(context).hasSingleBean(JmsHealthIndicator.class) this.contextRunner.run((context) -> assertThat(context).hasSingleBean(JmsHealthIndicator.class)
.doesNotHaveBean(ApplicationHealthIndicator.class)); .doesNotHaveBean(ApplicationHealthIndicator.class));
} }
@Test @Test
public void runWhenDisabledShouldNotCreateIndicator() { void runWhenDisabledShouldNotCreateIndicator() {
this.contextRunner.withPropertyValues("management.health.jms.enabled:false") this.contextRunner.withPropertyValues("management.health.jms.enabled:false")
.run((context) -> assertThat(context).doesNotHaveBean(LdapHealthIndicator.class) .run((context) -> assertThat(context).doesNotHaveBean(LdapHealthIndicator.class)
.hasSingleBean(ApplicationHealthIndicator.class)); .hasSingleBean(ApplicationHealthIndicator.class));

View File

@ -46,7 +46,7 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Andy Wilkinson * @author Andy Wilkinson
* @author Stephane Nicoll * @author Stephane Nicoll
*/ */
public class JolokiaEndpointAutoConfigurationTests { class JolokiaEndpointAutoConfigurationTests {
private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(DispatcherServletAutoConfiguration.class, .withConfiguration(AutoConfigurations.of(DispatcherServletAutoConfiguration.class,
@ -55,7 +55,7 @@ public class JolokiaEndpointAutoConfigurationTests {
TestConfiguration.class)); TestConfiguration.class));
@Test @Test
public void jolokiaServletShouldBeEnabledByDefault() { void jolokiaServletShouldBeEnabledByDefault() {
this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=jolokia").run((context) -> { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=jolokia").run((context) -> {
ExposableServletEndpoint endpoint = getEndpoint(context); ExposableServletEndpoint endpoint = getEndpoint(context);
assertThat(endpoint.getRootPath()).isEqualTo("jolokia"); assertThat(endpoint.getRootPath()).isEqualTo("jolokia");
@ -65,7 +65,7 @@ public class JolokiaEndpointAutoConfigurationTests {
} }
@Test @Test
public void jolokiaServletWhenEndpointNotExposedShouldNotBeDiscovered() { void jolokiaServletWhenEndpointNotExposedShouldNotBeDiscovered() {
this.contextRunner.run((context) -> { this.contextRunner.run((context) -> {
Collection<ExposableServletEndpoint> endpoints = context.getBean(ServletEndpointsSupplier.class) Collection<ExposableServletEndpoint> endpoints = context.getBean(ServletEndpointsSupplier.class)
.getEndpoints(); .getEndpoints();
@ -74,7 +74,7 @@ public class JolokiaEndpointAutoConfigurationTests {
} }
@Test @Test
public void jolokiaServletWhenDisabledShouldNotBeDiscovered() { void jolokiaServletWhenDisabledShouldNotBeDiscovered() {
this.contextRunner.withPropertyValues("management.endpoint.jolokia.enabled=false") this.contextRunner.withPropertyValues("management.endpoint.jolokia.enabled=false")
.withPropertyValues("management.endpoints.web.exposure.include=jolokia").run((context) -> { .withPropertyValues("management.endpoints.web.exposure.include=jolokia").run((context) -> {
Collection<ExposableServletEndpoint> endpoints = context.getBean(ServletEndpointsSupplier.class) Collection<ExposableServletEndpoint> endpoints = context.getBean(ServletEndpointsSupplier.class)
@ -84,7 +84,7 @@ public class JolokiaEndpointAutoConfigurationTests {
} }
@Test @Test
public void jolokiaServletWhenHasCustomConfigShouldApplyInitParams() { void jolokiaServletWhenHasCustomConfigShouldApplyInitParams() {
this.contextRunner.withPropertyValues("management.endpoint.jolokia.config.debug=true") this.contextRunner.withPropertyValues("management.endpoint.jolokia.config.debug=true")
.withPropertyValues("management.endpoints.web.exposure.include=jolokia").run((context) -> { .withPropertyValues("management.endpoints.web.exposure.include=jolokia").run((context) -> {
ExposableServletEndpoint endpoint = getEndpoint(context); ExposableServletEndpoint endpoint = getEndpoint(context);

View File

@ -34,20 +34,20 @@ import static org.mockito.Mockito.mock;
* @author Eddú Meléndez * @author Eddú Meléndez
* @author Stephane Nicoll * @author Stephane Nicoll
*/ */
public class LdapHealthIndicatorAutoConfigurationTests { class LdapHealthIndicatorAutoConfigurationTests {
private ApplicationContextRunner contextRunner = new ApplicationContextRunner() private ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withBean(LdapOperations.class, () -> mock(LdapOperations.class)).withConfiguration(AutoConfigurations .withBean(LdapOperations.class, () -> mock(LdapOperations.class)).withConfiguration(AutoConfigurations
.of(LdapHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class)); .of(LdapHealthIndicatorAutoConfiguration.class, HealthIndicatorAutoConfiguration.class));
@Test @Test
public void runShouldCreateIndicator() { void runShouldCreateIndicator() {
this.contextRunner.run((context) -> assertThat(context).hasSingleBean(LdapHealthIndicator.class) this.contextRunner.run((context) -> assertThat(context).hasSingleBean(LdapHealthIndicator.class)
.doesNotHaveBean(ApplicationHealthIndicator.class)); .doesNotHaveBean(ApplicationHealthIndicator.class));
} }
@Test @Test
public void runWhenDisabledShouldNotCreateIndicator() { void runWhenDisabledShouldNotCreateIndicator() {
this.contextRunner.withPropertyValues("management.health.ldap.enabled:false") this.contextRunner.withPropertyValues("management.health.ldap.enabled:false")
.run((context) -> assertThat(context).doesNotHaveBean(LdapHealthIndicator.class) .run((context) -> assertThat(context).doesNotHaveBean(LdapHealthIndicator.class)
.hasSingleBean(ApplicationHealthIndicator.class)); .hasSingleBean(ApplicationHealthIndicator.class));

View File

@ -34,32 +34,32 @@ import static org.mockito.Mockito.mock;
* *
* @author Phillip Webb * @author Phillip Webb
*/ */
public class LiquibaseEndpointAutoConfigurationTests { class LiquibaseEndpointAutoConfigurationTests {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(LiquibaseEndpointAutoConfiguration.class)); .withConfiguration(AutoConfigurations.of(LiquibaseEndpointAutoConfiguration.class));
@Test @Test
public void runShouldHaveEndpointBean() { void runShouldHaveEndpointBean() {
this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=liquibase") this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=liquibase")
.withBean(SpringLiquibase.class, () -> mock(SpringLiquibase.class)) .withBean(SpringLiquibase.class, () -> mock(SpringLiquibase.class))
.run((context) -> assertThat(context).hasSingleBean(LiquibaseEndpoint.class)); .run((context) -> assertThat(context).hasSingleBean(LiquibaseEndpoint.class));
} }
@Test @Test
public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() {
this.contextRunner.withBean(SpringLiquibase.class, () -> mock(SpringLiquibase.class)) this.contextRunner.withBean(SpringLiquibase.class, () -> mock(SpringLiquibase.class))
.withPropertyValues("management.endpoint.liquibase.enabled:false") .withPropertyValues("management.endpoint.liquibase.enabled:false")
.run((context) -> assertThat(context).doesNotHaveBean(LiquibaseEndpoint.class)); .run((context) -> assertThat(context).doesNotHaveBean(LiquibaseEndpoint.class));
} }
@Test @Test
public void runWhenNotExposedShouldNotHaveEndpointBean() { void runWhenNotExposedShouldNotHaveEndpointBean() {
this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(LiquibaseEndpoint.class)); this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(LiquibaseEndpoint.class));
} }
@Test @Test
public void disablesCloseOfDataSourceWhenEndpointIsEnabled() { void disablesCloseOfDataSourceWhenEndpointIsEnabled() {
this.contextRunner.withUserConfiguration(DataSourceClosingLiquibaseConfiguration.class) this.contextRunner.withUserConfiguration(DataSourceClosingLiquibaseConfiguration.class)
.withPropertyValues("management.endpoints.web.exposure.include=liquibase").run((context) -> { .withPropertyValues("management.endpoints.web.exposure.include=liquibase").run((context) -> {
assertThat(context).hasSingleBean(LiquibaseEndpoint.class); assertThat(context).hasSingleBean(LiquibaseEndpoint.class);
@ -69,7 +69,7 @@ public class LiquibaseEndpointAutoConfigurationTests {
} }
@Test @Test
public void doesNotDisableCloseOfDataSourceWhenEndpointIsDisabled() { void doesNotDisableCloseOfDataSourceWhenEndpointIsDisabled() {
this.contextRunner.withUserConfiguration(DataSourceClosingLiquibaseConfiguration.class) this.contextRunner.withUserConfiguration(DataSourceClosingLiquibaseConfiguration.class)
.withPropertyValues("management.endpoint.liquibase.enabled:false").run((context) -> { .withPropertyValues("management.endpoint.liquibase.enabled:false").run((context) -> {
assertThat(context).doesNotHaveBean(LiquibaseEndpoint.class); assertThat(context).doesNotHaveBean(LiquibaseEndpoint.class);

View File

@ -41,25 +41,25 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Phillip Webb * @author Phillip Webb
* @author Christian Carriere-Tisseur * @author Christian Carriere-Tisseur
*/ */
public class LogFileWebEndpointAutoConfigurationTests { class LogFileWebEndpointAutoConfigurationTests {
private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(LogFileWebEndpointAutoConfiguration.class)); .withConfiguration(AutoConfigurations.of(LogFileWebEndpointAutoConfiguration.class));
@Test @Test
public void runWithOnlyExposedShouldNotHaveEndpointBean() { void runWithOnlyExposedShouldNotHaveEndpointBean() {
this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=logfile") this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=logfile")
.run((context) -> assertThat(context).doesNotHaveBean(LogFileWebEndpoint.class)); .run((context) -> assertThat(context).doesNotHaveBean(LogFileWebEndpoint.class));
} }
@Test @Test
public void runWhenLoggingFileIsSetAndNotExposedShouldNotHaveEndpointBean() { void runWhenLoggingFileIsSetAndNotExposedShouldNotHaveEndpointBean() {
this.contextRunner.withPropertyValues("logging.file.name:test.log") this.contextRunner.withPropertyValues("logging.file.name:test.log")
.run((context) -> assertThat(context).doesNotHaveBean(LogFileWebEndpoint.class)); .run((context) -> assertThat(context).doesNotHaveBean(LogFileWebEndpoint.class));
} }
@Test @Test
public void runWhenLoggingFileIsSetAndExposedShouldHaveEndpointBean() { void runWhenLoggingFileIsSetAndExposedShouldHaveEndpointBean() {
this.contextRunner this.contextRunner
.withPropertyValues("logging.file.name:test.log", "management.endpoints.web.exposure.include=logfile") .withPropertyValues("logging.file.name:test.log", "management.endpoints.web.exposure.include=logfile")
.run((context) -> assertThat(context).hasSingleBean(LogFileWebEndpoint.class)); .run((context) -> assertThat(context).hasSingleBean(LogFileWebEndpoint.class));
@ -67,20 +67,20 @@ public class LogFileWebEndpointAutoConfigurationTests {
@Test @Test
@Deprecated @Deprecated
public void runWhenLoggingFileIsSetWithDeprecatedPropertyAndExposedShouldHaveEndpointBean() { void runWhenLoggingFileIsSetWithDeprecatedPropertyAndExposedShouldHaveEndpointBean() {
this.contextRunner this.contextRunner
.withPropertyValues("logging.file:test.log", "management.endpoints.web.exposure.include=logfile") .withPropertyValues("logging.file:test.log", "management.endpoints.web.exposure.include=logfile")
.run((context) -> assertThat(context).hasSingleBean(LogFileWebEndpoint.class)); .run((context) -> assertThat(context).hasSingleBean(LogFileWebEndpoint.class));
} }
@Test @Test
public void runWhenLoggingPathIsSetAndNotExposedShouldNotHaveEndpointBean() { void runWhenLoggingPathIsSetAndNotExposedShouldNotHaveEndpointBean() {
this.contextRunner.withPropertyValues("logging.file.path:test/logs") this.contextRunner.withPropertyValues("logging.file.path:test/logs")
.run((context) -> assertThat(context).doesNotHaveBean(LogFileWebEndpoint.class)); .run((context) -> assertThat(context).doesNotHaveBean(LogFileWebEndpoint.class));
} }
@Test @Test
public void runWhenLoggingPathIsSetAndExposedShouldHaveEndpointBean() { void runWhenLoggingPathIsSetAndExposedShouldHaveEndpointBean() {
this.contextRunner this.contextRunner
.withPropertyValues("logging.file.path:test/logs", "management.endpoints.web.exposure.include=logfile") .withPropertyValues("logging.file.path:test/logs", "management.endpoints.web.exposure.include=logfile")
.run((context) -> assertThat(context).hasSingleBean(LogFileWebEndpoint.class)); .run((context) -> assertThat(context).hasSingleBean(LogFileWebEndpoint.class));
@ -88,14 +88,14 @@ public class LogFileWebEndpointAutoConfigurationTests {
@Test @Test
@Deprecated @Deprecated
public void runWhenLoggingPathIsSetWithDeprecatedPropertyAndExposedShouldHaveEndpointBean() { void runWhenLoggingPathIsSetWithDeprecatedPropertyAndExposedShouldHaveEndpointBean() {
this.contextRunner this.contextRunner
.withPropertyValues("logging.path:test/logs", "management.endpoints.web.exposure.include=logfile") .withPropertyValues("logging.path:test/logs", "management.endpoints.web.exposure.include=logfile")
.run((context) -> assertThat(context).hasSingleBean(LogFileWebEndpoint.class)); .run((context) -> assertThat(context).hasSingleBean(LogFileWebEndpoint.class));
} }
@Test @Test
public void logFileWebEndpointIsAutoConfiguredWhenExternalFileIsSet() { void logFileWebEndpointIsAutoConfiguredWhenExternalFileIsSet() {
this.contextRunner this.contextRunner
.withPropertyValues("management.endpoint.logfile.external-file:external.log", .withPropertyValues("management.endpoint.logfile.external-file:external.log",
"management.endpoints.web.exposure.include=logfile") "management.endpoints.web.exposure.include=logfile")
@ -103,13 +103,13 @@ public class LogFileWebEndpointAutoConfigurationTests {
} }
@Test @Test
public void logFileWebEndpointCanBeDisabled() { void logFileWebEndpointCanBeDisabled() {
this.contextRunner.withPropertyValues("logging.file.name:test.log", "management.endpoint.logfile.enabled:false") this.contextRunner.withPropertyValues("logging.file.name:test.log", "management.endpoint.logfile.enabled:false")
.run((context) -> assertThat(context).doesNotHaveBean(LogFileWebEndpoint.class)); .run((context) -> assertThat(context).doesNotHaveBean(LogFileWebEndpoint.class));
} }
@Test @Test
public void logFileWebEndpointUsesConfiguredExternalFile(@TempDir Path temp) throws IOException { void logFileWebEndpointUsesConfiguredExternalFile(@TempDir Path temp) throws IOException {
File file = new File(temp.toFile(), "logfile"); File file = new File(temp.toFile(), "logfile");
FileCopyUtils.copy("--TEST--".getBytes(), file); FileCopyUtils.copy("--TEST--".getBytes(), file);
this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=logfile", this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=logfile",

View File

@ -33,31 +33,31 @@ import static org.mockito.Mockito.mock;
* *
* @author Phillip Webb * @author Phillip Webb
*/ */
public class LoggersEndpointAutoConfigurationTests { class LoggersEndpointAutoConfigurationTests {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(LoggersEndpointAutoConfiguration.class)) .withConfiguration(AutoConfigurations.of(LoggersEndpointAutoConfiguration.class))
.withUserConfiguration(LoggingConfiguration.class); .withUserConfiguration(LoggingConfiguration.class);
@Test @Test
public void runShouldHaveEndpointBean() { void runShouldHaveEndpointBean() {
this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=loggers") this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=loggers")
.run((context) -> assertThat(context).hasSingleBean(LoggersEndpoint.class)); .run((context) -> assertThat(context).hasSingleBean(LoggersEndpoint.class));
} }
@Test @Test
public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() {
this.contextRunner.withPropertyValues("management.endpoint.loggers.enabled:false") this.contextRunner.withPropertyValues("management.endpoint.loggers.enabled:false")
.run((context) -> assertThat(context).doesNotHaveBean(LoggersEndpoint.class)); .run((context) -> assertThat(context).doesNotHaveBean(LoggersEndpoint.class));
} }
@Test @Test
public void runWhenNotExposedShouldNotHaveEndpointBean() { void runWhenNotExposedShouldNotHaveEndpointBean() {
this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(LoggersEndpoint.class)); this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(LoggersEndpoint.class));
} }
@Test @Test
public void runWithNoneLoggingSystemShouldNotHaveEndpointBean() { void runWithNoneLoggingSystemShouldNotHaveEndpointBean() {
this.contextRunner.withSystemProperties("org.springframework.boot.logging.LoggingSystem=none") this.contextRunner.withSystemProperties("org.springframework.boot.logging.LoggingSystem=none")
.run((context) -> assertThat(context).doesNotHaveBean(LoggersEndpoint.class)); .run((context) -> assertThat(context).doesNotHaveBean(LoggersEndpoint.class));
} }

View File

@ -32,7 +32,7 @@ import static org.assertj.core.api.Assertions.assertThat;
* *
* @author Phillip Webb * @author Phillip Webb
*/ */
public class MailHealthIndicatorAutoConfigurationTests { class MailHealthIndicatorAutoConfigurationTests {
private ApplicationContextRunner contextRunner = new ApplicationContextRunner() private ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(MailSenderAutoConfiguration.class, .withConfiguration(AutoConfigurations.of(MailSenderAutoConfiguration.class,
@ -40,13 +40,13 @@ public class MailHealthIndicatorAutoConfigurationTests {
.withPropertyValues("spring.mail.host:smtp.example.com"); .withPropertyValues("spring.mail.host:smtp.example.com");
@Test @Test
public void runShouldCreateIndicator() { void runShouldCreateIndicator() {
this.contextRunner.run((context) -> assertThat(context).hasSingleBean(MailHealthIndicator.class) this.contextRunner.run((context) -> assertThat(context).hasSingleBean(MailHealthIndicator.class)
.doesNotHaveBean(ApplicationHealthIndicator.class)); .doesNotHaveBean(ApplicationHealthIndicator.class));
} }
@Test @Test
public void runWhenDisabledShouldNotCreateIndicator() { void runWhenDisabledShouldNotCreateIndicator() {
this.contextRunner.withPropertyValues("management.health.mail.enabled:false") this.contextRunner.withPropertyValues("management.health.mail.enabled:false")
.run((context) -> assertThat(context).doesNotHaveBean(MailHealthIndicator.class) .run((context) -> assertThat(context).doesNotHaveBean(MailHealthIndicator.class)
.hasSingleBean(ApplicationHealthIndicator.class)); .hasSingleBean(ApplicationHealthIndicator.class));

View File

@ -28,19 +28,19 @@ import static org.assertj.core.api.Assertions.assertThat;
* *
* @author Phillip Webb * @author Phillip Webb
*/ */
public class HeapDumpWebEndpointAutoConfigurationTests { class HeapDumpWebEndpointAutoConfigurationTests {
private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withPropertyValues("management.endpoints.web.exposure.include:*") .withPropertyValues("management.endpoints.web.exposure.include:*")
.withUserConfiguration(HeapDumpWebEndpointAutoConfiguration.class); .withUserConfiguration(HeapDumpWebEndpointAutoConfiguration.class);
@Test @Test
public void runShouldCreateIndicator() { void runShouldCreateIndicator() {
this.contextRunner.run((context) -> assertThat(context).hasSingleBean(HeapDumpWebEndpoint.class)); this.contextRunner.run((context) -> assertThat(context).hasSingleBean(HeapDumpWebEndpoint.class));
} }
@Test @Test
public void runWhenDisabledShouldNotCreateIndicator() { void runWhenDisabledShouldNotCreateIndicator() {
this.contextRunner.withPropertyValues("management.endpoint.heapdump.enabled:false") this.contextRunner.withPropertyValues("management.endpoint.heapdump.enabled:false")
.run((context) -> assertThat(context).doesNotHaveBean(HeapDumpWebEndpoint.class)); .run((context) -> assertThat(context).doesNotHaveBean(HeapDumpWebEndpoint.class));
} }

View File

@ -29,24 +29,24 @@ import static org.assertj.core.api.Assertions.assertThat;
* *
* @author Phillip Webb * @author Phillip Webb
*/ */
public class ThreadDumpEndpointAutoConfigurationTests { class ThreadDumpEndpointAutoConfigurationTests {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(ThreadDumpEndpointAutoConfiguration.class)); .withConfiguration(AutoConfigurations.of(ThreadDumpEndpointAutoConfiguration.class));
@Test @Test
public void runShouldHaveEndpointBean() { void runShouldHaveEndpointBean() {
this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=threaddump") this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=threaddump")
.run((context) -> assertThat(context).hasSingleBean(ThreadDumpEndpoint.class)); .run((context) -> assertThat(context).hasSingleBean(ThreadDumpEndpoint.class));
} }
@Test @Test
public void runWhenNotExposedShouldNotHaveEndpointBean() { void runWhenNotExposedShouldNotHaveEndpointBean() {
this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(ThreadDumpEndpoint.class)); this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(ThreadDumpEndpoint.class));
} }
@Test @Test
public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() {
this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=*") this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=*")
.withPropertyValues("management.endpoint.threaddump.enabled:false") .withPropertyValues("management.endpoint.threaddump.enabled:false")
.run((context) -> assertThat(context).doesNotHaveBean(ThreadDumpEndpoint.class)); .run((context) -> assertThat(context).doesNotHaveBean(ThreadDumpEndpoint.class));

View File

@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Phillip Webb * @author Phillip Webb
* @author Andy Wilkinson * @author Andy Wilkinson
*/ */
public class CompositeMeterRegistryAutoConfigurationTests { class CompositeMeterRegistryAutoConfigurationTests {
private static final String COMPOSITE_NAME = "compositeMeterRegistry"; private static final String COMPOSITE_NAME = "compositeMeterRegistry";
@ -46,7 +46,7 @@ public class CompositeMeterRegistryAutoConfigurationTests {
.withConfiguration(AutoConfigurations.of(CompositeMeterRegistryAutoConfiguration.class)); .withConfiguration(AutoConfigurations.of(CompositeMeterRegistryAutoConfiguration.class));
@Test @Test
public void registerWhenHasNoMeterRegistryShouldRegisterEmptyNoOpComposite() { void registerWhenHasNoMeterRegistryShouldRegisterEmptyNoOpComposite() {
this.contextRunner.withUserConfiguration(NoMeterRegistryConfig.class).run((context) -> { this.contextRunner.withUserConfiguration(NoMeterRegistryConfig.class).run((context) -> {
assertThat(context).hasSingleBean(MeterRegistry.class); assertThat(context).hasSingleBean(MeterRegistry.class);
CompositeMeterRegistry registry = context.getBean("noOpMeterRegistry", CompositeMeterRegistry.class); CompositeMeterRegistry registry = context.getBean("noOpMeterRegistry", CompositeMeterRegistry.class);
@ -55,7 +55,7 @@ public class CompositeMeterRegistryAutoConfigurationTests {
} }
@Test @Test
public void registerWhenHasSingleMeterRegistryShouldDoNothing() { void registerWhenHasSingleMeterRegistryShouldDoNothing() {
this.contextRunner.withUserConfiguration(SingleMeterRegistryConfig.class).run((context) -> { this.contextRunner.withUserConfiguration(SingleMeterRegistryConfig.class).run((context) -> {
assertThat(context).hasSingleBean(MeterRegistry.class); assertThat(context).hasSingleBean(MeterRegistry.class);
MeterRegistry registry = context.getBean(MeterRegistry.class); MeterRegistry registry = context.getBean(MeterRegistry.class);
@ -64,7 +64,7 @@ public class CompositeMeterRegistryAutoConfigurationTests {
} }
@Test @Test
public void registerWhenHasMultipleMeterRegistriesShouldAddPrimaryComposite() { void registerWhenHasMultipleMeterRegistriesShouldAddPrimaryComposite() {
this.contextRunner.withUserConfiguration(MultipleMeterRegistriesConfig.class).run((context) -> { this.contextRunner.withUserConfiguration(MultipleMeterRegistriesConfig.class).run((context) -> {
assertThat(context.getBeansOfType(MeterRegistry.class)).hasSize(3).containsKeys("meterRegistryOne", assertThat(context.getBeansOfType(MeterRegistry.class)).hasSize(3).containsKeys("meterRegistryOne",
"meterRegistryTwo", COMPOSITE_NAME); "meterRegistryTwo", COMPOSITE_NAME);
@ -76,7 +76,7 @@ public class CompositeMeterRegistryAutoConfigurationTests {
} }
@Test @Test
public void registerWhenHasMultipleRegistriesAndOneIsPrimaryShouldDoNothing() { void registerWhenHasMultipleRegistriesAndOneIsPrimaryShouldDoNothing() {
this.contextRunner.withUserConfiguration(MultipleMeterRegistriesWithOnePrimaryConfig.class).run((context) -> { this.contextRunner.withUserConfiguration(MultipleMeterRegistriesWithOnePrimaryConfig.class).run((context) -> {
assertThat(context.getBeansOfType(MeterRegistry.class)).hasSize(2).containsKeys("meterRegistryOne", assertThat(context.getBeansOfType(MeterRegistry.class)).hasSize(2).containsKeys("meterRegistryOne",
"meterRegistryTwo"); "meterRegistryTwo");

View File

@ -36,20 +36,20 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Andy Wilkinson * @author Andy Wilkinson
* @author Stephane Nicoll * @author Stephane Nicoll
*/ */
public class JvmMetricsAutoConfigurationTests { class JvmMetricsAutoConfigurationTests {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple())
.withConfiguration(AutoConfigurations.of(JvmMetricsAutoConfiguration.class)); .withConfiguration(AutoConfigurations.of(JvmMetricsAutoConfiguration.class));
@Test @Test
public void autoConfiguresJvmMetrics() { void autoConfiguresJvmMetrics() {
this.contextRunner.run( this.contextRunner.run(
(context) -> assertThat(context).hasSingleBean(JvmGcMetrics.class).hasSingleBean(JvmMemoryMetrics.class) (context) -> assertThat(context).hasSingleBean(JvmGcMetrics.class).hasSingleBean(JvmMemoryMetrics.class)
.hasSingleBean(JvmThreadMetrics.class).hasSingleBean(ClassLoaderMetrics.class)); .hasSingleBean(JvmThreadMetrics.class).hasSingleBean(ClassLoaderMetrics.class));
} }
@Test @Test
public void allowsCustomJvmGcMetricsToBeUsed() { void allowsCustomJvmGcMetricsToBeUsed() {
this.contextRunner.withUserConfiguration(CustomJvmGcMetricsConfiguration.class) this.contextRunner.withUserConfiguration(CustomJvmGcMetricsConfiguration.class)
.run((context) -> assertThat(context).hasSingleBean(JvmGcMetrics.class).hasBean("customJvmGcMetrics") .run((context) -> assertThat(context).hasSingleBean(JvmGcMetrics.class).hasBean("customJvmGcMetrics")
.hasSingleBean(JvmMemoryMetrics.class).hasSingleBean(JvmThreadMetrics.class) .hasSingleBean(JvmMemoryMetrics.class).hasSingleBean(JvmThreadMetrics.class)
@ -57,7 +57,7 @@ public class JvmMetricsAutoConfigurationTests {
} }
@Test @Test
public void allowsCustomJvmMemoryMetricsToBeUsed() { void allowsCustomJvmMemoryMetricsToBeUsed() {
this.contextRunner.withUserConfiguration(CustomJvmMemoryMetricsConfiguration.class) this.contextRunner.withUserConfiguration(CustomJvmMemoryMetricsConfiguration.class)
.run((context) -> assertThat(context).hasSingleBean(JvmGcMetrics.class) .run((context) -> assertThat(context).hasSingleBean(JvmGcMetrics.class)
.hasSingleBean(JvmMemoryMetrics.class).hasBean("customJvmMemoryMetrics") .hasSingleBean(JvmMemoryMetrics.class).hasBean("customJvmMemoryMetrics")
@ -65,7 +65,7 @@ public class JvmMetricsAutoConfigurationTests {
} }
@Test @Test
public void allowsCustomJvmThreadMetricsToBeUsed() { void allowsCustomJvmThreadMetricsToBeUsed() {
this.contextRunner.withUserConfiguration(CustomJvmThreadMetricsConfiguration.class) this.contextRunner.withUserConfiguration(CustomJvmThreadMetricsConfiguration.class)
.run((context) -> assertThat(context).hasSingleBean(JvmGcMetrics.class) .run((context) -> assertThat(context).hasSingleBean(JvmGcMetrics.class)
.hasSingleBean(JvmMemoryMetrics.class).hasSingleBean(JvmThreadMetrics.class) .hasSingleBean(JvmMemoryMetrics.class).hasSingleBean(JvmThreadMetrics.class)
@ -73,7 +73,7 @@ public class JvmMetricsAutoConfigurationTests {
} }
@Test @Test
public void allowsCustomClassLoaderMetricsToBeUsed() { void allowsCustomClassLoaderMetricsToBeUsed() {
this.contextRunner.withUserConfiguration(CustomClassLoaderMetricsConfiguration.class) this.contextRunner.withUserConfiguration(CustomClassLoaderMetricsConfiguration.class)
.run((context) -> assertThat(context).hasSingleBean(JvmGcMetrics.class) .run((context) -> assertThat(context).hasSingleBean(JvmGcMetrics.class)
.hasSingleBean(JvmMemoryMetrics.class).hasSingleBean(JvmThreadMetrics.class) .hasSingleBean(JvmMemoryMetrics.class).hasSingleBean(JvmThreadMetrics.class)

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