Bumping versions

This commit is contained in:
buildmaster
2024-07-22 16:32:04 +00:00
parent 632108159b
commit 4f304bfadb
68 changed files with 539 additions and 420 deletions

View File

@@ -100,8 +100,8 @@ public class ConsulInboundMessageProducer extends MessageProducerSupport {
// headers.put(MessageHeaders.REPLY_CHANNEL, outputChannel.)
String decoded = new String(decodeFromString(event.getPayload()));
sendMessage(getMessageBuilderFactory().withPayload(decoded)
// TODO: support headers
.build());
// TODO: support headers
.build());
}
}
catch (OperationException e) {

View File

@@ -101,7 +101,7 @@ public class EventService {
eventTimeout = this.properties.getEventTimeout();
}
Response<List<Event>> watch = this.consul
.eventList(EventListRequest.newBuilder().setQueryParams(new QueryParams(eventTimeout, index)).build());
.eventList(EventListRequest.newBuilder().setQueryParams(new QueryParams(eventTimeout, index)).build());
return filterEvents(readEvents(watch), lastIndex);
}

View File

@@ -42,7 +42,8 @@ public class ConsulBinderConfigurationTests {
public void consulBinderDisabledWorks() {
this.exception.expectMessage(containsString("no proper implementation found"));
new SpringApplicationBuilder(Application.class).initializers(new ConsulTestcontainers())
.properties("spring.cloud.consul.binder.enabled=false").run();
.properties("spring.cloud.consul.binder.enabled=false")
.run();
}
@Test
@@ -50,7 +51,8 @@ public class ConsulBinderConfigurationTests {
public void consulDisabledDisablesBinder() {
this.exception.expectMessage(containsString("no proper implementation found"));
new SpringApplicationBuilder(Application.class).initializers(new ConsulTestcontainers())
.properties("spring.cloud.consul.enabled=false").run();
.properties("spring.cloud.consul.enabled=false")
.run();
}
interface Events {

View File

@@ -252,8 +252,10 @@ public class ConfigWatch implements ApplicationEventPublisherAware, SmartLifecyc
@Override
public String toString() {
return new ToStringCreator(this).append("context", this.context).append("prevIndex", this.prevIndex)
.append("newIndex", this.newIndex).toString();
return new ToStringCreator(this).append("context", this.context)
.append("prevIndex", this.prevIndex)
.append("newIndex", this.newIndex)
.toString();
}
}

View File

@@ -64,7 +64,7 @@ public class ConsulConfigDataLoader implements ConfigDataLoader<ConsulConfigData
ConsulConfigIndexes indexes = getBean(context, ConsulConfigIndexes.class);
ConsulPropertySource propertySource = resource.getConsulPropertySources()
.createPropertySource(resource.getContext(), consul, indexes.getIndexes()::put);
.createPropertySource(resource.getContext(), consul, indexes.getIndexes()::put);
if (propertySource == null) {
return null;
}

View File

@@ -60,7 +60,7 @@ public class ConsulConfigDataLocationResolver implements ConfigDataLocationResol
protected static final List<String> DIR_SUFFIXES = Collections.singletonList("/");
protected static final List<String> FILES_SUFFIXES = Collections
.unmodifiableList(Arrays.asList(".yml", ".yaml", ".properties"));
.unmodifiableList(Arrays.asList(".yml", ".yaml", ".properties"));
private final Log log;
@@ -75,8 +75,9 @@ public class ConsulConfigDataLocationResolver implements ConfigDataLocationResol
}
// only bind if correct prefix
boolean enabled = context.getBinder().bind(ConsulProperties.PREFIX + ".enabled", Boolean.class).orElse(true);
boolean configEnabled = context.getBinder().bind(ConsulConfigProperties.PREFIX + ".enabled", Boolean.class)
.orElse(true);
boolean configEnabled = context.getBinder()
.bind(ConsulConfigProperties.PREFIX + ".enabled", Boolean.class)
.orElse(true);
return configEnabled && enabled;
}
@@ -110,10 +111,10 @@ public class ConsulConfigDataLocationResolver implements ConfigDataLocationResol
registerAndPromoteBean(resolverContext, ConsulConfigIndexes.class,
InstanceSupplier.from(ConsulConfigDataIndexes::new));
return contexts
.stream().map(propertySourceContext -> new ConsulConfigDataResource(propertySourceContext.getPath(),
properties, consulPropertySources, propertySourceContext.getProfile()))
.collect(Collectors.toList());
return contexts.stream()
.map(propertySourceContext -> new ConsulConfigDataResource(propertySourceContext.getPath(), properties,
consulPropertySources, propertySourceContext.getProfile()))
.collect(Collectors.toList());
}
private BindHandler getBindHandler(ConfigDataLocationResolverContext context) {
@@ -192,8 +193,8 @@ public class ConsulConfigDataLocationResolver implements ConfigDataLocationResol
UriComponents location) {
Binder binder = resolverContext.getBinder();
ConsulProperties consulProperties = binder
.bind(ConsulProperties.PREFIX, Bindable.of(ConsulProperties.class), getBindHandler(resolverContext))
.orElseGet(ConsulProperties::new);
.bind(ConsulProperties.PREFIX, Bindable.of(ConsulProperties.class), getBindHandler(resolverContext))
.orElseGet(ConsulProperties::new);
if (location != null) {
if (StringUtils.hasText(location.getHost())) {
@@ -211,8 +212,8 @@ public class ConsulConfigDataLocationResolver implements ConfigDataLocationResol
Binder binder = resolverContext.getBinder();
BindHandler bindHandler = getBindHandler(resolverContext);
ConsulConfigProperties properties = binder
.bind(ConsulConfigProperties.PREFIX, Bindable.of(ConsulConfigProperties.class), bindHandler)
.orElseGet(ConsulConfigProperties::new);
.bind(ConsulConfigProperties.PREFIX, Bindable.of(ConsulConfigProperties.class), bindHandler)
.orElseGet(ConsulConfigProperties::new);
if (!StringUtils.hasText(properties.getName())) {
properties.setName(binder.bind("spring.application.name", String.class).orElse("application"));
@@ -220,7 +221,7 @@ public class ConsulConfigDataLocationResolver implements ConfigDataLocationResol
if (!StringUtils.hasText(properties.getAclToken())) {
properties.setAclToken(binder.bind("spring.cloud.consul.token", String.class)
.orElse(binder.bind("consul.token", String.class).orElse(null)));
.orElse(binder.bind("consul.token", String.class).orElse(null)));
}
return properties;
}

View File

@@ -99,8 +99,11 @@ public class ConsulConfigDataResource extends ConfigDataResource {
@Override
public String toString() {
return new ToStringCreator(this).append("context", context).append("optional", optional)
.append("properties", properties).append("profile", profile).toString();
return new ToStringCreator(this).append("context", context)
.append("optional", optional)
.append("properties", properties)
.append("profile", profile)
.toString();
}

View File

@@ -191,10 +191,17 @@ public class ConsulConfigProperties {
@Override
public String toString() {
return new ToStringCreator(this).append("enabled", this.enabled).append("prefixes", this.prefixes)
.append("defaultContext", this.defaultContext).append("profileSeparator", this.profileSeparator)
.append("format", this.format).append("dataKey", this.dataKey).append("aclToken", this.aclToken)
.append("watch", this.watch).append("failFast", this.failFast).append("name", this.name).toString();
return new ToStringCreator(this).append("enabled", this.enabled)
.append("prefixes", this.prefixes)
.append("defaultContext", this.defaultContext)
.append("profileSeparator", this.profileSeparator)
.append("format", this.format)
.append("dataKey", this.dataKey)
.append("aclToken", this.aclToken)
.append("watch", this.watch)
.append("failFast", this.failFast)
.append("name", this.name)
.toString();
}
/**
@@ -295,8 +302,10 @@ public class ConsulConfigProperties {
@Override
public String toString() {
return new ToStringCreator(this).append("waitTime", this.waitTime).append("enabled", this.enabled)
.append("delay", this.delay).toString();
return new ToStringCreator(this).append("waitTime", this.waitTime)
.append("enabled", this.enabled)
.append("delay", this.delay)
.toString();
}
}

View File

@@ -38,7 +38,7 @@ public class ConsulPropertySources {
protected static final List<String> DIR_SUFFIXES = Collections.singletonList("/");
protected static final List<String> FILES_SUFFIXES = Collections
.unmodifiableList(Arrays.asList(".yml", ".yaml", ".properties"));
.unmodifiableList(Arrays.asList(".yml", ".yaml", ".properties"));
private final ConsulConfigProperties properties;

View File

@@ -41,16 +41,19 @@ public class ConsulRetryBootstrapper implements BootstrapRegistryInitializer {
return;
}
registry.registerIfAbsent(RetryProperties.class, context -> context.get(Binder.class)
.bind(RetryProperties.PREFIX, RetryProperties.class).orElseGet(RetryProperties::new));
registry.registerIfAbsent(RetryProperties.class,
context -> context.get(Binder.class)
.bind(RetryProperties.PREFIX, RetryProperties.class)
.orElseGet(RetryProperties::new));
registry.registerIfAbsent(RetryTemplate.class, context -> {
RetryProperties properties = context.get(RetryProperties.class);
if (properties.isEnabled()) {
return RetryTemplate.builder().maxAttempts(properties.getMaxAttempts())
.exponentialBackoff(properties.getInitialInterval(), properties.getMultiplier(),
properties.getMaxInterval())
.build();
return RetryTemplate.builder()
.maxAttempts(properties.getMaxAttempts())
.exponentialBackoff(properties.getInitialInterval(), properties.getMultiplier(),
properties.getMaxInterval())
.build();
}
return null;
});
@@ -58,7 +61,7 @@ public class ConsulRetryBootstrapper implements BootstrapRegistryInitializer {
RetryTemplate retryTemplate = context.get(RetryTemplate.class);
if (retryTemplate != null) {
return loadContext -> retryTemplate.execute(retryContext -> loadContext.getInvocation()
.apply(loadContext.getLoaderContext(), loadContext.getResource()));
.apply(loadContext.getLoaderContext(), loadContext.getResource()));
}
// disabled
return null;

View File

@@ -38,12 +38,14 @@ public class ConsulConfigBootstrapConfigurationTests {
*/
@Test
public void testConfigPropsBeanBacksOff() {
this.contextRunner.withUserConfiguration(TestConfig.class).withInitializer(new ConsulTestcontainers())
.withUserConfiguration(ConsulConfigBootstrapConfiguration.class).run(context -> {
ConsulConfigProperties config = context.getBean(ConsulConfigProperties.class);
assertThat(config.getPrefixes().get(0)).as("Prefix did not match").isEqualTo("platform-config");
assertThat(config.getDefaultContext()).as("Default context did not match").isEqualTo("defaults");
});
this.contextRunner.withUserConfiguration(TestConfig.class)
.withInitializer(new ConsulTestcontainers())
.withUserConfiguration(ConsulConfigBootstrapConfiguration.class)
.run(context -> {
ConsulConfigProperties config = context.getBean(ConsulConfigProperties.class);
assertThat(config.getPrefixes().get(0)).as("Prefix did not match").isEqualTo("platform-config");
assertThat(config.getDefaultContext()).as("Default context did not match").isEqualTo("defaults");
});
}
/**
@@ -53,11 +55,12 @@ public class ConsulConfigBootstrapConfigurationTests {
@Test
public void testConfigPropsBeanKicksIn() {
this.contextRunner.withUserConfiguration(ConsulConfigBootstrapConfiguration.class)
.withInitializer(new ConsulTestcontainers()).run(context -> {
ConsulConfigProperties config = context.getBean(ConsulConfigProperties.class);
assertThat(config.getPrefixes().get(0)).as("Prefix did not match").isEqualTo("config");
assertThat(config.getDefaultContext()).as("Default context did not match").isEqualTo("application");
});
.withInitializer(new ConsulTestcontainers())
.run(context -> {
ConsulConfigProperties config = context.getBean(ConsulConfigProperties.class);
assertThat(config.getPrefixes().get(0)).as("Prefix did not match").isEqualTo("config");
assertThat(config.getDefaultContext()).as("Default context did not match").isEqualTo("application");
});
}
/**

View File

@@ -70,15 +70,17 @@ public class ConsulConfigDataCustomizationIntegrationTests {
application.addBootstrapRegistryInitializer(ConsulBootstrapper.fromConsulProperties(TestConsulClient::new));
application.addBootstrapRegistryInitializer(
registry -> registry.register(ConsulBootstrapper.LoaderInterceptor.class, context1 -> loadContext -> {
ConfigData configData = loadContext.getInvocation().apply(loadContext.getLoaderContext(),
loadContext.getResource());
ConfigData configData = loadContext.getInvocation()
.apply(loadContext.getLoaderContext(), loadContext.getResource());
assertThat(configData).as("ConfigData was null for location %s", loadContext.getResource())
.isNotNull();
.isNotNull();
assertThat(configData.getPropertySources()).hasSize(1);
PropertySource<?> propertySource = configData.getPropertySources().iterator().next();
ConfigData.Options options = configData.getOptions(propertySource);
assertThat(options).as("ConfigData.options was null for location %s property source %s",
loadContext.getResource(), propertySource.getName()).isNotNull();
assertThat(options)
.as("ConfigData.options was null for location %s property source %s", loadContext.getResource(),
propertySource.getName())
.isNotNull();
assertThat(options.contains(ConfigData.Option.IGNORE_IMPORTS)).isTrue();
assertThat(options.contains(ConfigData.Option.IGNORE_PROFILES)).isTrue();
boolean hasProfile = StringUtils.hasText(loadContext.getResource().getProfile());

View File

@@ -84,11 +84,11 @@ public class ConsulConfigDataFileIntegrationTests {
client.deleteKVValues(PREFIX);
client.setKVValue(KEY1, TEST_PROP + "=" + VALUE1 + "\n" + TEST_PROP2 + "=" + VALUE2);
context = new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE).run(
"--spring.application.name=" + APP_NAME, "--spring.cloud.consul.config.format=files",
"--spring.config.import=optional:consul:" + ConsulTestcontainers.getHost() + ":"
+ ConsulTestcontainers.getPort(),
"--spring.cloud.consul.config.prefix=" + ROOT, "--spring.cloud.consul.config.watch.delay=10");
context = new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE)
.run("--spring.application.name=" + APP_NAME, "--spring.cloud.consul.config.format=files",
"--spring.config.import=optional:consul:" + ConsulTestcontainers.getHost() + ":"
+ ConsulTestcontainers.getPort(),
"--spring.cloud.consul.config.prefix=" + ROOT, "--spring.cloud.consul.config.watch.delay=10");
client = context.getBean(ConsulClient.class);
environment = context.getEnvironment();

View File

@@ -92,13 +92,13 @@ public class ConsulConfigDataIntegrationTests {
client.setKVValue(KEY2, VALUE2_DEFAULT);
client.setKVValue(KEY2_APP_NAME, VALUE2);
context = new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE).run(
"--logging.level.org.springframework.cloud.consul.config.ConfigWatch=TRACE",
"--spring.application.name=" + APP_NAME,
"--spring.config.import=consul:" + ConsulTestcontainers.getHost() + ":"
+ ConsulTestcontainers.getPort(),
"--spring.cloud.consul.config.prefix=" + ROOT, "--spring.cloud.consul.config.watch.delay=10",
"--spring.cloud.consul.config.watch.wait-time=1");
context = new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE)
.run("--logging.level.org.springframework.cloud.consul.config.ConfigWatch=TRACE",
"--spring.application.name=" + APP_NAME,
"--spring.config.import=consul:" + ConsulTestcontainers.getHost() + ":"
+ ConsulTestcontainers.getPort(),
"--spring.cloud.consul.config.prefix=" + ROOT, "--spring.cloud.consul.config.watch.delay=10",
"--spring.cloud.consul.config.watch.wait-time=1");
client = context.getBean(ConsulClient.class);
environment = context.getEnvironment();

View File

@@ -49,8 +49,10 @@ public class ConsulConfigDataLocationResolverTests {
destination -> LogFactory.getLog(ConsulConfigDataLocationResolver.class));
UriComponents uriComponents = resolver.parseLocation(null,
ConfigDataLocation.of("consul:myhost:8501/mypath1;/mypath2;/mypath3"));
assertThat(uriComponents.toUri()).hasScheme("consul").hasHost("myhost").hasPort(8501)
.hasPath("/mypath1;/mypath2;/mypath3");
assertThat(uriComponents.toUri()).hasScheme("consul")
.hasHost("myhost")
.hasPort(8501)
.hasPath("/mypath1;/mypath2;/mypath3");
uriComponents = resolver.parseLocation(null, ConfigDataLocation.of("consul:myhost:8501"));
assertThat(uriComponents.toUri()).hasScheme("consul").hasHost("myhost").hasPort(8501).hasPath("");

View File

@@ -36,7 +36,7 @@ class ConsulConfigDataMissingEnvironmentPostProcessorTests {
SpringApplication app = mock(SpringApplication.class);
ConsulConfigDataMissingEnvironmentPostProcessor processor = new ConsulConfigDataMissingEnvironmentPostProcessor();
assertThatThrownBy(() -> processor.postProcessEnvironment(environment, app))
.isInstanceOf(ConsulConfigDataMissingEnvironmentPostProcessor.ImportException.class);
.isInstanceOf(ConsulConfigDataMissingEnvironmentPostProcessor.ImportException.class);
}
@Test

View File

@@ -81,13 +81,13 @@ public class ConsulConfigDataMultiplePrefixesIntegrationTests {
client.setKVValue(KEY1, VALUE1);
client.setKVValue(KEY2, VALUE2);
context = new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE).run(
"--logging.level.org.springframework.cloud.consul.config.ConfigWatch=TRACE",
"--spring.application.name=" + APP_NAME,
"--spring.config.import=consul:" + ConsulTestcontainers.getHost() + ":"
+ ConsulTestcontainers.getPort(),
"--spring.cloud.consul.config.prefixes=" + ROOT + "," + ROOT2,
"--spring.cloud.consul.config.watch.delay=10", "--spring.cloud.consul.config.watch.wait-time=1");
context = new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE)
.run("--logging.level.org.springframework.cloud.consul.config.ConfigWatch=TRACE",
"--spring.application.name=" + APP_NAME,
"--spring.config.import=consul:" + ConsulTestcontainers.getHost() + ":"
+ ConsulTestcontainers.getPort(),
"--spring.cloud.consul.config.prefixes=" + ROOT + "," + ROOT2,
"--spring.cloud.consul.config.watch.delay=10", "--spring.cloud.consul.config.watch.wait-time=1");
client = context.getBean(ConsulClient.class);
environment = context.getEnvironment();

View File

@@ -63,31 +63,29 @@ public class ConsulConfigDataNoImportIntegrationTests {
@Test
public void exceptionThrownIfNoImport(CapturedOutput output) {
Assertions
.assertThatThrownBy(() -> new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE)
.run("--spring.application.name=" + APP_NAME))
.isInstanceOf(ConfigDataMissingEnvironmentPostProcessor.ImportException.class);
.assertThatThrownBy(() -> new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE)
.run("--spring.application.name=" + APP_NAME))
.isInstanceOf(ConfigDataMissingEnvironmentPostProcessor.ImportException.class);
assertThat(output).contains("No spring.config.import property has been defined")
.contains("Add a spring.config.import=consul: property to your configuration");
.contains("Add a spring.config.import=consul: property to your configuration");
}
@Test
public void exceptionThrownIfImportMissingConsul(CapturedOutput output) {
Assertions
.assertThatThrownBy(() -> new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE).run(
"--spring.config.import=optional:file:somefile.properties",
"--spring.application.name=" + APP_NAME))
.isInstanceOf(ConfigDataMissingEnvironmentPostProcessor.ImportException.class);
Assertions.assertThatThrownBy(() -> new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE)
.run("--spring.config.import=optional:file:somefile.properties", "--spring.application.name=" + APP_NAME))
.isInstanceOf(ConfigDataMissingEnvironmentPostProcessor.ImportException.class);
assertThat(output).contains("spring.config.import property is missing a " + PREFIX)
.contains("Add a spring.config.import=consul: property to your configuration");
.contains("Add a spring.config.import=consul: property to your configuration");
}
@Test
public void noExceptionThrownIfConsulDisabled() {
try (ConfigurableApplicationContext context = new SpringApplicationBuilder(Config.class)
.web(WebApplicationType.NONE)
.run("--spring.cloud.consul.enabled=false", "--spring.application.name=" + APP_NAME)) {
.web(WebApplicationType.NONE)
.run("--spring.cloud.consul.enabled=false", "--spring.application.name=" + APP_NAME)) {
// nothing to do
}
}
@@ -95,8 +93,8 @@ public class ConsulConfigDataNoImportIntegrationTests {
@Test
public void noExceptionThrownIfConsulConfigDisabled() {
try (ConfigurableApplicationContext context = new SpringApplicationBuilder(Config.class)
.web(WebApplicationType.NONE)
.run("--spring.cloud.consul.config.enabled=false", "--spring.application.name=" + APP_NAME)) {
.web(WebApplicationType.NONE)
.run("--spring.cloud.consul.config.enabled=false", "--spring.application.name=" + APP_NAME)) {
// nothing to do
}
}
@@ -104,8 +102,8 @@ public class ConsulConfigDataNoImportIntegrationTests {
@Test
public void noExceptionThrownIfImportCheckDisabled() {
try (ConfigurableApplicationContext context = new SpringApplicationBuilder(Config.class)
.web(WebApplicationType.NONE).run("--spring.cloud.consul.config.import-check.enabled=false",
"--spring.application.name=" + APP_NAME)) {
.web(WebApplicationType.NONE)
.run("--spring.cloud.consul.config.import-check.enabled=false", "--spring.application.name=" + APP_NAME)) {
// nothing to do
}
}

View File

@@ -72,12 +72,12 @@ public class ConsulPropertySourceLocatorAppNameCustomizedTests {
this.client.setKVValue(KEY1, VALUE1);
this.client.setKVValue(KEY2, VALUE2);
this.context = new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE).run(
"--spring.application.name=testConsulPropertySourceLocatorAppNameCustomized",
"--spring.config.use-legacy-processing=true",
"--spring.cloud.consul.host=" + ConsulTestcontainers.getHost(),
"--spring.cloud.consul.port=" + ConsulTestcontainers.getPort(),
"--spring.cloud.consul.config.name=" + CONFIG_NAME, "--spring.cloud.consul.config.prefix=" + ROOT);
this.context = new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE)
.run("--spring.application.name=testConsulPropertySourceLocatorAppNameCustomized",
"--spring.config.use-legacy-processing=true",
"--spring.cloud.consul.host=" + ConsulTestcontainers.getHost(),
"--spring.cloud.consul.port=" + ConsulTestcontainers.getPort(),
"--spring.cloud.consul.config.name=" + CONFIG_NAME, "--spring.cloud.consul.config.prefix=" + ROOT);
this.client = this.context.getBean(ConsulClient.class);
this.environment = this.context.getEnvironment();

View File

@@ -71,12 +71,12 @@ public class ConsulPropertySourceLocatorFilesTests {
this.client.setKVValue(ROOT + APP_NAME_PROPS, "foo: bar-app\nmy.baz: ${foo}");
this.client.setKVValue(ROOT + APP_NAME_DEV_PROPS, "foo: bar-app-dev\nmy.baz: ${foo}");
this.context = new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE).run(
"--spring.application.name=" + APP_NAME, "--spring.config.use-legacy-processing=true",
"--spring.cloud.consul.host=" + ConsulTestcontainers.getHost(),
"--spring.cloud.consul.port=" + ConsulTestcontainers.getPort(),
"--spring.cloud.consul.config.prefix=" + ROOT, "--spring.cloud.consul.config.format=FILES",
"--spring.profiles.active=dev", "spring.cloud.consul.config.watch.delay=1");
this.context = new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE)
.run("--spring.application.name=" + APP_NAME, "--spring.config.use-legacy-processing=true",
"--spring.cloud.consul.host=" + ConsulTestcontainers.getHost(),
"--spring.cloud.consul.port=" + ConsulTestcontainers.getPort(),
"--spring.cloud.consul.config.prefix=" + ROOT, "--spring.cloud.consul.config.format=FILES",
"--spring.profiles.active=dev", "spring.cloud.consul.config.watch.delay=1");
this.client = this.context.getBean(ConsulClient.class);
this.environment = this.context.getEnvironment();

View File

@@ -40,12 +40,14 @@ public class ConsulPropertySourceLocatorRetryTests {
@Test
public void testRetry() {
assertThatThrownBy(() -> {
new SpringApplicationBuilder(Config.class).properties(
"spring.application.name=testConsulPropertySourceLocatorRetry",
"spring.config.use-legacy-processing=true",
"spring.cloud.consul.host=53210a7c-4809-42cb-8b30-057d2db85fcc",
"logging.level.org.springframework.retry=TRACE", "server.port=0", "spring.cloud.consul.port=65530",
"spring.cloud.consul.retry.maxAttempts=1", "spring.cloud.consul.config.failFast=true").run();
new SpringApplicationBuilder(Config.class)
.properties("spring.application.name=testConsulPropertySourceLocatorRetry",
"spring.config.use-legacy-processing=true",
"spring.cloud.consul.host=53210a7c-4809-42cb-8b30-057d2db85fcc",
"logging.level.org.springframework.retry=TRACE", "server.port=0",
"spring.cloud.consul.port=65530", "spring.cloud.consul.retry.maxAttempts=1",
"spring.cloud.consul.config.failFast=true")
.run();
fail("Did not throw expected exception");
}).hasCauseInstanceOf(TransportException.class);
assertThat(output).contains("RetryContext retrieved");

View File

@@ -87,11 +87,11 @@ public class ConsulPropertySourceLocatorTests {
client.setKVValue(KEY1, VALUE1);
client.setKVValue(KEY2, VALUE2);
context = new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE).run(
"--spring.application.name=" + APP_NAME, "--spring.config.use-legacy-processing=true",
"--spring.cloud.consul.host=" + ConsulTestcontainers.getHost(),
"--spring.cloud.consul.port=" + ConsulTestcontainers.getPort(),
"--spring.cloud.consul.config.prefixes=" + ROOT, "--spring.cloud.consul.config.watch.delay=10");
context = new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE)
.run("--spring.application.name=" + APP_NAME, "--spring.config.use-legacy-processing=true",
"--spring.cloud.consul.host=" + ConsulTestcontainers.getHost(),
"--spring.cloud.consul.port=" + ConsulTestcontainers.getPort(),
"--spring.cloud.consul.config.prefixes=" + ROOT, "--spring.cloud.consul.config.watch.delay=10");
client = context.getBean(ConsulClient.class);
environment = context.getEnvironment();

View File

@@ -30,6 +30,7 @@ import org.springframework.context.annotation.Conditional;
/**
* When both property and consul classes are on the classpath.
*
* @author Spencer Gibb
*/
@Retention(RetentionPolicy.RUNTIME)

View File

@@ -130,9 +130,11 @@ public class ConsulAutoConfiguration {
@Bean(name = "consulRetryInterceptor")
@ConditionalOnMissingBean(name = "consulRetryInterceptor")
public RetryOperationsInterceptor consulRetryInterceptor(RetryProperties properties) {
return RetryInterceptorBuilder.stateless().backOffOptions(properties.getInitialInterval(),
properties.getMultiplier(), properties.getMaxInterval()).maxAttempts(properties.getMaxAttempts())
.build();
return RetryInterceptorBuilder.stateless()
.backOffOptions(properties.getInitialInterval(), properties.getMultiplier(),
properties.getMaxInterval())
.maxAttempts(properties.getMaxAttempts())
.build();
}
}

View File

@@ -54,7 +54,7 @@ public class ConsulEndpoint {
data.setAgentServices(agentServices.getValue());
Response<Map<String, List<String>>> catalogServices = this.consul
.getCatalogServices(CatalogServicesRequest.newBuilder().setQueryParams(QueryParams.DEFAULT).build());
.getCatalogServices(CatalogServicesRequest.newBuilder().setQueryParams(QueryParams.DEFAULT).build());
for (String serviceId : catalogServices.getValue().keySet()) {
Response<List<CatalogService>> response = this.consul.getCatalogService(serviceId,
@@ -63,7 +63,7 @@ public class ConsulEndpoint {
}
Response<List<Node>> catalogNodes = this.consul
.getCatalogNodes(CatalogNodesRequest.newBuilder().setQueryParams(QueryParams.DEFAULT).build());
.getCatalogNodes(CatalogNodesRequest.newBuilder().setQueryParams(QueryParams.DEFAULT).build());
data.setCatalogNodes(catalogNodes.getValue());
return data;
@@ -110,7 +110,9 @@ public class ConsulEndpoint {
@Override
public String toString() {
return new ToStringCreator(this).append("catalogServices", this.catalogServices)
.append("agentServices", this.agentServices).append("catalogNodes", this.catalogNodes).toString();
.append("agentServices", this.agentServices)
.append("catalogNodes", this.catalogNodes)
.toString();
}
}

View File

@@ -46,8 +46,8 @@ public class ConsulHealthIndicator extends AbstractHealthIndicator {
final Response<String> leaderStatus = this.consul.getStatusLeader();
builder.up().withDetail("leader", leaderStatus.getValue());
if (properties.isIncludeServicesQuery()) {
final Response<Map<String, List<String>>> services = this.consul.getCatalogServices(
CatalogServicesRequest.newBuilder().setQueryParams(QueryParams.DEFAULT).build());
final Response<Map<String, List<String>>> services = this.consul
.getCatalogServices(CatalogServicesRequest.newBuilder().setQueryParams(QueryParams.DEFAULT).build());
builder.withDetail("services", services.getValue());
}
}

View File

@@ -189,9 +189,11 @@ public class ConsulProperties {
@Override
public String toString() {
return new ToStringCreator(this).append("keyStoreInstanceType", this.keyStoreInstanceType)
.append("keyStorePath", this.keyStorePath).append("keyStorePassword", this.keyStorePassword)
.append("certificatePath", this.certificatePath)
.append("certificatePassword", this.certificatePassword).toString();
.append("keyStorePath", this.keyStorePath)
.append("keyStorePassword", this.keyStorePassword)
.append("certificatePath", this.certificatePath)
.append("certificatePassword", this.certificatePassword)
.toString();
}
}

View File

@@ -90,9 +90,12 @@ public class RetryProperties {
@Override
public String toString() {
return new ToStringCreator(this).append("enabled", this.enabled).append("initialInterval", this.initialInterval)
.append("multiplier", this.multiplier).append("maxInterval", this.maxInterval)
.append("maxAttempts", this.maxAttempts).toString();
return new ToStringCreator(this).append("enabled", this.enabled)
.append("initialInterval", this.initialInterval)
.append("multiplier", this.multiplier)
.append("maxInterval", this.maxInterval)
.append("maxAttempts", this.maxAttempts)
.toString();
}
}

View File

@@ -18,6 +18,7 @@ package org.springframework.cloud.consul.model;
/**
* Gossip pool (serf) statuses. Created by nicu on 10.03.2015.
*
* @author Nicu Marasoiu
*/
public enum SerfStatusEnum {

View File

@@ -42,22 +42,26 @@ import static org.assertj.core.api.Assertions.assertThat;
public class ConsulAutoConfigurationTests {
private final ApplicationContextRunner appContextRunner = new ApplicationContextRunner()
.withInitializer(new ConsulTestcontainers())
.withConfiguration(AutoConfigurations.of(ConsulAutoConfiguration.class));
.withInitializer(new ConsulTestcontainers())
.withConfiguration(AutoConfigurations.of(ConsulAutoConfiguration.class));
@Test
public void defaultConfiguration() {
appContextRunner.run(context -> assertThat(context).hasNotFailed().hasSingleBean(ConsulProperties.class)
.hasSingleBean(ConsulClient.class).hasSingleBean(ConsulHealthIndicator.class)
.doesNotHaveBean(ConsulEndpoint.class));
appContextRunner.run(context -> assertThat(context).hasNotFailed()
.hasSingleBean(ConsulProperties.class)
.hasSingleBean(ConsulClient.class)
.hasSingleBean(ConsulHealthIndicator.class)
.doesNotHaveBean(ConsulEndpoint.class));
}
@Test
public void consulDisabled() {
appContextRunner.withPropertyValues("spring.cloud.consul.enabled=false")
.run(context -> assertThat(context).hasNotFailed().doesNotHaveBean(ConsulProperties.class)
.doesNotHaveBean(ConsulClient.class).doesNotHaveBean(ConsulHealthIndicator.class)
.doesNotHaveBean(ConsulEndpoint.class));
.run(context -> assertThat(context).hasNotFailed()
.doesNotHaveBean(ConsulProperties.class)
.doesNotHaveBean(ConsulClient.class)
.doesNotHaveBean(ConsulHealthIndicator.class)
.doesNotHaveBean(ConsulEndpoint.class));
}
@Test
@@ -78,57 +82,61 @@ public class ConsulAutoConfigurationTests {
@Test
public void tlsConfigured() {
appContextRunner.withPropertyValues("spring.cloud.consul.tls.key-store-instance-type=JKS",
"spring.cloud.consul.tls.key-store-path=src/test/resources/server.jks",
"spring.cloud.consul.tls.key-store-password=letmein",
"spring.cloud.consul.tls.certificate-path=src/test/resources/trustStore.jks",
"spring.cloud.consul.tls.certificate-password=change_me").run(context -> {
assertThat(context).hasNotFailed().hasSingleBean(ConsulClient.class);
appContextRunner
.withPropertyValues("spring.cloud.consul.tls.key-store-instance-type=JKS",
"spring.cloud.consul.tls.key-store-path=src/test/resources/server.jks",
"spring.cloud.consul.tls.key-store-password=letmein",
"spring.cloud.consul.tls.certificate-path=src/test/resources/trustStore.jks",
"spring.cloud.consul.tls.certificate-password=change_me")
.run(context -> {
assertThat(context).hasNotFailed().hasSingleBean(ConsulClient.class);
ConsulClient consulClient = context.getBean(ConsulClient.class);
CatalogConsulClient client = (CatalogConsulClient) ReflectionTestUtils.getField(consulClient,
"catalogClient");
ConsulRawClient rawClient = (ConsulRawClient) ReflectionTestUtils.getField(client, "rawClient");
HttpTransport httpTransport = (HttpTransport) ReflectionTestUtils.getField(rawClient,
"httpTransport");
assertThat(httpTransport).isInstanceOf(DefaultHttpsTransport.class);
});
ConsulClient consulClient = context.getBean(ConsulClient.class);
CatalogConsulClient client = (CatalogConsulClient) ReflectionTestUtils.getField(consulClient,
"catalogClient");
ConsulRawClient rawClient = (ConsulRawClient) ReflectionTestUtils.getField(client, "rawClient");
HttpTransport httpTransport = (HttpTransport) ReflectionTestUtils.getField(rawClient, "httpTransport");
assertThat(httpTransport).isInstanceOf(DefaultHttpsTransport.class);
});
}
@Test
public void nonActuatorAppGetsNoEndpointOrHealthIndicator() {
appContextRunner.withClassLoader(new FilteredClassLoader(Endpoint.class))
.withPropertyValues("management.endpoints.web.exposure.include=consul")
.run(context -> assertThat(context).hasNotFailed().doesNotHaveBean(ConsulHealthIndicator.class)
.doesNotHaveBean(ConsulEndpoint.class));
.withPropertyValues("management.endpoints.web.exposure.include=consul")
.run(context -> assertThat(context).hasNotFailed()
.doesNotHaveBean(ConsulHealthIndicator.class)
.doesNotHaveBean(ConsulEndpoint.class));
}
@Test
public void consulEndpointAvailable() {
appContextRunner.withPropertyValues("management.endpoints.web.exposure.include=consul")
.run(context -> assertThat(context).hasNotFailed().hasSingleBean(ConsulEndpoint.class));
.run(context -> assertThat(context).hasNotFailed().hasSingleBean(ConsulEndpoint.class));
}
@Test
public void consulEndpointAvailableButDisabled() {
appContextRunner
.withPropertyValues("management.endpoints.web.exposure.include=consul",
"management.endpoint.consul.enabled=false")
.run(context -> assertThat(context).hasNotFailed().doesNotHaveBean(ConsulEndpoint.class));
.withPropertyValues("management.endpoints.web.exposure.include=consul",
"management.endpoint.consul.enabled=false")
.run(context -> assertThat(context).hasNotFailed().doesNotHaveBean(ConsulEndpoint.class));
}
@Test
public void consulEndpointDisabled() {
appContextRunner.withPropertyValues("spring.cloud.consul.enabled=false")
.run(context -> assertThat(context).hasNotFailed().doesNotHaveBean(ConsulProperties.class)
.doesNotHaveBean(ConsulClient.class).doesNotHaveBean(ConsulHealthIndicator.class)
.doesNotHaveBean(ConsulEndpoint.class));
.run(context -> assertThat(context).hasNotFailed()
.doesNotHaveBean(ConsulProperties.class)
.doesNotHaveBean(ConsulClient.class)
.doesNotHaveBean(ConsulHealthIndicator.class)
.doesNotHaveBean(ConsulEndpoint.class));
}
@Test
public void consulHealthIndicatorDisabled() {
appContextRunner.withPropertyValues("management.health.consul.enabled=false")
.run(context -> assertThat(context).hasNotFailed().doesNotHaveBean(ConsulHealthIndicator.class));
.run(context -> assertThat(context).hasNotFailed().doesNotHaveBean(ConsulHealthIndicator.class));
}
}

View File

@@ -63,7 +63,7 @@ public class ConsulHealthIndicatorDownTest {
Response<String> leaderStatus = new Response<>("OK", 5150L, true, System.currentTimeMillis());
when(consulClient.getStatusLeader()).thenReturn(leaderStatus);
when(consulClient.getCatalogServices(any(CatalogServicesRequest.class)))
.thenThrow(new RuntimeException("no services"));
.thenThrow(new RuntimeException("no services"));
assertThat(this.healthEndpoint.health().getStatus()).as("health status was not DOWN").isEqualTo(Status.DOWN);
verify(consulClient).getCatalogServices(any(CatalogServicesRequest.class));
}

View File

@@ -51,7 +51,7 @@ public class ConsulTestcontainers implements ApplicationContextInitializer<Confi
public static ConsulContainer createConsulContainer(String consulVersion) {
String dockerImageName = "consul:" + consulVersion;
return new ConsulContainer(dockerImageName)
.withLogConsumer(new Slf4jLogConsumer(logger).withSeparateOutputStreams());
.withLogConsumer(new Slf4jLogConsumer(logger).withSeparateOutputStreams());
}
@Override

View File

@@ -125,8 +125,9 @@ public class ConsulCatalogWatch implements ApplicationEventPublisherAware, Smart
}
CatalogServicesRequest request = CatalogServicesRequest.newBuilder()
.setQueryParams(new QueryParams(this.properties.getCatalogServicesWatchTimeout(), index))
.setToken(this.properties.getAclToken()).build();
.setQueryParams(new QueryParams(this.properties.getCatalogServicesWatchTimeout(), index))
.setToken(this.properties.getAclToken())
.build();
Response<Map<String, List<String>>> response = this.consul.getCatalogServices(request);
Long consulIndex = response.getConsulIndex();
if (consulIndex != null) {

View File

@@ -67,7 +67,9 @@ public class ConsulDiscoveryClient implements DiscoveryClient {
private void addInstancesToList(List<ServiceInstance> instances, String serviceId, QueryParams queryParams) {
HealthServicesRequest.Builder requestBuilder = HealthServicesRequest.newBuilder()
.setPassing(properties.isQueryPassing()).setQueryParams(queryParams).setToken(properties.getAclToken());
.setPassing(properties.isQueryPassing())
.setQueryParams(queryParams)
.setToken(properties.getAclToken());
String[] queryTags = properties.getQueryTagsForService(serviceId);
if (queryTags != null) {
requestBuilder.setTags(queryTags);
@@ -85,7 +87,7 @@ public class ConsulDiscoveryClient implements DiscoveryClient {
List<ServiceInstance> instances = new ArrayList<>();
Response<Map<String, List<String>>> services = this.client
.getCatalogServices(CatalogServicesRequest.newBuilder().setQueryParams(QueryParams.DEFAULT).build());
.getCatalogServices(CatalogServicesRequest.newBuilder().setQueryParams(QueryParams.DEFAULT).build());
for (String serviceId : services.getValue().keySet()) {
addInstancesToList(instances, serviceId, QueryParams.DEFAULT);
}
@@ -94,8 +96,10 @@ public class ConsulDiscoveryClient implements DiscoveryClient {
@Override
public List<String> getServices() {
CatalogServicesRequest request = CatalogServicesRequest.newBuilder().setQueryParams(QueryParams.DEFAULT)
.setToken(this.properties.getAclToken()).build();
CatalogServicesRequest request = CatalogServicesRequest.newBuilder()
.setQueryParams(QueryParams.DEFAULT)
.setToken(this.properties.getAclToken())
.build();
return new ArrayList<>(this.client.getCatalogServices(request).getValue().keySet());
}

View File

@@ -620,32 +620,49 @@ public class ConsulDiscoveryProperties {
@Override
public String toString() {
return new ToStringCreator(this).append("aclToken", this.aclToken)
.append("catalogServicesWatchDelay", this.catalogServicesWatchDelay)
.append("catalogServicesWatchTimeout", this.catalogServicesWatchTimeout)
.append("consistencyMode", this.consistencyMode).append("datacenters", this.datacenters)
.append("defaultQueryTag", this.defaultQueryTag)
.append("defaultZoneMetadataName", this.defaultZoneMetadataName).append("deregister", this.deregister)
.append("enabled", this.enabled).append("enableTagOverride", this.enableTagOverride)
.append("failFast", this.failFast).append("hostInfo", this.hostInfo)
.append("healthCheckCriticalTimeout", this.healthCheckCriticalTimeout)
.append("healthCheckHeaders", this.healthCheckHeaders)
.append("healthCheckInterval", this.healthCheckInterval).append("healthCheckPath", this.healthCheckPath)
.append("healthCheckTimeout", this.healthCheckTimeout)
.append("healthCheckTlsSkipVerify", this.healthCheckTlsSkipVerify)
.append("healthCheckUrl", this.healthCheckUrl).append("hostname", this.hostname)
.append("includeHostnameInInstanceId", this.includeHostnameInInstanceId)
.append("instanceId", this.instanceId).append("instanceGroup", this.instanceGroup)
.append("instanceZone", this.instanceZone).append("ipAddress", this.ipAddress)
.append("lifecycle", this.lifecycle).append("metadata", this.metadata)
.append("managementEnableTagOverride", this.managementEnableTagOverride)
.append("managementMetadata", this.managementMetadata).append("managementPort", this.managementPort)
.append("managementSuffix", this.managementSuffix).append("managementTags", this.managementTags)
.append("order", this.order).append("port", this.port)
.append("preferAgentAddress", this.preferAgentAddress).append("preferIpAddress", this.preferIpAddress)
.append("queryPassing", this.queryPassing).append("register", this.register)
.append("registerHealthCheck", this.registerHealthCheck).append("scheme", this.scheme)
.append("serviceName", this.serviceName).append("serverListQueryTags", this.serverListQueryTags)
.append("tags", this.tags).toString();
.append("catalogServicesWatchDelay", this.catalogServicesWatchDelay)
.append("catalogServicesWatchTimeout", this.catalogServicesWatchTimeout)
.append("consistencyMode", this.consistencyMode)
.append("datacenters", this.datacenters)
.append("defaultQueryTag", this.defaultQueryTag)
.append("defaultZoneMetadataName", this.defaultZoneMetadataName)
.append("deregister", this.deregister)
.append("enabled", this.enabled)
.append("enableTagOverride", this.enableTagOverride)
.append("failFast", this.failFast)
.append("hostInfo", this.hostInfo)
.append("healthCheckCriticalTimeout", this.healthCheckCriticalTimeout)
.append("healthCheckHeaders", this.healthCheckHeaders)
.append("healthCheckInterval", this.healthCheckInterval)
.append("healthCheckPath", this.healthCheckPath)
.append("healthCheckTimeout", this.healthCheckTimeout)
.append("healthCheckTlsSkipVerify", this.healthCheckTlsSkipVerify)
.append("healthCheckUrl", this.healthCheckUrl)
.append("hostname", this.hostname)
.append("includeHostnameInInstanceId", this.includeHostnameInInstanceId)
.append("instanceId", this.instanceId)
.append("instanceGroup", this.instanceGroup)
.append("instanceZone", this.instanceZone)
.append("ipAddress", this.ipAddress)
.append("lifecycle", this.lifecycle)
.append("metadata", this.metadata)
.append("managementEnableTagOverride", this.managementEnableTagOverride)
.append("managementMetadata", this.managementMetadata)
.append("managementPort", this.managementPort)
.append("managementSuffix", this.managementSuffix)
.append("managementTags", this.managementTags)
.append("order", this.order)
.append("port", this.port)
.append("preferAgentAddress", this.preferAgentAddress)
.append("preferIpAddress", this.preferIpAddress)
.append("queryPassing", this.queryPassing)
.append("register", this.register)
.append("registerHealthCheck", this.registerHealthCheck)
.append("scheme", this.scheme)
.append("serviceName", this.serviceName)
.append("serverListQueryTags", this.serverListQueryTags)
.append("tags", this.tags)
.toString();
}
/**

View File

@@ -96,10 +96,15 @@ public class ConsulServiceInstance extends DefaultServiceInstance {
@Override
public String toString() {
return new ToStringCreator(this).append("instanceId", getInstanceId()).append("serviceId", getServiceId())
.append("host", getHost()).append("port", getPort()).append("secure", isSecure())
.append("metadata", getMetadata()).append("uri", getUri()).append("healthService", healthService)
.toString();
return new ToStringCreator(this).append("instanceId", getInstanceId())
.append("serviceId", getServiceId())
.append("host", getHost())
.append("port", getPort())
.append("secure", isSecure())
.append("metadata", getMetadata())
.append("uri", getUri())
.append("healthService", healthService)
.toString();
}

View File

@@ -131,9 +131,12 @@ public class HeartbeatProperties {
@Override
public String toString() {
return new ToStringCreator(this).append("enabled", this.enabled).append("ttl", this.ttl)
.append("intervalRatio", this.intervalRatio).append("useActuatorHealth", this.useActuatorHealth)
.append("healthGroup", this.actuatorHealthGroup).toString();
return new ToStringCreator(this).append("enabled", this.enabled)
.append("ttl", this.ttl)
.append("intervalRatio", this.intervalRatio)
.append("useActuatorHealth", this.useActuatorHealth)
.append("healthGroup", this.actuatorHealthGroup)
.toString();
}
}

View File

@@ -69,7 +69,7 @@ public class TtlScheduler {
this.client = client;
this.reregistrationPredicate = reregistrationPredicate;
this.applicationStatusProvider = applicationStatusProviderFactory
.getIfAvailable(() -> () -> CheckStatus.PASSING);
.getIfAvailable(() -> () -> CheckStatus.PASSING);
}
public void add(final NewService service) {

View File

@@ -81,8 +81,9 @@ public class ConsulConfigServerBootstrapper implements BootstrapRegistryInitiali
}
ConsulDiscoveryClient discoveryClient = event.getBootstrapContext().get(ConsulDiscoveryClient.class);
if (discoveryClient != null) {
event.getApplicationContext().getBeanFactory().registerSingleton("consulDiscoveryClient",
discoveryClient);
event.getApplicationContext()
.getBeanFactory()
.registerSingleton("consulDiscoveryClient", discoveryClient);
}
});

View File

@@ -77,8 +77,9 @@ public class ConsulReactiveDiscoveryClient implements ReactiveDiscoveryClient {
private List<HealthService> getHealthServices(String serviceId) {
HealthServicesRequest.Builder requestBuilder = HealthServicesRequest.newBuilder()
.setPassing(properties.isQueryPassing()).setQueryParams(QueryParams.DEFAULT)
.setToken(properties.getAclToken());
.setPassing(properties.isQueryPassing())
.setQueryParams(QueryParams.DEFAULT)
.setToken(properties.getAclToken());
String[] queryTags = properties.getQueryTagsForService(serviceId);
if (queryTags != null) {
requestBuilder.setTags(queryTags);
@@ -93,8 +94,10 @@ public class ConsulReactiveDiscoveryClient implements ReactiveDiscoveryClient {
@Override
public Flux<String> getServices() {
return Flux.defer(() -> {
CatalogServicesRequest request = CatalogServicesRequest.newBuilder().setToken(properties.getAclToken())
.setQueryParams(QueryParams.DEFAULT).build();
CatalogServicesRequest request = CatalogServicesRequest.newBuilder()
.setToken(properties.getAclToken())
.setQueryParams(QueryParams.DEFAULT)
.build();
Response<Map<String, List<String>>> services = client.getCatalogServices(request);
return services == null ? Flux.empty() : Flux.fromIterable(services.getValue().keySet());
}).onErrorResume(exception -> {

View File

@@ -64,8 +64,10 @@ public class ActuatorHealthApplicationStatusProvider implements ApplicationStatu
public CheckStatus currentStatus() {
String healthGroup = heartbeatProperties.getActuatorHealthGroup();
String[] path = healthGroup == null ? new String[0] : new String[] { healthGroup };
return Optional.ofNullable(healthEndpoint.healthForPath(path)).map(HealthComponent::getStatus)
.map(this::healthStatusToCheckStatus).orElse(CheckStatus.UNKNOWN);
return Optional.ofNullable(healthEndpoint.healthForPath(path))
.map(HealthComponent::getStatus)
.map(this::healthStatusToCheckStatus)
.orElse(CheckStatus.UNKNOWN);
}
private CheckStatus healthStatusToCheckStatus(Status healthStatus) {

View File

@@ -60,10 +60,10 @@ public class ConsulDiscoveryClientAclTests {
@Test
public void getInstancesForSecondServiceWorks() throws Exception {
new SpringApplicationBuilder(MyTestConfig.class).initializers(new ConsulTestcontainers()).run(
"--spring.application.name=testSecondServiceAcl", "--server.port=0",
"--spring.cloud.consul.discovery.preferIpAddress=true",
"--consul.token=2d2e6b3b-1c82-40ab-8171-54609d8ad304");
new SpringApplicationBuilder(MyTestConfig.class).initializers(new ConsulTestcontainers())
.run("--spring.application.name=testSecondServiceAcl", "--server.port=0",
"--spring.cloud.consul.discovery.preferIpAddress=true",
"--consul.token=2d2e6b3b-1c82-40ab-8171-54609d8ad304");
List<ServiceInstance> instances = this.discoveryClient.getInstances("testSecondServiceAcl");
assertThat(instances).as("second service instances was null").isNotNull();

View File

@@ -80,7 +80,7 @@ public class ConsulDiscoveryClientConfigurationTests {
@Test
public void consulConfigNotLoadedWhenCloudDiscoveryDisabled_ConsulDiscoveryClientDisabled() {
TestPropertyValues.of("spring.cloud.discovery.enabled=false", "spring.cloud.consul.discovery.enabled=false")
.applyTo(this.context);
.applyTo(this.context);
setupContext();
assertBeanNotPresent(ConsulDiscoveryProperties.class);
assertBeanNotPresent(ConsulDiscoveryClient.class);
@@ -90,7 +90,7 @@ public class ConsulDiscoveryClientConfigurationTests {
@Test
public void consulConfigIsLoadedWhenCloudDiscoveryEnabled_ConsulDiscoveryClientEnabled() {
TestPropertyValues.of("spring.cloud.discovery.enabled=true", "spring.cloud.consul.discovery.enabled=true")
.applyTo(this.context);
.applyTo(this.context);
setupContext();
assertBeanIsPresent(ConsulDiscoveryProperties.class);
assertBeanIsPresent(ConsulDiscoveryClient.class);
@@ -99,7 +99,7 @@ public class ConsulDiscoveryClientConfigurationTests {
@Test
public void consulConfigNotLoadedWhenCloudDiscoveryEnabled_ConsulDiscoveryClientDisabled() {
TestPropertyValues.of("spring.cloud.discovery.enabled=true", "spring.cloud.consul.discovery.enabled=false")
.applyTo(this.context);
.applyTo(this.context);
setupContext();
assertBeanNotPresent(ConsulDiscoveryProperties.class);
assertBeanNotPresent(ConsulDiscoveryClient.class);
@@ -109,7 +109,7 @@ public class ConsulDiscoveryClientConfigurationTests {
@Test
public void consulConfigNotLoadedWhenCloudDiscoveryDisabled_ConsulDiscoveryClientEnabled() {
TestPropertyValues.of("spring.cloud.discovery.enabled=false", "spring.cloud.consul.discovery.enabled=true")
.applyTo(this.context);
.applyTo(this.context);
setupContext();
assertBeanNotPresent(ConsulDiscoveryProperties.class);
assertBeanNotPresent(ConsulDiscoveryClient.class);

View File

@@ -47,7 +47,7 @@ public class ConsulDiscoveryClientProbeTests {
@Test
public void probeSucceeds() {
when(consulClient.getStatusLeader())
.thenReturn(new Response<>("5150", 5150L, false, System.currentTimeMillis()));
.thenReturn(new Response<>("5150", 5150L, false, System.currentTimeMillis()));
discoveryClient.probe();
verify(consulClient).getStatusLeader();
}
@@ -56,7 +56,7 @@ public class ConsulDiscoveryClientProbeTests {
public void probeFails() {
when(consulClient.getStatusLeader()).thenThrow(new OperationException(5150, "5150", "No leader"));
assertThatThrownBy(() -> discoveryClient.probe()).isInstanceOf(OperationException.class)
.hasMessageContaining("No leader");
.hasMessageContaining("No leader");
verify(consulClient).getStatusLeader();
}

View File

@@ -53,9 +53,10 @@ class ConsulDiscoveryClientQueryTagsTests {
static NewService PROD_EAST_SERVICE = serviceForEnvironmentAndRegion("prod", "us-east", 9082);
private ApplicationContextRunner appContextRunner = new ApplicationContextRunner()
.withInitializer(new ConsulTestcontainers()).withConfiguration(AutoConfigurations.of(TestConfig.class))
.withPropertyValues("spring.application.name=consulServiceQueryTags",
"spring.cloud.consul.discovery.catalogServicesWatch.enabled=false");
.withInitializer(new ConsulTestcontainers())
.withConfiguration(AutoConfigurations.of(TestConfig.class))
.withPropertyValues("spring.application.name=consulServiceQueryTags",
"spring.cloud.consul.discovery.catalogServicesWatch.enabled=false");
private static NewService serviceForEnvironmentAndRegion(String env, String region, int port) {
NewService service = new NewService();
@@ -69,89 +70,89 @@ class ConsulDiscoveryClientQueryTagsTests {
@Test
void singleMatchingTagSpecifiedOnDefaultQueryTagProperty() {
appContextRunner.withPropertyValues("spring.cloud.consul.discovery.default-query-tag=qa").run(
context -> assertThatGetInstancesReturnsExpectedServices(context, QA_WEST_SERVICE, QA_EAST_SERVICE));
appContextRunner.withPropertyValues("spring.cloud.consul.discovery.default-query-tag=qa")
.run(context -> assertThatGetInstancesReturnsExpectedServices(context, QA_WEST_SERVICE, QA_EAST_SERVICE));
}
@Test
void singleNonMatchingTagSpecifiedOnDefaultQueryTagProperty() {
appContextRunner.withPropertyValues("spring.cloud.consul.discovery.default-query-tag=foo")
.run(context -> assertThatGetInstancesReturnsExpectedServices(context, new NewService[0]));
.run(context -> assertThatGetInstancesReturnsExpectedServices(context, new NewService[0]));
}
@Test
void multipleMatchingTagsSpecifiedOnDefaultQueryTagProperty() {
appContextRunner.withPropertyValues("spring.cloud.consul.discovery.default-query-tag=prod,us-west")
.run(context -> assertThatGetInstancesReturnsExpectedServices(context, PROD_WEST_SERVICE));
.run(context -> assertThatGetInstancesReturnsExpectedServices(context, PROD_WEST_SERVICE));
}
@Test
void multipleNonMatchingTagsSpecifiedOnDefaultQueryTagProperty() {
appContextRunner.withPropertyValues("spring.cloud.consul.discovery.default-query-tag=prod,foo")
.run(context -> assertThatGetInstancesReturnsExpectedServices(context, new NewService[0]));
.run(context -> assertThatGetInstancesReturnsExpectedServices(context, new NewService[0]));
}
@Test
void multipleConflictingMatchingTagsSpecifiedOnDefaultQueryTagsProperty() {
appContextRunner.withPropertyValues("spring.cloud.consul.discovery.default-query-tag=prod,qa")
.run(context -> assertThatGetInstancesReturnsExpectedServices(context));
.run(context -> assertThatGetInstancesReturnsExpectedServices(context));
}
@Test
void emptyTagSpecifiedOnDefaultQueryTagProperty() {
appContextRunner.withPropertyValues("spring.cloud.consul.discovery.default-query-tag=")
.run(context -> assertThatGetInstancesReturnsExpectedServices(context, QA_WEST_SERVICE, QA_EAST_SERVICE,
PROD_WEST_SERVICE, PROD_EAST_SERVICE));
.run(context -> assertThatGetInstancesReturnsExpectedServices(context, QA_WEST_SERVICE, QA_EAST_SERVICE,
PROD_WEST_SERVICE, PROD_EAST_SERVICE));
}
@Test
void singleTagSpecifiedOnServerListQueryTagsProperty() {
appContextRunner
.withPropertyValues("spring.cloud.consul.discovery.default-query-tag=qa",
"spring.cloud.consul.discovery.server-list-query-tags[" + NAME + "]=prod")
.run(context -> assertThatGetInstancesReturnsExpectedServices(context, PROD_WEST_SERVICE,
PROD_EAST_SERVICE));
.withPropertyValues("spring.cloud.consul.discovery.default-query-tag=qa",
"spring.cloud.consul.discovery.server-list-query-tags[" + NAME + "]=prod")
.run(context -> assertThatGetInstancesReturnsExpectedServices(context, PROD_WEST_SERVICE,
PROD_EAST_SERVICE));
}
@Test
void singleNonMatchingTagSpecifiedOnServerListQueryTagsProperty() {
appContextRunner
.withPropertyValues("spring.cloud.consul.discovery.default-query-tag=qa",
"spring.cloud.consul.discovery.server-list-query-tags[" + NAME + "]=foo")
.run(context -> assertThatGetInstancesReturnsExpectedServices(context, new NewService[0]));
.withPropertyValues("spring.cloud.consul.discovery.default-query-tag=qa",
"spring.cloud.consul.discovery.server-list-query-tags[" + NAME + "]=foo")
.run(context -> assertThatGetInstancesReturnsExpectedServices(context, new NewService[0]));
}
@Test
void multipleMatchingTagsSpecifiedOnServerListQueryTagsProperty() {
appContextRunner
.withPropertyValues("spring.cloud.consul.discovery.default-query-tag=qa",
"spring.cloud.consul.discovery.server-list-query-tags[" + NAME + "]=prod,us-west")
.run(context -> assertThatGetInstancesReturnsExpectedServices(context, PROD_WEST_SERVICE));
.withPropertyValues("spring.cloud.consul.discovery.default-query-tag=qa",
"spring.cloud.consul.discovery.server-list-query-tags[" + NAME + "]=prod,us-west")
.run(context -> assertThatGetInstancesReturnsExpectedServices(context, PROD_WEST_SERVICE));
}
@Test
void multipleNotAllMatchingTagsSpecifiedOnServerListQueryTagsProperty() {
appContextRunner
.withPropertyValues("spring.cloud.consul.discovery.default-query-tag=qa",
"spring.cloud.consul.discovery.server-list-query-tags[" + NAME + "]=prod,foo")
.run(context -> assertThatGetInstancesReturnsExpectedServices(context, new NewService[0]));
.withPropertyValues("spring.cloud.consul.discovery.default-query-tag=qa",
"spring.cloud.consul.discovery.server-list-query-tags[" + NAME + "]=prod,foo")
.run(context -> assertThatGetInstancesReturnsExpectedServices(context, new NewService[0]));
}
@Test
void multipleConflictingMatchingTagsSpecifiedOnServerListQueryTagsProperty() {
appContextRunner
.withPropertyValues("spring.cloud.consul.discovery.default-query-tag=qa",
"spring.cloud.consul.discovery.server-list-query-tags[" + NAME + "]=prod,qa")
.run(context -> assertThatGetInstancesReturnsExpectedServices(context, new NewService[0]));
.withPropertyValues("spring.cloud.consul.discovery.default-query-tag=qa",
"spring.cloud.consul.discovery.server-list-query-tags[" + NAME + "]=prod,qa")
.run(context -> assertThatGetInstancesReturnsExpectedServices(context, new NewService[0]));
}
@Test
void emptyTagSpecifiedOnServerListQueryTagsProperty() {
appContextRunner
.withPropertyValues("spring.cloud.consul.discovery.default-query-tag=qa",
"spring.cloud.consul.discovery.server-list-query-tags[" + NAME + "]=")
.run(context -> assertThatGetInstancesReturnsExpectedServices(context, QA_WEST_SERVICE, QA_EAST_SERVICE,
PROD_WEST_SERVICE, PROD_EAST_SERVICE));
.withPropertyValues("spring.cloud.consul.discovery.default-query-tag=qa",
"spring.cloud.consul.discovery.server-list-query-tags[" + NAME + "]=")
.run(context -> assertThatGetInstancesReturnsExpectedServices(context, QA_WEST_SERVICE, QA_EAST_SERVICE,
PROD_WEST_SERVICE, PROD_EAST_SERVICE));
}
@Test
@@ -169,11 +170,11 @@ class ConsulDiscoveryClientQueryTagsTests {
ConsulDiscoveryClient consulDiscoveryClient = context.getBean(ConsulDiscoveryClient.class);
List<ServiceInstance> serviceInstances = consulDiscoveryClient.getInstances(NAME);
assertThat(serviceInstances).hasSize(expectedServices.length)
.hasOnlyElementsOfType(ConsulServiceInstance.class);
.hasOnlyElementsOfType(ConsulServiceInstance.class);
for (NewService expectedService : expectedServices) {
assertThat(serviceInstances)
.anySatisfy(serviceInstance -> assertThatServicesMatch((ConsulServiceInstance) serviceInstance,
expectedService));
.anySatisfy(serviceInstance -> assertThatServicesMatch((ConsulServiceInstance) serviceInstance,
expectedService));
}
}

View File

@@ -60,7 +60,10 @@ public class ConsulConfigServerAutoConfigurationTests {
private void setup(String... env) {
this.context = new SpringApplicationBuilder(PropertyPlaceholderAutoConfiguration.class,
ConsulConfigServerAutoConfiguration.class, ConfigServerProperties.class,
ConsulDiscoveryProperties.class).web(WebApplicationType.NONE).properties(env).run();
ConsulDiscoveryProperties.class)
.web(WebApplicationType.NONE)
.properties(env)
.run();
}
}

View File

@@ -58,7 +58,7 @@ import static org.mockserver.model.HttpResponse.response;
public class ConsulConfigServerBootstrapperIT {
public static final DockerImageName MOCKSERVER_IMAGE = DockerImageName.parse("mockserver/mockserver")
.withTag("mockserver-" + MockServerClient.class.getPackage().getImplementationVersion());
.withTag("mockserver-" + MockServerClient.class.getPackage().getImplementationVersion());
@Container
static ConsulContainer consul = ConsulTestcontainers.createConsulContainer("1.10");
@@ -100,8 +100,8 @@ public class ConsulConfigServerBootstrapperIT {
try (MockServerClient mockServerClient = new MockServerClient(mockServer.getHost(),
mockServer.getMappedPort(MockServerContainer.PORT))) {
mockServerClient.when(request().withPath("/application/default"))
.respond(response().withBody(objectMapper.writeValueAsString(environment))
.withHeader("content-type", "application/json"));
.respond(response().withBody(objectMapper.writeValueAsString(environment))
.withHeader("content-type", "application/json"));
this.context = setup().run();
assertThat(this.context.getEnvironment().getProperty("hello")).isEqualTo("world");
}
@@ -110,7 +110,7 @@ public class ConsulConfigServerBootstrapperIT {
SpringApplicationBuilder setup(String... env) {
SpringApplicationBuilder builder = new SpringApplicationBuilder(TestConfig.class)
.properties(addDefaultEnv(env));
.properties(addDefaultEnv(env));
return builder;
}

View File

@@ -32,9 +32,10 @@ public class ConsulConfigServerBootstrapperNoConfigClientTests {
@Test
public void enabledAddsInstanceProviderFn() {
new SpringApplicationBuilder(TestConfig.class)
.properties("--server.port=0", "spring.cloud.config.discovery.enabled=true",
"spring.cloud.service-registry.auto-registration.enabled=false")
.run().close();
.properties("--server.port=0", "spring.cloud.config.discovery.enabled=true",
"spring.cloud.service-registry.auto-registration.enabled=false")
.run()
.close();
}
@SpringBootConfiguration

View File

@@ -46,46 +46,52 @@ public class ConsulConfigServerBootstrapperTests {
@Test
public void notEnabledDoesNotAddInstanceProviderFn() {
new SpringApplicationBuilder(TestConfig.class)
.properties("--server.port=0", "spring.cloud.service-registry.auto-registration.enabled=false")
.addBootstrapRegistryInitializer(registry -> registry.addCloseListener(event -> {
ConfigServerInstanceProvider.Function providerFn = event.getBootstrapContext()
.get(ConfigServerInstanceProvider.Function.class);
Log log = mock(Log.class);
assertThat(providerFn.apply("id", event.getBootstrapContext().get(Binder.class),
event.getBootstrapContext().get(BindHandler.class), log))
.as("ConfigServerInstanceProvider.Function should return empty list")
.isEqualTo(Collections.EMPTY_LIST);
})).run().close();
.properties("--server.port=0", "spring.cloud.service-registry.auto-registration.enabled=false")
.addBootstrapRegistryInitializer(registry -> registry.addCloseListener(event -> {
ConfigServerInstanceProvider.Function providerFn = event.getBootstrapContext()
.get(ConfigServerInstanceProvider.Function.class);
Log log = mock(Log.class);
assertThat(providerFn.apply("id", event.getBootstrapContext().get(Binder.class),
event.getBootstrapContext().get(BindHandler.class), log))
.as("ConfigServerInstanceProvider.Function should return empty list")
.isEqualTo(Collections.EMPTY_LIST);
}))
.run()
.close();
}
@Test
public void consulDiscoveryClientNotEnabledProvidesEmptyList() {
new SpringApplicationBuilder(TestConfig.class)
.properties("--server.port=0", "spring.cloud.service-registry.auto-registration.enabled=false")
.addBootstrapRegistryInitializer(registry -> registry.addCloseListener(event -> {
ConfigServerInstanceProvider.Function providerFn = event.getBootstrapContext()
.get(ConfigServerInstanceProvider.Function.class);
Log log = mock(Log.class);
assertThat(providerFn.apply("id", event.getBootstrapContext().get(Binder.class),
event.getBootstrapContext().get(BindHandler.class), log))
.as("ConfigServerInstanceProvider.Function should return empty list")
.isEqualTo(Collections.EMPTY_LIST);
})).run().close();
.properties("--server.port=0", "spring.cloud.service-registry.auto-registration.enabled=false")
.addBootstrapRegistryInitializer(registry -> registry.addCloseListener(event -> {
ConfigServerInstanceProvider.Function providerFn = event.getBootstrapContext()
.get(ConfigServerInstanceProvider.Function.class);
Log log = mock(Log.class);
assertThat(providerFn.apply("id", event.getBootstrapContext().get(Binder.class),
event.getBootstrapContext().get(BindHandler.class), log))
.as("ConfigServerInstanceProvider.Function should return empty list")
.isEqualTo(Collections.EMPTY_LIST);
}))
.run()
.close();
}
@Test
public void springCloudDiscoveryClientNotEnabledProvidesEmptyList() {
new SpringApplicationBuilder(TestConfig.class)
.properties("--server.port=0", "spring.cloud.service-registry.auto-registration.enabled=false")
.addBootstrapRegistryInitializer(registry -> registry.addCloseListener(event -> {
ConfigServerInstanceProvider.Function providerFn = event.getBootstrapContext()
.get(ConfigServerInstanceProvider.Function.class);
Log log = mock(Log.class);
assertThat(providerFn.apply("id", event.getBootstrapContext().get(Binder.class),
event.getBootstrapContext().get(BindHandler.class), log))
.as("ConfigServerInstanceProvider.Function should return empty list")
.isEqualTo(Collections.EMPTY_LIST);
})).run().close();
.properties("--server.port=0", "spring.cloud.service-registry.auto-registration.enabled=false")
.addBootstrapRegistryInitializer(registry -> registry.addCloseListener(event -> {
ConfigServerInstanceProvider.Function providerFn = event.getBootstrapContext()
.get(ConfigServerInstanceProvider.Function.class);
Log log = mock(Log.class);
assertThat(providerFn.apply("id", event.getBootstrapContext().get(Binder.class),
event.getBootstrapContext().get(BindHandler.class), log))
.as("ConfigServerInstanceProvider.Function should return empty list")
.isEqualTo(Collections.EMPTY_LIST);
}))
.run()
.close();
}
@Test
@@ -93,22 +99,22 @@ public class ConsulConfigServerBootstrapperTests {
AtomicReference<ConsulDiscoveryClient> bootstrapDiscoveryClient = new AtomicReference<>();
BindHandlerBootstrapper bindHandlerBootstrapper = new BindHandlerBootstrapper();
ConfigurableApplicationContext context = new SpringApplicationBuilder(TestConfig.class)
.properties("--server.port=0", "spring.cloud.config.discovery.enabled=true",
"spring.cloud.consul.discovery.hostname=myhost",
"spring.cloud.service-registry.auto-registration.enabled=false")
.addBootstrapRegistryInitializer(bindHandlerBootstrapper)
.addBootstrapRegistryInitializer(registry -> registry.addCloseListener(event -> {
bootstrapDiscoveryClient.set(event.getBootstrapContext().get(ConsulDiscoveryClient.class));
ConfigServerInstanceProvider.Function providerFn = event.getBootstrapContext()
.get(ConfigServerInstanceProvider.Function.class);
assertThatThrownBy(() -> providerFn.apply("id", event.getBootstrapContext().get(Binder.class),
event.getBootstrapContext().get(BindHandler.class), mock(Log.class)))
.isInstanceOf(TransportException.class)
.hasMessageContaining(
"org.apache.http.conn.HttpHostConnectException: Connect to localhost:8500")
.as("Should have tried to reach out to Consul to get config server instance")
.isNotNull();
})).run();
.properties("--server.port=0", "spring.cloud.config.discovery.enabled=true",
"spring.cloud.consul.discovery.hostname=myhost",
"spring.cloud.service-registry.auto-registration.enabled=false")
.addBootstrapRegistryInitializer(bindHandlerBootstrapper)
.addBootstrapRegistryInitializer(registry -> registry.addCloseListener(event -> {
bootstrapDiscoveryClient.set(event.getBootstrapContext().get(ConsulDiscoveryClient.class));
ConfigServerInstanceProvider.Function providerFn = event.getBootstrapContext()
.get(ConfigServerInstanceProvider.Function.class);
assertThatThrownBy(() -> providerFn.apply("id", event.getBootstrapContext().get(Binder.class),
event.getBootstrapContext().get(BindHandler.class), mock(Log.class)))
.isInstanceOf(TransportException.class)
.hasMessageContaining("org.apache.http.conn.HttpHostConnectException: Connect to localhost:8500")
.as("Should have tried to reach out to Consul to get config server instance")
.isNotNull();
}))
.run();
ConsulDiscoveryClient discoveryClient = context.getBean(ConsulDiscoveryClient.class);
assertThat(discoveryClient == bootstrapDiscoveryClient.get()).isTrue();
assertThat(bindHandlerBootstrapper.onSuccessCount).isGreaterThan(0);

View File

@@ -74,7 +74,7 @@ class ConsulReactiveDiscoveryClientTests {
public void shouldReturnEmptyFluxOfServicesWhenConsulFails() {
Flux<String> services = client.getServices();
when(consulClient.getCatalogServices(any(CatalogServicesRequest.class)))
.thenThrow(new RuntimeException("Possible runtime exception"));
.thenThrow(new RuntimeException("Possible runtime exception"));
StepVerifier.create(services).expectNextCount(0).expectComplete().verify();
verify(consulClient).getCatalogServices(any(CatalogServicesRequest.class));
}
@@ -102,7 +102,7 @@ class ConsulReactiveDiscoveryClientTests {
public void shouldReturnEmptyFluxForNonExistingService() {
configureCommonProperties();
when(consulClient.getHealthServices(eq("nonexistent-service"), any(HealthServicesRequest.class)))
.thenReturn(emptyConsulInstancesResponse());
.thenReturn(emptyConsulInstancesResponse());
Flux<ServiceInstance> instances = client.getInstances("nonexistent-service");
StepVerifier.create(instances).expectNextCount(0).expectComplete().verify();
verify(properties).getAclToken();
@@ -113,7 +113,7 @@ class ConsulReactiveDiscoveryClientTests {
public void shouldReturnEmptyFluxWhenConsulFails() {
configureCommonProperties();
when(consulClient.getHealthServices(eq("existing-service"), any(HealthServicesRequest.class)))
.thenThrow(new RuntimeException("Possible runtime exception"));
.thenThrow(new RuntimeException("Possible runtime exception"));
Flux<ServiceInstance> instances = client.getInstances("existing-service");
StepVerifier.create(instances).expectNextCount(0).expectComplete().verify();
verify(consulClient).getHealthServices(eq("existing-service"), any());
@@ -124,7 +124,7 @@ class ConsulReactiveDiscoveryClientTests {
configureCommonProperties();
Response<List<HealthService>> response = consulInstancesResponse();
when(consulClient.getHealthServices(eq("existing-service"), any(HealthServicesRequest.class)))
.thenReturn(response);
.thenReturn(response);
Flux<ServiceInstance> instances = client.getInstances("existing-service");
StepVerifier.create(instances).expectNextCount(1).expectComplete().verify();
verify(properties).getAclToken();
@@ -139,7 +139,7 @@ class ConsulReactiveDiscoveryClientTests {
when(properties.getAclToken()).thenReturn("aclToken");
Response<List<HealthService>> response = consulInstancesResponse();
when(consulClient.getHealthServices(eq("existing-service"), any(HealthServicesRequest.class)))
.thenReturn(response);
.thenReturn(response);
Flux<ServiceInstance> instances = client.getInstances("existing-service");
StepVerifier.create(instances).expectNextCount(1).expectComplete().verify();
verify(properties, times(1)).getAclToken();

View File

@@ -53,7 +53,8 @@ public class ConsulAutoRegistrationCheckTtlDeregisterCriticalServiceTests {
public void contextLoads() {
NewService service = registration.getService();
assertThat("1m".equals(service.getCheck().getDeregisterCriticalServiceAfter()))
.as("Service with heartbeat check and deregister critical timeout registered").isTrue();
.as("Service with heartbeat check and deregister critical timeout registered")
.isTrue();
}
@Configuration(proxyBeanMethods = false)

View File

@@ -62,7 +62,7 @@ public class ConsulAutoRegistrationHealthCheckHeadersTests {
assertThat(check.getHeader()).as("header is null").isNotNull();
assertThat(check.getHeader()).as("header is empty").isNotEmpty();
assertThat(check.getHeader().get("X-Config-Token").get(0)).as("expected header value not found")
.isEqualTo("ACCESSTOKEN");
.isEqualTo("ACCESSTOKEN");
// unable to call consul api to get health check details
}

View File

@@ -79,21 +79,22 @@ public class ConsulAutoServiceRegistrationCustomizedManagementServicePortTests {
assertThat(service.getService()).as("service name was wrong").isEqualTo("myprefix-myTestService-GG");
assertThat(ObjectUtils.isEmpty(service.getAddress())).as("service address must not be empty").isFalse();
assertThat(service.getAddress()).as("service address must equals hostname from discovery properties")
.isEqualTo(this.discoveryProperties.getHostname());
.isEqualTo(this.discoveryProperties.getHostname());
final Service managementService = services.get("myTestService1-GG-management");
assertThat(managementService).as("management service was null").isNotNull();
assertThat(managementService.getPort().intValue()).as("management service port is not 4452").isEqualTo(4452);
assertThat(this.managementServerProperties.getPort().intValue()).as("management port is not 0").isEqualTo(0);
assertThat(managementService.getId()).as("management service id was wrong")
.isEqualTo("myTestService1-GG-management");
.isEqualTo("myTestService1-GG-management");
assertThat(managementService.getService()).as("management service name was wrong")
.isEqualTo("myprefix-myTestService-GG-management");
.isEqualTo("myprefix-myTestService-GG-management");
assertThat(ObjectUtils.isEmpty(managementService.getAddress()))
.as("management service address must not be empty").isFalse();
.as("management service address must not be empty")
.isFalse();
assertThat(managementService.getAddress())
.as("management service address must equals hostname from discovery properties")
.isEqualTo(this.discoveryProperties.getHostname());
.as("management service address must equals hostname from discovery properties")
.isEqualTo(this.discoveryProperties.getHostname());
}
@Configuration(proxyBeanMethods = false)

View File

@@ -89,7 +89,7 @@ public class ConsulAutoServiceRegistrationCustomizedPropsTests {
entries.put("group", "mygroup");
entries.put("secure", "false");
assertThat(service.getMeta()).as("property metadata contains the wrong entries")
.containsExactlyInAnyOrderEntriesOf(entries);
.containsExactlyInAnyOrderEntriesOf(entries);
Response<List<Check>> checkResponse = this.consul.getHealthChecksForService("myTestService-B",
HealthChecksForServiceRequest.newBuilder().setQueryParams(QueryParams.DEFAULT).build());

View File

@@ -57,9 +57,9 @@ public class ConsulAutoServiceRegistrationCustomizedTests {
@Test
public void usesCustomConsulLifecycle() {
assertThat(this.registration1.getConfiguration()).as("configuration is not customized")
.isEqualTo("customconfiguration");
.isEqualTo("customconfiguration");
assertThat(this.registration2.getConfiguration()).as("configuration is not customized")
.isEqualTo("customconfiguration");
.isEqualTo("customconfiguration");
}
@SpringBootConfiguration

View File

@@ -59,22 +59,23 @@ public class ConsulAutoServiceRegistrationDisabledTests {
private void testAutoRegistrationDisabled(String testName, String disableProperty) {
new WebApplicationContextRunner().withUserConfiguration(TestConfig.class)
.withPropertyValues("spring.application.name=" + testName, disableProperty + "=false", "server.port=0")
.withInitializer(new ConsulTestcontainers()).run(context -> {
.withPropertyValues("spring.application.name=" + testName, disableProperty + "=false", "server.port=0")
.withInitializer(new ConsulTestcontainers())
.run(context -> {
assertThat(context).doesNotHaveBean(ConsulAutoServiceRegistration.class);
assertThat(context).doesNotHaveBean(ConsulAutoServiceRegistrationListener.class);
assertThat(context).doesNotHaveBean(ConsulAutoRegistration.class);
assertThat(context).doesNotHaveBean(ConsulRegistrationCustomizer.class);
assertThat(context).doesNotHaveBean(ConsulAutoServiceRegistration.class);
assertThat(context).doesNotHaveBean(ConsulAutoServiceRegistrationListener.class);
assertThat(context).doesNotHaveBean(ConsulAutoRegistration.class);
assertThat(context).doesNotHaveBean(ConsulRegistrationCustomizer.class);
ConsulClient consul = context.getBean(ConsulClient.class);
ConsulClient consul = context.getBean(ConsulClient.class);
Response<Map<String, Service>> response = consul.getAgentServices();
Map<String, Service> services = response.getValue();
Service service = services.get(testName);
assertThat(service).as("service was registered").isNull();
Response<Map<String, Service>> response = consul.getAgentServices();
Map<String, Service> services = response.getValue();
Service service = services.get(testName);
assertThat(service).as("service was registered").isNull();
});
});
}
@Configuration(proxyBeanMethods = false)

View File

@@ -51,9 +51,11 @@ public class ConsulAutoServiceRegistrationFailFastTests {
@Test
public void testFailFastEnabled() {
this.exception.expectCause(isA(ConsulException.class));
new SpringApplicationBuilder(TestConfig.class).properties("spring.application.name=testregistrationfails-fast",
"spring.jmx.default-domain=testautoregfailfast", "server.port=0",
"spring.cloud.consul.discovery.failFast=true").run();
new SpringApplicationBuilder(TestConfig.class)
.properties("spring.application.name=testregistrationfails-fast",
"spring.jmx.default-domain=testautoregfailfast", "server.port=0",
"spring.cloud.consul.discovery.failFast=true")
.run();
}
@SpringBootConfiguration

View File

@@ -74,7 +74,7 @@ public class ConsulAutoServiceRegistrationManagementDisabledServiceTests {
assertThat(service.getService()).as("service name was wrong").isEqualTo("myTestService-NM");
assertThat(ObjectUtils.isEmpty(service.getAddress())).as("service address must not be empty").isFalse();
assertThat(service.getAddress()).as("service address must equals hostname from discovery properties")
.isEqualTo(this.discoveryProperties.getHostname());
.isEqualTo(this.discoveryProperties.getHostname());
}

View File

@@ -70,20 +70,21 @@ public class ConsulAutoServiceRegistrationManagementServiceTests {
assertThat(service.getService()).as("service name was wrong").isEqualTo("myTestService-EE");
assertThat(ObjectUtils.isEmpty(service.getAddress())).as("service address must not be empty").isFalse();
assertThat(service.getAddress()).as("service address must equals hostname from discovery properties")
.isEqualTo(this.discoveryProperties.getHostname());
.isEqualTo(this.discoveryProperties.getHostname());
final Service managementService = services.get("myTestService-EE-0-management");
assertThat(managementService).as("management service was null").isNotNull();
assertThat(managementService.getPort().intValue()).as("management service port was wrong").isEqualTo(4452);
assertThat(managementService.getId()).as("management service id was wrong")
.isEqualTo("myTestService-EE-0-management");
.isEqualTo("myTestService-EE-0-management");
assertThat(managementService.getService()).as("management service name was wrong")
.isEqualTo("myTestService-EE-management");
.isEqualTo("myTestService-EE-management");
assertThat(ObjectUtils.isEmpty(managementService.getAddress()))
.as("management service address must not be empty").isFalse();
.as("management service address must not be empty")
.isFalse();
assertThat(managementService.getAddress())
.as("management service address must equals hostname from discovery properties")
.isEqualTo(this.discoveryProperties.getHostname());
.as("management service address must equals hostname from discovery properties")
.isEqualTo(this.discoveryProperties.getHostname());
}
@Configuration(proxyBeanMethods = false)

View File

@@ -58,10 +58,10 @@ public class ConsulAutoServiceRegistrationRetryTests {
public void testRetry() {
this.exception.expectCause(isA(ConsulException.class));
try (ConfigurableApplicationContext context = new SpringApplicationBuilder(TestConfig.class)
.properties("spring.application.name=testregistrationretry",
"spring.jmx.default-domain=testautoregretry", "spring.cloud.consul.retry.max-attempts=2",
"logging.level.org.springframework.retry=DEBUG", "server.port=0")
.run()) {
.properties("spring.application.name=testregistrationretry", "spring.jmx.default-domain=testautoregretry",
"spring.cloud.consul.retry.max-attempts=2", "logging.level.org.springframework.retry=DEBUG",
"server.port=0")
.run()) {
this.output.expect(Matchers.containsString("Retry: count="));
}
}

View File

@@ -67,12 +67,12 @@ public class ConsulAutoServiceRegistrationTests {
assertThat(service).as("service was null").isNotNull();
assertThat(service.getPort().intValue()).as("service port is 0").isNotEqualTo(0);
assertThat(service.getId().contains(":")).as("service id contained invalid character: " + service.getId())
.isFalse();
.isFalse();
assertThat(service.getId()).as("service id was wrong").isEqualTo(this.registration.getInstanceId());
assertThat(service.getService()).as("service name was wrong").isEqualTo("myTestService1-FF-something");
assertThat(ObjectUtils.isEmpty(service.getAddress())).as("service address must not be empty").isFalse();
assertThat(service.getAddress()).as("service address must equals hostname from discovery properties")
.isEqualTo(this.discoveryProperties.getHostname());
.isEqualTo(this.discoveryProperties.getHostname());
}
@Test

View File

@@ -96,8 +96,10 @@ class ConsulAutoServiceRegistrationTtlCheckTests {
}
private void assertThatConsulTtlCheckIsInStatus(String serviceName, CheckStatus expectedStatus) {
await().atMost(10, TimeUnit.SECONDS).untilAsserted(() -> assertThat(getCheckForService(serviceName)).isNotNull()
.extracting(Check::getStatus).isEqualTo(expectedStatus));
await().atMost(10, TimeUnit.SECONDS)
.untilAsserted(() -> assertThat(getCheckForService(serviceName)).isNotNull()
.extracting(Check::getStatus)
.isEqualTo(expectedStatus));
}
private Check getCheckForService(String serviceName) {

View File

@@ -87,8 +87,10 @@ public class ConsulAutoServiceRegistrationTtlCheckWithActuatorHealthTests {
}
private void assertThatConsulTtlCheckIsInStatus(Check.CheckStatus expectedStatus) {
await().atMost(10, TimeUnit.SECONDS).untilAsserted(() -> assertThat(getCheckForService(SERVICE_NAME))
.isNotNull().extracting(Check::getStatus).isEqualTo(expectedStatus));
await().atMost(10, TimeUnit.SECONDS)
.untilAsserted(() -> assertThat(getCheckForService(SERVICE_NAME)).isNotNull()
.extracting(Check::getStatus)
.isEqualTo(expectedStatus));
}
private Check getCheckForService(String serviceName) {

View File

@@ -38,11 +38,11 @@ import static org.mockito.Mockito.mock;
class ConsulHeartbeatAutoConfigurationTests {
private ApplicationContextRunner appContextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(ConsulHeartbeatAutoConfiguration.class))
.withBean(ConsulClient.class, () -> mock(ConsulClient.class))
.withBean(HealthEndpoint.class, () -> mock(HealthEndpoint.class))
.withBean(ConsulDiscoveryProperties.class, () -> mock(ConsulDiscoveryProperties.class))
.withPropertyValues("spring.cloud.consul.discovery.heartbeat.enabled=true");
.withConfiguration(AutoConfigurations.of(ConsulHeartbeatAutoConfiguration.class))
.withBean(ConsulClient.class, () -> mock(ConsulClient.class))
.withBean(HealthEndpoint.class, () -> mock(HealthEndpoint.class))
.withBean(ConsulDiscoveryProperties.class, () -> mock(ConsulDiscoveryProperties.class))
.withPropertyValues("spring.cloud.consul.discovery.heartbeat.enabled=true");
@Test
void heartbeatEnabled() {
@@ -52,83 +52,93 @@ class ConsulHeartbeatAutoConfigurationTests {
@Test
void heartbeatDisabled() {
appContextRunner.withPropertyValues("spring.cloud.consul.discovery.heartbeat.enabled=false")
.run(this::assertThatHeartbeatNotConfigured);
.run(this::assertThatHeartbeatNotConfigured);
}
@Test
void heartbeatEnabledPropertyNotSpecified() {
new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(ConsulHeartbeatAutoConfiguration.class))
.withBean(ConsulClient.class, () -> mock(ConsulClient.class))
.withBean(HealthEndpoint.class, () -> mock(HealthEndpoint.class))
.run(this::assertThatHeartbeatNotConfigured);
.withBean(ConsulClient.class, () -> mock(ConsulClient.class))
.withBean(HealthEndpoint.class, () -> mock(HealthEndpoint.class))
.run(this::assertThatHeartbeatNotConfigured);
}
@Test
void heartbeatEnabledButConsulDisabled() {
appContextRunner.withPropertyValues("spring.cloud.consul.enabled=false")
.run(this::assertThatHeartbeatNotConfigured);
.run(this::assertThatHeartbeatNotConfigured);
}
@Test
void heartbeatEnabledButDiscoveryDisabled() {
appContextRunner.withPropertyValues("spring.cloud.discovery.enabled=false")
.run(this::assertThatHeartbeatNotConfigured);
.run(this::assertThatHeartbeatNotConfigured);
}
private void assertThatHeartbeatNotConfigured(AssertableApplicationContext context) {
assertThat(context).hasNotFailed().doesNotHaveBean(HeartbeatProperties.class)
.doesNotHaveBean(TtlScheduler.class).doesNotHaveBean(ApplicationStatusProvider.class);
assertThat(context).hasNotFailed()
.doesNotHaveBean(HeartbeatProperties.class)
.doesNotHaveBean(TtlScheduler.class)
.doesNotHaveBean(ApplicationStatusProvider.class);
}
private void assertThatHeartbeatConfigured(AssertableApplicationContext context) {
assertThat(context).hasNotFailed().hasSingleBean(HeartbeatProperties.class).hasSingleBean(TtlScheduler.class)
.hasSingleBean(ApplicationStatusProvider.class);
assertThat(context).hasNotFailed()
.hasSingleBean(HeartbeatProperties.class)
.hasSingleBean(TtlScheduler.class)
.hasSingleBean(ApplicationStatusProvider.class);
}
@Test
void heartbeatEnabledAndActuatorNotOnClasspath() {
new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(ConsulHeartbeatAutoConfiguration.class))
.withBean(ConsulClient.class, () -> mock(ConsulClient.class))
.withBean(ConsulDiscoveryProperties.class, () -> mock(ConsulDiscoveryProperties.class))
.withPropertyValues("spring.cloud.consul.discovery.heartbeat.enabled=true")
.withClassLoader(new FilteredClassLoader(HealthEndpoint.class))
.run(this::assertThatHeartbeatConfiguredWithoutAppStatusProvider);
.withBean(ConsulClient.class, () -> mock(ConsulClient.class))
.withBean(ConsulDiscoveryProperties.class, () -> mock(ConsulDiscoveryProperties.class))
.withPropertyValues("spring.cloud.consul.discovery.heartbeat.enabled=true")
.withClassLoader(new FilteredClassLoader(HealthEndpoint.class))
.run(this::assertThatHeartbeatConfiguredWithoutAppStatusProvider);
}
@Test
void heartbeatEnabledAndActuatorOnClasspathButNoHealthEndpointBeanRegistered() {
new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(ConsulHeartbeatAutoConfiguration.class))
.withBean(ConsulClient.class, () -> mock(ConsulClient.class))
.withBean(ConsulDiscoveryProperties.class, () -> mock(ConsulDiscoveryProperties.class))
.withPropertyValues("spring.cloud.consul.discovery.heartbeat.enabled=true")
.run(this::assertThatHeartbeatConfiguredWithoutAppStatusProvider);
.withBean(ConsulClient.class, () -> mock(ConsulClient.class))
.withBean(ConsulDiscoveryProperties.class, () -> mock(ConsulDiscoveryProperties.class))
.withPropertyValues("spring.cloud.consul.discovery.heartbeat.enabled=true")
.run(this::assertThatHeartbeatConfiguredWithoutAppStatusProvider);
}
@Test
void heartbeatEnabledButUseActuatorHealthPropertySetToFalse() {
appContextRunner.withPropertyValues("spring.cloud.consul.discovery.heartbeat.use-actuator-health=false")
.run(this::assertThatHeartbeatConfiguredWithoutAppStatusProvider);
.run(this::assertThatHeartbeatConfiguredWithoutAppStatusProvider);
}
private void assertThatHeartbeatConfiguredWithoutAppStatusProvider(AssertableApplicationContext context) {
assertThat(context).hasNotFailed().hasSingleBean(HeartbeatProperties.class).hasSingleBean(TtlScheduler.class)
.doesNotHaveBean(ApplicationStatusProvider.class);
assertThat(context).hasNotFailed()
.hasSingleBean(HeartbeatProperties.class)
.hasSingleBean(TtlScheduler.class)
.doesNotHaveBean(ApplicationStatusProvider.class);
}
@Test
void customHeartbeatPropertiesRespected() {
HeartbeatProperties customHeartbeatProps = mock(HeartbeatProperties.class);
appContextRunner.withBean(HeartbeatProperties.class, () -> customHeartbeatProps)
.run(context -> assertThat(context).hasNotFailed().hasSingleBean(HeartbeatProperties.class)
.getBean(HeartbeatProperties.class).isSameAs(customHeartbeatProps));
.run(context -> assertThat(context).hasNotFailed()
.hasSingleBean(HeartbeatProperties.class)
.getBean(HeartbeatProperties.class)
.isSameAs(customHeartbeatProps));
}
@Test
void customTtlSchedulerRespected() {
TtlScheduler customTtlScheduler = mock(TtlScheduler.class);
appContextRunner.withBean(TtlScheduler.class, () -> customTtlScheduler)
.run(context -> assertThat(context).hasNotFailed().hasSingleBean(TtlScheduler.class)
.getBean(TtlScheduler.class).isSameAs(customTtlScheduler));
.run(context -> assertThat(context).hasNotFailed()
.hasSingleBean(TtlScheduler.class)
.getBean(TtlScheduler.class)
.isSameAs(customTtlScheduler));
}
@@ -136,8 +146,10 @@ class ConsulHeartbeatAutoConfigurationTests {
void customApplicationStatusProviderRespected() {
ApplicationStatusProvider customAppStatusProvider = mock(ApplicationStatusProvider.class);
appContextRunner.withBean(ApplicationStatusProvider.class, () -> customAppStatusProvider)
.run(context -> assertThat(context).hasNotFailed().hasSingleBean(ApplicationStatusProvider.class)
.getBean(ApplicationStatusProvider.class).isSameAs(customAppStatusProvider));
.run(context -> assertThat(context).hasNotFailed()
.hasSingleBean(ApplicationStatusProvider.class)
.getBean(ApplicationStatusProvider.class)
.isSameAs(customAppStatusProvider));
}

View File

@@ -88,9 +88,11 @@ public class ConsulServiceRegistryCheckTtlTests {
serviceHeartbeatsField.setAccessible(true);
Map serviceHeartbeats = (Map) serviceHeartbeatsField.get(this.ttlScheduler);
assertThat(serviceHeartbeats.keySet().contains(this.registration.getInstanceId()))
.as("Service with heartbeat check not registered in TTL scheduler").isTrue();
.as("Service with heartbeat check not registered in TTL scheduler")
.isTrue();
assertThat(serviceHeartbeats.keySet().contains(httpRegistration.getInstanceId()))
.as("Service with HTTP check registered in TTL scheduler").isFalse();
.as("Service with HTTP check registered in TTL scheduler")
.isFalse();
}
finally {
this.consulServiceRegistry.deregister(httpRegistration);

View File

@@ -48,18 +48,19 @@ public class ConsulServiceRegistryDisabledTests {
private void testAutoRegistrationDisabled(String testName, String disableProperty) {
new WebApplicationContextRunner().withUserConfiguration(TestConfig.class)
.withPropertyValues("spring.application.name=" + testName, disableProperty + "=false", "server.port=0")
.withInitializer(new ConsulTestcontainers()).run(context -> {
assertThat(context).doesNotHaveBean(ConsulServiceRegistry.class);
assertThat(context).doesNotHaveBean(HeartbeatProperties.class);
.withPropertyValues("spring.application.name=" + testName, disableProperty + "=false", "server.port=0")
.withInitializer(new ConsulTestcontainers())
.run(context -> {
assertThat(context).doesNotHaveBean(ConsulServiceRegistry.class);
assertThat(context).doesNotHaveBean(HeartbeatProperties.class);
ConsulClient consul = context.getBean(ConsulClient.class);
ConsulClient consul = context.getBean(ConsulClient.class);
Response<Map<String, Service>> response = consul.getAgentServices();
Map<String, Service> services = response.getValue();
Service service = services.get(testName);
assertThat(service).as("service was registered").isNull();
});
Response<Map<String, Service>> response = consul.getAgentServices();
Map<String, Service> services = response.getValue();
Service service = services.get(testName);
assertThat(service).as("service was registered").isNull();
});
}
@Configuration(proxyBeanMethods = false)

View File

@@ -47,24 +47,25 @@ public class ConsulConfigDataRetryApplicationTests {
@BeforeAll
public static void setup() {
context = new SpringApplicationBuilder(ConsulConfigDataRetryApplication.class)
.addBootstrapRegistryInitializer(registry -> {
registry.register(ConsulBootstrapper.LoaderInterceptor.class, context -> {
RetryTemplate retryTemplate = context.get(RetryTemplate.class);
if (retryTemplate != null) {
return loadContext -> retryTemplate.execute(retryContext -> {
count.incrementAndGet();
return loadContext.getInvocation().apply(loadContext.getLoaderContext(),
loadContext.getResource());
});
}
// disabled
return null;
});
}).run("--spring.application.name=" + APP_NAME, "--spring.cloud.consul.retry.enabled=true",
"--spring.cloud.consul.retry.max-attempts=2",
// non-existent consul host and port
"--spring.config.import=optional:consul:somehost:1234",
"--spring.cloud.consul.config.prefix=" + ROOT, "--spring.cloud.consul.config.watch.delay=10");
.addBootstrapRegistryInitializer(registry -> {
registry.register(ConsulBootstrapper.LoaderInterceptor.class, context -> {
RetryTemplate retryTemplate = context.get(RetryTemplate.class);
if (retryTemplate != null) {
return loadContext -> retryTemplate.execute(retryContext -> {
count.incrementAndGet();
return loadContext.getInvocation()
.apply(loadContext.getLoaderContext(), loadContext.getResource());
});
}
// disabled
return null;
});
})
.run("--spring.application.name=" + APP_NAME, "--spring.cloud.consul.retry.enabled=true",
"--spring.cloud.consul.retry.max-attempts=2",
// non-existent consul host and port
"--spring.config.import=optional:consul:somehost:1234",
"--spring.cloud.consul.config.prefix=" + ROOT, "--spring.cloud.consul.config.watch.delay=10");
}

View File

@@ -88,7 +88,7 @@ public class ConsulConfigDataOrderingIntegrationTests {
public void contextLoads() {
Integer port = env.getProperty("local.server.port", Integer.class);
ResponseEntity<Map> response = new TestRestTemplate()
.getForEntity("http://localhost:" + port + BASE_PATH + "/env/my.prop", Map.class);
.getForEntity("http://localhost:" + port + BASE_PATH + "/env/my.prop", Map.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
Map res = response.getBody();
assertThat(res).containsKey("propertySources");